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/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/NonTrivialTypeVisitor.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 std::unique_ptr<CorrectionCandidateCallback> clone() override { 110 return std::make_unique<TypeNameValidatorCCC>(*this); 111 } 112 113 private: 114 bool AllowInvalidDecl; 115 bool WantClassName; 116 bool AllowTemplates; 117 bool AllowNonTemplates; 118 }; 119 120 } // end anonymous namespace 121 122 /// Determine whether the token kind starts a simple-type-specifier. 123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 124 switch (Kind) { 125 // FIXME: Take into account the current language when deciding whether a 126 // token kind is a valid type specifier 127 case tok::kw_short: 128 case tok::kw_long: 129 case tok::kw___int64: 130 case tok::kw___int128: 131 case tok::kw_signed: 132 case tok::kw_unsigned: 133 case tok::kw_void: 134 case tok::kw_char: 135 case tok::kw_int: 136 case tok::kw_half: 137 case tok::kw_float: 138 case tok::kw_double: 139 case tok::kw__Float16: 140 case tok::kw___float128: 141 case tok::kw_wchar_t: 142 case tok::kw_bool: 143 case tok::kw___underlying_type: 144 case tok::kw___auto_type: 145 return true; 146 147 case tok::annot_typename: 148 case tok::kw_char16_t: 149 case tok::kw_char32_t: 150 case tok::kw_typeof: 151 case tok::annot_decltype: 152 case tok::kw_decltype: 153 return getLangOpts().CPlusPlus; 154 155 case tok::kw_char8_t: 156 return getLangOpts().Char8; 157 158 default: 159 break; 160 } 161 162 return false; 163 } 164 165 namespace { 166 enum class UnqualifiedTypeNameLookupResult { 167 NotFound, 168 FoundNonType, 169 FoundType 170 }; 171 } // end anonymous namespace 172 173 /// Tries to perform unqualified lookup of the type decls in bases for 174 /// dependent class. 175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 176 /// type decl, \a FoundType if only type decls are found. 177 static UnqualifiedTypeNameLookupResult 178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 179 SourceLocation NameLoc, 180 const CXXRecordDecl *RD) { 181 if (!RD->hasDefinition()) 182 return UnqualifiedTypeNameLookupResult::NotFound; 183 // Look for type decls in base classes. 184 UnqualifiedTypeNameLookupResult FoundTypeDecl = 185 UnqualifiedTypeNameLookupResult::NotFound; 186 for (const auto &Base : RD->bases()) { 187 const CXXRecordDecl *BaseRD = nullptr; 188 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 189 BaseRD = BaseTT->getAsCXXRecordDecl(); 190 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 191 // Look for type decls in dependent base classes that have known primary 192 // templates. 193 if (!TST || !TST->isDependentType()) 194 continue; 195 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 196 if (!TD) 197 continue; 198 if (auto *BasePrimaryTemplate = 199 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 200 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 201 BaseRD = BasePrimaryTemplate; 202 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 203 if (const ClassTemplatePartialSpecializationDecl *PS = 204 CTD->findPartialSpecialization(Base.getType())) 205 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 206 BaseRD = PS; 207 } 208 } 209 } 210 if (BaseRD) { 211 for (NamedDecl *ND : BaseRD->lookup(&II)) { 212 if (!isa<TypeDecl>(ND)) 213 return UnqualifiedTypeNameLookupResult::FoundNonType; 214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 215 } 216 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 217 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 218 case UnqualifiedTypeNameLookupResult::FoundNonType: 219 return UnqualifiedTypeNameLookupResult::FoundNonType; 220 case UnqualifiedTypeNameLookupResult::FoundType: 221 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 222 break; 223 case UnqualifiedTypeNameLookupResult::NotFound: 224 break; 225 } 226 } 227 } 228 } 229 230 return FoundTypeDecl; 231 } 232 233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 234 const IdentifierInfo &II, 235 SourceLocation NameLoc) { 236 // Lookup in the parent class template context, if any. 237 const CXXRecordDecl *RD = nullptr; 238 UnqualifiedTypeNameLookupResult FoundTypeDecl = 239 UnqualifiedTypeNameLookupResult::NotFound; 240 for (DeclContext *DC = S.CurContext; 241 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 242 DC = DC->getParent()) { 243 // Look for type decls in dependent base classes that have known primary 244 // templates. 245 RD = dyn_cast<CXXRecordDecl>(DC); 246 if (RD && RD->getDescribedClassTemplate()) 247 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 248 } 249 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 250 return nullptr; 251 252 // We found some types in dependent base classes. Recover as if the user 253 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 254 // lookup during template instantiation. 255 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 256 257 ASTContext &Context = S.Context; 258 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 259 cast<Type>(Context.getRecordType(RD))); 260 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 261 262 CXXScopeSpec SS; 263 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 264 265 TypeLocBuilder Builder; 266 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 267 DepTL.setNameLoc(NameLoc); 268 DepTL.setElaboratedKeywordLoc(SourceLocation()); 269 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 270 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 271 } 272 273 /// If the identifier refers to a type name within this scope, 274 /// return the declaration of that type. 275 /// 276 /// This routine performs ordinary name lookup of the identifier II 277 /// within the given scope, with optional C++ scope specifier SS, to 278 /// determine whether the name refers to a type. If so, returns an 279 /// opaque pointer (actually a QualType) corresponding to that 280 /// type. Otherwise, returns NULL. 281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 282 Scope *S, CXXScopeSpec *SS, 283 bool isClassName, bool HasTrailingDot, 284 ParsedType ObjectTypePtr, 285 bool IsCtorOrDtorName, 286 bool WantNontrivialTypeSourceInfo, 287 bool IsClassTemplateDeductionContext, 288 IdentifierInfo **CorrectedII) { 289 // FIXME: Consider allowing this outside C++1z mode as an extension. 290 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 291 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 292 !isClassName && !HasTrailingDot; 293 294 // Determine where we will perform name lookup. 295 DeclContext *LookupCtx = nullptr; 296 if (ObjectTypePtr) { 297 QualType ObjectType = ObjectTypePtr.get(); 298 if (ObjectType->isRecordType()) 299 LookupCtx = computeDeclContext(ObjectType); 300 } else if (SS && SS->isNotEmpty()) { 301 LookupCtx = computeDeclContext(*SS, false); 302 303 if (!LookupCtx) { 304 if (isDependentScopeSpecifier(*SS)) { 305 // C++ [temp.res]p3: 306 // A qualified-id that refers to a type and in which the 307 // nested-name-specifier depends on a template-parameter (14.6.2) 308 // shall be prefixed by the keyword typename to indicate that the 309 // qualified-id denotes a type, forming an 310 // elaborated-type-specifier (7.1.5.3). 311 // 312 // We therefore do not perform any name lookup if the result would 313 // refer to a member of an unknown specialization. 314 if (!isClassName && !IsCtorOrDtorName) 315 return nullptr; 316 317 // We know from the grammar that this name refers to a type, 318 // so build a dependent node to describe the type. 319 if (WantNontrivialTypeSourceInfo) 320 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 321 322 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 323 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 324 II, NameLoc); 325 return ParsedType::make(T); 326 } 327 328 return nullptr; 329 } 330 331 if (!LookupCtx->isDependentContext() && 332 RequireCompleteDeclContext(*SS, LookupCtx)) 333 return nullptr; 334 } 335 336 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 337 // lookup for class-names. 338 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 339 LookupOrdinaryName; 340 LookupResult Result(*this, &II, NameLoc, Kind); 341 if (LookupCtx) { 342 // Perform "qualified" name lookup into the declaration context we 343 // computed, which is either the type of the base of a member access 344 // expression or the declaration context associated with a prior 345 // nested-name-specifier. 346 LookupQualifiedName(Result, LookupCtx); 347 348 if (ObjectTypePtr && Result.empty()) { 349 // C++ [basic.lookup.classref]p3: 350 // If the unqualified-id is ~type-name, the type-name is looked up 351 // in the context of the entire postfix-expression. If the type T of 352 // the object expression is of a class type C, the type-name is also 353 // looked up in the scope of class C. At least one of the lookups shall 354 // find a name that refers to (possibly cv-qualified) T. 355 LookupName(Result, S); 356 } 357 } else { 358 // Perform unqualified name lookup. 359 LookupName(Result, S); 360 361 // For unqualified lookup in a class template in MSVC mode, look into 362 // dependent base classes where the primary class template is known. 363 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 364 if (ParsedType TypeInBase = 365 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 366 return TypeInBase; 367 } 368 } 369 370 NamedDecl *IIDecl = nullptr; 371 switch (Result.getResultKind()) { 372 case LookupResult::NotFound: 373 case LookupResult::NotFoundInCurrentInstantiation: 374 if (CorrectedII) { 375 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 376 AllowDeducedTemplate); 377 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 378 S, SS, CCC, CTK_ErrorRecovery); 379 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 380 TemplateTy Template; 381 bool MemberOfUnknownSpecialization; 382 UnqualifiedId TemplateName; 383 TemplateName.setIdentifier(NewII, NameLoc); 384 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 385 CXXScopeSpec NewSS, *NewSSPtr = SS; 386 if (SS && NNS) { 387 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 388 NewSSPtr = &NewSS; 389 } 390 if (Correction && (NNS || NewII != &II) && 391 // Ignore a correction to a template type as the to-be-corrected 392 // identifier is not a template (typo correction for template names 393 // is handled elsewhere). 394 !(getLangOpts().CPlusPlus && NewSSPtr && 395 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 396 Template, MemberOfUnknownSpecialization))) { 397 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 398 isClassName, HasTrailingDot, ObjectTypePtr, 399 IsCtorOrDtorName, 400 WantNontrivialTypeSourceInfo, 401 IsClassTemplateDeductionContext); 402 if (Ty) { 403 diagnoseTypo(Correction, 404 PDiag(diag::err_unknown_type_or_class_name_suggest) 405 << Result.getLookupName() << isClassName); 406 if (SS && NNS) 407 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 408 *CorrectedII = NewII; 409 return Ty; 410 } 411 } 412 } 413 // If typo correction failed or was not performed, fall through 414 LLVM_FALLTHROUGH; 415 case LookupResult::FoundOverloaded: 416 case LookupResult::FoundUnresolvedValue: 417 Result.suppressDiagnostics(); 418 return nullptr; 419 420 case LookupResult::Ambiguous: 421 // Recover from type-hiding ambiguities by hiding the type. We'll 422 // do the lookup again when looking for an object, and we can 423 // diagnose the error then. If we don't do this, then the error 424 // about hiding the type will be immediately followed by an error 425 // that only makes sense if the identifier was treated like a type. 426 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 427 Result.suppressDiagnostics(); 428 return nullptr; 429 } 430 431 // Look to see if we have a type anywhere in the list of results. 432 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 433 Res != ResEnd; ++Res) { 434 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 435 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 436 if (!IIDecl || 437 (*Res)->getLocation().getRawEncoding() < 438 IIDecl->getLocation().getRawEncoding()) 439 IIDecl = *Res; 440 } 441 } 442 443 if (!IIDecl) { 444 // None of the entities we found is a type, so there is no way 445 // to even assume that the result is a type. In this case, don't 446 // complain about the ambiguity. The parser will either try to 447 // perform this lookup again (e.g., as an object name), which 448 // will produce the ambiguity, or will complain that it expected 449 // a type name. 450 Result.suppressDiagnostics(); 451 return nullptr; 452 } 453 454 // We found a type within the ambiguous lookup; diagnose the 455 // ambiguity and then return that type. This might be the right 456 // answer, or it might not be, but it suppresses any attempt to 457 // perform the name lookup again. 458 break; 459 460 case LookupResult::Found: 461 IIDecl = Result.getFoundDecl(); 462 break; 463 } 464 465 assert(IIDecl && "Didn't find decl"); 466 467 QualType T; 468 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 469 // C++ [class.qual]p2: A lookup that would find the injected-class-name 470 // instead names the constructors of the class, except when naming a class. 471 // This is ill-formed when we're not actually forming a ctor or dtor name. 472 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 473 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 474 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 475 FoundRD->isInjectedClassName() && 476 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 477 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 478 << &II << /*Type*/1; 479 480 DiagnoseUseOfDecl(IIDecl, NameLoc); 481 482 T = Context.getTypeDeclType(TD); 483 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 484 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 485 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 486 if (!HasTrailingDot) 487 T = Context.getObjCInterfaceType(IDecl); 488 } else if (AllowDeducedTemplate) { 489 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 490 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 491 QualType(), false); 492 } 493 494 if (T.isNull()) { 495 // If it's not plausibly a type, suppress diagnostics. 496 Result.suppressDiagnostics(); 497 return nullptr; 498 } 499 500 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 501 // constructor or destructor name (in such a case, the scope specifier 502 // will be attached to the enclosing Expr or Decl node). 503 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 504 !isa<ObjCInterfaceDecl>(IIDecl)) { 505 if (WantNontrivialTypeSourceInfo) { 506 // Construct a type with type-source information. 507 TypeLocBuilder Builder; 508 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 509 510 T = getElaboratedType(ETK_None, *SS, T); 511 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 512 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 513 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 514 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 515 } else { 516 T = getElaboratedType(ETK_None, *SS, T); 517 } 518 } 519 520 return ParsedType::make(T); 521 } 522 523 // Builds a fake NNS for the given decl context. 524 static NestedNameSpecifier * 525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 526 for (;; DC = DC->getLookupParent()) { 527 DC = DC->getPrimaryContext(); 528 auto *ND = dyn_cast<NamespaceDecl>(DC); 529 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 530 return NestedNameSpecifier::Create(Context, nullptr, ND); 531 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 532 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 533 RD->getTypeForDecl()); 534 else if (isa<TranslationUnitDecl>(DC)) 535 return NestedNameSpecifier::GlobalSpecifier(Context); 536 } 537 llvm_unreachable("something isn't in TU scope?"); 538 } 539 540 /// Find the parent class with dependent bases of the innermost enclosing method 541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 542 /// up allowing unqualified dependent type names at class-level, which MSVC 543 /// correctly rejects. 544 static const CXXRecordDecl * 545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 546 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 547 DC = DC->getPrimaryContext(); 548 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 549 if (MD->getParent()->hasAnyDependentBases()) 550 return MD->getParent(); 551 } 552 return nullptr; 553 } 554 555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 556 SourceLocation NameLoc, 557 bool IsTemplateTypeArg) { 558 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 559 560 NestedNameSpecifier *NNS = nullptr; 561 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 562 // If we weren't able to parse a default template argument, delay lookup 563 // until instantiation time by making a non-dependent DependentTypeName. We 564 // pretend we saw a NestedNameSpecifier referring to the current scope, and 565 // lookup is retried. 566 // FIXME: This hurts our diagnostic quality, since we get errors like "no 567 // type named 'Foo' in 'current_namespace'" when the user didn't write any 568 // name specifiers. 569 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 570 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 571 } else if (const CXXRecordDecl *RD = 572 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 573 // Build a DependentNameType that will perform lookup into RD at 574 // instantiation time. 575 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 576 RD->getTypeForDecl()); 577 578 // Diagnose that this identifier was undeclared, and retry the lookup during 579 // template instantiation. 580 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 581 << RD; 582 } else { 583 // This is not a situation that we should recover from. 584 return ParsedType(); 585 } 586 587 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 588 589 // Build type location information. We synthesized the qualifier, so we have 590 // to build a fake NestedNameSpecifierLoc. 591 NestedNameSpecifierLocBuilder NNSLocBuilder; 592 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 593 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 594 595 TypeLocBuilder Builder; 596 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 597 DepTL.setNameLoc(NameLoc); 598 DepTL.setElaboratedKeywordLoc(SourceLocation()); 599 DepTL.setQualifierLoc(QualifierLoc); 600 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 601 } 602 603 /// isTagName() - This method is called *for error recovery purposes only* 604 /// to determine if the specified name is a valid tag name ("struct foo"). If 605 /// so, this returns the TST for the tag corresponding to it (TST_enum, 606 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 607 /// cases in C where the user forgot to specify the tag. 608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 609 // Do a tag name lookup in this scope. 610 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 611 LookupName(R, S, false); 612 R.suppressDiagnostics(); 613 if (R.getResultKind() == LookupResult::Found) 614 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 615 switch (TD->getTagKind()) { 616 case TTK_Struct: return DeclSpec::TST_struct; 617 case TTK_Interface: return DeclSpec::TST_interface; 618 case TTK_Union: return DeclSpec::TST_union; 619 case TTK_Class: return DeclSpec::TST_class; 620 case TTK_Enum: return DeclSpec::TST_enum; 621 } 622 } 623 624 return DeclSpec::TST_unspecified; 625 } 626 627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 629 /// then downgrade the missing typename error to a warning. 630 /// This is needed for MSVC compatibility; Example: 631 /// @code 632 /// template<class T> class A { 633 /// public: 634 /// typedef int TYPE; 635 /// }; 636 /// template<class T> class B : public A<T> { 637 /// public: 638 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 639 /// }; 640 /// @endcode 641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 642 if (CurContext->isRecord()) { 643 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 644 return true; 645 646 const Type *Ty = SS->getScopeRep()->getAsType(); 647 648 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 649 for (const auto &Base : RD->bases()) 650 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 651 return true; 652 return S->isFunctionPrototypeScope(); 653 } 654 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 655 } 656 657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 658 SourceLocation IILoc, 659 Scope *S, 660 CXXScopeSpec *SS, 661 ParsedType &SuggestedType, 662 bool IsTemplateName) { 663 // Don't report typename errors for editor placeholders. 664 if (II->isEditorPlaceholder()) 665 return; 666 // We don't have anything to suggest (yet). 667 SuggestedType = nullptr; 668 669 // There may have been a typo in the name of the type. Look up typo 670 // results, in case we have something that we can suggest. 671 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 672 /*AllowTemplates=*/IsTemplateName, 673 /*AllowNonTemplates=*/!IsTemplateName); 674 if (TypoCorrection Corrected = 675 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 676 CCC, CTK_ErrorRecovery)) { 677 // FIXME: Support error recovery for the template-name case. 678 bool CanRecover = !IsTemplateName; 679 if (Corrected.isKeyword()) { 680 // We corrected to a keyword. 681 diagnoseTypo(Corrected, 682 PDiag(IsTemplateName ? diag::err_no_template_suggest 683 : diag::err_unknown_typename_suggest) 684 << II); 685 II = Corrected.getCorrectionAsIdentifierInfo(); 686 } else { 687 // We found a similarly-named type or interface; suggest that. 688 if (!SS || !SS->isSet()) { 689 diagnoseTypo(Corrected, 690 PDiag(IsTemplateName ? diag::err_no_template_suggest 691 : diag::err_unknown_typename_suggest) 692 << II, CanRecover); 693 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 694 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 695 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 696 II->getName().equals(CorrectedStr); 697 diagnoseTypo(Corrected, 698 PDiag(IsTemplateName 699 ? diag::err_no_member_template_suggest 700 : diag::err_unknown_nested_typename_suggest) 701 << II << DC << DroppedSpecifier << SS->getRange(), 702 CanRecover); 703 } else { 704 llvm_unreachable("could not have corrected a typo here"); 705 } 706 707 if (!CanRecover) 708 return; 709 710 CXXScopeSpec tmpSS; 711 if (Corrected.getCorrectionSpecifier()) 712 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 713 SourceRange(IILoc)); 714 // FIXME: Support class template argument deduction here. 715 SuggestedType = 716 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 717 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 718 /*IsCtorOrDtorName=*/false, 719 /*WantNontrivialTypeSourceInfo=*/true); 720 } 721 return; 722 } 723 724 if (getLangOpts().CPlusPlus && !IsTemplateName) { 725 // See if II is a class template that the user forgot to pass arguments to. 726 UnqualifiedId Name; 727 Name.setIdentifier(II, IILoc); 728 CXXScopeSpec EmptySS; 729 TemplateTy TemplateResult; 730 bool MemberOfUnknownSpecialization; 731 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 732 Name, nullptr, true, TemplateResult, 733 MemberOfUnknownSpecialization) == TNK_Type_template) { 734 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 735 return; 736 } 737 } 738 739 // FIXME: Should we move the logic that tries to recover from a missing tag 740 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 741 742 if (!SS || (!SS->isSet() && !SS->isInvalid())) 743 Diag(IILoc, IsTemplateName ? diag::err_no_template 744 : diag::err_unknown_typename) 745 << II; 746 else if (DeclContext *DC = computeDeclContext(*SS, false)) 747 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 748 : diag::err_typename_nested_not_found) 749 << II << DC << SS->getRange(); 750 else if (isDependentScopeSpecifier(*SS)) { 751 unsigned DiagID = diag::err_typename_missing; 752 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 753 DiagID = diag::ext_typename_missing; 754 755 Diag(SS->getRange().getBegin(), DiagID) 756 << SS->getScopeRep() << II->getName() 757 << SourceRange(SS->getRange().getBegin(), IILoc) 758 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 759 SuggestedType = ActOnTypenameType(S, SourceLocation(), 760 *SS, *II, IILoc).get(); 761 } else { 762 assert(SS && SS->isInvalid() && 763 "Invalid scope specifier has already been diagnosed"); 764 } 765 } 766 767 /// Determine whether the given result set contains either a type name 768 /// or 769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 770 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 771 NextToken.is(tok::less); 772 773 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 774 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 775 return true; 776 777 if (CheckTemplate && isa<TemplateDecl>(*I)) 778 return true; 779 } 780 781 return false; 782 } 783 784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 785 Scope *S, CXXScopeSpec &SS, 786 IdentifierInfo *&Name, 787 SourceLocation NameLoc) { 788 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 789 SemaRef.LookupParsedName(R, S, &SS); 790 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 791 StringRef FixItTagName; 792 switch (Tag->getTagKind()) { 793 case TTK_Class: 794 FixItTagName = "class "; 795 break; 796 797 case TTK_Enum: 798 FixItTagName = "enum "; 799 break; 800 801 case TTK_Struct: 802 FixItTagName = "struct "; 803 break; 804 805 case TTK_Interface: 806 FixItTagName = "__interface "; 807 break; 808 809 case TTK_Union: 810 FixItTagName = "union "; 811 break; 812 } 813 814 StringRef TagName = FixItTagName.drop_back(); 815 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 816 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 817 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 818 819 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 820 I != IEnd; ++I) 821 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 822 << Name << TagName; 823 824 // Replace lookup results with just the tag decl. 825 Result.clear(Sema::LookupTagName); 826 SemaRef.LookupParsedName(Result, S, &SS); 827 return true; 828 } 829 830 return false; 831 } 832 833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 835 QualType T, SourceLocation NameLoc) { 836 ASTContext &Context = S.Context; 837 838 TypeLocBuilder Builder; 839 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 840 841 T = S.getElaboratedType(ETK_None, SS, T); 842 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 843 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 844 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 845 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 846 } 847 848 Sema::NameClassification 849 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 850 SourceLocation NameLoc, const Token &NextToken, 851 bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) { 852 DeclarationNameInfo NameInfo(Name, NameLoc); 853 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 854 855 if (NextToken.is(tok::coloncolon)) { 856 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 857 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 858 } else if (getLangOpts().CPlusPlus && SS.isSet() && 859 isCurrentClassName(*Name, S, &SS)) { 860 // Per [class.qual]p2, this names the constructors of SS, not the 861 // injected-class-name. We don't have a classification for that. 862 // There's not much point caching this result, since the parser 863 // will reject it later. 864 return NameClassification::Unknown(); 865 } 866 867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 868 LookupParsedName(Result, S, &SS, !CurMethod); 869 870 // For unqualified lookup in a class template in MSVC mode, look into 871 // dependent base classes where the primary class template is known. 872 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 873 if (ParsedType TypeInBase = 874 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 875 return TypeInBase; 876 } 877 878 // Perform lookup for Objective-C instance variables (including automatically 879 // synthesized instance variables), if we're in an Objective-C method. 880 // FIXME: This lookup really, really needs to be folded in to the normal 881 // unqualified lookup mechanism. 882 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 883 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 884 if (E.get() || E.isInvalid()) 885 return E; 886 } 887 888 bool SecondTry = false; 889 bool IsFilteredTemplateName = false; 890 891 Corrected: 892 switch (Result.getResultKind()) { 893 case LookupResult::NotFound: 894 // If an unqualified-id is followed by a '(', then we have a function 895 // call. 896 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 897 // In C++, this is an ADL-only call. 898 // FIXME: Reference? 899 if (getLangOpts().CPlusPlus) 900 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 901 902 // C90 6.3.2.2: 903 // If the expression that precedes the parenthesized argument list in a 904 // function call consists solely of an identifier, and if no 905 // declaration is visible for this identifier, the identifier is 906 // implicitly declared exactly as if, in the innermost block containing 907 // the function call, the declaration 908 // 909 // extern int identifier (); 910 // 911 // appeared. 912 // 913 // We also allow this in C99 as an extension. 914 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 915 Result.addDecl(D); 916 Result.resolveKind(); 917 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 918 } 919 } 920 921 if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) { 922 // In C++20 onwards, this could be an ADL-only call to a function 923 // template, and we're required to assume that this is a template name. 924 // 925 // FIXME: Find a way to still do typo correction in this case. 926 TemplateName Template = 927 Context.getAssumedTemplateName(NameInfo.getName()); 928 return NameClassification::UndeclaredTemplate(Template); 929 } 930 931 // In C, we first see whether there is a tag type by the same name, in 932 // which case it's likely that the user just forgot to write "enum", 933 // "struct", or "union". 934 if (!getLangOpts().CPlusPlus && !SecondTry && 935 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 936 break; 937 } 938 939 // Perform typo correction to determine if there is another name that is 940 // close to this name. 941 if (!SecondTry && CCC) { 942 SecondTry = true; 943 if (TypoCorrection Corrected = 944 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 945 &SS, *CCC, CTK_ErrorRecovery)) { 946 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 947 unsigned QualifiedDiag = diag::err_no_member_suggest; 948 949 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 950 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 951 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 952 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 953 UnqualifiedDiag = diag::err_no_template_suggest; 954 QualifiedDiag = diag::err_no_member_template_suggest; 955 } else if (UnderlyingFirstDecl && 956 (isa<TypeDecl>(UnderlyingFirstDecl) || 957 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 958 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 959 UnqualifiedDiag = diag::err_unknown_typename_suggest; 960 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 961 } 962 963 if (SS.isEmpty()) { 964 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 965 } else {// FIXME: is this even reachable? Test it. 966 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 967 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 968 Name->getName().equals(CorrectedStr); 969 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 970 << Name << computeDeclContext(SS, false) 971 << DroppedSpecifier << SS.getRange()); 972 } 973 974 // Update the name, so that the caller has the new name. 975 Name = Corrected.getCorrectionAsIdentifierInfo(); 976 977 // Typo correction corrected to a keyword. 978 if (Corrected.isKeyword()) 979 return Name; 980 981 // Also update the LookupResult... 982 // FIXME: This should probably go away at some point 983 Result.clear(); 984 Result.setLookupName(Corrected.getCorrection()); 985 if (FirstDecl) 986 Result.addDecl(FirstDecl); 987 988 // If we found an Objective-C instance variable, let 989 // LookupInObjCMethod build the appropriate expression to 990 // reference the ivar. 991 // FIXME: This is a gross hack. 992 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 993 Result.clear(); 994 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 995 return E; 996 } 997 998 goto Corrected; 999 } 1000 } 1001 1002 // We failed to correct; just fall through and let the parser deal with it. 1003 Result.suppressDiagnostics(); 1004 return NameClassification::Unknown(); 1005 1006 case LookupResult::NotFoundInCurrentInstantiation: { 1007 // We performed name lookup into the current instantiation, and there were 1008 // dependent bases, so we treat this result the same way as any other 1009 // dependent nested-name-specifier. 1010 1011 // C++ [temp.res]p2: 1012 // A name used in a template declaration or definition and that is 1013 // dependent on a template-parameter is assumed not to name a type 1014 // unless the applicable name lookup finds a type name or the name is 1015 // qualified by the keyword typename. 1016 // 1017 // FIXME: If the next token is '<', we might want to ask the parser to 1018 // perform some heroics to see if we actually have a 1019 // template-argument-list, which would indicate a missing 'template' 1020 // keyword here. 1021 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1022 NameInfo, IsAddressOfOperand, 1023 /*TemplateArgs=*/nullptr); 1024 } 1025 1026 case LookupResult::Found: 1027 case LookupResult::FoundOverloaded: 1028 case LookupResult::FoundUnresolvedValue: 1029 break; 1030 1031 case LookupResult::Ambiguous: 1032 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1033 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1034 /*AllowDependent=*/false)) { 1035 // C++ [temp.local]p3: 1036 // A lookup that finds an injected-class-name (10.2) can result in an 1037 // ambiguity in certain cases (for example, if it is found in more than 1038 // one base class). If all of the injected-class-names that are found 1039 // refer to specializations of the same class template, and if the name 1040 // is followed by a template-argument-list, the reference refers to the 1041 // class template itself and not a specialization thereof, and is not 1042 // ambiguous. 1043 // 1044 // This filtering can make an ambiguous result into an unambiguous one, 1045 // so try again after filtering out template names. 1046 FilterAcceptableTemplateNames(Result); 1047 if (!Result.isAmbiguous()) { 1048 IsFilteredTemplateName = true; 1049 break; 1050 } 1051 } 1052 1053 // Diagnose the ambiguity and return an error. 1054 return NameClassification::Error(); 1055 } 1056 1057 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1058 (IsFilteredTemplateName || 1059 hasAnyAcceptableTemplateNames( 1060 Result, /*AllowFunctionTemplates=*/true, 1061 /*AllowDependent=*/false, 1062 /*AllowNonTemplateFunctions*/ !SS.isSet() && 1063 getLangOpts().CPlusPlus2a))) { 1064 // C++ [temp.names]p3: 1065 // After name lookup (3.4) finds that a name is a template-name or that 1066 // an operator-function-id or a literal- operator-id refers to a set of 1067 // overloaded functions any member of which is a function template if 1068 // this is followed by a <, the < is always taken as the delimiter of a 1069 // template-argument-list and never as the less-than operator. 1070 // C++2a [temp.names]p2: 1071 // A name is also considered to refer to a template if it is an 1072 // unqualified-id followed by a < and name lookup finds either one 1073 // or more functions or finds nothing. 1074 if (!IsFilteredTemplateName) 1075 FilterAcceptableTemplateNames(Result); 1076 1077 bool IsFunctionTemplate; 1078 bool IsVarTemplate; 1079 TemplateName Template; 1080 if (Result.end() - Result.begin() > 1) { 1081 IsFunctionTemplate = true; 1082 Template = Context.getOverloadedTemplateName(Result.begin(), 1083 Result.end()); 1084 } else if (!Result.empty()) { 1085 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1086 *Result.begin(), /*AllowFunctionTemplates=*/true, 1087 /*AllowDependent=*/false)); 1088 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1089 IsVarTemplate = isa<VarTemplateDecl>(TD); 1090 1091 if (SS.isSet() && !SS.isInvalid()) 1092 Template = 1093 Context.getQualifiedTemplateName(SS.getScopeRep(), 1094 /*TemplateKeyword=*/false, TD); 1095 else 1096 Template = TemplateName(TD); 1097 } else { 1098 // All results were non-template functions. This is a function template 1099 // name. 1100 IsFunctionTemplate = true; 1101 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1102 } 1103 1104 if (IsFunctionTemplate) { 1105 // Function templates always go through overload resolution, at which 1106 // point we'll perform the various checks (e.g., accessibility) we need 1107 // to based on which function we selected. 1108 Result.suppressDiagnostics(); 1109 1110 return NameClassification::FunctionTemplate(Template); 1111 } 1112 1113 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1114 : NameClassification::TypeTemplate(Template); 1115 } 1116 1117 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1118 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1119 DiagnoseUseOfDecl(Type, NameLoc); 1120 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1121 QualType T = Context.getTypeDeclType(Type); 1122 if (SS.isNotEmpty()) 1123 return buildNestedType(*this, SS, T, NameLoc); 1124 return ParsedType::make(T); 1125 } 1126 1127 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1128 if (!Class) { 1129 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1130 if (ObjCCompatibleAliasDecl *Alias = 1131 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1132 Class = Alias->getClassInterface(); 1133 } 1134 1135 if (Class) { 1136 DiagnoseUseOfDecl(Class, NameLoc); 1137 1138 if (NextToken.is(tok::period)) { 1139 // Interface. <something> is parsed as a property reference expression. 1140 // Just return "unknown" as a fall-through for now. 1141 Result.suppressDiagnostics(); 1142 return NameClassification::Unknown(); 1143 } 1144 1145 QualType T = Context.getObjCInterfaceType(Class); 1146 return ParsedType::make(T); 1147 } 1148 1149 // We can have a type template here if we're classifying a template argument. 1150 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1151 !isa<VarTemplateDecl>(FirstDecl)) 1152 return NameClassification::TypeTemplate( 1153 TemplateName(cast<TemplateDecl>(FirstDecl))); 1154 1155 // Check for a tag type hidden by a non-type decl in a few cases where it 1156 // seems likely a type is wanted instead of the non-type that was found. 1157 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1158 if ((NextToken.is(tok::identifier) || 1159 (NextIsOp && 1160 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1161 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1162 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1163 DiagnoseUseOfDecl(Type, NameLoc); 1164 QualType T = Context.getTypeDeclType(Type); 1165 if (SS.isNotEmpty()) 1166 return buildNestedType(*this, SS, T, NameLoc); 1167 return ParsedType::make(T); 1168 } 1169 1170 if (FirstDecl->isCXXClassMember()) 1171 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1172 nullptr, S); 1173 1174 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1175 return BuildDeclarationNameExpr(SS, Result, ADL); 1176 } 1177 1178 Sema::TemplateNameKindForDiagnostics 1179 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1180 auto *TD = Name.getAsTemplateDecl(); 1181 if (!TD) 1182 return TemplateNameKindForDiagnostics::DependentTemplate; 1183 if (isa<ClassTemplateDecl>(TD)) 1184 return TemplateNameKindForDiagnostics::ClassTemplate; 1185 if (isa<FunctionTemplateDecl>(TD)) 1186 return TemplateNameKindForDiagnostics::FunctionTemplate; 1187 if (isa<VarTemplateDecl>(TD)) 1188 return TemplateNameKindForDiagnostics::VarTemplate; 1189 if (isa<TypeAliasTemplateDecl>(TD)) 1190 return TemplateNameKindForDiagnostics::AliasTemplate; 1191 if (isa<TemplateTemplateParmDecl>(TD)) 1192 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1193 if (isa<ConceptDecl>(TD)) 1194 return TemplateNameKindForDiagnostics::Concept; 1195 return TemplateNameKindForDiagnostics::DependentTemplate; 1196 } 1197 1198 // Determines the context to return to after temporarily entering a 1199 // context. This depends in an unnecessarily complicated way on the 1200 // exact ordering of callbacks from the parser. 1201 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1202 1203 // Functions defined inline within classes aren't parsed until we've 1204 // finished parsing the top-level class, so the top-level class is 1205 // the context we'll need to return to. 1206 // A Lambda call operator whose parent is a class must not be treated 1207 // as an inline member function. A Lambda can be used legally 1208 // either as an in-class member initializer or a default argument. These 1209 // are parsed once the class has been marked complete and so the containing 1210 // context would be the nested class (when the lambda is defined in one); 1211 // If the class is not complete, then the lambda is being used in an 1212 // ill-formed fashion (such as to specify the width of a bit-field, or 1213 // in an array-bound) - in which case we still want to return the 1214 // lexically containing DC (which could be a nested class). 1215 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1216 DC = DC->getLexicalParent(); 1217 1218 // A function not defined within a class will always return to its 1219 // lexical context. 1220 if (!isa<CXXRecordDecl>(DC)) 1221 return DC; 1222 1223 // A C++ inline method/friend is parsed *after* the topmost class 1224 // it was declared in is fully parsed ("complete"); the topmost 1225 // class is the context we need to return to. 1226 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1227 DC = RD; 1228 1229 // Return the declaration context of the topmost class the inline method is 1230 // declared in. 1231 return DC; 1232 } 1233 1234 return DC->getLexicalParent(); 1235 } 1236 1237 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1238 assert(getContainingDC(DC) == CurContext && 1239 "The next DeclContext should be lexically contained in the current one."); 1240 CurContext = DC; 1241 S->setEntity(DC); 1242 } 1243 1244 void Sema::PopDeclContext() { 1245 assert(CurContext && "DeclContext imbalance!"); 1246 1247 CurContext = getContainingDC(CurContext); 1248 assert(CurContext && "Popped translation unit!"); 1249 } 1250 1251 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1252 Decl *D) { 1253 // Unlike PushDeclContext, the context to which we return is not necessarily 1254 // the containing DC of TD, because the new context will be some pre-existing 1255 // TagDecl definition instead of a fresh one. 1256 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1257 CurContext = cast<TagDecl>(D)->getDefinition(); 1258 assert(CurContext && "skipping definition of undefined tag"); 1259 // Start lookups from the parent of the current context; we don't want to look 1260 // into the pre-existing complete definition. 1261 S->setEntity(CurContext->getLookupParent()); 1262 return Result; 1263 } 1264 1265 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1266 CurContext = static_cast<decltype(CurContext)>(Context); 1267 } 1268 1269 /// EnterDeclaratorContext - Used when we must lookup names in the context 1270 /// of a declarator's nested name specifier. 1271 /// 1272 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1273 // C++0x [basic.lookup.unqual]p13: 1274 // A name used in the definition of a static data member of class 1275 // X (after the qualified-id of the static member) is looked up as 1276 // if the name was used in a member function of X. 1277 // C++0x [basic.lookup.unqual]p14: 1278 // If a variable member of a namespace is defined outside of the 1279 // scope of its namespace then any name used in the definition of 1280 // the variable member (after the declarator-id) is looked up as 1281 // if the definition of the variable member occurred in its 1282 // namespace. 1283 // Both of these imply that we should push a scope whose context 1284 // is the semantic context of the declaration. We can't use 1285 // PushDeclContext here because that context is not necessarily 1286 // lexically contained in the current context. Fortunately, 1287 // the containing scope should have the appropriate information. 1288 1289 assert(!S->getEntity() && "scope already has entity"); 1290 1291 #ifndef NDEBUG 1292 Scope *Ancestor = S->getParent(); 1293 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1294 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1295 #endif 1296 1297 CurContext = DC; 1298 S->setEntity(DC); 1299 } 1300 1301 void Sema::ExitDeclaratorContext(Scope *S) { 1302 assert(S->getEntity() == CurContext && "Context imbalance!"); 1303 1304 // Switch back to the lexical context. The safety of this is 1305 // enforced by an assert in EnterDeclaratorContext. 1306 Scope *Ancestor = S->getParent(); 1307 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1308 CurContext = Ancestor->getEntity(); 1309 1310 // We don't need to do anything with the scope, which is going to 1311 // disappear. 1312 } 1313 1314 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1315 // We assume that the caller has already called 1316 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1317 FunctionDecl *FD = D->getAsFunction(); 1318 if (!FD) 1319 return; 1320 1321 // Same implementation as PushDeclContext, but enters the context 1322 // from the lexical parent, rather than the top-level class. 1323 assert(CurContext == FD->getLexicalParent() && 1324 "The next DeclContext should be lexically contained in the current one."); 1325 CurContext = FD; 1326 S->setEntity(CurContext); 1327 1328 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1329 ParmVarDecl *Param = FD->getParamDecl(P); 1330 // If the parameter has an identifier, then add it to the scope 1331 if (Param->getIdentifier()) { 1332 S->AddDecl(Param); 1333 IdResolver.AddDecl(Param); 1334 } 1335 } 1336 } 1337 1338 void Sema::ActOnExitFunctionContext() { 1339 // Same implementation as PopDeclContext, but returns to the lexical parent, 1340 // rather than the top-level class. 1341 assert(CurContext && "DeclContext imbalance!"); 1342 CurContext = CurContext->getLexicalParent(); 1343 assert(CurContext && "Popped translation unit!"); 1344 } 1345 1346 /// Determine whether we allow overloading of the function 1347 /// PrevDecl with another declaration. 1348 /// 1349 /// This routine determines whether overloading is possible, not 1350 /// whether some new function is actually an overload. It will return 1351 /// true in C++ (where we can always provide overloads) or, as an 1352 /// extension, in C when the previous function is already an 1353 /// overloaded function declaration or has the "overloadable" 1354 /// attribute. 1355 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1356 ASTContext &Context, 1357 const FunctionDecl *New) { 1358 if (Context.getLangOpts().CPlusPlus) 1359 return true; 1360 1361 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1362 return true; 1363 1364 return Previous.getResultKind() == LookupResult::Found && 1365 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1366 New->hasAttr<OverloadableAttr>()); 1367 } 1368 1369 /// Add this decl to the scope shadowed decl chains. 1370 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1371 // Move up the scope chain until we find the nearest enclosing 1372 // non-transparent context. The declaration will be introduced into this 1373 // scope. 1374 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1375 S = S->getParent(); 1376 1377 // Add scoped declarations into their context, so that they can be 1378 // found later. Declarations without a context won't be inserted 1379 // into any context. 1380 if (AddToContext) 1381 CurContext->addDecl(D); 1382 1383 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1384 // are function-local declarations. 1385 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1386 !D->getDeclContext()->getRedeclContext()->Equals( 1387 D->getLexicalDeclContext()->getRedeclContext()) && 1388 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1389 return; 1390 1391 // Template instantiations should also not be pushed into scope. 1392 if (isa<FunctionDecl>(D) && 1393 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1394 return; 1395 1396 // If this replaces anything in the current scope, 1397 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1398 IEnd = IdResolver.end(); 1399 for (; I != IEnd; ++I) { 1400 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1401 S->RemoveDecl(*I); 1402 IdResolver.RemoveDecl(*I); 1403 1404 // Should only need to replace one decl. 1405 break; 1406 } 1407 } 1408 1409 S->AddDecl(D); 1410 1411 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1412 // Implicitly-generated labels may end up getting generated in an order that 1413 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1414 // the label at the appropriate place in the identifier chain. 1415 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1416 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1417 if (IDC == CurContext) { 1418 if (!S->isDeclScope(*I)) 1419 continue; 1420 } else if (IDC->Encloses(CurContext)) 1421 break; 1422 } 1423 1424 IdResolver.InsertDeclAfter(I, D); 1425 } else { 1426 IdResolver.AddDecl(D); 1427 } 1428 } 1429 1430 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1431 bool AllowInlineNamespace) { 1432 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1433 } 1434 1435 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1436 DeclContext *TargetDC = DC->getPrimaryContext(); 1437 do { 1438 if (DeclContext *ScopeDC = S->getEntity()) 1439 if (ScopeDC->getPrimaryContext() == TargetDC) 1440 return S; 1441 } while ((S = S->getParent())); 1442 1443 return nullptr; 1444 } 1445 1446 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1447 DeclContext*, 1448 ASTContext&); 1449 1450 /// Filters out lookup results that don't fall within the given scope 1451 /// as determined by isDeclInScope. 1452 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1453 bool ConsiderLinkage, 1454 bool AllowInlineNamespace) { 1455 LookupResult::Filter F = R.makeFilter(); 1456 while (F.hasNext()) { 1457 NamedDecl *D = F.next(); 1458 1459 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1460 continue; 1461 1462 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1463 continue; 1464 1465 F.erase(); 1466 } 1467 1468 F.done(); 1469 } 1470 1471 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1472 /// have compatible owning modules. 1473 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1474 // FIXME: The Modules TS is not clear about how friend declarations are 1475 // to be treated. It's not meaningful to have different owning modules for 1476 // linkage in redeclarations of the same entity, so for now allow the 1477 // redeclaration and change the owning modules to match. 1478 if (New->getFriendObjectKind() && 1479 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1480 New->setLocalOwningModule(Old->getOwningModule()); 1481 makeMergedDefinitionVisible(New); 1482 return false; 1483 } 1484 1485 Module *NewM = New->getOwningModule(); 1486 Module *OldM = Old->getOwningModule(); 1487 1488 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1489 NewM = NewM->Parent; 1490 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1491 OldM = OldM->Parent; 1492 1493 if (NewM == OldM) 1494 return false; 1495 1496 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1497 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1498 if (NewIsModuleInterface || OldIsModuleInterface) { 1499 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1500 // if a declaration of D [...] appears in the purview of a module, all 1501 // other such declarations shall appear in the purview of the same module 1502 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1503 << New 1504 << NewIsModuleInterface 1505 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1506 << OldIsModuleInterface 1507 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1508 Diag(Old->getLocation(), diag::note_previous_declaration); 1509 New->setInvalidDecl(); 1510 return true; 1511 } 1512 1513 return false; 1514 } 1515 1516 static bool isUsingDecl(NamedDecl *D) { 1517 return isa<UsingShadowDecl>(D) || 1518 isa<UnresolvedUsingTypenameDecl>(D) || 1519 isa<UnresolvedUsingValueDecl>(D); 1520 } 1521 1522 /// Removes using shadow declarations from the lookup results. 1523 static void RemoveUsingDecls(LookupResult &R) { 1524 LookupResult::Filter F = R.makeFilter(); 1525 while (F.hasNext()) 1526 if (isUsingDecl(F.next())) 1527 F.erase(); 1528 1529 F.done(); 1530 } 1531 1532 /// Check for this common pattern: 1533 /// @code 1534 /// class S { 1535 /// S(const S&); // DO NOT IMPLEMENT 1536 /// void operator=(const S&); // DO NOT IMPLEMENT 1537 /// }; 1538 /// @endcode 1539 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1540 // FIXME: Should check for private access too but access is set after we get 1541 // the decl here. 1542 if (D->doesThisDeclarationHaveABody()) 1543 return false; 1544 1545 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1546 return CD->isCopyConstructor(); 1547 return D->isCopyAssignmentOperator(); 1548 } 1549 1550 // We need this to handle 1551 // 1552 // typedef struct { 1553 // void *foo() { return 0; } 1554 // } A; 1555 // 1556 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1557 // for example. If 'A', foo will have external linkage. If we have '*A', 1558 // foo will have no linkage. Since we can't know until we get to the end 1559 // of the typedef, this function finds out if D might have non-external linkage. 1560 // Callers should verify at the end of the TU if it D has external linkage or 1561 // not. 1562 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1563 const DeclContext *DC = D->getDeclContext(); 1564 while (!DC->isTranslationUnit()) { 1565 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1566 if (!RD->hasNameForLinkage()) 1567 return true; 1568 } 1569 DC = DC->getParent(); 1570 } 1571 1572 return !D->isExternallyVisible(); 1573 } 1574 1575 // FIXME: This needs to be refactored; some other isInMainFile users want 1576 // these semantics. 1577 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1578 if (S.TUKind != TU_Complete) 1579 return false; 1580 return S.SourceMgr.isInMainFile(Loc); 1581 } 1582 1583 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1584 assert(D); 1585 1586 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1587 return false; 1588 1589 // Ignore all entities declared within templates, and out-of-line definitions 1590 // of members of class templates. 1591 if (D->getDeclContext()->isDependentContext() || 1592 D->getLexicalDeclContext()->isDependentContext()) 1593 return false; 1594 1595 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1596 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1597 return false; 1598 // A non-out-of-line declaration of a member specialization was implicitly 1599 // instantiated; it's the out-of-line declaration that we're interested in. 1600 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1601 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1602 return false; 1603 1604 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1605 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1606 return false; 1607 } else { 1608 // 'static inline' functions are defined in headers; don't warn. 1609 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1610 return false; 1611 } 1612 1613 if (FD->doesThisDeclarationHaveABody() && 1614 Context.DeclMustBeEmitted(FD)) 1615 return false; 1616 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1617 // Constants and utility variables are defined in headers with internal 1618 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1619 // like "inline".) 1620 if (!isMainFileLoc(*this, VD->getLocation())) 1621 return false; 1622 1623 if (Context.DeclMustBeEmitted(VD)) 1624 return false; 1625 1626 if (VD->isStaticDataMember() && 1627 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1628 return false; 1629 if (VD->isStaticDataMember() && 1630 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1631 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1632 return false; 1633 1634 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1635 return false; 1636 } else { 1637 return false; 1638 } 1639 1640 // Only warn for unused decls internal to the translation unit. 1641 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1642 // for inline functions defined in the main source file, for instance. 1643 return mightHaveNonExternalLinkage(D); 1644 } 1645 1646 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1647 if (!D) 1648 return; 1649 1650 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1651 const FunctionDecl *First = FD->getFirstDecl(); 1652 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1653 return; // First should already be in the vector. 1654 } 1655 1656 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1657 const VarDecl *First = VD->getFirstDecl(); 1658 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1659 return; // First should already be in the vector. 1660 } 1661 1662 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1663 UnusedFileScopedDecls.push_back(D); 1664 } 1665 1666 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1667 if (D->isInvalidDecl()) 1668 return false; 1669 1670 bool Referenced = false; 1671 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1672 // For a decomposition declaration, warn if none of the bindings are 1673 // referenced, instead of if the variable itself is referenced (which 1674 // it is, by the bindings' expressions). 1675 for (auto *BD : DD->bindings()) { 1676 if (BD->isReferenced()) { 1677 Referenced = true; 1678 break; 1679 } 1680 } 1681 } else if (!D->getDeclName()) { 1682 return false; 1683 } else if (D->isReferenced() || D->isUsed()) { 1684 Referenced = true; 1685 } 1686 1687 if (Referenced || D->hasAttr<UnusedAttr>() || 1688 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1689 return false; 1690 1691 if (isa<LabelDecl>(D)) 1692 return true; 1693 1694 // Except for labels, we only care about unused decls that are local to 1695 // functions. 1696 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1697 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1698 // For dependent types, the diagnostic is deferred. 1699 WithinFunction = 1700 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1701 if (!WithinFunction) 1702 return false; 1703 1704 if (isa<TypedefNameDecl>(D)) 1705 return true; 1706 1707 // White-list anything that isn't a local variable. 1708 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1709 return false; 1710 1711 // Types of valid local variables should be complete, so this should succeed. 1712 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1713 1714 // White-list anything with an __attribute__((unused)) type. 1715 const auto *Ty = VD->getType().getTypePtr(); 1716 1717 // Only look at the outermost level of typedef. 1718 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1719 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1720 return false; 1721 } 1722 1723 // If we failed to complete the type for some reason, or if the type is 1724 // dependent, don't diagnose the variable. 1725 if (Ty->isIncompleteType() || Ty->isDependentType()) 1726 return false; 1727 1728 // Look at the element type to ensure that the warning behaviour is 1729 // consistent for both scalars and arrays. 1730 Ty = Ty->getBaseElementTypeUnsafe(); 1731 1732 if (const TagType *TT = Ty->getAs<TagType>()) { 1733 const TagDecl *Tag = TT->getDecl(); 1734 if (Tag->hasAttr<UnusedAttr>()) 1735 return false; 1736 1737 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1738 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1739 return false; 1740 1741 if (const Expr *Init = VD->getInit()) { 1742 if (const ExprWithCleanups *Cleanups = 1743 dyn_cast<ExprWithCleanups>(Init)) 1744 Init = Cleanups->getSubExpr(); 1745 const CXXConstructExpr *Construct = 1746 dyn_cast<CXXConstructExpr>(Init); 1747 if (Construct && !Construct->isElidable()) { 1748 CXXConstructorDecl *CD = Construct->getConstructor(); 1749 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1750 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1751 return false; 1752 } 1753 } 1754 } 1755 } 1756 1757 // TODO: __attribute__((unused)) templates? 1758 } 1759 1760 return true; 1761 } 1762 1763 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1764 FixItHint &Hint) { 1765 if (isa<LabelDecl>(D)) { 1766 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1767 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1768 true); 1769 if (AfterColon.isInvalid()) 1770 return; 1771 Hint = FixItHint::CreateRemoval( 1772 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1773 } 1774 } 1775 1776 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1777 if (D->getTypeForDecl()->isDependentType()) 1778 return; 1779 1780 for (auto *TmpD : D->decls()) { 1781 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1782 DiagnoseUnusedDecl(T); 1783 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1784 DiagnoseUnusedNestedTypedefs(R); 1785 } 1786 } 1787 1788 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1789 /// unless they are marked attr(unused). 1790 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1791 if (!ShouldDiagnoseUnusedDecl(D)) 1792 return; 1793 1794 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1795 // typedefs can be referenced later on, so the diagnostics are emitted 1796 // at end-of-translation-unit. 1797 UnusedLocalTypedefNameCandidates.insert(TD); 1798 return; 1799 } 1800 1801 FixItHint Hint; 1802 GenerateFixForUnusedDecl(D, Context, Hint); 1803 1804 unsigned DiagID; 1805 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1806 DiagID = diag::warn_unused_exception_param; 1807 else if (isa<LabelDecl>(D)) 1808 DiagID = diag::warn_unused_label; 1809 else 1810 DiagID = diag::warn_unused_variable; 1811 1812 Diag(D->getLocation(), DiagID) << D << Hint; 1813 } 1814 1815 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1816 // Verify that we have no forward references left. If so, there was a goto 1817 // or address of a label taken, but no definition of it. Label fwd 1818 // definitions are indicated with a null substmt which is also not a resolved 1819 // MS inline assembly label name. 1820 bool Diagnose = false; 1821 if (L->isMSAsmLabel()) 1822 Diagnose = !L->isResolvedMSAsmLabel(); 1823 else 1824 Diagnose = L->getStmt() == nullptr; 1825 if (Diagnose) 1826 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1827 } 1828 1829 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1830 S->mergeNRVOIntoParent(); 1831 1832 if (S->decl_empty()) return; 1833 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1834 "Scope shouldn't contain decls!"); 1835 1836 for (auto *TmpD : S->decls()) { 1837 assert(TmpD && "This decl didn't get pushed??"); 1838 1839 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1840 NamedDecl *D = cast<NamedDecl>(TmpD); 1841 1842 // Diagnose unused variables in this scope. 1843 if (!S->hasUnrecoverableErrorOccurred()) { 1844 DiagnoseUnusedDecl(D); 1845 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1846 DiagnoseUnusedNestedTypedefs(RD); 1847 } 1848 1849 if (!D->getDeclName()) continue; 1850 1851 // If this was a forward reference to a label, verify it was defined. 1852 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1853 CheckPoppedLabel(LD, *this); 1854 1855 // Remove this name from our lexical scope, and warn on it if we haven't 1856 // already. 1857 IdResolver.RemoveDecl(D); 1858 auto ShadowI = ShadowingDecls.find(D); 1859 if (ShadowI != ShadowingDecls.end()) { 1860 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1861 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1862 << D << FD << FD->getParent(); 1863 Diag(FD->getLocation(), diag::note_previous_declaration); 1864 } 1865 ShadowingDecls.erase(ShadowI); 1866 } 1867 } 1868 } 1869 1870 /// Look for an Objective-C class in the translation unit. 1871 /// 1872 /// \param Id The name of the Objective-C class we're looking for. If 1873 /// typo-correction fixes this name, the Id will be updated 1874 /// to the fixed name. 1875 /// 1876 /// \param IdLoc The location of the name in the translation unit. 1877 /// 1878 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1879 /// if there is no class with the given name. 1880 /// 1881 /// \returns The declaration of the named Objective-C class, or NULL if the 1882 /// class could not be found. 1883 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1884 SourceLocation IdLoc, 1885 bool DoTypoCorrection) { 1886 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1887 // creation from this context. 1888 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1889 1890 if (!IDecl && DoTypoCorrection) { 1891 // Perform typo correction at the given location, but only if we 1892 // find an Objective-C class name. 1893 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1894 if (TypoCorrection C = 1895 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1896 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1897 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1898 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1899 Id = IDecl->getIdentifier(); 1900 } 1901 } 1902 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1903 // This routine must always return a class definition, if any. 1904 if (Def && Def->getDefinition()) 1905 Def = Def->getDefinition(); 1906 return Def; 1907 } 1908 1909 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1910 /// from S, where a non-field would be declared. This routine copes 1911 /// with the difference between C and C++ scoping rules in structs and 1912 /// unions. For example, the following code is well-formed in C but 1913 /// ill-formed in C++: 1914 /// @code 1915 /// struct S6 { 1916 /// enum { BAR } e; 1917 /// }; 1918 /// 1919 /// void test_S6() { 1920 /// struct S6 a; 1921 /// a.e = BAR; 1922 /// } 1923 /// @endcode 1924 /// For the declaration of BAR, this routine will return a different 1925 /// scope. The scope S will be the scope of the unnamed enumeration 1926 /// within S6. In C++, this routine will return the scope associated 1927 /// with S6, because the enumeration's scope is a transparent 1928 /// context but structures can contain non-field names. In C, this 1929 /// routine will return the translation unit scope, since the 1930 /// enumeration's scope is a transparent context and structures cannot 1931 /// contain non-field names. 1932 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1933 while (((S->getFlags() & Scope::DeclScope) == 0) || 1934 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1935 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1936 S = S->getParent(); 1937 return S; 1938 } 1939 1940 /// Looks up the declaration of "struct objc_super" and 1941 /// saves it for later use in building builtin declaration of 1942 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1943 /// pre-existing declaration exists no action takes place. 1944 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1945 IdentifierInfo *II) { 1946 if (!II->isStr("objc_msgSendSuper")) 1947 return; 1948 ASTContext &Context = ThisSema.Context; 1949 1950 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1951 SourceLocation(), Sema::LookupTagName); 1952 ThisSema.LookupName(Result, S); 1953 if (Result.getResultKind() == LookupResult::Found) 1954 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1955 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1956 } 1957 1958 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 1959 ASTContext::GetBuiltinTypeError Error) { 1960 switch (Error) { 1961 case ASTContext::GE_None: 1962 return ""; 1963 case ASTContext::GE_Missing_type: 1964 return BuiltinInfo.getHeaderName(ID); 1965 case ASTContext::GE_Missing_stdio: 1966 return "stdio.h"; 1967 case ASTContext::GE_Missing_setjmp: 1968 return "setjmp.h"; 1969 case ASTContext::GE_Missing_ucontext: 1970 return "ucontext.h"; 1971 } 1972 llvm_unreachable("unhandled error kind"); 1973 } 1974 1975 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1976 /// file scope. lazily create a decl for it. ForRedeclaration is true 1977 /// if we're creating this built-in in anticipation of redeclaring the 1978 /// built-in. 1979 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1980 Scope *S, bool ForRedeclaration, 1981 SourceLocation Loc) { 1982 LookupPredefedObjCSuperType(*this, S, II); 1983 1984 ASTContext::GetBuiltinTypeError Error; 1985 QualType R = Context.GetBuiltinType(ID, Error); 1986 if (Error) { 1987 if (!ForRedeclaration) 1988 return nullptr; 1989 1990 // If we have a builtin without an associated type we should not emit a 1991 // warning when we were not able to find a type for it. 1992 if (Error == ASTContext::GE_Missing_type) 1993 return nullptr; 1994 1995 // If we could not find a type for setjmp it is because the jmp_buf type was 1996 // not defined prior to the setjmp declaration. 1997 if (Error == ASTContext::GE_Missing_setjmp) { 1998 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 1999 << Context.BuiltinInfo.getName(ID); 2000 return nullptr; 2001 } 2002 2003 // Generally, we emit a warning that the declaration requires the 2004 // appropriate header. 2005 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2006 << getHeaderName(Context.BuiltinInfo, ID, Error) 2007 << Context.BuiltinInfo.getName(ID); 2008 return nullptr; 2009 } 2010 2011 if (!ForRedeclaration && 2012 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2013 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2014 Diag(Loc, diag::ext_implicit_lib_function_decl) 2015 << Context.BuiltinInfo.getName(ID) << R; 2016 if (Context.BuiltinInfo.getHeaderName(ID) && 2017 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2018 Diag(Loc, diag::note_include_header_or_declare) 2019 << Context.BuiltinInfo.getHeaderName(ID) 2020 << Context.BuiltinInfo.getName(ID); 2021 } 2022 2023 if (R.isNull()) 2024 return nullptr; 2025 2026 DeclContext *Parent = Context.getTranslationUnitDecl(); 2027 if (getLangOpts().CPlusPlus) { 2028 LinkageSpecDecl *CLinkageDecl = 2029 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2030 LinkageSpecDecl::lang_c, false); 2031 CLinkageDecl->setImplicit(); 2032 Parent->addDecl(CLinkageDecl); 2033 Parent = CLinkageDecl; 2034 } 2035 2036 FunctionDecl *New = FunctionDecl::Create(Context, 2037 Parent, 2038 Loc, Loc, II, R, /*TInfo=*/nullptr, 2039 SC_Extern, 2040 false, 2041 R->isFunctionProtoType()); 2042 New->setImplicit(); 2043 2044 // Create Decl objects for each parameter, adding them to the 2045 // FunctionDecl. 2046 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2047 SmallVector<ParmVarDecl*, 16> Params; 2048 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2049 ParmVarDecl *parm = 2050 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2051 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2052 SC_None, nullptr); 2053 parm->setScopeInfo(0, i); 2054 Params.push_back(parm); 2055 } 2056 New->setParams(Params); 2057 } 2058 2059 AddKnownFunctionAttributes(New); 2060 RegisterLocallyScopedExternCDecl(New, S); 2061 2062 // TUScope is the translation-unit scope to insert this function into. 2063 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2064 // relate Scopes to DeclContexts, and probably eliminate CurContext 2065 // entirely, but we're not there yet. 2066 DeclContext *SavedContext = CurContext; 2067 CurContext = Parent; 2068 PushOnScopeChains(New, TUScope); 2069 CurContext = SavedContext; 2070 return New; 2071 } 2072 2073 /// Typedef declarations don't have linkage, but they still denote the same 2074 /// entity if their types are the same. 2075 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2076 /// isSameEntity. 2077 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2078 TypedefNameDecl *Decl, 2079 LookupResult &Previous) { 2080 // This is only interesting when modules are enabled. 2081 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2082 return; 2083 2084 // Empty sets are uninteresting. 2085 if (Previous.empty()) 2086 return; 2087 2088 LookupResult::Filter Filter = Previous.makeFilter(); 2089 while (Filter.hasNext()) { 2090 NamedDecl *Old = Filter.next(); 2091 2092 // Non-hidden declarations are never ignored. 2093 if (S.isVisible(Old)) 2094 continue; 2095 2096 // Declarations of the same entity are not ignored, even if they have 2097 // different linkages. 2098 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2099 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2100 Decl->getUnderlyingType())) 2101 continue; 2102 2103 // If both declarations give a tag declaration a typedef name for linkage 2104 // purposes, then they declare the same entity. 2105 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2106 Decl->getAnonDeclWithTypedefName()) 2107 continue; 2108 } 2109 2110 Filter.erase(); 2111 } 2112 2113 Filter.done(); 2114 } 2115 2116 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2117 QualType OldType; 2118 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2119 OldType = OldTypedef->getUnderlyingType(); 2120 else 2121 OldType = Context.getTypeDeclType(Old); 2122 QualType NewType = New->getUnderlyingType(); 2123 2124 if (NewType->isVariablyModifiedType()) { 2125 // Must not redefine a typedef with a variably-modified type. 2126 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2127 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2128 << Kind << NewType; 2129 if (Old->getLocation().isValid()) 2130 notePreviousDefinition(Old, New->getLocation()); 2131 New->setInvalidDecl(); 2132 return true; 2133 } 2134 2135 if (OldType != NewType && 2136 !OldType->isDependentType() && 2137 !NewType->isDependentType() && 2138 !Context.hasSameType(OldType, NewType)) { 2139 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2140 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2141 << Kind << NewType << OldType; 2142 if (Old->getLocation().isValid()) 2143 notePreviousDefinition(Old, New->getLocation()); 2144 New->setInvalidDecl(); 2145 return true; 2146 } 2147 return false; 2148 } 2149 2150 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2151 /// same name and scope as a previous declaration 'Old'. Figure out 2152 /// how to resolve this situation, merging decls or emitting 2153 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2154 /// 2155 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2156 LookupResult &OldDecls) { 2157 // If the new decl is known invalid already, don't bother doing any 2158 // merging checks. 2159 if (New->isInvalidDecl()) return; 2160 2161 // Allow multiple definitions for ObjC built-in typedefs. 2162 // FIXME: Verify the underlying types are equivalent! 2163 if (getLangOpts().ObjC) { 2164 const IdentifierInfo *TypeID = New->getIdentifier(); 2165 switch (TypeID->getLength()) { 2166 default: break; 2167 case 2: 2168 { 2169 if (!TypeID->isStr("id")) 2170 break; 2171 QualType T = New->getUnderlyingType(); 2172 if (!T->isPointerType()) 2173 break; 2174 if (!T->isVoidPointerType()) { 2175 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2176 if (!PT->isStructureType()) 2177 break; 2178 } 2179 Context.setObjCIdRedefinitionType(T); 2180 // Install the built-in type for 'id', ignoring the current definition. 2181 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2182 return; 2183 } 2184 case 5: 2185 if (!TypeID->isStr("Class")) 2186 break; 2187 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2188 // Install the built-in type for 'Class', ignoring the current definition. 2189 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2190 return; 2191 case 3: 2192 if (!TypeID->isStr("SEL")) 2193 break; 2194 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2195 // Install the built-in type for 'SEL', ignoring the current definition. 2196 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2197 return; 2198 } 2199 // Fall through - the typedef name was not a builtin type. 2200 } 2201 2202 // Verify the old decl was also a type. 2203 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2204 if (!Old) { 2205 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2206 << New->getDeclName(); 2207 2208 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2209 if (OldD->getLocation().isValid()) 2210 notePreviousDefinition(OldD, New->getLocation()); 2211 2212 return New->setInvalidDecl(); 2213 } 2214 2215 // If the old declaration is invalid, just give up here. 2216 if (Old->isInvalidDecl()) 2217 return New->setInvalidDecl(); 2218 2219 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2220 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2221 auto *NewTag = New->getAnonDeclWithTypedefName(); 2222 NamedDecl *Hidden = nullptr; 2223 if (OldTag && NewTag && 2224 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2225 !hasVisibleDefinition(OldTag, &Hidden)) { 2226 // There is a definition of this tag, but it is not visible. Use it 2227 // instead of our tag. 2228 New->setTypeForDecl(OldTD->getTypeForDecl()); 2229 if (OldTD->isModed()) 2230 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2231 OldTD->getUnderlyingType()); 2232 else 2233 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2234 2235 // Make the old tag definition visible. 2236 makeMergedDefinitionVisible(Hidden); 2237 2238 // If this was an unscoped enumeration, yank all of its enumerators 2239 // out of the scope. 2240 if (isa<EnumDecl>(NewTag)) { 2241 Scope *EnumScope = getNonFieldDeclScope(S); 2242 for (auto *D : NewTag->decls()) { 2243 auto *ED = cast<EnumConstantDecl>(D); 2244 assert(EnumScope->isDeclScope(ED)); 2245 EnumScope->RemoveDecl(ED); 2246 IdResolver.RemoveDecl(ED); 2247 ED->getLexicalDeclContext()->removeDecl(ED); 2248 } 2249 } 2250 } 2251 } 2252 2253 // If the typedef types are not identical, reject them in all languages and 2254 // with any extensions enabled. 2255 if (isIncompatibleTypedef(Old, New)) 2256 return; 2257 2258 // The types match. Link up the redeclaration chain and merge attributes if 2259 // the old declaration was a typedef. 2260 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2261 New->setPreviousDecl(Typedef); 2262 mergeDeclAttributes(New, Old); 2263 } 2264 2265 if (getLangOpts().MicrosoftExt) 2266 return; 2267 2268 if (getLangOpts().CPlusPlus) { 2269 // C++ [dcl.typedef]p2: 2270 // In a given non-class scope, a typedef specifier can be used to 2271 // redefine the name of any type declared in that scope to refer 2272 // to the type to which it already refers. 2273 if (!isa<CXXRecordDecl>(CurContext)) 2274 return; 2275 2276 // C++0x [dcl.typedef]p4: 2277 // In a given class scope, a typedef specifier can be used to redefine 2278 // any class-name declared in that scope that is not also a typedef-name 2279 // to refer to the type to which it already refers. 2280 // 2281 // This wording came in via DR424, which was a correction to the 2282 // wording in DR56, which accidentally banned code like: 2283 // 2284 // struct S { 2285 // typedef struct A { } A; 2286 // }; 2287 // 2288 // in the C++03 standard. We implement the C++0x semantics, which 2289 // allow the above but disallow 2290 // 2291 // struct S { 2292 // typedef int I; 2293 // typedef int I; 2294 // }; 2295 // 2296 // since that was the intent of DR56. 2297 if (!isa<TypedefNameDecl>(Old)) 2298 return; 2299 2300 Diag(New->getLocation(), diag::err_redefinition) 2301 << New->getDeclName(); 2302 notePreviousDefinition(Old, New->getLocation()); 2303 return New->setInvalidDecl(); 2304 } 2305 2306 // Modules always permit redefinition of typedefs, as does C11. 2307 if (getLangOpts().Modules || getLangOpts().C11) 2308 return; 2309 2310 // If we have a redefinition of a typedef in C, emit a warning. This warning 2311 // is normally mapped to an error, but can be controlled with 2312 // -Wtypedef-redefinition. If either the original or the redefinition is 2313 // in a system header, don't emit this for compatibility with GCC. 2314 if (getDiagnostics().getSuppressSystemWarnings() && 2315 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2316 (Old->isImplicit() || 2317 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2318 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2319 return; 2320 2321 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2322 << New->getDeclName(); 2323 notePreviousDefinition(Old, New->getLocation()); 2324 } 2325 2326 /// DeclhasAttr - returns true if decl Declaration already has the target 2327 /// attribute. 2328 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2329 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2330 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2331 for (const auto *i : D->attrs()) 2332 if (i->getKind() == A->getKind()) { 2333 if (Ann) { 2334 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2335 return true; 2336 continue; 2337 } 2338 // FIXME: Don't hardcode this check 2339 if (OA && isa<OwnershipAttr>(i)) 2340 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2341 return true; 2342 } 2343 2344 return false; 2345 } 2346 2347 static bool isAttributeTargetADefinition(Decl *D) { 2348 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2349 return VD->isThisDeclarationADefinition(); 2350 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2351 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2352 return true; 2353 } 2354 2355 /// Merge alignment attributes from \p Old to \p New, taking into account the 2356 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2357 /// 2358 /// \return \c true if any attributes were added to \p New. 2359 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2360 // Look for alignas attributes on Old, and pick out whichever attribute 2361 // specifies the strictest alignment requirement. 2362 AlignedAttr *OldAlignasAttr = nullptr; 2363 AlignedAttr *OldStrictestAlignAttr = nullptr; 2364 unsigned OldAlign = 0; 2365 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2366 // FIXME: We have no way of representing inherited dependent alignments 2367 // in a case like: 2368 // template<int A, int B> struct alignas(A) X; 2369 // template<int A, int B> struct alignas(B) X {}; 2370 // For now, we just ignore any alignas attributes which are not on the 2371 // definition in such a case. 2372 if (I->isAlignmentDependent()) 2373 return false; 2374 2375 if (I->isAlignas()) 2376 OldAlignasAttr = I; 2377 2378 unsigned Align = I->getAlignment(S.Context); 2379 if (Align > OldAlign) { 2380 OldAlign = Align; 2381 OldStrictestAlignAttr = I; 2382 } 2383 } 2384 2385 // Look for alignas attributes on New. 2386 AlignedAttr *NewAlignasAttr = nullptr; 2387 unsigned NewAlign = 0; 2388 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2389 if (I->isAlignmentDependent()) 2390 return false; 2391 2392 if (I->isAlignas()) 2393 NewAlignasAttr = I; 2394 2395 unsigned Align = I->getAlignment(S.Context); 2396 if (Align > NewAlign) 2397 NewAlign = Align; 2398 } 2399 2400 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2401 // Both declarations have 'alignas' attributes. We require them to match. 2402 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2403 // fall short. (If two declarations both have alignas, they must both match 2404 // every definition, and so must match each other if there is a definition.) 2405 2406 // If either declaration only contains 'alignas(0)' specifiers, then it 2407 // specifies the natural alignment for the type. 2408 if (OldAlign == 0 || NewAlign == 0) { 2409 QualType Ty; 2410 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2411 Ty = VD->getType(); 2412 else 2413 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2414 2415 if (OldAlign == 0) 2416 OldAlign = S.Context.getTypeAlign(Ty); 2417 if (NewAlign == 0) 2418 NewAlign = S.Context.getTypeAlign(Ty); 2419 } 2420 2421 if (OldAlign != NewAlign) { 2422 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2423 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2424 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2425 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2426 } 2427 } 2428 2429 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2430 // C++11 [dcl.align]p6: 2431 // if any declaration of an entity has an alignment-specifier, 2432 // every defining declaration of that entity shall specify an 2433 // equivalent alignment. 2434 // C11 6.7.5/7: 2435 // If the definition of an object does not have an alignment 2436 // specifier, any other declaration of that object shall also 2437 // have no alignment specifier. 2438 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2439 << OldAlignasAttr; 2440 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2441 << OldAlignasAttr; 2442 } 2443 2444 bool AnyAdded = false; 2445 2446 // Ensure we have an attribute representing the strictest alignment. 2447 if (OldAlign > NewAlign) { 2448 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2449 Clone->setInherited(true); 2450 New->addAttr(Clone); 2451 AnyAdded = true; 2452 } 2453 2454 // Ensure we have an alignas attribute if the old declaration had one. 2455 if (OldAlignasAttr && !NewAlignasAttr && 2456 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2457 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2458 Clone->setInherited(true); 2459 New->addAttr(Clone); 2460 AnyAdded = true; 2461 } 2462 2463 return AnyAdded; 2464 } 2465 2466 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2467 const InheritableAttr *Attr, 2468 Sema::AvailabilityMergeKind AMK) { 2469 // This function copies an attribute Attr from a previous declaration to the 2470 // new declaration D if the new declaration doesn't itself have that attribute 2471 // yet or if that attribute allows duplicates. 2472 // If you're adding a new attribute that requires logic different from 2473 // "use explicit attribute on decl if present, else use attribute from 2474 // previous decl", for example if the attribute needs to be consistent 2475 // between redeclarations, you need to call a custom merge function here. 2476 InheritableAttr *NewAttr = nullptr; 2477 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2478 NewAttr = S.mergeAvailabilityAttr( 2479 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2480 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2481 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2482 AA->getPriority()); 2483 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2484 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2485 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2486 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2487 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2488 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2489 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2490 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2491 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2492 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2493 FA->getFirstArg()); 2494 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2495 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2496 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2497 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2498 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2499 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2500 IA->getSemanticSpelling()); 2501 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2502 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2503 &S.Context.Idents.get(AA->getSpelling())); 2504 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2505 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2506 isa<CUDAGlobalAttr>(Attr))) { 2507 // CUDA target attributes are part of function signature for 2508 // overloading purposes and must not be merged. 2509 return false; 2510 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2511 NewAttr = S.mergeMinSizeAttr(D, *MA); 2512 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2513 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2514 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2515 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2516 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2517 NewAttr = S.mergeCommonAttr(D, *CommonA); 2518 else if (isa<AlignedAttr>(Attr)) 2519 // AlignedAttrs are handled separately, because we need to handle all 2520 // such attributes on a declaration at the same time. 2521 NewAttr = nullptr; 2522 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2523 (AMK == Sema::AMK_Override || 2524 AMK == Sema::AMK_ProtocolImplementation)) 2525 NewAttr = nullptr; 2526 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2527 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid()); 2528 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2529 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2530 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2531 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2532 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2533 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2534 2535 if (NewAttr) { 2536 NewAttr->setInherited(true); 2537 D->addAttr(NewAttr); 2538 if (isa<MSInheritanceAttr>(NewAttr)) 2539 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2540 return true; 2541 } 2542 2543 return false; 2544 } 2545 2546 static const NamedDecl *getDefinition(const Decl *D) { 2547 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2548 return TD->getDefinition(); 2549 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2550 const VarDecl *Def = VD->getDefinition(); 2551 if (Def) 2552 return Def; 2553 return VD->getActingDefinition(); 2554 } 2555 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2556 return FD->getDefinition(); 2557 return nullptr; 2558 } 2559 2560 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2561 for (const auto *Attribute : D->attrs()) 2562 if (Attribute->getKind() == Kind) 2563 return true; 2564 return false; 2565 } 2566 2567 /// checkNewAttributesAfterDef - If we already have a definition, check that 2568 /// there are no new attributes in this declaration. 2569 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2570 if (!New->hasAttrs()) 2571 return; 2572 2573 const NamedDecl *Def = getDefinition(Old); 2574 if (!Def || Def == New) 2575 return; 2576 2577 AttrVec &NewAttributes = New->getAttrs(); 2578 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2579 const Attr *NewAttribute = NewAttributes[I]; 2580 2581 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2582 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2583 Sema::SkipBodyInfo SkipBody; 2584 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2585 2586 // If we're skipping this definition, drop the "alias" attribute. 2587 if (SkipBody.ShouldSkip) { 2588 NewAttributes.erase(NewAttributes.begin() + I); 2589 --E; 2590 continue; 2591 } 2592 } else { 2593 VarDecl *VD = cast<VarDecl>(New); 2594 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2595 VarDecl::TentativeDefinition 2596 ? diag::err_alias_after_tentative 2597 : diag::err_redefinition; 2598 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2599 if (Diag == diag::err_redefinition) 2600 S.notePreviousDefinition(Def, VD->getLocation()); 2601 else 2602 S.Diag(Def->getLocation(), diag::note_previous_definition); 2603 VD->setInvalidDecl(); 2604 } 2605 ++I; 2606 continue; 2607 } 2608 2609 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2610 // Tentative definitions are only interesting for the alias check above. 2611 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2612 ++I; 2613 continue; 2614 } 2615 } 2616 2617 if (hasAttribute(Def, NewAttribute->getKind())) { 2618 ++I; 2619 continue; // regular attr merging will take care of validating this. 2620 } 2621 2622 if (isa<C11NoReturnAttr>(NewAttribute)) { 2623 // C's _Noreturn is allowed to be added to a function after it is defined. 2624 ++I; 2625 continue; 2626 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2627 if (AA->isAlignas()) { 2628 // C++11 [dcl.align]p6: 2629 // if any declaration of an entity has an alignment-specifier, 2630 // every defining declaration of that entity shall specify an 2631 // equivalent alignment. 2632 // C11 6.7.5/7: 2633 // If the definition of an object does not have an alignment 2634 // specifier, any other declaration of that object shall also 2635 // have no alignment specifier. 2636 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2637 << AA; 2638 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2639 << AA; 2640 NewAttributes.erase(NewAttributes.begin() + I); 2641 --E; 2642 continue; 2643 } 2644 } else if (isa<SelectAnyAttr>(NewAttribute) && 2645 cast<VarDecl>(New)->isInline() && 2646 !cast<VarDecl>(New)->isInlineSpecified()) { 2647 // Don't warn about applying selectany to implicitly inline variables. 2648 // Older compilers and language modes would require the use of selectany 2649 // to make such variables inline, and it would have no effect if we 2650 // honored it. 2651 ++I; 2652 continue; 2653 } 2654 2655 S.Diag(NewAttribute->getLocation(), 2656 diag::warn_attribute_precede_definition); 2657 S.Diag(Def->getLocation(), diag::note_previous_definition); 2658 NewAttributes.erase(NewAttributes.begin() + I); 2659 --E; 2660 } 2661 } 2662 2663 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2664 const ConstInitAttr *CIAttr, 2665 bool AttrBeforeInit) { 2666 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2667 2668 // Figure out a good way to write this specifier on the old declaration. 2669 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2670 // enough of the attribute list spelling information to extract that without 2671 // heroics. 2672 std::string SuitableSpelling; 2673 if (S.getLangOpts().CPlusPlus2a) 2674 SuitableSpelling = 2675 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}); 2676 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2677 SuitableSpelling = S.PP.getLastMacroWithSpelling( 2678 InsertLoc, 2679 {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"), 2680 tok::coloncolon, 2681 S.PP.getIdentifierInfo("require_constant_initialization"), 2682 tok::r_square, tok::r_square}); 2683 if (SuitableSpelling.empty()) 2684 SuitableSpelling = S.PP.getLastMacroWithSpelling( 2685 InsertLoc, 2686 {tok::kw___attribute, tok::l_paren, tok::r_paren, 2687 S.PP.getIdentifierInfo("require_constant_initialization"), 2688 tok::r_paren, tok::r_paren}); 2689 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a) 2690 SuitableSpelling = "constinit"; 2691 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2692 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2693 if (SuitableSpelling.empty()) 2694 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2695 SuitableSpelling += " "; 2696 2697 if (AttrBeforeInit) { 2698 // extern constinit int a; 2699 // int a = 0; // error (missing 'constinit'), accepted as extension 2700 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2701 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2702 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2703 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2704 } else { 2705 // int a = 0; 2706 // constinit extern int a; // error (missing 'constinit') 2707 S.Diag(CIAttr->getLocation(), 2708 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2709 : diag::warn_require_const_init_added_too_late) 2710 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2711 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2712 << CIAttr->isConstinit() 2713 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2714 } 2715 } 2716 2717 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2718 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2719 AvailabilityMergeKind AMK) { 2720 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2721 UsedAttr *NewAttr = OldAttr->clone(Context); 2722 NewAttr->setInherited(true); 2723 New->addAttr(NewAttr); 2724 } 2725 2726 if (!Old->hasAttrs() && !New->hasAttrs()) 2727 return; 2728 2729 // [dcl.constinit]p1: 2730 // If the [constinit] specifier is applied to any declaration of a 2731 // variable, it shall be applied to the initializing declaration. 2732 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2733 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2734 if (bool(OldConstInit) != bool(NewConstInit)) { 2735 const auto *OldVD = cast<VarDecl>(Old); 2736 auto *NewVD = cast<VarDecl>(New); 2737 2738 // Find the initializing declaration. Note that we might not have linked 2739 // the new declaration into the redeclaration chain yet. 2740 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2741 if (!InitDecl && 2742 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2743 InitDecl = NewVD; 2744 2745 if (InitDecl == NewVD) { 2746 // This is the initializing declaration. If it would inherit 'constinit', 2747 // that's ill-formed. (Note that we do not apply this to the attribute 2748 // form). 2749 if (OldConstInit && OldConstInit->isConstinit()) 2750 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2751 /*AttrBeforeInit=*/true); 2752 } else if (NewConstInit) { 2753 // This is the first time we've been told that this declaration should 2754 // have a constant initializer. If we already saw the initializing 2755 // declaration, this is too late. 2756 if (InitDecl && InitDecl != NewVD) { 2757 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2758 /*AttrBeforeInit=*/false); 2759 NewVD->dropAttr<ConstInitAttr>(); 2760 } 2761 } 2762 } 2763 2764 // Attributes declared post-definition are currently ignored. 2765 checkNewAttributesAfterDef(*this, New, Old); 2766 2767 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2768 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2769 if (OldA->getLabel() != NewA->getLabel()) { 2770 // This redeclaration changes __asm__ label. 2771 Diag(New->getLocation(), diag::err_different_asm_label); 2772 Diag(OldA->getLocation(), diag::note_previous_declaration); 2773 } 2774 } else if (Old->isUsed()) { 2775 // This redeclaration adds an __asm__ label to a declaration that has 2776 // already been ODR-used. 2777 Diag(New->getLocation(), diag::err_late_asm_label_name) 2778 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2779 } 2780 } 2781 2782 // Re-declaration cannot add abi_tag's. 2783 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2784 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2785 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2786 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2787 NewTag) == OldAbiTagAttr->tags_end()) { 2788 Diag(NewAbiTagAttr->getLocation(), 2789 diag::err_new_abi_tag_on_redeclaration) 2790 << NewTag; 2791 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2792 } 2793 } 2794 } else { 2795 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2796 Diag(Old->getLocation(), diag::note_previous_declaration); 2797 } 2798 } 2799 2800 // This redeclaration adds a section attribute. 2801 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2802 if (auto *VD = dyn_cast<VarDecl>(New)) { 2803 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2804 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2805 Diag(Old->getLocation(), diag::note_previous_declaration); 2806 } 2807 } 2808 } 2809 2810 // Redeclaration adds code-seg attribute. 2811 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2812 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2813 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2814 Diag(New->getLocation(), diag::warn_mismatched_section) 2815 << 0 /*codeseg*/; 2816 Diag(Old->getLocation(), diag::note_previous_declaration); 2817 } 2818 2819 if (!Old->hasAttrs()) 2820 return; 2821 2822 bool foundAny = New->hasAttrs(); 2823 2824 // Ensure that any moving of objects within the allocated map is done before 2825 // we process them. 2826 if (!foundAny) New->setAttrs(AttrVec()); 2827 2828 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2829 // Ignore deprecated/unavailable/availability attributes if requested. 2830 AvailabilityMergeKind LocalAMK = AMK_None; 2831 if (isa<DeprecatedAttr>(I) || 2832 isa<UnavailableAttr>(I) || 2833 isa<AvailabilityAttr>(I)) { 2834 switch (AMK) { 2835 case AMK_None: 2836 continue; 2837 2838 case AMK_Redeclaration: 2839 case AMK_Override: 2840 case AMK_ProtocolImplementation: 2841 LocalAMK = AMK; 2842 break; 2843 } 2844 } 2845 2846 // Already handled. 2847 if (isa<UsedAttr>(I)) 2848 continue; 2849 2850 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2851 foundAny = true; 2852 } 2853 2854 if (mergeAlignedAttrs(*this, New, Old)) 2855 foundAny = true; 2856 2857 if (!foundAny) New->dropAttrs(); 2858 } 2859 2860 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2861 /// to the new one. 2862 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2863 const ParmVarDecl *oldDecl, 2864 Sema &S) { 2865 // C++11 [dcl.attr.depend]p2: 2866 // The first declaration of a function shall specify the 2867 // carries_dependency attribute for its declarator-id if any declaration 2868 // of the function specifies the carries_dependency attribute. 2869 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2870 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2871 S.Diag(CDA->getLocation(), 2872 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2873 // Find the first declaration of the parameter. 2874 // FIXME: Should we build redeclaration chains for function parameters? 2875 const FunctionDecl *FirstFD = 2876 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2877 const ParmVarDecl *FirstVD = 2878 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2879 S.Diag(FirstVD->getLocation(), 2880 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2881 } 2882 2883 if (!oldDecl->hasAttrs()) 2884 return; 2885 2886 bool foundAny = newDecl->hasAttrs(); 2887 2888 // Ensure that any moving of objects within the allocated map is 2889 // done before we process them. 2890 if (!foundAny) newDecl->setAttrs(AttrVec()); 2891 2892 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2893 if (!DeclHasAttr(newDecl, I)) { 2894 InheritableAttr *newAttr = 2895 cast<InheritableParamAttr>(I->clone(S.Context)); 2896 newAttr->setInherited(true); 2897 newDecl->addAttr(newAttr); 2898 foundAny = true; 2899 } 2900 } 2901 2902 if (!foundAny) newDecl->dropAttrs(); 2903 } 2904 2905 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2906 const ParmVarDecl *OldParam, 2907 Sema &S) { 2908 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2909 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2910 if (*Oldnullability != *Newnullability) { 2911 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2912 << DiagNullabilityKind( 2913 *Newnullability, 2914 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2915 != 0)) 2916 << DiagNullabilityKind( 2917 *Oldnullability, 2918 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2919 != 0)); 2920 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2921 } 2922 } else { 2923 QualType NewT = NewParam->getType(); 2924 NewT = S.Context.getAttributedType( 2925 AttributedType::getNullabilityAttrKind(*Oldnullability), 2926 NewT, NewT); 2927 NewParam->setType(NewT); 2928 } 2929 } 2930 } 2931 2932 namespace { 2933 2934 /// Used in MergeFunctionDecl to keep track of function parameters in 2935 /// C. 2936 struct GNUCompatibleParamWarning { 2937 ParmVarDecl *OldParm; 2938 ParmVarDecl *NewParm; 2939 QualType PromotedType; 2940 }; 2941 2942 } // end anonymous namespace 2943 2944 /// getSpecialMember - get the special member enum for a method. 2945 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2946 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2947 if (Ctor->isDefaultConstructor()) 2948 return Sema::CXXDefaultConstructor; 2949 2950 if (Ctor->isCopyConstructor()) 2951 return Sema::CXXCopyConstructor; 2952 2953 if (Ctor->isMoveConstructor()) 2954 return Sema::CXXMoveConstructor; 2955 } else if (isa<CXXDestructorDecl>(MD)) { 2956 return Sema::CXXDestructor; 2957 } else if (MD->isCopyAssignmentOperator()) { 2958 return Sema::CXXCopyAssignment; 2959 } else if (MD->isMoveAssignmentOperator()) { 2960 return Sema::CXXMoveAssignment; 2961 } 2962 2963 return Sema::CXXInvalid; 2964 } 2965 2966 // Determine whether the previous declaration was a definition, implicit 2967 // declaration, or a declaration. 2968 template <typename T> 2969 static std::pair<diag::kind, SourceLocation> 2970 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2971 diag::kind PrevDiag; 2972 SourceLocation OldLocation = Old->getLocation(); 2973 if (Old->isThisDeclarationADefinition()) 2974 PrevDiag = diag::note_previous_definition; 2975 else if (Old->isImplicit()) { 2976 PrevDiag = diag::note_previous_implicit_declaration; 2977 if (OldLocation.isInvalid()) 2978 OldLocation = New->getLocation(); 2979 } else 2980 PrevDiag = diag::note_previous_declaration; 2981 return std::make_pair(PrevDiag, OldLocation); 2982 } 2983 2984 /// canRedefineFunction - checks if a function can be redefined. Currently, 2985 /// only extern inline functions can be redefined, and even then only in 2986 /// GNU89 mode. 2987 static bool canRedefineFunction(const FunctionDecl *FD, 2988 const LangOptions& LangOpts) { 2989 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2990 !LangOpts.CPlusPlus && 2991 FD->isInlineSpecified() && 2992 FD->getStorageClass() == SC_Extern); 2993 } 2994 2995 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2996 const AttributedType *AT = T->getAs<AttributedType>(); 2997 while (AT && !AT->isCallingConv()) 2998 AT = AT->getModifiedType()->getAs<AttributedType>(); 2999 return AT; 3000 } 3001 3002 template <typename T> 3003 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3004 const DeclContext *DC = Old->getDeclContext(); 3005 if (DC->isRecord()) 3006 return false; 3007 3008 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3009 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3010 return true; 3011 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3012 return true; 3013 return false; 3014 } 3015 3016 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3017 static bool isExternC(VarTemplateDecl *) { return false; } 3018 3019 /// Check whether a redeclaration of an entity introduced by a 3020 /// using-declaration is valid, given that we know it's not an overload 3021 /// (nor a hidden tag declaration). 3022 template<typename ExpectedDecl> 3023 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3024 ExpectedDecl *New) { 3025 // C++11 [basic.scope.declarative]p4: 3026 // Given a set of declarations in a single declarative region, each of 3027 // which specifies the same unqualified name, 3028 // -- they shall all refer to the same entity, or all refer to functions 3029 // and function templates; or 3030 // -- exactly one declaration shall declare a class name or enumeration 3031 // name that is not a typedef name and the other declarations shall all 3032 // refer to the same variable or enumerator, or all refer to functions 3033 // and function templates; in this case the class name or enumeration 3034 // name is hidden (3.3.10). 3035 3036 // C++11 [namespace.udecl]p14: 3037 // If a function declaration in namespace scope or block scope has the 3038 // same name and the same parameter-type-list as a function introduced 3039 // by a using-declaration, and the declarations do not declare the same 3040 // function, the program is ill-formed. 3041 3042 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3043 if (Old && 3044 !Old->getDeclContext()->getRedeclContext()->Equals( 3045 New->getDeclContext()->getRedeclContext()) && 3046 !(isExternC(Old) && isExternC(New))) 3047 Old = nullptr; 3048 3049 if (!Old) { 3050 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3051 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3052 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3053 return true; 3054 } 3055 return false; 3056 } 3057 3058 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3059 const FunctionDecl *B) { 3060 assert(A->getNumParams() == B->getNumParams()); 3061 3062 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3063 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3064 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3065 if (AttrA == AttrB) 3066 return true; 3067 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3068 AttrA->isDynamic() == AttrB->isDynamic(); 3069 }; 3070 3071 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3072 } 3073 3074 /// If necessary, adjust the semantic declaration context for a qualified 3075 /// declaration to name the correct inline namespace within the qualifier. 3076 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3077 DeclaratorDecl *OldD) { 3078 // The only case where we need to update the DeclContext is when 3079 // redeclaration lookup for a qualified name finds a declaration 3080 // in an inline namespace within the context named by the qualifier: 3081 // 3082 // inline namespace N { int f(); } 3083 // int ::f(); // Sema DC needs adjusting from :: to N::. 3084 // 3085 // For unqualified declarations, the semantic context *can* change 3086 // along the redeclaration chain (for local extern declarations, 3087 // extern "C" declarations, and friend declarations in particular). 3088 if (!NewD->getQualifier()) 3089 return; 3090 3091 // NewD is probably already in the right context. 3092 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3093 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3094 if (NamedDC->Equals(SemaDC)) 3095 return; 3096 3097 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3098 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3099 "unexpected context for redeclaration"); 3100 3101 auto *LexDC = NewD->getLexicalDeclContext(); 3102 auto FixSemaDC = [=](NamedDecl *D) { 3103 if (!D) 3104 return; 3105 D->setDeclContext(SemaDC); 3106 D->setLexicalDeclContext(LexDC); 3107 }; 3108 3109 FixSemaDC(NewD); 3110 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3111 FixSemaDC(FD->getDescribedFunctionTemplate()); 3112 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3113 FixSemaDC(VD->getDescribedVarTemplate()); 3114 } 3115 3116 /// MergeFunctionDecl - We just parsed a function 'New' from 3117 /// declarator D which has the same name and scope as a previous 3118 /// declaration 'Old'. Figure out how to resolve this situation, 3119 /// merging decls or emitting diagnostics as appropriate. 3120 /// 3121 /// In C++, New and Old must be declarations that are not 3122 /// overloaded. Use IsOverload to determine whether New and Old are 3123 /// overloaded, and to select the Old declaration that New should be 3124 /// merged with. 3125 /// 3126 /// Returns true if there was an error, false otherwise. 3127 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3128 Scope *S, bool MergeTypeWithOld) { 3129 // Verify the old decl was also a function. 3130 FunctionDecl *Old = OldD->getAsFunction(); 3131 if (!Old) { 3132 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3133 if (New->getFriendObjectKind()) { 3134 Diag(New->getLocation(), diag::err_using_decl_friend); 3135 Diag(Shadow->getTargetDecl()->getLocation(), 3136 diag::note_using_decl_target); 3137 Diag(Shadow->getUsingDecl()->getLocation(), 3138 diag::note_using_decl) << 0; 3139 return true; 3140 } 3141 3142 // Check whether the two declarations might declare the same function. 3143 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3144 return true; 3145 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3146 } else { 3147 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3148 << New->getDeclName(); 3149 notePreviousDefinition(OldD, New->getLocation()); 3150 return true; 3151 } 3152 } 3153 3154 // If the old declaration is invalid, just give up here. 3155 if (Old->isInvalidDecl()) 3156 return true; 3157 3158 // Disallow redeclaration of some builtins. 3159 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3160 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3161 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3162 << Old << Old->getType(); 3163 return true; 3164 } 3165 3166 diag::kind PrevDiag; 3167 SourceLocation OldLocation; 3168 std::tie(PrevDiag, OldLocation) = 3169 getNoteDiagForInvalidRedeclaration(Old, New); 3170 3171 // Don't complain about this if we're in GNU89 mode and the old function 3172 // is an extern inline function. 3173 // Don't complain about specializations. They are not supposed to have 3174 // storage classes. 3175 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3176 New->getStorageClass() == SC_Static && 3177 Old->hasExternalFormalLinkage() && 3178 !New->getTemplateSpecializationInfo() && 3179 !canRedefineFunction(Old, getLangOpts())) { 3180 if (getLangOpts().MicrosoftExt) { 3181 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3182 Diag(OldLocation, PrevDiag); 3183 } else { 3184 Diag(New->getLocation(), diag::err_static_non_static) << New; 3185 Diag(OldLocation, PrevDiag); 3186 return true; 3187 } 3188 } 3189 3190 if (New->hasAttr<InternalLinkageAttr>() && 3191 !Old->hasAttr<InternalLinkageAttr>()) { 3192 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3193 << New->getDeclName(); 3194 notePreviousDefinition(Old, New->getLocation()); 3195 New->dropAttr<InternalLinkageAttr>(); 3196 } 3197 3198 if (CheckRedeclarationModuleOwnership(New, Old)) 3199 return true; 3200 3201 if (!getLangOpts().CPlusPlus) { 3202 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3203 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3204 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3205 << New << OldOvl; 3206 3207 // Try our best to find a decl that actually has the overloadable 3208 // attribute for the note. In most cases (e.g. programs with only one 3209 // broken declaration/definition), this won't matter. 3210 // 3211 // FIXME: We could do this if we juggled some extra state in 3212 // OverloadableAttr, rather than just removing it. 3213 const Decl *DiagOld = Old; 3214 if (OldOvl) { 3215 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3216 const auto *A = D->getAttr<OverloadableAttr>(); 3217 return A && !A->isImplicit(); 3218 }); 3219 // If we've implicitly added *all* of the overloadable attrs to this 3220 // chain, emitting a "previous redecl" note is pointless. 3221 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3222 } 3223 3224 if (DiagOld) 3225 Diag(DiagOld->getLocation(), 3226 diag::note_attribute_overloadable_prev_overload) 3227 << OldOvl; 3228 3229 if (OldOvl) 3230 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3231 else 3232 New->dropAttr<OverloadableAttr>(); 3233 } 3234 } 3235 3236 // If a function is first declared with a calling convention, but is later 3237 // declared or defined without one, all following decls assume the calling 3238 // convention of the first. 3239 // 3240 // It's OK if a function is first declared without a calling convention, 3241 // but is later declared or defined with the default calling convention. 3242 // 3243 // To test if either decl has an explicit calling convention, we look for 3244 // AttributedType sugar nodes on the type as written. If they are missing or 3245 // were canonicalized away, we assume the calling convention was implicit. 3246 // 3247 // Note also that we DO NOT return at this point, because we still have 3248 // other tests to run. 3249 QualType OldQType = Context.getCanonicalType(Old->getType()); 3250 QualType NewQType = Context.getCanonicalType(New->getType()); 3251 const FunctionType *OldType = cast<FunctionType>(OldQType); 3252 const FunctionType *NewType = cast<FunctionType>(NewQType); 3253 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3254 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3255 bool RequiresAdjustment = false; 3256 3257 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3258 FunctionDecl *First = Old->getFirstDecl(); 3259 const FunctionType *FT = 3260 First->getType().getCanonicalType()->castAs<FunctionType>(); 3261 FunctionType::ExtInfo FI = FT->getExtInfo(); 3262 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3263 if (!NewCCExplicit) { 3264 // Inherit the CC from the previous declaration if it was specified 3265 // there but not here. 3266 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3267 RequiresAdjustment = true; 3268 } else if (New->getBuiltinID()) { 3269 // Calling Conventions on a Builtin aren't really useful and setting a 3270 // default calling convention and cdecl'ing some builtin redeclarations is 3271 // common, so warn and ignore the calling convention on the redeclaration. 3272 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3273 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3274 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3275 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3276 RequiresAdjustment = true; 3277 } else { 3278 // Calling conventions aren't compatible, so complain. 3279 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3280 Diag(New->getLocation(), diag::err_cconv_change) 3281 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3282 << !FirstCCExplicit 3283 << (!FirstCCExplicit ? "" : 3284 FunctionType::getNameForCallConv(FI.getCC())); 3285 3286 // Put the note on the first decl, since it is the one that matters. 3287 Diag(First->getLocation(), diag::note_previous_declaration); 3288 return true; 3289 } 3290 } 3291 3292 // FIXME: diagnose the other way around? 3293 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3294 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3295 RequiresAdjustment = true; 3296 } 3297 3298 // Merge regparm attribute. 3299 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3300 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3301 if (NewTypeInfo.getHasRegParm()) { 3302 Diag(New->getLocation(), diag::err_regparm_mismatch) 3303 << NewType->getRegParmType() 3304 << OldType->getRegParmType(); 3305 Diag(OldLocation, diag::note_previous_declaration); 3306 return true; 3307 } 3308 3309 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3310 RequiresAdjustment = true; 3311 } 3312 3313 // Merge ns_returns_retained attribute. 3314 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3315 if (NewTypeInfo.getProducesResult()) { 3316 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3317 << "'ns_returns_retained'"; 3318 Diag(OldLocation, diag::note_previous_declaration); 3319 return true; 3320 } 3321 3322 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3323 RequiresAdjustment = true; 3324 } 3325 3326 if (OldTypeInfo.getNoCallerSavedRegs() != 3327 NewTypeInfo.getNoCallerSavedRegs()) { 3328 if (NewTypeInfo.getNoCallerSavedRegs()) { 3329 AnyX86NoCallerSavedRegistersAttr *Attr = 3330 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3331 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3332 Diag(OldLocation, diag::note_previous_declaration); 3333 return true; 3334 } 3335 3336 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3337 RequiresAdjustment = true; 3338 } 3339 3340 if (RequiresAdjustment) { 3341 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3342 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3343 New->setType(QualType(AdjustedType, 0)); 3344 NewQType = Context.getCanonicalType(New->getType()); 3345 } 3346 3347 // If this redeclaration makes the function inline, we may need to add it to 3348 // UndefinedButUsed. 3349 if (!Old->isInlined() && New->isInlined() && 3350 !New->hasAttr<GNUInlineAttr>() && 3351 !getLangOpts().GNUInline && 3352 Old->isUsed(false) && 3353 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3354 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3355 SourceLocation())); 3356 3357 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3358 // about it. 3359 if (New->hasAttr<GNUInlineAttr>() && 3360 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3361 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3362 } 3363 3364 // If pass_object_size params don't match up perfectly, this isn't a valid 3365 // redeclaration. 3366 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3367 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3368 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3369 << New->getDeclName(); 3370 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3371 return true; 3372 } 3373 3374 if (getLangOpts().CPlusPlus) { 3375 // C++1z [over.load]p2 3376 // Certain function declarations cannot be overloaded: 3377 // -- Function declarations that differ only in the return type, 3378 // the exception specification, or both cannot be overloaded. 3379 3380 // Check the exception specifications match. This may recompute the type of 3381 // both Old and New if it resolved exception specifications, so grab the 3382 // types again after this. Because this updates the type, we do this before 3383 // any of the other checks below, which may update the "de facto" NewQType 3384 // but do not necessarily update the type of New. 3385 if (CheckEquivalentExceptionSpec(Old, New)) 3386 return true; 3387 OldQType = Context.getCanonicalType(Old->getType()); 3388 NewQType = Context.getCanonicalType(New->getType()); 3389 3390 // Go back to the type source info to compare the declared return types, 3391 // per C++1y [dcl.type.auto]p13: 3392 // Redeclarations or specializations of a function or function template 3393 // with a declared return type that uses a placeholder type shall also 3394 // use that placeholder, not a deduced type. 3395 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3396 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3397 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3398 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3399 OldDeclaredReturnType)) { 3400 QualType ResQT; 3401 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3402 OldDeclaredReturnType->isObjCObjectPointerType()) 3403 // FIXME: This does the wrong thing for a deduced return type. 3404 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3405 if (ResQT.isNull()) { 3406 if (New->isCXXClassMember() && New->isOutOfLine()) 3407 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3408 << New << New->getReturnTypeSourceRange(); 3409 else 3410 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3411 << New->getReturnTypeSourceRange(); 3412 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3413 << Old->getReturnTypeSourceRange(); 3414 return true; 3415 } 3416 else 3417 NewQType = ResQT; 3418 } 3419 3420 QualType OldReturnType = OldType->getReturnType(); 3421 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3422 if (OldReturnType != NewReturnType) { 3423 // If this function has a deduced return type and has already been 3424 // defined, copy the deduced value from the old declaration. 3425 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3426 if (OldAT && OldAT->isDeduced()) { 3427 New->setType( 3428 SubstAutoType(New->getType(), 3429 OldAT->isDependentType() ? Context.DependentTy 3430 : OldAT->getDeducedType())); 3431 NewQType = Context.getCanonicalType( 3432 SubstAutoType(NewQType, 3433 OldAT->isDependentType() ? Context.DependentTy 3434 : OldAT->getDeducedType())); 3435 } 3436 } 3437 3438 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3439 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3440 if (OldMethod && NewMethod) { 3441 // Preserve triviality. 3442 NewMethod->setTrivial(OldMethod->isTrivial()); 3443 3444 // MSVC allows explicit template specialization at class scope: 3445 // 2 CXXMethodDecls referring to the same function will be injected. 3446 // We don't want a redeclaration error. 3447 bool IsClassScopeExplicitSpecialization = 3448 OldMethod->isFunctionTemplateSpecialization() && 3449 NewMethod->isFunctionTemplateSpecialization(); 3450 bool isFriend = NewMethod->getFriendObjectKind(); 3451 3452 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3453 !IsClassScopeExplicitSpecialization) { 3454 // -- Member function declarations with the same name and the 3455 // same parameter types cannot be overloaded if any of them 3456 // is a static member function declaration. 3457 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3458 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3459 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3460 return true; 3461 } 3462 3463 // C++ [class.mem]p1: 3464 // [...] A member shall not be declared twice in the 3465 // member-specification, except that a nested class or member 3466 // class template can be declared and then later defined. 3467 if (!inTemplateInstantiation()) { 3468 unsigned NewDiag; 3469 if (isa<CXXConstructorDecl>(OldMethod)) 3470 NewDiag = diag::err_constructor_redeclared; 3471 else if (isa<CXXDestructorDecl>(NewMethod)) 3472 NewDiag = diag::err_destructor_redeclared; 3473 else if (isa<CXXConversionDecl>(NewMethod)) 3474 NewDiag = diag::err_conv_function_redeclared; 3475 else 3476 NewDiag = diag::err_member_redeclared; 3477 3478 Diag(New->getLocation(), NewDiag); 3479 } else { 3480 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3481 << New << New->getType(); 3482 } 3483 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3484 return true; 3485 3486 // Complain if this is an explicit declaration of a special 3487 // member that was initially declared implicitly. 3488 // 3489 // As an exception, it's okay to befriend such methods in order 3490 // to permit the implicit constructor/destructor/operator calls. 3491 } else if (OldMethod->isImplicit()) { 3492 if (isFriend) { 3493 NewMethod->setImplicit(); 3494 } else { 3495 Diag(NewMethod->getLocation(), 3496 diag::err_definition_of_implicitly_declared_member) 3497 << New << getSpecialMember(OldMethod); 3498 return true; 3499 } 3500 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3501 Diag(NewMethod->getLocation(), 3502 diag::err_definition_of_explicitly_defaulted_member) 3503 << getSpecialMember(OldMethod); 3504 return true; 3505 } 3506 } 3507 3508 // C++11 [dcl.attr.noreturn]p1: 3509 // The first declaration of a function shall specify the noreturn 3510 // attribute if any declaration of that function specifies the noreturn 3511 // attribute. 3512 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3513 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3514 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3515 Diag(Old->getFirstDecl()->getLocation(), 3516 diag::note_noreturn_missing_first_decl); 3517 } 3518 3519 // C++11 [dcl.attr.depend]p2: 3520 // The first declaration of a function shall specify the 3521 // carries_dependency attribute for its declarator-id if any declaration 3522 // of the function specifies the carries_dependency attribute. 3523 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3524 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3525 Diag(CDA->getLocation(), 3526 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3527 Diag(Old->getFirstDecl()->getLocation(), 3528 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3529 } 3530 3531 // (C++98 8.3.5p3): 3532 // All declarations for a function shall agree exactly in both the 3533 // return type and the parameter-type-list. 3534 // We also want to respect all the extended bits except noreturn. 3535 3536 // noreturn should now match unless the old type info didn't have it. 3537 QualType OldQTypeForComparison = OldQType; 3538 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3539 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3540 const FunctionType *OldTypeForComparison 3541 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3542 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3543 assert(OldQTypeForComparison.isCanonical()); 3544 } 3545 3546 if (haveIncompatibleLanguageLinkages(Old, New)) { 3547 // As a special case, retain the language linkage from previous 3548 // declarations of a friend function as an extension. 3549 // 3550 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3551 // and is useful because there's otherwise no way to specify language 3552 // linkage within class scope. 3553 // 3554 // Check cautiously as the friend object kind isn't yet complete. 3555 if (New->getFriendObjectKind() != Decl::FOK_None) { 3556 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3557 Diag(OldLocation, PrevDiag); 3558 } else { 3559 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3560 Diag(OldLocation, PrevDiag); 3561 return true; 3562 } 3563 } 3564 3565 if (OldQTypeForComparison == NewQType) 3566 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3567 3568 // If the types are imprecise (due to dependent constructs in friends or 3569 // local extern declarations), it's OK if they differ. We'll check again 3570 // during instantiation. 3571 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3572 return false; 3573 3574 // Fall through for conflicting redeclarations and redefinitions. 3575 } 3576 3577 // C: Function types need to be compatible, not identical. This handles 3578 // duplicate function decls like "void f(int); void f(enum X);" properly. 3579 if (!getLangOpts().CPlusPlus && 3580 Context.typesAreCompatible(OldQType, NewQType)) { 3581 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3582 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3583 const FunctionProtoType *OldProto = nullptr; 3584 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3585 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3586 // The old declaration provided a function prototype, but the 3587 // new declaration does not. Merge in the prototype. 3588 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3589 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3590 NewQType = 3591 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3592 OldProto->getExtProtoInfo()); 3593 New->setType(NewQType); 3594 New->setHasInheritedPrototype(); 3595 3596 // Synthesize parameters with the same types. 3597 SmallVector<ParmVarDecl*, 16> Params; 3598 for (const auto &ParamType : OldProto->param_types()) { 3599 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3600 SourceLocation(), nullptr, 3601 ParamType, /*TInfo=*/nullptr, 3602 SC_None, nullptr); 3603 Param->setScopeInfo(0, Params.size()); 3604 Param->setImplicit(); 3605 Params.push_back(Param); 3606 } 3607 3608 New->setParams(Params); 3609 } 3610 3611 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3612 } 3613 3614 // GNU C permits a K&R definition to follow a prototype declaration 3615 // if the declared types of the parameters in the K&R definition 3616 // match the types in the prototype declaration, even when the 3617 // promoted types of the parameters from the K&R definition differ 3618 // from the types in the prototype. GCC then keeps the types from 3619 // the prototype. 3620 // 3621 // If a variadic prototype is followed by a non-variadic K&R definition, 3622 // the K&R definition becomes variadic. This is sort of an edge case, but 3623 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3624 // C99 6.9.1p8. 3625 if (!getLangOpts().CPlusPlus && 3626 Old->hasPrototype() && !New->hasPrototype() && 3627 New->getType()->getAs<FunctionProtoType>() && 3628 Old->getNumParams() == New->getNumParams()) { 3629 SmallVector<QualType, 16> ArgTypes; 3630 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3631 const FunctionProtoType *OldProto 3632 = Old->getType()->getAs<FunctionProtoType>(); 3633 const FunctionProtoType *NewProto 3634 = New->getType()->getAs<FunctionProtoType>(); 3635 3636 // Determine whether this is the GNU C extension. 3637 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3638 NewProto->getReturnType()); 3639 bool LooseCompatible = !MergedReturn.isNull(); 3640 for (unsigned Idx = 0, End = Old->getNumParams(); 3641 LooseCompatible && Idx != End; ++Idx) { 3642 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3643 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3644 if (Context.typesAreCompatible(OldParm->getType(), 3645 NewProto->getParamType(Idx))) { 3646 ArgTypes.push_back(NewParm->getType()); 3647 } else if (Context.typesAreCompatible(OldParm->getType(), 3648 NewParm->getType(), 3649 /*CompareUnqualified=*/true)) { 3650 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3651 NewProto->getParamType(Idx) }; 3652 Warnings.push_back(Warn); 3653 ArgTypes.push_back(NewParm->getType()); 3654 } else 3655 LooseCompatible = false; 3656 } 3657 3658 if (LooseCompatible) { 3659 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3660 Diag(Warnings[Warn].NewParm->getLocation(), 3661 diag::ext_param_promoted_not_compatible_with_prototype) 3662 << Warnings[Warn].PromotedType 3663 << Warnings[Warn].OldParm->getType(); 3664 if (Warnings[Warn].OldParm->getLocation().isValid()) 3665 Diag(Warnings[Warn].OldParm->getLocation(), 3666 diag::note_previous_declaration); 3667 } 3668 3669 if (MergeTypeWithOld) 3670 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3671 OldProto->getExtProtoInfo())); 3672 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3673 } 3674 3675 // Fall through to diagnose conflicting types. 3676 } 3677 3678 // A function that has already been declared has been redeclared or 3679 // defined with a different type; show an appropriate diagnostic. 3680 3681 // If the previous declaration was an implicitly-generated builtin 3682 // declaration, then at the very least we should use a specialized note. 3683 unsigned BuiltinID; 3684 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3685 // If it's actually a library-defined builtin function like 'malloc' 3686 // or 'printf', just warn about the incompatible redeclaration. 3687 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3688 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3689 Diag(OldLocation, diag::note_previous_builtin_declaration) 3690 << Old << Old->getType(); 3691 3692 // If this is a global redeclaration, just forget hereafter 3693 // about the "builtin-ness" of the function. 3694 // 3695 // Doing this for local extern declarations is problematic. If 3696 // the builtin declaration remains visible, a second invalid 3697 // local declaration will produce a hard error; if it doesn't 3698 // remain visible, a single bogus local redeclaration (which is 3699 // actually only a warning) could break all the downstream code. 3700 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3701 New->getIdentifier()->revertBuiltin(); 3702 3703 return false; 3704 } 3705 3706 PrevDiag = diag::note_previous_builtin_declaration; 3707 } 3708 3709 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3710 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3711 return true; 3712 } 3713 3714 /// Completes the merge of two function declarations that are 3715 /// known to be compatible. 3716 /// 3717 /// This routine handles the merging of attributes and other 3718 /// properties of function declarations from the old declaration to 3719 /// the new declaration, once we know that New is in fact a 3720 /// redeclaration of Old. 3721 /// 3722 /// \returns false 3723 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3724 Scope *S, bool MergeTypeWithOld) { 3725 // Merge the attributes 3726 mergeDeclAttributes(New, Old); 3727 3728 // Merge "pure" flag. 3729 if (Old->isPure()) 3730 New->setPure(); 3731 3732 // Merge "used" flag. 3733 if (Old->getMostRecentDecl()->isUsed(false)) 3734 New->setIsUsed(); 3735 3736 // Merge attributes from the parameters. These can mismatch with K&R 3737 // declarations. 3738 if (New->getNumParams() == Old->getNumParams()) 3739 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3740 ParmVarDecl *NewParam = New->getParamDecl(i); 3741 ParmVarDecl *OldParam = Old->getParamDecl(i); 3742 mergeParamDeclAttributes(NewParam, OldParam, *this); 3743 mergeParamDeclTypes(NewParam, OldParam, *this); 3744 } 3745 3746 if (getLangOpts().CPlusPlus) 3747 return MergeCXXFunctionDecl(New, Old, S); 3748 3749 // Merge the function types so the we get the composite types for the return 3750 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3751 // was visible. 3752 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3753 if (!Merged.isNull() && MergeTypeWithOld) 3754 New->setType(Merged); 3755 3756 return false; 3757 } 3758 3759 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3760 ObjCMethodDecl *oldMethod) { 3761 // Merge the attributes, including deprecated/unavailable 3762 AvailabilityMergeKind MergeKind = 3763 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3764 ? AMK_ProtocolImplementation 3765 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3766 : AMK_Override; 3767 3768 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3769 3770 // Merge attributes from the parameters. 3771 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3772 oe = oldMethod->param_end(); 3773 for (ObjCMethodDecl::param_iterator 3774 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3775 ni != ne && oi != oe; ++ni, ++oi) 3776 mergeParamDeclAttributes(*ni, *oi, *this); 3777 3778 CheckObjCMethodOverride(newMethod, oldMethod); 3779 } 3780 3781 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3782 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3783 3784 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3785 ? diag::err_redefinition_different_type 3786 : diag::err_redeclaration_different_type) 3787 << New->getDeclName() << New->getType() << Old->getType(); 3788 3789 diag::kind PrevDiag; 3790 SourceLocation OldLocation; 3791 std::tie(PrevDiag, OldLocation) 3792 = getNoteDiagForInvalidRedeclaration(Old, New); 3793 S.Diag(OldLocation, PrevDiag); 3794 New->setInvalidDecl(); 3795 } 3796 3797 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3798 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3799 /// emitting diagnostics as appropriate. 3800 /// 3801 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3802 /// to here in AddInitializerToDecl. We can't check them before the initializer 3803 /// is attached. 3804 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3805 bool MergeTypeWithOld) { 3806 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3807 return; 3808 3809 QualType MergedT; 3810 if (getLangOpts().CPlusPlus) { 3811 if (New->getType()->isUndeducedType()) { 3812 // We don't know what the new type is until the initializer is attached. 3813 return; 3814 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3815 // These could still be something that needs exception specs checked. 3816 return MergeVarDeclExceptionSpecs(New, Old); 3817 } 3818 // C++ [basic.link]p10: 3819 // [...] the types specified by all declarations referring to a given 3820 // object or function shall be identical, except that declarations for an 3821 // array object can specify array types that differ by the presence or 3822 // absence of a major array bound (8.3.4). 3823 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3824 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3825 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3826 3827 // We are merging a variable declaration New into Old. If it has an array 3828 // bound, and that bound differs from Old's bound, we should diagnose the 3829 // mismatch. 3830 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3831 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3832 PrevVD = PrevVD->getPreviousDecl()) { 3833 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3834 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3835 continue; 3836 3837 if (!Context.hasSameType(NewArray, PrevVDTy)) 3838 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3839 } 3840 } 3841 3842 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3843 if (Context.hasSameType(OldArray->getElementType(), 3844 NewArray->getElementType())) 3845 MergedT = New->getType(); 3846 } 3847 // FIXME: Check visibility. New is hidden but has a complete type. If New 3848 // has no array bound, it should not inherit one from Old, if Old is not 3849 // visible. 3850 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3851 if (Context.hasSameType(OldArray->getElementType(), 3852 NewArray->getElementType())) 3853 MergedT = Old->getType(); 3854 } 3855 } 3856 else if (New->getType()->isObjCObjectPointerType() && 3857 Old->getType()->isObjCObjectPointerType()) { 3858 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3859 Old->getType()); 3860 } 3861 } else { 3862 // C 6.2.7p2: 3863 // All declarations that refer to the same object or function shall have 3864 // compatible type. 3865 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3866 } 3867 if (MergedT.isNull()) { 3868 // It's OK if we couldn't merge types if either type is dependent, for a 3869 // block-scope variable. In other cases (static data members of class 3870 // templates, variable templates, ...), we require the types to be 3871 // equivalent. 3872 // FIXME: The C++ standard doesn't say anything about this. 3873 if ((New->getType()->isDependentType() || 3874 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3875 // If the old type was dependent, we can't merge with it, so the new type 3876 // becomes dependent for now. We'll reproduce the original type when we 3877 // instantiate the TypeSourceInfo for the variable. 3878 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3879 New->setType(Context.DependentTy); 3880 return; 3881 } 3882 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3883 } 3884 3885 // Don't actually update the type on the new declaration if the old 3886 // declaration was an extern declaration in a different scope. 3887 if (MergeTypeWithOld) 3888 New->setType(MergedT); 3889 } 3890 3891 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3892 LookupResult &Previous) { 3893 // C11 6.2.7p4: 3894 // For an identifier with internal or external linkage declared 3895 // in a scope in which a prior declaration of that identifier is 3896 // visible, if the prior declaration specifies internal or 3897 // external linkage, the type of the identifier at the later 3898 // declaration becomes the composite type. 3899 // 3900 // If the variable isn't visible, we do not merge with its type. 3901 if (Previous.isShadowed()) 3902 return false; 3903 3904 if (S.getLangOpts().CPlusPlus) { 3905 // C++11 [dcl.array]p3: 3906 // If there is a preceding declaration of the entity in the same 3907 // scope in which the bound was specified, an omitted array bound 3908 // is taken to be the same as in that earlier declaration. 3909 return NewVD->isPreviousDeclInSameBlockScope() || 3910 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3911 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3912 } else { 3913 // If the old declaration was function-local, don't merge with its 3914 // type unless we're in the same function. 3915 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3916 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3917 } 3918 } 3919 3920 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3921 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3922 /// situation, merging decls or emitting diagnostics as appropriate. 3923 /// 3924 /// Tentative definition rules (C99 6.9.2p2) are checked by 3925 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3926 /// definitions here, since the initializer hasn't been attached. 3927 /// 3928 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3929 // If the new decl is already invalid, don't do any other checking. 3930 if (New->isInvalidDecl()) 3931 return; 3932 3933 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3934 return; 3935 3936 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3937 3938 // Verify the old decl was also a variable or variable template. 3939 VarDecl *Old = nullptr; 3940 VarTemplateDecl *OldTemplate = nullptr; 3941 if (Previous.isSingleResult()) { 3942 if (NewTemplate) { 3943 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3944 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3945 3946 if (auto *Shadow = 3947 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3948 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3949 return New->setInvalidDecl(); 3950 } else { 3951 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3952 3953 if (auto *Shadow = 3954 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3955 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3956 return New->setInvalidDecl(); 3957 } 3958 } 3959 if (!Old) { 3960 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3961 << New->getDeclName(); 3962 notePreviousDefinition(Previous.getRepresentativeDecl(), 3963 New->getLocation()); 3964 return New->setInvalidDecl(); 3965 } 3966 3967 // Ensure the template parameters are compatible. 3968 if (NewTemplate && 3969 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3970 OldTemplate->getTemplateParameters(), 3971 /*Complain=*/true, TPL_TemplateMatch)) 3972 return New->setInvalidDecl(); 3973 3974 // C++ [class.mem]p1: 3975 // A member shall not be declared twice in the member-specification [...] 3976 // 3977 // Here, we need only consider static data members. 3978 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3979 Diag(New->getLocation(), diag::err_duplicate_member) 3980 << New->getIdentifier(); 3981 Diag(Old->getLocation(), diag::note_previous_declaration); 3982 New->setInvalidDecl(); 3983 } 3984 3985 mergeDeclAttributes(New, Old); 3986 // Warn if an already-declared variable is made a weak_import in a subsequent 3987 // declaration 3988 if (New->hasAttr<WeakImportAttr>() && 3989 Old->getStorageClass() == SC_None && 3990 !Old->hasAttr<WeakImportAttr>()) { 3991 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3992 notePreviousDefinition(Old, New->getLocation()); 3993 // Remove weak_import attribute on new declaration. 3994 New->dropAttr<WeakImportAttr>(); 3995 } 3996 3997 if (New->hasAttr<InternalLinkageAttr>() && 3998 !Old->hasAttr<InternalLinkageAttr>()) { 3999 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4000 << New->getDeclName(); 4001 notePreviousDefinition(Old, New->getLocation()); 4002 New->dropAttr<InternalLinkageAttr>(); 4003 } 4004 4005 // Merge the types. 4006 VarDecl *MostRecent = Old->getMostRecentDecl(); 4007 if (MostRecent != Old) { 4008 MergeVarDeclTypes(New, MostRecent, 4009 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4010 if (New->isInvalidDecl()) 4011 return; 4012 } 4013 4014 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4015 if (New->isInvalidDecl()) 4016 return; 4017 4018 diag::kind PrevDiag; 4019 SourceLocation OldLocation; 4020 std::tie(PrevDiag, OldLocation) = 4021 getNoteDiagForInvalidRedeclaration(Old, New); 4022 4023 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4024 if (New->getStorageClass() == SC_Static && 4025 !New->isStaticDataMember() && 4026 Old->hasExternalFormalLinkage()) { 4027 if (getLangOpts().MicrosoftExt) { 4028 Diag(New->getLocation(), diag::ext_static_non_static) 4029 << New->getDeclName(); 4030 Diag(OldLocation, PrevDiag); 4031 } else { 4032 Diag(New->getLocation(), diag::err_static_non_static) 4033 << New->getDeclName(); 4034 Diag(OldLocation, PrevDiag); 4035 return New->setInvalidDecl(); 4036 } 4037 } 4038 // C99 6.2.2p4: 4039 // For an identifier declared with the storage-class specifier 4040 // extern in a scope in which a prior declaration of that 4041 // identifier is visible,23) if the prior declaration specifies 4042 // internal or external linkage, the linkage of the identifier at 4043 // the later declaration is the same as the linkage specified at 4044 // the prior declaration. If no prior declaration is visible, or 4045 // if the prior declaration specifies no linkage, then the 4046 // identifier has external linkage. 4047 if (New->hasExternalStorage() && Old->hasLinkage()) 4048 /* Okay */; 4049 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4050 !New->isStaticDataMember() && 4051 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4052 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4053 Diag(OldLocation, PrevDiag); 4054 return New->setInvalidDecl(); 4055 } 4056 4057 // Check if extern is followed by non-extern and vice-versa. 4058 if (New->hasExternalStorage() && 4059 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4060 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4061 Diag(OldLocation, PrevDiag); 4062 return New->setInvalidDecl(); 4063 } 4064 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4065 !New->hasExternalStorage()) { 4066 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4067 Diag(OldLocation, PrevDiag); 4068 return New->setInvalidDecl(); 4069 } 4070 4071 if (CheckRedeclarationModuleOwnership(New, Old)) 4072 return; 4073 4074 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4075 4076 // FIXME: The test for external storage here seems wrong? We still 4077 // need to check for mismatches. 4078 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4079 // Don't complain about out-of-line definitions of static members. 4080 !(Old->getLexicalDeclContext()->isRecord() && 4081 !New->getLexicalDeclContext()->isRecord())) { 4082 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4083 Diag(OldLocation, PrevDiag); 4084 return New->setInvalidDecl(); 4085 } 4086 4087 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4088 if (VarDecl *Def = Old->getDefinition()) { 4089 // C++1z [dcl.fcn.spec]p4: 4090 // If the definition of a variable appears in a translation unit before 4091 // its first declaration as inline, the program is ill-formed. 4092 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4093 Diag(Def->getLocation(), diag::note_previous_definition); 4094 } 4095 } 4096 4097 // If this redeclaration makes the variable inline, we may need to add it to 4098 // UndefinedButUsed. 4099 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4100 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4101 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4102 SourceLocation())); 4103 4104 if (New->getTLSKind() != Old->getTLSKind()) { 4105 if (!Old->getTLSKind()) { 4106 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4107 Diag(OldLocation, PrevDiag); 4108 } else if (!New->getTLSKind()) { 4109 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4110 Diag(OldLocation, PrevDiag); 4111 } else { 4112 // Do not allow redeclaration to change the variable between requiring 4113 // static and dynamic initialization. 4114 // FIXME: GCC allows this, but uses the TLS keyword on the first 4115 // declaration to determine the kind. Do we need to be compatible here? 4116 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4117 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4118 Diag(OldLocation, PrevDiag); 4119 } 4120 } 4121 4122 // C++ doesn't have tentative definitions, so go right ahead and check here. 4123 if (getLangOpts().CPlusPlus && 4124 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4125 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4126 Old->getCanonicalDecl()->isConstexpr()) { 4127 // This definition won't be a definition any more once it's been merged. 4128 Diag(New->getLocation(), 4129 diag::warn_deprecated_redundant_constexpr_static_def); 4130 } else if (VarDecl *Def = Old->getDefinition()) { 4131 if (checkVarDeclRedefinition(Def, New)) 4132 return; 4133 } 4134 } 4135 4136 if (haveIncompatibleLanguageLinkages(Old, New)) { 4137 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4138 Diag(OldLocation, PrevDiag); 4139 New->setInvalidDecl(); 4140 return; 4141 } 4142 4143 // Merge "used" flag. 4144 if (Old->getMostRecentDecl()->isUsed(false)) 4145 New->setIsUsed(); 4146 4147 // Keep a chain of previous declarations. 4148 New->setPreviousDecl(Old); 4149 if (NewTemplate) 4150 NewTemplate->setPreviousDecl(OldTemplate); 4151 adjustDeclContextForDeclaratorDecl(New, Old); 4152 4153 // Inherit access appropriately. 4154 New->setAccess(Old->getAccess()); 4155 if (NewTemplate) 4156 NewTemplate->setAccess(New->getAccess()); 4157 4158 if (Old->isInline()) 4159 New->setImplicitlyInline(); 4160 } 4161 4162 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4163 SourceManager &SrcMgr = getSourceManager(); 4164 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4165 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4166 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4167 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4168 auto &HSI = PP.getHeaderSearchInfo(); 4169 StringRef HdrFilename = 4170 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4171 4172 auto noteFromModuleOrInclude = [&](Module *Mod, 4173 SourceLocation IncLoc) -> bool { 4174 // Redefinition errors with modules are common with non modular mapped 4175 // headers, example: a non-modular header H in module A that also gets 4176 // included directly in a TU. Pointing twice to the same header/definition 4177 // is confusing, try to get better diagnostics when modules is on. 4178 if (IncLoc.isValid()) { 4179 if (Mod) { 4180 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4181 << HdrFilename.str() << Mod->getFullModuleName(); 4182 if (!Mod->DefinitionLoc.isInvalid()) 4183 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4184 << Mod->getFullModuleName(); 4185 } else { 4186 Diag(IncLoc, diag::note_redefinition_include_same_file) 4187 << HdrFilename.str(); 4188 } 4189 return true; 4190 } 4191 4192 return false; 4193 }; 4194 4195 // Is it the same file and same offset? Provide more information on why 4196 // this leads to a redefinition error. 4197 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4198 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4199 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4200 bool EmittedDiag = 4201 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4202 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4203 4204 // If the header has no guards, emit a note suggesting one. 4205 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4206 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4207 4208 if (EmittedDiag) 4209 return; 4210 } 4211 4212 // Redefinition coming from different files or couldn't do better above. 4213 if (Old->getLocation().isValid()) 4214 Diag(Old->getLocation(), diag::note_previous_definition); 4215 } 4216 4217 /// We've just determined that \p Old and \p New both appear to be definitions 4218 /// of the same variable. Either diagnose or fix the problem. 4219 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4220 if (!hasVisibleDefinition(Old) && 4221 (New->getFormalLinkage() == InternalLinkage || 4222 New->isInline() || 4223 New->getDescribedVarTemplate() || 4224 New->getNumTemplateParameterLists() || 4225 New->getDeclContext()->isDependentContext())) { 4226 // The previous definition is hidden, and multiple definitions are 4227 // permitted (in separate TUs). Demote this to a declaration. 4228 New->demoteThisDefinitionToDeclaration(); 4229 4230 // Make the canonical definition visible. 4231 if (auto *OldTD = Old->getDescribedVarTemplate()) 4232 makeMergedDefinitionVisible(OldTD); 4233 makeMergedDefinitionVisible(Old); 4234 return false; 4235 } else { 4236 Diag(New->getLocation(), diag::err_redefinition) << New; 4237 notePreviousDefinition(Old, New->getLocation()); 4238 New->setInvalidDecl(); 4239 return true; 4240 } 4241 } 4242 4243 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4244 /// no declarator (e.g. "struct foo;") is parsed. 4245 Decl * 4246 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4247 RecordDecl *&AnonRecord) { 4248 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4249 AnonRecord); 4250 } 4251 4252 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4253 // disambiguate entities defined in different scopes. 4254 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4255 // compatibility. 4256 // We will pick our mangling number depending on which version of MSVC is being 4257 // targeted. 4258 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4259 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4260 ? S->getMSCurManglingNumber() 4261 : S->getMSLastManglingNumber(); 4262 } 4263 4264 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4265 if (!Context.getLangOpts().CPlusPlus) 4266 return; 4267 4268 if (isa<CXXRecordDecl>(Tag->getParent())) { 4269 // If this tag is the direct child of a class, number it if 4270 // it is anonymous. 4271 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4272 return; 4273 MangleNumberingContext &MCtx = 4274 Context.getManglingNumberContext(Tag->getParent()); 4275 Context.setManglingNumber( 4276 Tag, MCtx.getManglingNumber( 4277 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4278 return; 4279 } 4280 4281 // If this tag isn't a direct child of a class, number it if it is local. 4282 Decl *ManglingContextDecl; 4283 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4284 Tag->getDeclContext(), ManglingContextDecl)) { 4285 Context.setManglingNumber( 4286 Tag, MCtx->getManglingNumber( 4287 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4288 } 4289 } 4290 4291 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4292 TypedefNameDecl *NewTD) { 4293 if (TagFromDeclSpec->isInvalidDecl()) 4294 return; 4295 4296 // Do nothing if the tag already has a name for linkage purposes. 4297 if (TagFromDeclSpec->hasNameForLinkage()) 4298 return; 4299 4300 // A well-formed anonymous tag must always be a TUK_Definition. 4301 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4302 4303 // The type must match the tag exactly; no qualifiers allowed. 4304 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4305 Context.getTagDeclType(TagFromDeclSpec))) { 4306 if (getLangOpts().CPlusPlus) 4307 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4308 return; 4309 } 4310 4311 // If we've already computed linkage for the anonymous tag, then 4312 // adding a typedef name for the anonymous decl can change that 4313 // linkage, which might be a serious problem. Diagnose this as 4314 // unsupported and ignore the typedef name. TODO: we should 4315 // pursue this as a language defect and establish a formal rule 4316 // for how to handle it. 4317 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4318 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4319 4320 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4321 tagLoc = getLocForEndOfToken(tagLoc); 4322 4323 llvm::SmallString<40> textToInsert; 4324 textToInsert += ' '; 4325 textToInsert += NewTD->getIdentifier()->getName(); 4326 Diag(tagLoc, diag::note_typedef_changes_linkage) 4327 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4328 return; 4329 } 4330 4331 // Otherwise, set this is the anon-decl typedef for the tag. 4332 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4333 } 4334 4335 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4336 switch (T) { 4337 case DeclSpec::TST_class: 4338 return 0; 4339 case DeclSpec::TST_struct: 4340 return 1; 4341 case DeclSpec::TST_interface: 4342 return 2; 4343 case DeclSpec::TST_union: 4344 return 3; 4345 case DeclSpec::TST_enum: 4346 return 4; 4347 default: 4348 llvm_unreachable("unexpected type specifier"); 4349 } 4350 } 4351 4352 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4353 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4354 /// parameters to cope with template friend declarations. 4355 Decl * 4356 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4357 MultiTemplateParamsArg TemplateParams, 4358 bool IsExplicitInstantiation, 4359 RecordDecl *&AnonRecord) { 4360 Decl *TagD = nullptr; 4361 TagDecl *Tag = nullptr; 4362 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4363 DS.getTypeSpecType() == DeclSpec::TST_struct || 4364 DS.getTypeSpecType() == DeclSpec::TST_interface || 4365 DS.getTypeSpecType() == DeclSpec::TST_union || 4366 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4367 TagD = DS.getRepAsDecl(); 4368 4369 if (!TagD) // We probably had an error 4370 return nullptr; 4371 4372 // Note that the above type specs guarantee that the 4373 // type rep is a Decl, whereas in many of the others 4374 // it's a Type. 4375 if (isa<TagDecl>(TagD)) 4376 Tag = cast<TagDecl>(TagD); 4377 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4378 Tag = CTD->getTemplatedDecl(); 4379 } 4380 4381 if (Tag) { 4382 handleTagNumbering(Tag, S); 4383 Tag->setFreeStanding(); 4384 if (Tag->isInvalidDecl()) 4385 return Tag; 4386 } 4387 4388 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4389 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4390 // or incomplete types shall not be restrict-qualified." 4391 if (TypeQuals & DeclSpec::TQ_restrict) 4392 Diag(DS.getRestrictSpecLoc(), 4393 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4394 << DS.getSourceRange(); 4395 } 4396 4397 if (DS.isInlineSpecified()) 4398 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4399 << getLangOpts().CPlusPlus17; 4400 4401 if (DS.hasConstexprSpecifier()) { 4402 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4403 // and definitions of functions and variables. 4404 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4405 // the declaration of a function or function template 4406 if (Tag) 4407 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4408 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4409 << DS.getConstexprSpecifier(); 4410 else 4411 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4412 << DS.getConstexprSpecifier(); 4413 // Don't emit warnings after this error. 4414 return TagD; 4415 } 4416 4417 DiagnoseFunctionSpecifiers(DS); 4418 4419 if (DS.isFriendSpecified()) { 4420 // If we're dealing with a decl but not a TagDecl, assume that 4421 // whatever routines created it handled the friendship aspect. 4422 if (TagD && !Tag) 4423 return nullptr; 4424 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4425 } 4426 4427 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4428 bool IsExplicitSpecialization = 4429 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4430 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4431 !IsExplicitInstantiation && !IsExplicitSpecialization && 4432 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4433 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4434 // nested-name-specifier unless it is an explicit instantiation 4435 // or an explicit specialization. 4436 // 4437 // FIXME: We allow class template partial specializations here too, per the 4438 // obvious intent of DR1819. 4439 // 4440 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4441 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4442 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4443 return nullptr; 4444 } 4445 4446 // Track whether this decl-specifier declares anything. 4447 bool DeclaresAnything = true; 4448 4449 // Handle anonymous struct definitions. 4450 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4451 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4452 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4453 if (getLangOpts().CPlusPlus || 4454 Record->getDeclContext()->isRecord()) { 4455 // If CurContext is a DeclContext that can contain statements, 4456 // RecursiveASTVisitor won't visit the decls that 4457 // BuildAnonymousStructOrUnion() will put into CurContext. 4458 // Also store them here so that they can be part of the 4459 // DeclStmt that gets created in this case. 4460 // FIXME: Also return the IndirectFieldDecls created by 4461 // BuildAnonymousStructOr union, for the same reason? 4462 if (CurContext->isFunctionOrMethod()) 4463 AnonRecord = Record; 4464 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4465 Context.getPrintingPolicy()); 4466 } 4467 4468 DeclaresAnything = false; 4469 } 4470 } 4471 4472 // C11 6.7.2.1p2: 4473 // A struct-declaration that does not declare an anonymous structure or 4474 // anonymous union shall contain a struct-declarator-list. 4475 // 4476 // This rule also existed in C89 and C99; the grammar for struct-declaration 4477 // did not permit a struct-declaration without a struct-declarator-list. 4478 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4479 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4480 // Check for Microsoft C extension: anonymous struct/union member. 4481 // Handle 2 kinds of anonymous struct/union: 4482 // struct STRUCT; 4483 // union UNION; 4484 // and 4485 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4486 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4487 if ((Tag && Tag->getDeclName()) || 4488 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4489 RecordDecl *Record = nullptr; 4490 if (Tag) 4491 Record = dyn_cast<RecordDecl>(Tag); 4492 else if (const RecordType *RT = 4493 DS.getRepAsType().get()->getAsStructureType()) 4494 Record = RT->getDecl(); 4495 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4496 Record = UT->getDecl(); 4497 4498 if (Record && getLangOpts().MicrosoftExt) { 4499 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4500 << Record->isUnion() << DS.getSourceRange(); 4501 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4502 } 4503 4504 DeclaresAnything = false; 4505 } 4506 } 4507 4508 // Skip all the checks below if we have a type error. 4509 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4510 (TagD && TagD->isInvalidDecl())) 4511 return TagD; 4512 4513 if (getLangOpts().CPlusPlus && 4514 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4515 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4516 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4517 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4518 DeclaresAnything = false; 4519 4520 if (!DS.isMissingDeclaratorOk()) { 4521 // Customize diagnostic for a typedef missing a name. 4522 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4523 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4524 << DS.getSourceRange(); 4525 else 4526 DeclaresAnything = false; 4527 } 4528 4529 if (DS.isModulePrivateSpecified() && 4530 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4531 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4532 << Tag->getTagKind() 4533 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4534 4535 ActOnDocumentableDecl(TagD); 4536 4537 // C 6.7/2: 4538 // A declaration [...] shall declare at least a declarator [...], a tag, 4539 // or the members of an enumeration. 4540 // C++ [dcl.dcl]p3: 4541 // [If there are no declarators], and except for the declaration of an 4542 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4543 // names into the program, or shall redeclare a name introduced by a 4544 // previous declaration. 4545 if (!DeclaresAnything) { 4546 // In C, we allow this as a (popular) extension / bug. Don't bother 4547 // producing further diagnostics for redundant qualifiers after this. 4548 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4549 return TagD; 4550 } 4551 4552 // C++ [dcl.stc]p1: 4553 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4554 // init-declarator-list of the declaration shall not be empty. 4555 // C++ [dcl.fct.spec]p1: 4556 // If a cv-qualifier appears in a decl-specifier-seq, the 4557 // init-declarator-list of the declaration shall not be empty. 4558 // 4559 // Spurious qualifiers here appear to be valid in C. 4560 unsigned DiagID = diag::warn_standalone_specifier; 4561 if (getLangOpts().CPlusPlus) 4562 DiagID = diag::ext_standalone_specifier; 4563 4564 // Note that a linkage-specification sets a storage class, but 4565 // 'extern "C" struct foo;' is actually valid and not theoretically 4566 // useless. 4567 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4568 if (SCS == DeclSpec::SCS_mutable) 4569 // Since mutable is not a viable storage class specifier in C, there is 4570 // no reason to treat it as an extension. Instead, diagnose as an error. 4571 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4572 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4573 Diag(DS.getStorageClassSpecLoc(), DiagID) 4574 << DeclSpec::getSpecifierName(SCS); 4575 } 4576 4577 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4578 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4579 << DeclSpec::getSpecifierName(TSCS); 4580 if (DS.getTypeQualifiers()) { 4581 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4582 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4583 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4584 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4585 // Restrict is covered above. 4586 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4587 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4588 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4589 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4590 } 4591 4592 // Warn about ignored type attributes, for example: 4593 // __attribute__((aligned)) struct A; 4594 // Attributes should be placed after tag to apply to type declaration. 4595 if (!DS.getAttributes().empty()) { 4596 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4597 if (TypeSpecType == DeclSpec::TST_class || 4598 TypeSpecType == DeclSpec::TST_struct || 4599 TypeSpecType == DeclSpec::TST_interface || 4600 TypeSpecType == DeclSpec::TST_union || 4601 TypeSpecType == DeclSpec::TST_enum) { 4602 for (const ParsedAttr &AL : DS.getAttributes()) 4603 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4604 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4605 } 4606 } 4607 4608 return TagD; 4609 } 4610 4611 /// We are trying to inject an anonymous member into the given scope; 4612 /// check if there's an existing declaration that can't be overloaded. 4613 /// 4614 /// \return true if this is a forbidden redeclaration 4615 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4616 Scope *S, 4617 DeclContext *Owner, 4618 DeclarationName Name, 4619 SourceLocation NameLoc, 4620 bool IsUnion) { 4621 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4622 Sema::ForVisibleRedeclaration); 4623 if (!SemaRef.LookupName(R, S)) return false; 4624 4625 // Pick a representative declaration. 4626 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4627 assert(PrevDecl && "Expected a non-null Decl"); 4628 4629 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4630 return false; 4631 4632 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4633 << IsUnion << Name; 4634 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4635 4636 return true; 4637 } 4638 4639 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4640 /// anonymous struct or union AnonRecord into the owning context Owner 4641 /// and scope S. This routine will be invoked just after we realize 4642 /// that an unnamed union or struct is actually an anonymous union or 4643 /// struct, e.g., 4644 /// 4645 /// @code 4646 /// union { 4647 /// int i; 4648 /// float f; 4649 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4650 /// // f into the surrounding scope.x 4651 /// @endcode 4652 /// 4653 /// This routine is recursive, injecting the names of nested anonymous 4654 /// structs/unions into the owning context and scope as well. 4655 static bool 4656 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4657 RecordDecl *AnonRecord, AccessSpecifier AS, 4658 SmallVectorImpl<NamedDecl *> &Chaining) { 4659 bool Invalid = false; 4660 4661 // Look every FieldDecl and IndirectFieldDecl with a name. 4662 for (auto *D : AnonRecord->decls()) { 4663 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4664 cast<NamedDecl>(D)->getDeclName()) { 4665 ValueDecl *VD = cast<ValueDecl>(D); 4666 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4667 VD->getLocation(), 4668 AnonRecord->isUnion())) { 4669 // C++ [class.union]p2: 4670 // The names of the members of an anonymous union shall be 4671 // distinct from the names of any other entity in the 4672 // scope in which the anonymous union is declared. 4673 Invalid = true; 4674 } else { 4675 // C++ [class.union]p2: 4676 // For the purpose of name lookup, after the anonymous union 4677 // definition, the members of the anonymous union are 4678 // considered to have been defined in the scope in which the 4679 // anonymous union is declared. 4680 unsigned OldChainingSize = Chaining.size(); 4681 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4682 Chaining.append(IF->chain_begin(), IF->chain_end()); 4683 else 4684 Chaining.push_back(VD); 4685 4686 assert(Chaining.size() >= 2); 4687 NamedDecl **NamedChain = 4688 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4689 for (unsigned i = 0; i < Chaining.size(); i++) 4690 NamedChain[i] = Chaining[i]; 4691 4692 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4693 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4694 VD->getType(), {NamedChain, Chaining.size()}); 4695 4696 for (const auto *Attr : VD->attrs()) 4697 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4698 4699 IndirectField->setAccess(AS); 4700 IndirectField->setImplicit(); 4701 SemaRef.PushOnScopeChains(IndirectField, S); 4702 4703 // That includes picking up the appropriate access specifier. 4704 if (AS != AS_none) IndirectField->setAccess(AS); 4705 4706 Chaining.resize(OldChainingSize); 4707 } 4708 } 4709 } 4710 4711 return Invalid; 4712 } 4713 4714 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4715 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4716 /// illegal input values are mapped to SC_None. 4717 static StorageClass 4718 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4719 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4720 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4721 "Parser allowed 'typedef' as storage class VarDecl."); 4722 switch (StorageClassSpec) { 4723 case DeclSpec::SCS_unspecified: return SC_None; 4724 case DeclSpec::SCS_extern: 4725 if (DS.isExternInLinkageSpec()) 4726 return SC_None; 4727 return SC_Extern; 4728 case DeclSpec::SCS_static: return SC_Static; 4729 case DeclSpec::SCS_auto: return SC_Auto; 4730 case DeclSpec::SCS_register: return SC_Register; 4731 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4732 // Illegal SCSs map to None: error reporting is up to the caller. 4733 case DeclSpec::SCS_mutable: // Fall through. 4734 case DeclSpec::SCS_typedef: return SC_None; 4735 } 4736 llvm_unreachable("unknown storage class specifier"); 4737 } 4738 4739 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4740 assert(Record->hasInClassInitializer()); 4741 4742 for (const auto *I : Record->decls()) { 4743 const auto *FD = dyn_cast<FieldDecl>(I); 4744 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4745 FD = IFD->getAnonField(); 4746 if (FD && FD->hasInClassInitializer()) 4747 return FD->getLocation(); 4748 } 4749 4750 llvm_unreachable("couldn't find in-class initializer"); 4751 } 4752 4753 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4754 SourceLocation DefaultInitLoc) { 4755 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4756 return; 4757 4758 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4759 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4760 } 4761 4762 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4763 CXXRecordDecl *AnonUnion) { 4764 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4765 return; 4766 4767 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4768 } 4769 4770 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4771 /// anonymous structure or union. Anonymous unions are a C++ feature 4772 /// (C++ [class.union]) and a C11 feature; anonymous structures 4773 /// are a C11 feature and GNU C++ extension. 4774 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4775 AccessSpecifier AS, 4776 RecordDecl *Record, 4777 const PrintingPolicy &Policy) { 4778 DeclContext *Owner = Record->getDeclContext(); 4779 4780 // Diagnose whether this anonymous struct/union is an extension. 4781 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4782 Diag(Record->getLocation(), diag::ext_anonymous_union); 4783 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4784 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4785 else if (!Record->isUnion() && !getLangOpts().C11) 4786 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4787 4788 // C and C++ require different kinds of checks for anonymous 4789 // structs/unions. 4790 bool Invalid = false; 4791 if (getLangOpts().CPlusPlus) { 4792 const char *PrevSpec = nullptr; 4793 if (Record->isUnion()) { 4794 // C++ [class.union]p6: 4795 // C++17 [class.union.anon]p2: 4796 // Anonymous unions declared in a named namespace or in the 4797 // global namespace shall be declared static. 4798 unsigned DiagID; 4799 DeclContext *OwnerScope = Owner->getRedeclContext(); 4800 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4801 (OwnerScope->isTranslationUnit() || 4802 (OwnerScope->isNamespace() && 4803 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4804 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4805 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4806 4807 // Recover by adding 'static'. 4808 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4809 PrevSpec, DiagID, Policy); 4810 } 4811 // C++ [class.union]p6: 4812 // A storage class is not allowed in a declaration of an 4813 // anonymous union in a class scope. 4814 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4815 isa<RecordDecl>(Owner)) { 4816 Diag(DS.getStorageClassSpecLoc(), 4817 diag::err_anonymous_union_with_storage_spec) 4818 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4819 4820 // Recover by removing the storage specifier. 4821 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4822 SourceLocation(), 4823 PrevSpec, DiagID, Context.getPrintingPolicy()); 4824 } 4825 } 4826 4827 // Ignore const/volatile/restrict qualifiers. 4828 if (DS.getTypeQualifiers()) { 4829 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4830 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4831 << Record->isUnion() << "const" 4832 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4833 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4834 Diag(DS.getVolatileSpecLoc(), 4835 diag::ext_anonymous_struct_union_qualified) 4836 << Record->isUnion() << "volatile" 4837 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4838 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4839 Diag(DS.getRestrictSpecLoc(), 4840 diag::ext_anonymous_struct_union_qualified) 4841 << Record->isUnion() << "restrict" 4842 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4843 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4844 Diag(DS.getAtomicSpecLoc(), 4845 diag::ext_anonymous_struct_union_qualified) 4846 << Record->isUnion() << "_Atomic" 4847 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4848 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4849 Diag(DS.getUnalignedSpecLoc(), 4850 diag::ext_anonymous_struct_union_qualified) 4851 << Record->isUnion() << "__unaligned" 4852 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4853 4854 DS.ClearTypeQualifiers(); 4855 } 4856 4857 // C++ [class.union]p2: 4858 // The member-specification of an anonymous union shall only 4859 // define non-static data members. [Note: nested types and 4860 // functions cannot be declared within an anonymous union. ] 4861 for (auto *Mem : Record->decls()) { 4862 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4863 // C++ [class.union]p3: 4864 // An anonymous union shall not have private or protected 4865 // members (clause 11). 4866 assert(FD->getAccess() != AS_none); 4867 if (FD->getAccess() != AS_public) { 4868 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4869 << Record->isUnion() << (FD->getAccess() == AS_protected); 4870 Invalid = true; 4871 } 4872 4873 // C++ [class.union]p1 4874 // An object of a class with a non-trivial constructor, a non-trivial 4875 // copy constructor, a non-trivial destructor, or a non-trivial copy 4876 // assignment operator cannot be a member of a union, nor can an 4877 // array of such objects. 4878 if (CheckNontrivialField(FD)) 4879 Invalid = true; 4880 } else if (Mem->isImplicit()) { 4881 // Any implicit members are fine. 4882 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4883 // This is a type that showed up in an 4884 // elaborated-type-specifier inside the anonymous struct or 4885 // union, but which actually declares a type outside of the 4886 // anonymous struct or union. It's okay. 4887 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4888 if (!MemRecord->isAnonymousStructOrUnion() && 4889 MemRecord->getDeclName()) { 4890 // Visual C++ allows type definition in anonymous struct or union. 4891 if (getLangOpts().MicrosoftExt) 4892 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4893 << Record->isUnion(); 4894 else { 4895 // This is a nested type declaration. 4896 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4897 << Record->isUnion(); 4898 Invalid = true; 4899 } 4900 } else { 4901 // This is an anonymous type definition within another anonymous type. 4902 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4903 // not part of standard C++. 4904 Diag(MemRecord->getLocation(), 4905 diag::ext_anonymous_record_with_anonymous_type) 4906 << Record->isUnion(); 4907 } 4908 } else if (isa<AccessSpecDecl>(Mem)) { 4909 // Any access specifier is fine. 4910 } else if (isa<StaticAssertDecl>(Mem)) { 4911 // In C++1z, static_assert declarations are also fine. 4912 } else { 4913 // We have something that isn't a non-static data 4914 // member. Complain about it. 4915 unsigned DK = diag::err_anonymous_record_bad_member; 4916 if (isa<TypeDecl>(Mem)) 4917 DK = diag::err_anonymous_record_with_type; 4918 else if (isa<FunctionDecl>(Mem)) 4919 DK = diag::err_anonymous_record_with_function; 4920 else if (isa<VarDecl>(Mem)) 4921 DK = diag::err_anonymous_record_with_static; 4922 4923 // Visual C++ allows type definition in anonymous struct or union. 4924 if (getLangOpts().MicrosoftExt && 4925 DK == diag::err_anonymous_record_with_type) 4926 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4927 << Record->isUnion(); 4928 else { 4929 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4930 Invalid = true; 4931 } 4932 } 4933 } 4934 4935 // C++11 [class.union]p8 (DR1460): 4936 // At most one variant member of a union may have a 4937 // brace-or-equal-initializer. 4938 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4939 Owner->isRecord()) 4940 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4941 cast<CXXRecordDecl>(Record)); 4942 } 4943 4944 if (!Record->isUnion() && !Owner->isRecord()) { 4945 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4946 << getLangOpts().CPlusPlus; 4947 Invalid = true; 4948 } 4949 4950 // C++ [dcl.dcl]p3: 4951 // [If there are no declarators], and except for the declaration of an 4952 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4953 // names into the program 4954 // C++ [class.mem]p2: 4955 // each such member-declaration shall either declare at least one member 4956 // name of the class or declare at least one unnamed bit-field 4957 // 4958 // For C this is an error even for a named struct, and is diagnosed elsewhere. 4959 if (getLangOpts().CPlusPlus && Record->field_empty()) 4960 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4961 4962 // Mock up a declarator. 4963 Declarator Dc(DS, DeclaratorContext::MemberContext); 4964 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4965 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4966 4967 // Create a declaration for this anonymous struct/union. 4968 NamedDecl *Anon = nullptr; 4969 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4970 Anon = FieldDecl::Create( 4971 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 4972 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 4973 /*BitWidth=*/nullptr, /*Mutable=*/false, 4974 /*InitStyle=*/ICIS_NoInit); 4975 Anon->setAccess(AS); 4976 if (getLangOpts().CPlusPlus) 4977 FieldCollector->Add(cast<FieldDecl>(Anon)); 4978 } else { 4979 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4980 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4981 if (SCSpec == DeclSpec::SCS_mutable) { 4982 // mutable can only appear on non-static class members, so it's always 4983 // an error here 4984 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4985 Invalid = true; 4986 SC = SC_None; 4987 } 4988 4989 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 4990 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4991 Context.getTypeDeclType(Record), TInfo, SC); 4992 4993 // Default-initialize the implicit variable. This initialization will be 4994 // trivial in almost all cases, except if a union member has an in-class 4995 // initializer: 4996 // union { int n = 0; }; 4997 ActOnUninitializedDecl(Anon); 4998 } 4999 Anon->setImplicit(); 5000 5001 // Mark this as an anonymous struct/union type. 5002 Record->setAnonymousStructOrUnion(true); 5003 5004 // Add the anonymous struct/union object to the current 5005 // context. We'll be referencing this object when we refer to one of 5006 // its members. 5007 Owner->addDecl(Anon); 5008 5009 // Inject the members of the anonymous struct/union into the owning 5010 // context and into the identifier resolver chain for name lookup 5011 // purposes. 5012 SmallVector<NamedDecl*, 2> Chain; 5013 Chain.push_back(Anon); 5014 5015 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5016 Invalid = true; 5017 5018 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5019 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5020 Decl *ManglingContextDecl; 5021 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 5022 NewVD->getDeclContext(), ManglingContextDecl)) { 5023 Context.setManglingNumber( 5024 NewVD, MCtx->getManglingNumber( 5025 NewVD, getMSManglingNumber(getLangOpts(), S))); 5026 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5027 } 5028 } 5029 } 5030 5031 if (Invalid) 5032 Anon->setInvalidDecl(); 5033 5034 return Anon; 5035 } 5036 5037 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5038 /// Microsoft C anonymous structure. 5039 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5040 /// Example: 5041 /// 5042 /// struct A { int a; }; 5043 /// struct B { struct A; int b; }; 5044 /// 5045 /// void foo() { 5046 /// B var; 5047 /// var.a = 3; 5048 /// } 5049 /// 5050 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5051 RecordDecl *Record) { 5052 assert(Record && "expected a record!"); 5053 5054 // Mock up a declarator. 5055 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5056 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5057 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5058 5059 auto *ParentDecl = cast<RecordDecl>(CurContext); 5060 QualType RecTy = Context.getTypeDeclType(Record); 5061 5062 // Create a declaration for this anonymous struct. 5063 NamedDecl *Anon = 5064 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5065 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5066 /*BitWidth=*/nullptr, /*Mutable=*/false, 5067 /*InitStyle=*/ICIS_NoInit); 5068 Anon->setImplicit(); 5069 5070 // Add the anonymous struct object to the current context. 5071 CurContext->addDecl(Anon); 5072 5073 // Inject the members of the anonymous struct into the current 5074 // context and into the identifier resolver chain for name lookup 5075 // purposes. 5076 SmallVector<NamedDecl*, 2> Chain; 5077 Chain.push_back(Anon); 5078 5079 RecordDecl *RecordDef = Record->getDefinition(); 5080 if (RequireCompleteType(Anon->getLocation(), RecTy, 5081 diag::err_field_incomplete) || 5082 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5083 AS_none, Chain)) { 5084 Anon->setInvalidDecl(); 5085 ParentDecl->setInvalidDecl(); 5086 } 5087 5088 return Anon; 5089 } 5090 5091 /// GetNameForDeclarator - Determine the full declaration name for the 5092 /// given Declarator. 5093 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5094 return GetNameFromUnqualifiedId(D.getName()); 5095 } 5096 5097 /// Retrieves the declaration name from a parsed unqualified-id. 5098 DeclarationNameInfo 5099 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5100 DeclarationNameInfo NameInfo; 5101 NameInfo.setLoc(Name.StartLocation); 5102 5103 switch (Name.getKind()) { 5104 5105 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5106 case UnqualifiedIdKind::IK_Identifier: 5107 NameInfo.setName(Name.Identifier); 5108 return NameInfo; 5109 5110 case UnqualifiedIdKind::IK_DeductionGuideName: { 5111 // C++ [temp.deduct.guide]p3: 5112 // The simple-template-id shall name a class template specialization. 5113 // The template-name shall be the same identifier as the template-name 5114 // of the simple-template-id. 5115 // These together intend to imply that the template-name shall name a 5116 // class template. 5117 // FIXME: template<typename T> struct X {}; 5118 // template<typename T> using Y = X<T>; 5119 // Y(int) -> Y<int>; 5120 // satisfies these rules but does not name a class template. 5121 TemplateName TN = Name.TemplateName.get().get(); 5122 auto *Template = TN.getAsTemplateDecl(); 5123 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5124 Diag(Name.StartLocation, 5125 diag::err_deduction_guide_name_not_class_template) 5126 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5127 if (Template) 5128 Diag(Template->getLocation(), diag::note_template_decl_here); 5129 return DeclarationNameInfo(); 5130 } 5131 5132 NameInfo.setName( 5133 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5134 return NameInfo; 5135 } 5136 5137 case UnqualifiedIdKind::IK_OperatorFunctionId: 5138 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5139 Name.OperatorFunctionId.Operator)); 5140 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5141 = Name.OperatorFunctionId.SymbolLocations[0]; 5142 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5143 = Name.EndLocation.getRawEncoding(); 5144 return NameInfo; 5145 5146 case UnqualifiedIdKind::IK_LiteralOperatorId: 5147 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5148 Name.Identifier)); 5149 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5150 return NameInfo; 5151 5152 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5153 TypeSourceInfo *TInfo; 5154 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5155 if (Ty.isNull()) 5156 return DeclarationNameInfo(); 5157 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5158 Context.getCanonicalType(Ty))); 5159 NameInfo.setNamedTypeInfo(TInfo); 5160 return NameInfo; 5161 } 5162 5163 case UnqualifiedIdKind::IK_ConstructorName: { 5164 TypeSourceInfo *TInfo; 5165 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5166 if (Ty.isNull()) 5167 return DeclarationNameInfo(); 5168 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5169 Context.getCanonicalType(Ty))); 5170 NameInfo.setNamedTypeInfo(TInfo); 5171 return NameInfo; 5172 } 5173 5174 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5175 // In well-formed code, we can only have a constructor 5176 // template-id that refers to the current context, so go there 5177 // to find the actual type being constructed. 5178 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5179 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5180 return DeclarationNameInfo(); 5181 5182 // Determine the type of the class being constructed. 5183 QualType CurClassType = Context.getTypeDeclType(CurClass); 5184 5185 // FIXME: Check two things: that the template-id names the same type as 5186 // CurClassType, and that the template-id does not occur when the name 5187 // was qualified. 5188 5189 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5190 Context.getCanonicalType(CurClassType))); 5191 // FIXME: should we retrieve TypeSourceInfo? 5192 NameInfo.setNamedTypeInfo(nullptr); 5193 return NameInfo; 5194 } 5195 5196 case UnqualifiedIdKind::IK_DestructorName: { 5197 TypeSourceInfo *TInfo; 5198 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5199 if (Ty.isNull()) 5200 return DeclarationNameInfo(); 5201 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5202 Context.getCanonicalType(Ty))); 5203 NameInfo.setNamedTypeInfo(TInfo); 5204 return NameInfo; 5205 } 5206 5207 case UnqualifiedIdKind::IK_TemplateId: { 5208 TemplateName TName = Name.TemplateId->Template.get(); 5209 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5210 return Context.getNameForTemplate(TName, TNameLoc); 5211 } 5212 5213 } // switch (Name.getKind()) 5214 5215 llvm_unreachable("Unknown name kind"); 5216 } 5217 5218 static QualType getCoreType(QualType Ty) { 5219 do { 5220 if (Ty->isPointerType() || Ty->isReferenceType()) 5221 Ty = Ty->getPointeeType(); 5222 else if (Ty->isArrayType()) 5223 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5224 else 5225 return Ty.withoutLocalFastQualifiers(); 5226 } while (true); 5227 } 5228 5229 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5230 /// and Definition have "nearly" matching parameters. This heuristic is 5231 /// used to improve diagnostics in the case where an out-of-line function 5232 /// definition doesn't match any declaration within the class or namespace. 5233 /// Also sets Params to the list of indices to the parameters that differ 5234 /// between the declaration and the definition. If hasSimilarParameters 5235 /// returns true and Params is empty, then all of the parameters match. 5236 static bool hasSimilarParameters(ASTContext &Context, 5237 FunctionDecl *Declaration, 5238 FunctionDecl *Definition, 5239 SmallVectorImpl<unsigned> &Params) { 5240 Params.clear(); 5241 if (Declaration->param_size() != Definition->param_size()) 5242 return false; 5243 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5244 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5245 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5246 5247 // The parameter types are identical 5248 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5249 continue; 5250 5251 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5252 QualType DefParamBaseTy = getCoreType(DefParamTy); 5253 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5254 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5255 5256 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5257 (DeclTyName && DeclTyName == DefTyName)) 5258 Params.push_back(Idx); 5259 else // The two parameters aren't even close 5260 return false; 5261 } 5262 5263 return true; 5264 } 5265 5266 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5267 /// declarator needs to be rebuilt in the current instantiation. 5268 /// Any bits of declarator which appear before the name are valid for 5269 /// consideration here. That's specifically the type in the decl spec 5270 /// and the base type in any member-pointer chunks. 5271 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5272 DeclarationName Name) { 5273 // The types we specifically need to rebuild are: 5274 // - typenames, typeofs, and decltypes 5275 // - types which will become injected class names 5276 // Of course, we also need to rebuild any type referencing such a 5277 // type. It's safest to just say "dependent", but we call out a 5278 // few cases here. 5279 5280 DeclSpec &DS = D.getMutableDeclSpec(); 5281 switch (DS.getTypeSpecType()) { 5282 case DeclSpec::TST_typename: 5283 case DeclSpec::TST_typeofType: 5284 case DeclSpec::TST_underlyingType: 5285 case DeclSpec::TST_atomic: { 5286 // Grab the type from the parser. 5287 TypeSourceInfo *TSI = nullptr; 5288 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5289 if (T.isNull() || !T->isDependentType()) break; 5290 5291 // Make sure there's a type source info. This isn't really much 5292 // of a waste; most dependent types should have type source info 5293 // attached already. 5294 if (!TSI) 5295 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5296 5297 // Rebuild the type in the current instantiation. 5298 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5299 if (!TSI) return true; 5300 5301 // Store the new type back in the decl spec. 5302 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5303 DS.UpdateTypeRep(LocType); 5304 break; 5305 } 5306 5307 case DeclSpec::TST_decltype: 5308 case DeclSpec::TST_typeofExpr: { 5309 Expr *E = DS.getRepAsExpr(); 5310 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5311 if (Result.isInvalid()) return true; 5312 DS.UpdateExprRep(Result.get()); 5313 break; 5314 } 5315 5316 default: 5317 // Nothing to do for these decl specs. 5318 break; 5319 } 5320 5321 // It doesn't matter what order we do this in. 5322 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5323 DeclaratorChunk &Chunk = D.getTypeObject(I); 5324 5325 // The only type information in the declarator which can come 5326 // before the declaration name is the base type of a member 5327 // pointer. 5328 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5329 continue; 5330 5331 // Rebuild the scope specifier in-place. 5332 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5333 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5334 return true; 5335 } 5336 5337 return false; 5338 } 5339 5340 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5341 D.setFunctionDefinitionKind(FDK_Declaration); 5342 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5343 5344 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5345 Dcl && Dcl->getDeclContext()->isFileContext()) 5346 Dcl->setTopLevelDeclInObjCContainer(); 5347 5348 if (getLangOpts().OpenCL) 5349 setCurrentOpenCLExtensionForDecl(Dcl); 5350 5351 return Dcl; 5352 } 5353 5354 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5355 /// If T is the name of a class, then each of the following shall have a 5356 /// name different from T: 5357 /// - every static data member of class T; 5358 /// - every member function of class T 5359 /// - every member of class T that is itself a type; 5360 /// \returns true if the declaration name violates these rules. 5361 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5362 DeclarationNameInfo NameInfo) { 5363 DeclarationName Name = NameInfo.getName(); 5364 5365 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5366 while (Record && Record->isAnonymousStructOrUnion()) 5367 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5368 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5369 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5370 return true; 5371 } 5372 5373 return false; 5374 } 5375 5376 /// Diagnose a declaration whose declarator-id has the given 5377 /// nested-name-specifier. 5378 /// 5379 /// \param SS The nested-name-specifier of the declarator-id. 5380 /// 5381 /// \param DC The declaration context to which the nested-name-specifier 5382 /// resolves. 5383 /// 5384 /// \param Name The name of the entity being declared. 5385 /// 5386 /// \param Loc The location of the name of the entity being declared. 5387 /// 5388 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5389 /// we're declaring an explicit / partial specialization / instantiation. 5390 /// 5391 /// \returns true if we cannot safely recover from this error, false otherwise. 5392 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5393 DeclarationName Name, 5394 SourceLocation Loc, bool IsTemplateId) { 5395 DeclContext *Cur = CurContext; 5396 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5397 Cur = Cur->getParent(); 5398 5399 // If the user provided a superfluous scope specifier that refers back to the 5400 // class in which the entity is already declared, diagnose and ignore it. 5401 // 5402 // class X { 5403 // void X::f(); 5404 // }; 5405 // 5406 // Note, it was once ill-formed to give redundant qualification in all 5407 // contexts, but that rule was removed by DR482. 5408 if (Cur->Equals(DC)) { 5409 if (Cur->isRecord()) { 5410 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5411 : diag::err_member_extra_qualification) 5412 << Name << FixItHint::CreateRemoval(SS.getRange()); 5413 SS.clear(); 5414 } else { 5415 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5416 } 5417 return false; 5418 } 5419 5420 // Check whether the qualifying scope encloses the scope of the original 5421 // declaration. For a template-id, we perform the checks in 5422 // CheckTemplateSpecializationScope. 5423 if (!Cur->Encloses(DC) && !IsTemplateId) { 5424 if (Cur->isRecord()) 5425 Diag(Loc, diag::err_member_qualification) 5426 << Name << SS.getRange(); 5427 else if (isa<TranslationUnitDecl>(DC)) 5428 Diag(Loc, diag::err_invalid_declarator_global_scope) 5429 << Name << SS.getRange(); 5430 else if (isa<FunctionDecl>(Cur)) 5431 Diag(Loc, diag::err_invalid_declarator_in_function) 5432 << Name << SS.getRange(); 5433 else if (isa<BlockDecl>(Cur)) 5434 Diag(Loc, diag::err_invalid_declarator_in_block) 5435 << Name << SS.getRange(); 5436 else 5437 Diag(Loc, diag::err_invalid_declarator_scope) 5438 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5439 5440 return true; 5441 } 5442 5443 if (Cur->isRecord()) { 5444 // Cannot qualify members within a class. 5445 Diag(Loc, diag::err_member_qualification) 5446 << Name << SS.getRange(); 5447 SS.clear(); 5448 5449 // C++ constructors and destructors with incorrect scopes can break 5450 // our AST invariants by having the wrong underlying types. If 5451 // that's the case, then drop this declaration entirely. 5452 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5453 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5454 !Context.hasSameType(Name.getCXXNameType(), 5455 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5456 return true; 5457 5458 return false; 5459 } 5460 5461 // C++11 [dcl.meaning]p1: 5462 // [...] "The nested-name-specifier of the qualified declarator-id shall 5463 // not begin with a decltype-specifer" 5464 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5465 while (SpecLoc.getPrefix()) 5466 SpecLoc = SpecLoc.getPrefix(); 5467 if (dyn_cast_or_null<DecltypeType>( 5468 SpecLoc.getNestedNameSpecifier()->getAsType())) 5469 Diag(Loc, diag::err_decltype_in_declarator) 5470 << SpecLoc.getTypeLoc().getSourceRange(); 5471 5472 return false; 5473 } 5474 5475 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5476 MultiTemplateParamsArg TemplateParamLists) { 5477 // TODO: consider using NameInfo for diagnostic. 5478 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5479 DeclarationName Name = NameInfo.getName(); 5480 5481 // All of these full declarators require an identifier. If it doesn't have 5482 // one, the ParsedFreeStandingDeclSpec action should be used. 5483 if (D.isDecompositionDeclarator()) { 5484 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5485 } else if (!Name) { 5486 if (!D.isInvalidType()) // Reject this if we think it is valid. 5487 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5488 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5489 return nullptr; 5490 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5491 return nullptr; 5492 5493 // The scope passed in may not be a decl scope. Zip up the scope tree until 5494 // we find one that is. 5495 while ((S->getFlags() & Scope::DeclScope) == 0 || 5496 (S->getFlags() & Scope::TemplateParamScope) != 0) 5497 S = S->getParent(); 5498 5499 DeclContext *DC = CurContext; 5500 if (D.getCXXScopeSpec().isInvalid()) 5501 D.setInvalidType(); 5502 else if (D.getCXXScopeSpec().isSet()) { 5503 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5504 UPPC_DeclarationQualifier)) 5505 return nullptr; 5506 5507 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5508 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5509 if (!DC || isa<EnumDecl>(DC)) { 5510 // If we could not compute the declaration context, it's because the 5511 // declaration context is dependent but does not refer to a class, 5512 // class template, or class template partial specialization. Complain 5513 // and return early, to avoid the coming semantic disaster. 5514 Diag(D.getIdentifierLoc(), 5515 diag::err_template_qualified_declarator_no_match) 5516 << D.getCXXScopeSpec().getScopeRep() 5517 << D.getCXXScopeSpec().getRange(); 5518 return nullptr; 5519 } 5520 bool IsDependentContext = DC->isDependentContext(); 5521 5522 if (!IsDependentContext && 5523 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5524 return nullptr; 5525 5526 // If a class is incomplete, do not parse entities inside it. 5527 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5528 Diag(D.getIdentifierLoc(), 5529 diag::err_member_def_undefined_record) 5530 << Name << DC << D.getCXXScopeSpec().getRange(); 5531 return nullptr; 5532 } 5533 if (!D.getDeclSpec().isFriendSpecified()) { 5534 if (diagnoseQualifiedDeclaration( 5535 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5536 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5537 if (DC->isRecord()) 5538 return nullptr; 5539 5540 D.setInvalidType(); 5541 } 5542 } 5543 5544 // Check whether we need to rebuild the type of the given 5545 // declaration in the current instantiation. 5546 if (EnteringContext && IsDependentContext && 5547 TemplateParamLists.size() != 0) { 5548 ContextRAII SavedContext(*this, DC); 5549 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5550 D.setInvalidType(); 5551 } 5552 } 5553 5554 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5555 QualType R = TInfo->getType(); 5556 5557 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5558 UPPC_DeclarationType)) 5559 D.setInvalidType(); 5560 5561 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5562 forRedeclarationInCurContext()); 5563 5564 // See if this is a redefinition of a variable in the same scope. 5565 if (!D.getCXXScopeSpec().isSet()) { 5566 bool IsLinkageLookup = false; 5567 bool CreateBuiltins = false; 5568 5569 // If the declaration we're planning to build will be a function 5570 // or object with linkage, then look for another declaration with 5571 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5572 // 5573 // If the declaration we're planning to build will be declared with 5574 // external linkage in the translation unit, create any builtin with 5575 // the same name. 5576 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5577 /* Do nothing*/; 5578 else if (CurContext->isFunctionOrMethod() && 5579 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5580 R->isFunctionType())) { 5581 IsLinkageLookup = true; 5582 CreateBuiltins = 5583 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5584 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5585 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5586 CreateBuiltins = true; 5587 5588 if (IsLinkageLookup) { 5589 Previous.clear(LookupRedeclarationWithLinkage); 5590 Previous.setRedeclarationKind(ForExternalRedeclaration); 5591 } 5592 5593 LookupName(Previous, S, CreateBuiltins); 5594 } else { // Something like "int foo::x;" 5595 LookupQualifiedName(Previous, DC); 5596 5597 // C++ [dcl.meaning]p1: 5598 // When the declarator-id is qualified, the declaration shall refer to a 5599 // previously declared member of the class or namespace to which the 5600 // qualifier refers (or, in the case of a namespace, of an element of the 5601 // inline namespace set of that namespace (7.3.1)) or to a specialization 5602 // thereof; [...] 5603 // 5604 // Note that we already checked the context above, and that we do not have 5605 // enough information to make sure that Previous contains the declaration 5606 // we want to match. For example, given: 5607 // 5608 // class X { 5609 // void f(); 5610 // void f(float); 5611 // }; 5612 // 5613 // void X::f(int) { } // ill-formed 5614 // 5615 // In this case, Previous will point to the overload set 5616 // containing the two f's declared in X, but neither of them 5617 // matches. 5618 5619 // C++ [dcl.meaning]p1: 5620 // [...] the member shall not merely have been introduced by a 5621 // using-declaration in the scope of the class or namespace nominated by 5622 // the nested-name-specifier of the declarator-id. 5623 RemoveUsingDecls(Previous); 5624 } 5625 5626 if (Previous.isSingleResult() && 5627 Previous.getFoundDecl()->isTemplateParameter()) { 5628 // Maybe we will complain about the shadowed template parameter. 5629 if (!D.isInvalidType()) 5630 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5631 Previous.getFoundDecl()); 5632 5633 // Just pretend that we didn't see the previous declaration. 5634 Previous.clear(); 5635 } 5636 5637 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5638 // Forget that the previous declaration is the injected-class-name. 5639 Previous.clear(); 5640 5641 // In C++, the previous declaration we find might be a tag type 5642 // (class or enum). In this case, the new declaration will hide the 5643 // tag type. Note that this applies to functions, function templates, and 5644 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5645 if (Previous.isSingleTagDecl() && 5646 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5647 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5648 Previous.clear(); 5649 5650 // Check that there are no default arguments other than in the parameters 5651 // of a function declaration (C++ only). 5652 if (getLangOpts().CPlusPlus) 5653 CheckExtraCXXDefaultArguments(D); 5654 5655 NamedDecl *New; 5656 5657 bool AddToScope = true; 5658 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5659 if (TemplateParamLists.size()) { 5660 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5661 return nullptr; 5662 } 5663 5664 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5665 } else if (R->isFunctionType()) { 5666 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5667 TemplateParamLists, 5668 AddToScope); 5669 } else { 5670 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5671 AddToScope); 5672 } 5673 5674 if (!New) 5675 return nullptr; 5676 5677 // If this has an identifier and is not a function template specialization, 5678 // add it to the scope stack. 5679 if (New->getDeclName() && AddToScope) 5680 PushOnScopeChains(New, S); 5681 5682 if (isInOpenMPDeclareTargetContext()) 5683 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5684 5685 return New; 5686 } 5687 5688 /// Helper method to turn variable array types into constant array 5689 /// types in certain situations which would otherwise be errors (for 5690 /// GCC compatibility). 5691 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5692 ASTContext &Context, 5693 bool &SizeIsNegative, 5694 llvm::APSInt &Oversized) { 5695 // This method tries to turn a variable array into a constant 5696 // array even when the size isn't an ICE. This is necessary 5697 // for compatibility with code that depends on gcc's buggy 5698 // constant expression folding, like struct {char x[(int)(char*)2];} 5699 SizeIsNegative = false; 5700 Oversized = 0; 5701 5702 if (T->isDependentType()) 5703 return QualType(); 5704 5705 QualifierCollector Qs; 5706 const Type *Ty = Qs.strip(T); 5707 5708 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5709 QualType Pointee = PTy->getPointeeType(); 5710 QualType FixedType = 5711 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5712 Oversized); 5713 if (FixedType.isNull()) return FixedType; 5714 FixedType = Context.getPointerType(FixedType); 5715 return Qs.apply(Context, FixedType); 5716 } 5717 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5718 QualType Inner = PTy->getInnerType(); 5719 QualType FixedType = 5720 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5721 Oversized); 5722 if (FixedType.isNull()) return FixedType; 5723 FixedType = Context.getParenType(FixedType); 5724 return Qs.apply(Context, FixedType); 5725 } 5726 5727 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5728 if (!VLATy) 5729 return QualType(); 5730 // FIXME: We should probably handle this case 5731 if (VLATy->getElementType()->isVariablyModifiedType()) 5732 return QualType(); 5733 5734 Expr::EvalResult Result; 5735 if (!VLATy->getSizeExpr() || 5736 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5737 return QualType(); 5738 5739 llvm::APSInt Res = Result.Val.getInt(); 5740 5741 // Check whether the array size is negative. 5742 if (Res.isSigned() && Res.isNegative()) { 5743 SizeIsNegative = true; 5744 return QualType(); 5745 } 5746 5747 // Check whether the array is too large to be addressed. 5748 unsigned ActiveSizeBits 5749 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5750 Res); 5751 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5752 Oversized = Res; 5753 return QualType(); 5754 } 5755 5756 return Context.getConstantArrayType(VLATy->getElementType(), 5757 Res, ArrayType::Normal, 0); 5758 } 5759 5760 static void 5761 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5762 SrcTL = SrcTL.getUnqualifiedLoc(); 5763 DstTL = DstTL.getUnqualifiedLoc(); 5764 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5765 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5766 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5767 DstPTL.getPointeeLoc()); 5768 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5769 return; 5770 } 5771 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5772 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5773 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5774 DstPTL.getInnerLoc()); 5775 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5776 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5777 return; 5778 } 5779 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5780 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5781 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5782 TypeLoc DstElemTL = DstATL.getElementLoc(); 5783 DstElemTL.initializeFullCopy(SrcElemTL); 5784 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5785 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5786 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5787 } 5788 5789 /// Helper method to turn variable array types into constant array 5790 /// types in certain situations which would otherwise be errors (for 5791 /// GCC compatibility). 5792 static TypeSourceInfo* 5793 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5794 ASTContext &Context, 5795 bool &SizeIsNegative, 5796 llvm::APSInt &Oversized) { 5797 QualType FixedTy 5798 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5799 SizeIsNegative, Oversized); 5800 if (FixedTy.isNull()) 5801 return nullptr; 5802 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5803 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5804 FixedTInfo->getTypeLoc()); 5805 return FixedTInfo; 5806 } 5807 5808 /// Register the given locally-scoped extern "C" declaration so 5809 /// that it can be found later for redeclarations. We include any extern "C" 5810 /// declaration that is not visible in the translation unit here, not just 5811 /// function-scope declarations. 5812 void 5813 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5814 if (!getLangOpts().CPlusPlus && 5815 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5816 // Don't need to track declarations in the TU in C. 5817 return; 5818 5819 // Note that we have a locally-scoped external with this name. 5820 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5821 } 5822 5823 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5824 // FIXME: We can have multiple results via __attribute__((overloadable)). 5825 auto Result = Context.getExternCContextDecl()->lookup(Name); 5826 return Result.empty() ? nullptr : *Result.begin(); 5827 } 5828 5829 /// Diagnose function specifiers on a declaration of an identifier that 5830 /// does not identify a function. 5831 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5832 // FIXME: We should probably indicate the identifier in question to avoid 5833 // confusion for constructs like "virtual int a(), b;" 5834 if (DS.isVirtualSpecified()) 5835 Diag(DS.getVirtualSpecLoc(), 5836 diag::err_virtual_non_function); 5837 5838 if (DS.hasExplicitSpecifier()) 5839 Diag(DS.getExplicitSpecLoc(), 5840 diag::err_explicit_non_function); 5841 5842 if (DS.isNoreturnSpecified()) 5843 Diag(DS.getNoreturnSpecLoc(), 5844 diag::err_noreturn_non_function); 5845 } 5846 5847 NamedDecl* 5848 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5849 TypeSourceInfo *TInfo, LookupResult &Previous) { 5850 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5851 if (D.getCXXScopeSpec().isSet()) { 5852 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5853 << D.getCXXScopeSpec().getRange(); 5854 D.setInvalidType(); 5855 // Pretend we didn't see the scope specifier. 5856 DC = CurContext; 5857 Previous.clear(); 5858 } 5859 5860 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5861 5862 if (D.getDeclSpec().isInlineSpecified()) 5863 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5864 << getLangOpts().CPlusPlus17; 5865 if (D.getDeclSpec().hasConstexprSpecifier()) 5866 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5867 << 1 << D.getDeclSpec().getConstexprSpecifier(); 5868 5869 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5870 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5871 Diag(D.getName().StartLocation, 5872 diag::err_deduction_guide_invalid_specifier) 5873 << "typedef"; 5874 else 5875 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5876 << D.getName().getSourceRange(); 5877 return nullptr; 5878 } 5879 5880 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5881 if (!NewTD) return nullptr; 5882 5883 // Handle attributes prior to checking for duplicates in MergeVarDecl 5884 ProcessDeclAttributes(S, NewTD, D); 5885 5886 CheckTypedefForVariablyModifiedType(S, NewTD); 5887 5888 bool Redeclaration = D.isRedeclaration(); 5889 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5890 D.setRedeclaration(Redeclaration); 5891 return ND; 5892 } 5893 5894 void 5895 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5896 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5897 // then it shall have block scope. 5898 // Note that variably modified types must be fixed before merging the decl so 5899 // that redeclarations will match. 5900 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5901 QualType T = TInfo->getType(); 5902 if (T->isVariablyModifiedType()) { 5903 setFunctionHasBranchProtectedScope(); 5904 5905 if (S->getFnParent() == nullptr) { 5906 bool SizeIsNegative; 5907 llvm::APSInt Oversized; 5908 TypeSourceInfo *FixedTInfo = 5909 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5910 SizeIsNegative, 5911 Oversized); 5912 if (FixedTInfo) { 5913 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5914 NewTD->setTypeSourceInfo(FixedTInfo); 5915 } else { 5916 if (SizeIsNegative) 5917 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5918 else if (T->isVariableArrayType()) 5919 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5920 else if (Oversized.getBoolValue()) 5921 Diag(NewTD->getLocation(), diag::err_array_too_large) 5922 << Oversized.toString(10); 5923 else 5924 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5925 NewTD->setInvalidDecl(); 5926 } 5927 } 5928 } 5929 } 5930 5931 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5932 /// declares a typedef-name, either using the 'typedef' type specifier or via 5933 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5934 NamedDecl* 5935 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5936 LookupResult &Previous, bool &Redeclaration) { 5937 5938 // Find the shadowed declaration before filtering for scope. 5939 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5940 5941 // Merge the decl with the existing one if appropriate. If the decl is 5942 // in an outer scope, it isn't the same thing. 5943 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5944 /*AllowInlineNamespace*/false); 5945 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5946 if (!Previous.empty()) { 5947 Redeclaration = true; 5948 MergeTypedefNameDecl(S, NewTD, Previous); 5949 } else { 5950 inferGslPointerAttribute(NewTD); 5951 } 5952 5953 if (ShadowedDecl && !Redeclaration) 5954 CheckShadow(NewTD, ShadowedDecl, Previous); 5955 5956 // If this is the C FILE type, notify the AST context. 5957 if (IdentifierInfo *II = NewTD->getIdentifier()) 5958 if (!NewTD->isInvalidDecl() && 5959 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5960 if (II->isStr("FILE")) 5961 Context.setFILEDecl(NewTD); 5962 else if (II->isStr("jmp_buf")) 5963 Context.setjmp_bufDecl(NewTD); 5964 else if (II->isStr("sigjmp_buf")) 5965 Context.setsigjmp_bufDecl(NewTD); 5966 else if (II->isStr("ucontext_t")) 5967 Context.setucontext_tDecl(NewTD); 5968 } 5969 5970 return NewTD; 5971 } 5972 5973 /// Determines whether the given declaration is an out-of-scope 5974 /// previous declaration. 5975 /// 5976 /// This routine should be invoked when name lookup has found a 5977 /// previous declaration (PrevDecl) that is not in the scope where a 5978 /// new declaration by the same name is being introduced. If the new 5979 /// declaration occurs in a local scope, previous declarations with 5980 /// linkage may still be considered previous declarations (C99 5981 /// 6.2.2p4-5, C++ [basic.link]p6). 5982 /// 5983 /// \param PrevDecl the previous declaration found by name 5984 /// lookup 5985 /// 5986 /// \param DC the context in which the new declaration is being 5987 /// declared. 5988 /// 5989 /// \returns true if PrevDecl is an out-of-scope previous declaration 5990 /// for a new delcaration with the same name. 5991 static bool 5992 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5993 ASTContext &Context) { 5994 if (!PrevDecl) 5995 return false; 5996 5997 if (!PrevDecl->hasLinkage()) 5998 return false; 5999 6000 if (Context.getLangOpts().CPlusPlus) { 6001 // C++ [basic.link]p6: 6002 // If there is a visible declaration of an entity with linkage 6003 // having the same name and type, ignoring entities declared 6004 // outside the innermost enclosing namespace scope, the block 6005 // scope declaration declares that same entity and receives the 6006 // linkage of the previous declaration. 6007 DeclContext *OuterContext = DC->getRedeclContext(); 6008 if (!OuterContext->isFunctionOrMethod()) 6009 // This rule only applies to block-scope declarations. 6010 return false; 6011 6012 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6013 if (PrevOuterContext->isRecord()) 6014 // We found a member function: ignore it. 6015 return false; 6016 6017 // Find the innermost enclosing namespace for the new and 6018 // previous declarations. 6019 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6020 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6021 6022 // The previous declaration is in a different namespace, so it 6023 // isn't the same function. 6024 if (!OuterContext->Equals(PrevOuterContext)) 6025 return false; 6026 } 6027 6028 return true; 6029 } 6030 6031 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6032 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6033 if (!SS.isSet()) return; 6034 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6035 } 6036 6037 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6038 QualType type = decl->getType(); 6039 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6040 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6041 // Various kinds of declaration aren't allowed to be __autoreleasing. 6042 unsigned kind = -1U; 6043 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6044 if (var->hasAttr<BlocksAttr>()) 6045 kind = 0; // __block 6046 else if (!var->hasLocalStorage()) 6047 kind = 1; // global 6048 } else if (isa<ObjCIvarDecl>(decl)) { 6049 kind = 3; // ivar 6050 } else if (isa<FieldDecl>(decl)) { 6051 kind = 2; // field 6052 } 6053 6054 if (kind != -1U) { 6055 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6056 << kind; 6057 } 6058 } else if (lifetime == Qualifiers::OCL_None) { 6059 // Try to infer lifetime. 6060 if (!type->isObjCLifetimeType()) 6061 return false; 6062 6063 lifetime = type->getObjCARCImplicitLifetime(); 6064 type = Context.getLifetimeQualifiedType(type, lifetime); 6065 decl->setType(type); 6066 } 6067 6068 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6069 // Thread-local variables cannot have lifetime. 6070 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6071 var->getTLSKind()) { 6072 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6073 << var->getType(); 6074 return true; 6075 } 6076 } 6077 6078 return false; 6079 } 6080 6081 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6082 // Ensure that an auto decl is deduced otherwise the checks below might cache 6083 // the wrong linkage. 6084 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6085 6086 // 'weak' only applies to declarations with external linkage. 6087 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6088 if (!ND.isExternallyVisible()) { 6089 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6090 ND.dropAttr<WeakAttr>(); 6091 } 6092 } 6093 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6094 if (ND.isExternallyVisible()) { 6095 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6096 ND.dropAttr<WeakRefAttr>(); 6097 ND.dropAttr<AliasAttr>(); 6098 } 6099 } 6100 6101 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6102 if (VD->hasInit()) { 6103 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6104 assert(VD->isThisDeclarationADefinition() && 6105 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6106 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6107 VD->dropAttr<AliasAttr>(); 6108 } 6109 } 6110 } 6111 6112 // 'selectany' only applies to externally visible variable declarations. 6113 // It does not apply to functions. 6114 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6115 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6116 S.Diag(Attr->getLocation(), 6117 diag::err_attribute_selectany_non_extern_data); 6118 ND.dropAttr<SelectAnyAttr>(); 6119 } 6120 } 6121 6122 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6123 auto *VD = dyn_cast<VarDecl>(&ND); 6124 bool IsAnonymousNS = false; 6125 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6126 if (VD) { 6127 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6128 while (NS && !IsAnonymousNS) { 6129 IsAnonymousNS = NS->isAnonymousNamespace(); 6130 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6131 } 6132 } 6133 // dll attributes require external linkage. Static locals may have external 6134 // linkage but still cannot be explicitly imported or exported. 6135 // In Microsoft mode, a variable defined in anonymous namespace must have 6136 // external linkage in order to be exported. 6137 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6138 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6139 (!AnonNSInMicrosoftMode && 6140 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6141 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6142 << &ND << Attr; 6143 ND.setInvalidDecl(); 6144 } 6145 } 6146 6147 // Virtual functions cannot be marked as 'notail'. 6148 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6149 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6150 if (MD->isVirtual()) { 6151 S.Diag(ND.getLocation(), 6152 diag::err_invalid_attribute_on_virtual_function) 6153 << Attr; 6154 ND.dropAttr<NotTailCalledAttr>(); 6155 } 6156 6157 // Check the attributes on the function type, if any. 6158 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6159 // Don't declare this variable in the second operand of the for-statement; 6160 // GCC miscompiles that by ending its lifetime before evaluating the 6161 // third operand. See gcc.gnu.org/PR86769. 6162 AttributedTypeLoc ATL; 6163 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6164 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6165 TL = ATL.getModifiedLoc()) { 6166 // The [[lifetimebound]] attribute can be applied to the implicit object 6167 // parameter of a non-static member function (other than a ctor or dtor) 6168 // by applying it to the function type. 6169 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6170 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6171 if (!MD || MD->isStatic()) { 6172 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6173 << !MD << A->getRange(); 6174 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6175 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6176 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6177 } 6178 } 6179 } 6180 } 6181 } 6182 6183 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6184 NamedDecl *NewDecl, 6185 bool IsSpecialization, 6186 bool IsDefinition) { 6187 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6188 return; 6189 6190 bool IsTemplate = false; 6191 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6192 OldDecl = OldTD->getTemplatedDecl(); 6193 IsTemplate = true; 6194 if (!IsSpecialization) 6195 IsDefinition = false; 6196 } 6197 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6198 NewDecl = NewTD->getTemplatedDecl(); 6199 IsTemplate = true; 6200 } 6201 6202 if (!OldDecl || !NewDecl) 6203 return; 6204 6205 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6206 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6207 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6208 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6209 6210 // dllimport and dllexport are inheritable attributes so we have to exclude 6211 // inherited attribute instances. 6212 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6213 (NewExportAttr && !NewExportAttr->isInherited()); 6214 6215 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6216 // the only exception being explicit specializations. 6217 // Implicitly generated declarations are also excluded for now because there 6218 // is no other way to switch these to use dllimport or dllexport. 6219 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6220 6221 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6222 // Allow with a warning for free functions and global variables. 6223 bool JustWarn = false; 6224 if (!OldDecl->isCXXClassMember()) { 6225 auto *VD = dyn_cast<VarDecl>(OldDecl); 6226 if (VD && !VD->getDescribedVarTemplate()) 6227 JustWarn = true; 6228 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6229 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6230 JustWarn = true; 6231 } 6232 6233 // We cannot change a declaration that's been used because IR has already 6234 // been emitted. Dllimported functions will still work though (modulo 6235 // address equality) as they can use the thunk. 6236 if (OldDecl->isUsed()) 6237 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6238 JustWarn = false; 6239 6240 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6241 : diag::err_attribute_dll_redeclaration; 6242 S.Diag(NewDecl->getLocation(), DiagID) 6243 << NewDecl 6244 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6245 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6246 if (!JustWarn) { 6247 NewDecl->setInvalidDecl(); 6248 return; 6249 } 6250 } 6251 6252 // A redeclaration is not allowed to drop a dllimport attribute, the only 6253 // exceptions being inline function definitions (except for function 6254 // templates), local extern declarations, qualified friend declarations or 6255 // special MSVC extension: in the last case, the declaration is treated as if 6256 // it were marked dllexport. 6257 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6258 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6259 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6260 // Ignore static data because out-of-line definitions are diagnosed 6261 // separately. 6262 IsStaticDataMember = VD->isStaticDataMember(); 6263 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6264 VarDecl::DeclarationOnly; 6265 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6266 IsInline = FD->isInlined(); 6267 IsQualifiedFriend = FD->getQualifier() && 6268 FD->getFriendObjectKind() == Decl::FOK_Declared; 6269 } 6270 6271 if (OldImportAttr && !HasNewAttr && 6272 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6273 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6274 if (IsMicrosoft && IsDefinition) { 6275 S.Diag(NewDecl->getLocation(), 6276 diag::warn_redeclaration_without_import_attribute) 6277 << NewDecl; 6278 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6279 NewDecl->dropAttr<DLLImportAttr>(); 6280 NewDecl->addAttr( 6281 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6282 } else { 6283 S.Diag(NewDecl->getLocation(), 6284 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6285 << NewDecl << OldImportAttr; 6286 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6287 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6288 OldDecl->dropAttr<DLLImportAttr>(); 6289 NewDecl->dropAttr<DLLImportAttr>(); 6290 } 6291 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6292 // In MinGW, seeing a function declared inline drops the dllimport 6293 // attribute. 6294 OldDecl->dropAttr<DLLImportAttr>(); 6295 NewDecl->dropAttr<DLLImportAttr>(); 6296 S.Diag(NewDecl->getLocation(), 6297 diag::warn_dllimport_dropped_from_inline_function) 6298 << NewDecl << OldImportAttr; 6299 } 6300 6301 // A specialization of a class template member function is processed here 6302 // since it's a redeclaration. If the parent class is dllexport, the 6303 // specialization inherits that attribute. This doesn't happen automatically 6304 // since the parent class isn't instantiated until later. 6305 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6306 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6307 !NewImportAttr && !NewExportAttr) { 6308 if (const DLLExportAttr *ParentExportAttr = 6309 MD->getParent()->getAttr<DLLExportAttr>()) { 6310 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6311 NewAttr->setInherited(true); 6312 NewDecl->addAttr(NewAttr); 6313 } 6314 } 6315 } 6316 } 6317 6318 /// Given that we are within the definition of the given function, 6319 /// will that definition behave like C99's 'inline', where the 6320 /// definition is discarded except for optimization purposes? 6321 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6322 // Try to avoid calling GetGVALinkageForFunction. 6323 6324 // All cases of this require the 'inline' keyword. 6325 if (!FD->isInlined()) return false; 6326 6327 // This is only possible in C++ with the gnu_inline attribute. 6328 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6329 return false; 6330 6331 // Okay, go ahead and call the relatively-more-expensive function. 6332 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6333 } 6334 6335 /// Determine whether a variable is extern "C" prior to attaching 6336 /// an initializer. We can't just call isExternC() here, because that 6337 /// will also compute and cache whether the declaration is externally 6338 /// visible, which might change when we attach the initializer. 6339 /// 6340 /// This can only be used if the declaration is known to not be a 6341 /// redeclaration of an internal linkage declaration. 6342 /// 6343 /// For instance: 6344 /// 6345 /// auto x = []{}; 6346 /// 6347 /// Attaching the initializer here makes this declaration not externally 6348 /// visible, because its type has internal linkage. 6349 /// 6350 /// FIXME: This is a hack. 6351 template<typename T> 6352 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6353 if (S.getLangOpts().CPlusPlus) { 6354 // In C++, the overloadable attribute negates the effects of extern "C". 6355 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6356 return false; 6357 6358 // So do CUDA's host/device attributes. 6359 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6360 D->template hasAttr<CUDAHostAttr>())) 6361 return false; 6362 } 6363 return D->isExternC(); 6364 } 6365 6366 static bool shouldConsiderLinkage(const VarDecl *VD) { 6367 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6368 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6369 isa<OMPDeclareMapperDecl>(DC)) 6370 return VD->hasExternalStorage(); 6371 if (DC->isFileContext()) 6372 return true; 6373 if (DC->isRecord()) 6374 return false; 6375 llvm_unreachable("Unexpected context"); 6376 } 6377 6378 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6379 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6380 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6381 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6382 return true; 6383 if (DC->isRecord()) 6384 return false; 6385 llvm_unreachable("Unexpected context"); 6386 } 6387 6388 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6389 ParsedAttr::Kind Kind) { 6390 // Check decl attributes on the DeclSpec. 6391 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6392 return true; 6393 6394 // Walk the declarator structure, checking decl attributes that were in a type 6395 // position to the decl itself. 6396 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6397 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6398 return true; 6399 } 6400 6401 // Finally, check attributes on the decl itself. 6402 return PD.getAttributes().hasAttribute(Kind); 6403 } 6404 6405 /// Adjust the \c DeclContext for a function or variable that might be a 6406 /// function-local external declaration. 6407 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6408 if (!DC->isFunctionOrMethod()) 6409 return false; 6410 6411 // If this is a local extern function or variable declared within a function 6412 // template, don't add it into the enclosing namespace scope until it is 6413 // instantiated; it might have a dependent type right now. 6414 if (DC->isDependentContext()) 6415 return true; 6416 6417 // C++11 [basic.link]p7: 6418 // When a block scope declaration of an entity with linkage is not found to 6419 // refer to some other declaration, then that entity is a member of the 6420 // innermost enclosing namespace. 6421 // 6422 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6423 // semantically-enclosing namespace, not a lexically-enclosing one. 6424 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6425 DC = DC->getParent(); 6426 return true; 6427 } 6428 6429 /// Returns true if given declaration has external C language linkage. 6430 static bool isDeclExternC(const Decl *D) { 6431 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6432 return FD->isExternC(); 6433 if (const auto *VD = dyn_cast<VarDecl>(D)) 6434 return VD->isExternC(); 6435 6436 llvm_unreachable("Unknown type of decl!"); 6437 } 6438 6439 NamedDecl *Sema::ActOnVariableDeclarator( 6440 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6441 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6442 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6443 QualType R = TInfo->getType(); 6444 DeclarationName Name = GetNameForDeclarator(D).getName(); 6445 6446 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6447 6448 if (D.isDecompositionDeclarator()) { 6449 // Take the name of the first declarator as our name for diagnostic 6450 // purposes. 6451 auto &Decomp = D.getDecompositionDeclarator(); 6452 if (!Decomp.bindings().empty()) { 6453 II = Decomp.bindings()[0].Name; 6454 Name = II; 6455 } 6456 } else if (!II) { 6457 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6458 return nullptr; 6459 } 6460 6461 if (getLangOpts().OpenCL) { 6462 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6463 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6464 // argument. 6465 if (R->isImageType() || R->isPipeType()) { 6466 Diag(D.getIdentifierLoc(), 6467 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6468 << R; 6469 D.setInvalidType(); 6470 return nullptr; 6471 } 6472 6473 // OpenCL v1.2 s6.9.r: 6474 // The event type cannot be used to declare a program scope variable. 6475 // OpenCL v2.0 s6.9.q: 6476 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6477 if (NULL == S->getParent()) { 6478 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6479 Diag(D.getIdentifierLoc(), 6480 diag::err_invalid_type_for_program_scope_var) << R; 6481 D.setInvalidType(); 6482 return nullptr; 6483 } 6484 } 6485 6486 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6487 QualType NR = R; 6488 while (NR->isPointerType()) { 6489 if (NR->isFunctionPointerType()) { 6490 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6491 D.setInvalidType(); 6492 break; 6493 } 6494 NR = NR->getPointeeType(); 6495 } 6496 6497 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6498 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6499 // half array type (unless the cl_khr_fp16 extension is enabled). 6500 if (Context.getBaseElementType(R)->isHalfType()) { 6501 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6502 D.setInvalidType(); 6503 } 6504 } 6505 6506 if (R->isSamplerT()) { 6507 // OpenCL v1.2 s6.9.b p4: 6508 // The sampler type cannot be used with the __local and __global address 6509 // space qualifiers. 6510 if (R.getAddressSpace() == LangAS::opencl_local || 6511 R.getAddressSpace() == LangAS::opencl_global) { 6512 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6513 } 6514 6515 // OpenCL v1.2 s6.12.14.1: 6516 // A global sampler must be declared with either the constant address 6517 // space qualifier or with the const qualifier. 6518 if (DC->isTranslationUnit() && 6519 !(R.getAddressSpace() == LangAS::opencl_constant || 6520 R.isConstQualified())) { 6521 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6522 D.setInvalidType(); 6523 } 6524 } 6525 6526 // OpenCL v1.2 s6.9.r: 6527 // The event type cannot be used with the __local, __constant and __global 6528 // address space qualifiers. 6529 if (R->isEventT()) { 6530 if (R.getAddressSpace() != LangAS::opencl_private) { 6531 Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6532 D.setInvalidType(); 6533 } 6534 } 6535 6536 // C++ for OpenCL does not allow the thread_local storage qualifier. 6537 // OpenCL C does not support thread_local either, and 6538 // also reject all other thread storage class specifiers. 6539 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6540 if (TSC != TSCS_unspecified) { 6541 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6542 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6543 diag::err_opencl_unknown_type_specifier) 6544 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6545 << DeclSpec::getSpecifierName(TSC) << 1; 6546 D.setInvalidType(); 6547 return nullptr; 6548 } 6549 } 6550 6551 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6552 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6553 6554 // dllimport globals without explicit storage class are treated as extern. We 6555 // have to change the storage class this early to get the right DeclContext. 6556 if (SC == SC_None && !DC->isRecord() && 6557 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6558 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6559 SC = SC_Extern; 6560 6561 DeclContext *OriginalDC = DC; 6562 bool IsLocalExternDecl = SC == SC_Extern && 6563 adjustContextForLocalExternDecl(DC); 6564 6565 if (SCSpec == DeclSpec::SCS_mutable) { 6566 // mutable can only appear on non-static class members, so it's always 6567 // an error here 6568 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6569 D.setInvalidType(); 6570 SC = SC_None; 6571 } 6572 6573 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6574 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6575 D.getDeclSpec().getStorageClassSpecLoc())) { 6576 // In C++11, the 'register' storage class specifier is deprecated. 6577 // Suppress the warning in system macros, it's used in macros in some 6578 // popular C system headers, such as in glibc's htonl() macro. 6579 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6580 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6581 : diag::warn_deprecated_register) 6582 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6583 } 6584 6585 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6586 6587 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6588 // C99 6.9p2: The storage-class specifiers auto and register shall not 6589 // appear in the declaration specifiers in an external declaration. 6590 // Global Register+Asm is a GNU extension we support. 6591 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6592 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6593 D.setInvalidType(); 6594 } 6595 } 6596 6597 bool IsMemberSpecialization = false; 6598 bool IsVariableTemplateSpecialization = false; 6599 bool IsPartialSpecialization = false; 6600 bool IsVariableTemplate = false; 6601 VarDecl *NewVD = nullptr; 6602 VarTemplateDecl *NewTemplate = nullptr; 6603 TemplateParameterList *TemplateParams = nullptr; 6604 if (!getLangOpts().CPlusPlus) { 6605 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6606 II, R, TInfo, SC); 6607 6608 if (R->getContainedDeducedType()) 6609 ParsingInitForAutoVars.insert(NewVD); 6610 6611 if (D.isInvalidType()) 6612 NewVD->setInvalidDecl(); 6613 6614 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6615 NewVD->hasLocalStorage()) 6616 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6617 NTCUC_AutoVar, NTCUK_Destruct); 6618 } else { 6619 bool Invalid = false; 6620 6621 if (DC->isRecord() && !CurContext->isRecord()) { 6622 // This is an out-of-line definition of a static data member. 6623 switch (SC) { 6624 case SC_None: 6625 break; 6626 case SC_Static: 6627 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6628 diag::err_static_out_of_line) 6629 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6630 break; 6631 case SC_Auto: 6632 case SC_Register: 6633 case SC_Extern: 6634 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6635 // to names of variables declared in a block or to function parameters. 6636 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6637 // of class members 6638 6639 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6640 diag::err_storage_class_for_static_member) 6641 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6642 break; 6643 case SC_PrivateExtern: 6644 llvm_unreachable("C storage class in c++!"); 6645 } 6646 } 6647 6648 if (SC == SC_Static && CurContext->isRecord()) { 6649 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6650 if (RD->isLocalClass()) 6651 Diag(D.getIdentifierLoc(), 6652 diag::err_static_data_member_not_allowed_in_local_class) 6653 << Name << RD->getDeclName(); 6654 6655 // C++98 [class.union]p1: If a union contains a static data member, 6656 // the program is ill-formed. C++11 drops this restriction. 6657 if (RD->isUnion()) 6658 Diag(D.getIdentifierLoc(), 6659 getLangOpts().CPlusPlus11 6660 ? diag::warn_cxx98_compat_static_data_member_in_union 6661 : diag::ext_static_data_member_in_union) << Name; 6662 // We conservatively disallow static data members in anonymous structs. 6663 else if (!RD->getDeclName()) 6664 Diag(D.getIdentifierLoc(), 6665 diag::err_static_data_member_not_allowed_in_anon_struct) 6666 << Name << RD->isUnion(); 6667 } 6668 } 6669 6670 // Match up the template parameter lists with the scope specifier, then 6671 // determine whether we have a template or a template specialization. 6672 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6673 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6674 D.getCXXScopeSpec(), 6675 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6676 ? D.getName().TemplateId 6677 : nullptr, 6678 TemplateParamLists, 6679 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6680 6681 if (TemplateParams) { 6682 if (!TemplateParams->size() && 6683 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6684 // There is an extraneous 'template<>' for this variable. Complain 6685 // about it, but allow the declaration of the variable. 6686 Diag(TemplateParams->getTemplateLoc(), 6687 diag::err_template_variable_noparams) 6688 << II 6689 << SourceRange(TemplateParams->getTemplateLoc(), 6690 TemplateParams->getRAngleLoc()); 6691 TemplateParams = nullptr; 6692 } else { 6693 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6694 // This is an explicit specialization or a partial specialization. 6695 // FIXME: Check that we can declare a specialization here. 6696 IsVariableTemplateSpecialization = true; 6697 IsPartialSpecialization = TemplateParams->size() > 0; 6698 } else { // if (TemplateParams->size() > 0) 6699 // This is a template declaration. 6700 IsVariableTemplate = true; 6701 6702 // Check that we can declare a template here. 6703 if (CheckTemplateDeclScope(S, TemplateParams)) 6704 return nullptr; 6705 6706 // Only C++1y supports variable templates (N3651). 6707 Diag(D.getIdentifierLoc(), 6708 getLangOpts().CPlusPlus14 6709 ? diag::warn_cxx11_compat_variable_template 6710 : diag::ext_variable_template); 6711 } 6712 } 6713 } else { 6714 assert((Invalid || 6715 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6716 "should have a 'template<>' for this decl"); 6717 } 6718 6719 if (IsVariableTemplateSpecialization) { 6720 SourceLocation TemplateKWLoc = 6721 TemplateParamLists.size() > 0 6722 ? TemplateParamLists[0]->getTemplateLoc() 6723 : SourceLocation(); 6724 DeclResult Res = ActOnVarTemplateSpecialization( 6725 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6726 IsPartialSpecialization); 6727 if (Res.isInvalid()) 6728 return nullptr; 6729 NewVD = cast<VarDecl>(Res.get()); 6730 AddToScope = false; 6731 } else if (D.isDecompositionDeclarator()) { 6732 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6733 D.getIdentifierLoc(), R, TInfo, SC, 6734 Bindings); 6735 } else 6736 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6737 D.getIdentifierLoc(), II, R, TInfo, SC); 6738 6739 // If this is supposed to be a variable template, create it as such. 6740 if (IsVariableTemplate) { 6741 NewTemplate = 6742 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6743 TemplateParams, NewVD); 6744 NewVD->setDescribedVarTemplate(NewTemplate); 6745 } 6746 6747 // If this decl has an auto type in need of deduction, make a note of the 6748 // Decl so we can diagnose uses of it in its own initializer. 6749 if (R->getContainedDeducedType()) 6750 ParsingInitForAutoVars.insert(NewVD); 6751 6752 if (D.isInvalidType() || Invalid) { 6753 NewVD->setInvalidDecl(); 6754 if (NewTemplate) 6755 NewTemplate->setInvalidDecl(); 6756 } 6757 6758 SetNestedNameSpecifier(*this, NewVD, D); 6759 6760 // If we have any template parameter lists that don't directly belong to 6761 // the variable (matching the scope specifier), store them. 6762 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6763 if (TemplateParamLists.size() > VDTemplateParamLists) 6764 NewVD->setTemplateParameterListsInfo( 6765 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6766 } 6767 6768 if (D.getDeclSpec().isInlineSpecified()) { 6769 if (!getLangOpts().CPlusPlus) { 6770 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6771 << 0; 6772 } else if (CurContext->isFunctionOrMethod()) { 6773 // 'inline' is not allowed on block scope variable declaration. 6774 Diag(D.getDeclSpec().getInlineSpecLoc(), 6775 diag::err_inline_declaration_block_scope) << Name 6776 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6777 } else { 6778 Diag(D.getDeclSpec().getInlineSpecLoc(), 6779 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6780 : diag::ext_inline_variable); 6781 NewVD->setInlineSpecified(); 6782 } 6783 } 6784 6785 // Set the lexical context. If the declarator has a C++ scope specifier, the 6786 // lexical context will be different from the semantic context. 6787 NewVD->setLexicalDeclContext(CurContext); 6788 if (NewTemplate) 6789 NewTemplate->setLexicalDeclContext(CurContext); 6790 6791 if (IsLocalExternDecl) { 6792 if (D.isDecompositionDeclarator()) 6793 for (auto *B : Bindings) 6794 B->setLocalExternDecl(); 6795 else 6796 NewVD->setLocalExternDecl(); 6797 } 6798 6799 bool EmitTLSUnsupportedError = false; 6800 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6801 // C++11 [dcl.stc]p4: 6802 // When thread_local is applied to a variable of block scope the 6803 // storage-class-specifier static is implied if it does not appear 6804 // explicitly. 6805 // Core issue: 'static' is not implied if the variable is declared 6806 // 'extern'. 6807 if (NewVD->hasLocalStorage() && 6808 (SCSpec != DeclSpec::SCS_unspecified || 6809 TSCS != DeclSpec::TSCS_thread_local || 6810 !DC->isFunctionOrMethod())) 6811 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6812 diag::err_thread_non_global) 6813 << DeclSpec::getSpecifierName(TSCS); 6814 else if (!Context.getTargetInfo().isTLSSupported()) { 6815 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6816 // Postpone error emission until we've collected attributes required to 6817 // figure out whether it's a host or device variable and whether the 6818 // error should be ignored. 6819 EmitTLSUnsupportedError = true; 6820 // We still need to mark the variable as TLS so it shows up in AST with 6821 // proper storage class for other tools to use even if we're not going 6822 // to emit any code for it. 6823 NewVD->setTSCSpec(TSCS); 6824 } else 6825 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6826 diag::err_thread_unsupported); 6827 } else 6828 NewVD->setTSCSpec(TSCS); 6829 } 6830 6831 switch (D.getDeclSpec().getConstexprSpecifier()) { 6832 case CSK_unspecified: 6833 break; 6834 6835 case CSK_consteval: 6836 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6837 diag::err_constexpr_wrong_decl_kind) 6838 << D.getDeclSpec().getConstexprSpecifier(); 6839 LLVM_FALLTHROUGH; 6840 6841 case CSK_constexpr: 6842 NewVD->setConstexpr(true); 6843 // C++1z [dcl.spec.constexpr]p1: 6844 // A static data member declared with the constexpr specifier is 6845 // implicitly an inline variable. 6846 if (NewVD->isStaticDataMember() && 6847 (getLangOpts().CPlusPlus17 || 6848 Context.getTargetInfo().getCXXABI().isMicrosoft())) 6849 NewVD->setImplicitlyInline(); 6850 break; 6851 6852 case CSK_constinit: 6853 if (!NewVD->hasGlobalStorage()) 6854 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6855 diag::err_constinit_local_variable); 6856 else 6857 NewVD->addAttr(ConstInitAttr::Create( 6858 Context, D.getDeclSpec().getConstexprSpecLoc(), 6859 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 6860 break; 6861 } 6862 6863 // C99 6.7.4p3 6864 // An inline definition of a function with external linkage shall 6865 // not contain a definition of a modifiable object with static or 6866 // thread storage duration... 6867 // We only apply this when the function is required to be defined 6868 // elsewhere, i.e. when the function is not 'extern inline'. Note 6869 // that a local variable with thread storage duration still has to 6870 // be marked 'static'. Also note that it's possible to get these 6871 // semantics in C++ using __attribute__((gnu_inline)). 6872 if (SC == SC_Static && S->getFnParent() != nullptr && 6873 !NewVD->getType().isConstQualified()) { 6874 FunctionDecl *CurFD = getCurFunctionDecl(); 6875 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6876 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6877 diag::warn_static_local_in_extern_inline); 6878 MaybeSuggestAddingStaticToDecl(CurFD); 6879 } 6880 } 6881 6882 if (D.getDeclSpec().isModulePrivateSpecified()) { 6883 if (IsVariableTemplateSpecialization) 6884 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6885 << (IsPartialSpecialization ? 1 : 0) 6886 << FixItHint::CreateRemoval( 6887 D.getDeclSpec().getModulePrivateSpecLoc()); 6888 else if (IsMemberSpecialization) 6889 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6890 << 2 6891 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6892 else if (NewVD->hasLocalStorage()) 6893 Diag(NewVD->getLocation(), diag::err_module_private_local) 6894 << 0 << NewVD->getDeclName() 6895 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6896 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6897 else { 6898 NewVD->setModulePrivate(); 6899 if (NewTemplate) 6900 NewTemplate->setModulePrivate(); 6901 for (auto *B : Bindings) 6902 B->setModulePrivate(); 6903 } 6904 } 6905 6906 // Handle attributes prior to checking for duplicates in MergeVarDecl 6907 ProcessDeclAttributes(S, NewVD, D); 6908 6909 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6910 if (EmitTLSUnsupportedError && 6911 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6912 (getLangOpts().OpenMPIsDevice && 6913 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 6914 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6915 diag::err_thread_unsupported); 6916 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6917 // storage [duration]." 6918 if (SC == SC_None && S->getFnParent() != nullptr && 6919 (NewVD->hasAttr<CUDASharedAttr>() || 6920 NewVD->hasAttr<CUDAConstantAttr>())) { 6921 NewVD->setStorageClass(SC_Static); 6922 } 6923 } 6924 6925 // Ensure that dllimport globals without explicit storage class are treated as 6926 // extern. The storage class is set above using parsed attributes. Now we can 6927 // check the VarDecl itself. 6928 assert(!NewVD->hasAttr<DLLImportAttr>() || 6929 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6930 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6931 6932 // In auto-retain/release, infer strong retension for variables of 6933 // retainable type. 6934 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6935 NewVD->setInvalidDecl(); 6936 6937 // Handle GNU asm-label extension (encoded as an attribute). 6938 if (Expr *E = (Expr*)D.getAsmLabel()) { 6939 // The parser guarantees this is a string. 6940 StringLiteral *SE = cast<StringLiteral>(E); 6941 StringRef Label = SE->getString(); 6942 if (S->getFnParent() != nullptr) { 6943 switch (SC) { 6944 case SC_None: 6945 case SC_Auto: 6946 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6947 break; 6948 case SC_Register: 6949 // Local Named register 6950 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6951 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6952 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6953 break; 6954 case SC_Static: 6955 case SC_Extern: 6956 case SC_PrivateExtern: 6957 break; 6958 } 6959 } else if (SC == SC_Register) { 6960 // Global Named register 6961 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6962 const auto &TI = Context.getTargetInfo(); 6963 bool HasSizeMismatch; 6964 6965 if (!TI.isValidGCCRegisterName(Label)) 6966 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6967 else if (!TI.validateGlobalRegisterVariable(Label, 6968 Context.getTypeSize(R), 6969 HasSizeMismatch)) 6970 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6971 else if (HasSizeMismatch) 6972 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6973 } 6974 6975 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6976 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 6977 NewVD->setInvalidDecl(true); 6978 } 6979 } 6980 6981 NewVD->addAttr(::new (Context) 6982 AsmLabelAttr(Context, SE->getStrTokenLoc(0), Label)); 6983 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6984 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6985 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6986 if (I != ExtnameUndeclaredIdentifiers.end()) { 6987 if (isDeclExternC(NewVD)) { 6988 NewVD->addAttr(I->second); 6989 ExtnameUndeclaredIdentifiers.erase(I); 6990 } else 6991 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6992 << /*Variable*/1 << NewVD; 6993 } 6994 } 6995 6996 // Find the shadowed declaration before filtering for scope. 6997 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6998 ? getShadowedDeclaration(NewVD, Previous) 6999 : nullptr; 7000 7001 // Don't consider existing declarations that are in a different 7002 // scope and are out-of-semantic-context declarations (if the new 7003 // declaration has linkage). 7004 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7005 D.getCXXScopeSpec().isNotEmpty() || 7006 IsMemberSpecialization || 7007 IsVariableTemplateSpecialization); 7008 7009 // Check whether the previous declaration is in the same block scope. This 7010 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7011 if (getLangOpts().CPlusPlus && 7012 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7013 NewVD->setPreviousDeclInSameBlockScope( 7014 Previous.isSingleResult() && !Previous.isShadowed() && 7015 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7016 7017 if (!getLangOpts().CPlusPlus) { 7018 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7019 } else { 7020 // If this is an explicit specialization of a static data member, check it. 7021 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7022 CheckMemberSpecialization(NewVD, Previous)) 7023 NewVD->setInvalidDecl(); 7024 7025 // Merge the decl with the existing one if appropriate. 7026 if (!Previous.empty()) { 7027 if (Previous.isSingleResult() && 7028 isa<FieldDecl>(Previous.getFoundDecl()) && 7029 D.getCXXScopeSpec().isSet()) { 7030 // The user tried to define a non-static data member 7031 // out-of-line (C++ [dcl.meaning]p1). 7032 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7033 << D.getCXXScopeSpec().getRange(); 7034 Previous.clear(); 7035 NewVD->setInvalidDecl(); 7036 } 7037 } else if (D.getCXXScopeSpec().isSet()) { 7038 // No previous declaration in the qualifying scope. 7039 Diag(D.getIdentifierLoc(), diag::err_no_member) 7040 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7041 << D.getCXXScopeSpec().getRange(); 7042 NewVD->setInvalidDecl(); 7043 } 7044 7045 if (!IsVariableTemplateSpecialization) 7046 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7047 7048 if (NewTemplate) { 7049 VarTemplateDecl *PrevVarTemplate = 7050 NewVD->getPreviousDecl() 7051 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7052 : nullptr; 7053 7054 // Check the template parameter list of this declaration, possibly 7055 // merging in the template parameter list from the previous variable 7056 // template declaration. 7057 if (CheckTemplateParameterList( 7058 TemplateParams, 7059 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7060 : nullptr, 7061 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7062 DC->isDependentContext()) 7063 ? TPC_ClassTemplateMember 7064 : TPC_VarTemplate)) 7065 NewVD->setInvalidDecl(); 7066 7067 // If we are providing an explicit specialization of a static variable 7068 // template, make a note of that. 7069 if (PrevVarTemplate && 7070 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7071 PrevVarTemplate->setMemberSpecialization(); 7072 } 7073 } 7074 7075 // Diagnose shadowed variables iff this isn't a redeclaration. 7076 if (ShadowedDecl && !D.isRedeclaration()) 7077 CheckShadow(NewVD, ShadowedDecl, Previous); 7078 7079 ProcessPragmaWeak(S, NewVD); 7080 7081 // If this is the first declaration of an extern C variable, update 7082 // the map of such variables. 7083 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7084 isIncompleteDeclExternC(*this, NewVD)) 7085 RegisterLocallyScopedExternCDecl(NewVD, S); 7086 7087 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7088 Decl *ManglingContextDecl; 7089 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 7090 NewVD->getDeclContext(), ManglingContextDecl)) { 7091 Context.setManglingNumber( 7092 NewVD, MCtx->getManglingNumber( 7093 NewVD, getMSManglingNumber(getLangOpts(), S))); 7094 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7095 } 7096 } 7097 7098 // Special handling of variable named 'main'. 7099 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7100 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7101 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7102 7103 // C++ [basic.start.main]p3 7104 // A program that declares a variable main at global scope is ill-formed. 7105 if (getLangOpts().CPlusPlus) 7106 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7107 7108 // In C, and external-linkage variable named main results in undefined 7109 // behavior. 7110 else if (NewVD->hasExternalFormalLinkage()) 7111 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7112 } 7113 7114 if (D.isRedeclaration() && !Previous.empty()) { 7115 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7116 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7117 D.isFunctionDefinition()); 7118 } 7119 7120 if (NewTemplate) { 7121 if (NewVD->isInvalidDecl()) 7122 NewTemplate->setInvalidDecl(); 7123 ActOnDocumentableDecl(NewTemplate); 7124 return NewTemplate; 7125 } 7126 7127 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7128 CompleteMemberSpecialization(NewVD, Previous); 7129 7130 return NewVD; 7131 } 7132 7133 /// Enum describing the %select options in diag::warn_decl_shadow. 7134 enum ShadowedDeclKind { 7135 SDK_Local, 7136 SDK_Global, 7137 SDK_StaticMember, 7138 SDK_Field, 7139 SDK_Typedef, 7140 SDK_Using 7141 }; 7142 7143 /// Determine what kind of declaration we're shadowing. 7144 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7145 const DeclContext *OldDC) { 7146 if (isa<TypeAliasDecl>(ShadowedDecl)) 7147 return SDK_Using; 7148 else if (isa<TypedefDecl>(ShadowedDecl)) 7149 return SDK_Typedef; 7150 else if (isa<RecordDecl>(OldDC)) 7151 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7152 7153 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7154 } 7155 7156 /// Return the location of the capture if the given lambda captures the given 7157 /// variable \p VD, or an invalid source location otherwise. 7158 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7159 const VarDecl *VD) { 7160 for (const Capture &Capture : LSI->Captures) { 7161 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7162 return Capture.getLocation(); 7163 } 7164 return SourceLocation(); 7165 } 7166 7167 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7168 const LookupResult &R) { 7169 // Only diagnose if we're shadowing an unambiguous field or variable. 7170 if (R.getResultKind() != LookupResult::Found) 7171 return false; 7172 7173 // Return false if warning is ignored. 7174 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7175 } 7176 7177 /// Return the declaration shadowed by the given variable \p D, or null 7178 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7179 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7180 const LookupResult &R) { 7181 if (!shouldWarnIfShadowedDecl(Diags, R)) 7182 return nullptr; 7183 7184 // Don't diagnose declarations at file scope. 7185 if (D->hasGlobalStorage()) 7186 return nullptr; 7187 7188 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7189 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7190 ? ShadowedDecl 7191 : nullptr; 7192 } 7193 7194 /// Return the declaration shadowed by the given typedef \p D, or null 7195 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7196 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7197 const LookupResult &R) { 7198 // Don't warn if typedef declaration is part of a class 7199 if (D->getDeclContext()->isRecord()) 7200 return nullptr; 7201 7202 if (!shouldWarnIfShadowedDecl(Diags, R)) 7203 return nullptr; 7204 7205 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7206 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7207 } 7208 7209 /// Diagnose variable or built-in function shadowing. Implements 7210 /// -Wshadow. 7211 /// 7212 /// This method is called whenever a VarDecl is added to a "useful" 7213 /// scope. 7214 /// 7215 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7216 /// \param R the lookup of the name 7217 /// 7218 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7219 const LookupResult &R) { 7220 DeclContext *NewDC = D->getDeclContext(); 7221 7222 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7223 // Fields are not shadowed by variables in C++ static methods. 7224 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7225 if (MD->isStatic()) 7226 return; 7227 7228 // Fields shadowed by constructor parameters are a special case. Usually 7229 // the constructor initializes the field with the parameter. 7230 if (isa<CXXConstructorDecl>(NewDC)) 7231 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7232 // Remember that this was shadowed so we can either warn about its 7233 // modification or its existence depending on warning settings. 7234 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7235 return; 7236 } 7237 } 7238 7239 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7240 if (shadowedVar->isExternC()) { 7241 // For shadowing external vars, make sure that we point to the global 7242 // declaration, not a locally scoped extern declaration. 7243 for (auto I : shadowedVar->redecls()) 7244 if (I->isFileVarDecl()) { 7245 ShadowedDecl = I; 7246 break; 7247 } 7248 } 7249 7250 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7251 7252 unsigned WarningDiag = diag::warn_decl_shadow; 7253 SourceLocation CaptureLoc; 7254 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7255 isa<CXXMethodDecl>(NewDC)) { 7256 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7257 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7258 if (RD->getLambdaCaptureDefault() == LCD_None) { 7259 // Try to avoid warnings for lambdas with an explicit capture list. 7260 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7261 // Warn only when the lambda captures the shadowed decl explicitly. 7262 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7263 if (CaptureLoc.isInvalid()) 7264 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7265 } else { 7266 // Remember that this was shadowed so we can avoid the warning if the 7267 // shadowed decl isn't captured and the warning settings allow it. 7268 cast<LambdaScopeInfo>(getCurFunction()) 7269 ->ShadowingDecls.push_back( 7270 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7271 return; 7272 } 7273 } 7274 7275 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7276 // A variable can't shadow a local variable in an enclosing scope, if 7277 // they are separated by a non-capturing declaration context. 7278 for (DeclContext *ParentDC = NewDC; 7279 ParentDC && !ParentDC->Equals(OldDC); 7280 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7281 // Only block literals, captured statements, and lambda expressions 7282 // can capture; other scopes don't. 7283 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7284 !isLambdaCallOperator(ParentDC)) { 7285 return; 7286 } 7287 } 7288 } 7289 } 7290 } 7291 7292 // Only warn about certain kinds of shadowing for class members. 7293 if (NewDC && NewDC->isRecord()) { 7294 // In particular, don't warn about shadowing non-class members. 7295 if (!OldDC->isRecord()) 7296 return; 7297 7298 // TODO: should we warn about static data members shadowing 7299 // static data members from base classes? 7300 7301 // TODO: don't diagnose for inaccessible shadowed members. 7302 // This is hard to do perfectly because we might friend the 7303 // shadowing context, but that's just a false negative. 7304 } 7305 7306 7307 DeclarationName Name = R.getLookupName(); 7308 7309 // Emit warning and note. 7310 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7311 return; 7312 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7313 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7314 if (!CaptureLoc.isInvalid()) 7315 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7316 << Name << /*explicitly*/ 1; 7317 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7318 } 7319 7320 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7321 /// when these variables are captured by the lambda. 7322 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7323 for (const auto &Shadow : LSI->ShadowingDecls) { 7324 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7325 // Try to avoid the warning when the shadowed decl isn't captured. 7326 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7327 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7328 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7329 ? diag::warn_decl_shadow_uncaptured_local 7330 : diag::warn_decl_shadow) 7331 << Shadow.VD->getDeclName() 7332 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7333 if (!CaptureLoc.isInvalid()) 7334 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7335 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7336 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7337 } 7338 } 7339 7340 /// Check -Wshadow without the advantage of a previous lookup. 7341 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7342 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7343 return; 7344 7345 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7346 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7347 LookupName(R, S); 7348 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7349 CheckShadow(D, ShadowedDecl, R); 7350 } 7351 7352 /// Check if 'E', which is an expression that is about to be modified, refers 7353 /// to a constructor parameter that shadows a field. 7354 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7355 // Quickly ignore expressions that can't be shadowing ctor parameters. 7356 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7357 return; 7358 E = E->IgnoreParenImpCasts(); 7359 auto *DRE = dyn_cast<DeclRefExpr>(E); 7360 if (!DRE) 7361 return; 7362 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7363 auto I = ShadowingDecls.find(D); 7364 if (I == ShadowingDecls.end()) 7365 return; 7366 const NamedDecl *ShadowedDecl = I->second; 7367 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7368 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7369 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7370 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7371 7372 // Avoid issuing multiple warnings about the same decl. 7373 ShadowingDecls.erase(I); 7374 } 7375 7376 /// Check for conflict between this global or extern "C" declaration and 7377 /// previous global or extern "C" declarations. This is only used in C++. 7378 template<typename T> 7379 static bool checkGlobalOrExternCConflict( 7380 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7381 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7382 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7383 7384 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7385 // The common case: this global doesn't conflict with any extern "C" 7386 // declaration. 7387 return false; 7388 } 7389 7390 if (Prev) { 7391 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7392 // Both the old and new declarations have C language linkage. This is a 7393 // redeclaration. 7394 Previous.clear(); 7395 Previous.addDecl(Prev); 7396 return true; 7397 } 7398 7399 // This is a global, non-extern "C" declaration, and there is a previous 7400 // non-global extern "C" declaration. Diagnose if this is a variable 7401 // declaration. 7402 if (!isa<VarDecl>(ND)) 7403 return false; 7404 } else { 7405 // The declaration is extern "C". Check for any declaration in the 7406 // translation unit which might conflict. 7407 if (IsGlobal) { 7408 // We have already performed the lookup into the translation unit. 7409 IsGlobal = false; 7410 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7411 I != E; ++I) { 7412 if (isa<VarDecl>(*I)) { 7413 Prev = *I; 7414 break; 7415 } 7416 } 7417 } else { 7418 DeclContext::lookup_result R = 7419 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7420 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7421 I != E; ++I) { 7422 if (isa<VarDecl>(*I)) { 7423 Prev = *I; 7424 break; 7425 } 7426 // FIXME: If we have any other entity with this name in global scope, 7427 // the declaration is ill-formed, but that is a defect: it breaks the 7428 // 'stat' hack, for instance. Only variables can have mangled name 7429 // clashes with extern "C" declarations, so only they deserve a 7430 // diagnostic. 7431 } 7432 } 7433 7434 if (!Prev) 7435 return false; 7436 } 7437 7438 // Use the first declaration's location to ensure we point at something which 7439 // is lexically inside an extern "C" linkage-spec. 7440 assert(Prev && "should have found a previous declaration to diagnose"); 7441 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7442 Prev = FD->getFirstDecl(); 7443 else 7444 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7445 7446 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7447 << IsGlobal << ND; 7448 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7449 << IsGlobal; 7450 return false; 7451 } 7452 7453 /// Apply special rules for handling extern "C" declarations. Returns \c true 7454 /// if we have found that this is a redeclaration of some prior entity. 7455 /// 7456 /// Per C++ [dcl.link]p6: 7457 /// Two declarations [for a function or variable] with C language linkage 7458 /// with the same name that appear in different scopes refer to the same 7459 /// [entity]. An entity with C language linkage shall not be declared with 7460 /// the same name as an entity in global scope. 7461 template<typename T> 7462 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7463 LookupResult &Previous) { 7464 if (!S.getLangOpts().CPlusPlus) { 7465 // In C, when declaring a global variable, look for a corresponding 'extern' 7466 // variable declared in function scope. We don't need this in C++, because 7467 // we find local extern decls in the surrounding file-scope DeclContext. 7468 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7469 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7470 Previous.clear(); 7471 Previous.addDecl(Prev); 7472 return true; 7473 } 7474 } 7475 return false; 7476 } 7477 7478 // A declaration in the translation unit can conflict with an extern "C" 7479 // declaration. 7480 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7481 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7482 7483 // An extern "C" declaration can conflict with a declaration in the 7484 // translation unit or can be a redeclaration of an extern "C" declaration 7485 // in another scope. 7486 if (isIncompleteDeclExternC(S,ND)) 7487 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7488 7489 // Neither global nor extern "C": nothing to do. 7490 return false; 7491 } 7492 7493 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7494 // If the decl is already known invalid, don't check it. 7495 if (NewVD->isInvalidDecl()) 7496 return; 7497 7498 QualType T = NewVD->getType(); 7499 7500 // Defer checking an 'auto' type until its initializer is attached. 7501 if (T->isUndeducedType()) 7502 return; 7503 7504 if (NewVD->hasAttrs()) 7505 CheckAlignasUnderalignment(NewVD); 7506 7507 if (T->isObjCObjectType()) { 7508 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7509 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7510 T = Context.getObjCObjectPointerType(T); 7511 NewVD->setType(T); 7512 } 7513 7514 // Emit an error if an address space was applied to decl with local storage. 7515 // This includes arrays of objects with address space qualifiers, but not 7516 // automatic variables that point to other address spaces. 7517 // ISO/IEC TR 18037 S5.1.2 7518 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7519 T.getAddressSpace() != LangAS::Default) { 7520 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7521 NewVD->setInvalidDecl(); 7522 return; 7523 } 7524 7525 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7526 // scope. 7527 if (getLangOpts().OpenCLVersion == 120 && 7528 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7529 NewVD->isStaticLocal()) { 7530 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7531 NewVD->setInvalidDecl(); 7532 return; 7533 } 7534 7535 if (getLangOpts().OpenCL) { 7536 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7537 if (NewVD->hasAttr<BlocksAttr>()) { 7538 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7539 return; 7540 } 7541 7542 if (T->isBlockPointerType()) { 7543 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7544 // can't use 'extern' storage class. 7545 if (!T.isConstQualified()) { 7546 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7547 << 0 /*const*/; 7548 NewVD->setInvalidDecl(); 7549 return; 7550 } 7551 if (NewVD->hasExternalStorage()) { 7552 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7553 NewVD->setInvalidDecl(); 7554 return; 7555 } 7556 } 7557 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7558 // __constant address space. 7559 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7560 // variables inside a function can also be declared in the global 7561 // address space. 7562 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7563 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7564 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7565 NewVD->hasExternalStorage()) { 7566 if (!T->isSamplerT() && 7567 !(T.getAddressSpace() == LangAS::opencl_constant || 7568 (T.getAddressSpace() == LangAS::opencl_global && 7569 (getLangOpts().OpenCLVersion == 200 || 7570 getLangOpts().OpenCLCPlusPlus)))) { 7571 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7572 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7573 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7574 << Scope << "global or constant"; 7575 else 7576 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7577 << Scope << "constant"; 7578 NewVD->setInvalidDecl(); 7579 return; 7580 } 7581 } else { 7582 if (T.getAddressSpace() == LangAS::opencl_global) { 7583 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7584 << 1 /*is any function*/ << "global"; 7585 NewVD->setInvalidDecl(); 7586 return; 7587 } 7588 if (T.getAddressSpace() == LangAS::opencl_constant || 7589 T.getAddressSpace() == LangAS::opencl_local) { 7590 FunctionDecl *FD = getCurFunctionDecl(); 7591 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7592 // in functions. 7593 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7594 if (T.getAddressSpace() == LangAS::opencl_constant) 7595 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7596 << 0 /*non-kernel only*/ << "constant"; 7597 else 7598 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7599 << 0 /*non-kernel only*/ << "local"; 7600 NewVD->setInvalidDecl(); 7601 return; 7602 } 7603 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7604 // in the outermost scope of a kernel function. 7605 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7606 if (!getCurScope()->isFunctionScope()) { 7607 if (T.getAddressSpace() == LangAS::opencl_constant) 7608 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7609 << "constant"; 7610 else 7611 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7612 << "local"; 7613 NewVD->setInvalidDecl(); 7614 return; 7615 } 7616 } 7617 } else if (T.getAddressSpace() != LangAS::opencl_private && 7618 // If we are parsing a template we didn't deduce an addr 7619 // space yet. 7620 T.getAddressSpace() != LangAS::Default) { 7621 // Do not allow other address spaces on automatic variable. 7622 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7623 NewVD->setInvalidDecl(); 7624 return; 7625 } 7626 } 7627 } 7628 7629 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7630 && !NewVD->hasAttr<BlocksAttr>()) { 7631 if (getLangOpts().getGC() != LangOptions::NonGC) 7632 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7633 else { 7634 assert(!getLangOpts().ObjCAutoRefCount); 7635 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7636 } 7637 } 7638 7639 bool isVM = T->isVariablyModifiedType(); 7640 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7641 NewVD->hasAttr<BlocksAttr>()) 7642 setFunctionHasBranchProtectedScope(); 7643 7644 if ((isVM && NewVD->hasLinkage()) || 7645 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7646 bool SizeIsNegative; 7647 llvm::APSInt Oversized; 7648 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7649 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7650 QualType FixedT; 7651 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7652 FixedT = FixedTInfo->getType(); 7653 else if (FixedTInfo) { 7654 // Type and type-as-written are canonically different. We need to fix up 7655 // both types separately. 7656 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7657 Oversized); 7658 } 7659 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7660 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7661 // FIXME: This won't give the correct result for 7662 // int a[10][n]; 7663 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7664 7665 if (NewVD->isFileVarDecl()) 7666 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7667 << SizeRange; 7668 else if (NewVD->isStaticLocal()) 7669 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7670 << SizeRange; 7671 else 7672 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7673 << SizeRange; 7674 NewVD->setInvalidDecl(); 7675 return; 7676 } 7677 7678 if (!FixedTInfo) { 7679 if (NewVD->isFileVarDecl()) 7680 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7681 else 7682 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7683 NewVD->setInvalidDecl(); 7684 return; 7685 } 7686 7687 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7688 NewVD->setType(FixedT); 7689 NewVD->setTypeSourceInfo(FixedTInfo); 7690 } 7691 7692 if (T->isVoidType()) { 7693 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7694 // of objects and functions. 7695 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7696 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7697 << T; 7698 NewVD->setInvalidDecl(); 7699 return; 7700 } 7701 } 7702 7703 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7704 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7705 NewVD->setInvalidDecl(); 7706 return; 7707 } 7708 7709 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7710 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7711 NewVD->setInvalidDecl(); 7712 return; 7713 } 7714 7715 if (NewVD->isConstexpr() && !T->isDependentType() && 7716 RequireLiteralType(NewVD->getLocation(), T, 7717 diag::err_constexpr_var_non_literal)) { 7718 NewVD->setInvalidDecl(); 7719 return; 7720 } 7721 } 7722 7723 /// Perform semantic checking on a newly-created variable 7724 /// declaration. 7725 /// 7726 /// This routine performs all of the type-checking required for a 7727 /// variable declaration once it has been built. It is used both to 7728 /// check variables after they have been parsed and their declarators 7729 /// have been translated into a declaration, and to check variables 7730 /// that have been instantiated from a template. 7731 /// 7732 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7733 /// 7734 /// Returns true if the variable declaration is a redeclaration. 7735 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7736 CheckVariableDeclarationType(NewVD); 7737 7738 // If the decl is already known invalid, don't check it. 7739 if (NewVD->isInvalidDecl()) 7740 return false; 7741 7742 // If we did not find anything by this name, look for a non-visible 7743 // extern "C" declaration with the same name. 7744 if (Previous.empty() && 7745 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7746 Previous.setShadowed(); 7747 7748 if (!Previous.empty()) { 7749 MergeVarDecl(NewVD, Previous); 7750 return true; 7751 } 7752 return false; 7753 } 7754 7755 namespace { 7756 struct FindOverriddenMethod { 7757 Sema *S; 7758 CXXMethodDecl *Method; 7759 7760 /// Member lookup function that determines whether a given C++ 7761 /// method overrides a method in a base class, to be used with 7762 /// CXXRecordDecl::lookupInBases(). 7763 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7764 RecordDecl *BaseRecord = 7765 Specifier->getType()->getAs<RecordType>()->getDecl(); 7766 7767 DeclarationName Name = Method->getDeclName(); 7768 7769 // FIXME: Do we care about other names here too? 7770 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7771 // We really want to find the base class destructor here. 7772 QualType T = S->Context.getTypeDeclType(BaseRecord); 7773 CanQualType CT = S->Context.getCanonicalType(T); 7774 7775 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7776 } 7777 7778 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7779 Path.Decls = Path.Decls.slice(1)) { 7780 NamedDecl *D = Path.Decls.front(); 7781 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7782 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7783 return true; 7784 } 7785 } 7786 7787 return false; 7788 } 7789 }; 7790 7791 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7792 } // end anonymous namespace 7793 7794 /// Report an error regarding overriding, along with any relevant 7795 /// overridden methods. 7796 /// 7797 /// \param DiagID the primary error to report. 7798 /// \param MD the overriding method. 7799 /// \param OEK which overrides to include as notes. 7800 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7801 OverrideErrorKind OEK = OEK_All) { 7802 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7803 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7804 // This check (& the OEK parameter) could be replaced by a predicate, but 7805 // without lambdas that would be overkill. This is still nicer than writing 7806 // out the diag loop 3 times. 7807 if ((OEK == OEK_All) || 7808 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7809 (OEK == OEK_Deleted && O->isDeleted())) 7810 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7811 } 7812 } 7813 7814 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7815 /// and if so, check that it's a valid override and remember it. 7816 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7817 // Look for methods in base classes that this method might override. 7818 CXXBasePaths Paths; 7819 FindOverriddenMethod FOM; 7820 FOM.Method = MD; 7821 FOM.S = this; 7822 bool hasDeletedOverridenMethods = false; 7823 bool hasNonDeletedOverridenMethods = false; 7824 bool AddedAny = false; 7825 if (DC->lookupInBases(FOM, Paths)) { 7826 for (auto *I : Paths.found_decls()) { 7827 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7828 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7829 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7830 !CheckOverridingFunctionAttributes(MD, OldMD) && 7831 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7832 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7833 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7834 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7835 AddedAny = true; 7836 } 7837 } 7838 } 7839 } 7840 7841 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7842 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7843 } 7844 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7845 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7846 } 7847 7848 return AddedAny; 7849 } 7850 7851 namespace { 7852 // Struct for holding all of the extra arguments needed by 7853 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7854 struct ActOnFDArgs { 7855 Scope *S; 7856 Declarator &D; 7857 MultiTemplateParamsArg TemplateParamLists; 7858 bool AddToScope; 7859 }; 7860 } // end anonymous namespace 7861 7862 namespace { 7863 7864 // Callback to only accept typo corrections that have a non-zero edit distance. 7865 // Also only accept corrections that have the same parent decl. 7866 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 7867 public: 7868 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7869 CXXRecordDecl *Parent) 7870 : Context(Context), OriginalFD(TypoFD), 7871 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7872 7873 bool ValidateCandidate(const TypoCorrection &candidate) override { 7874 if (candidate.getEditDistance() == 0) 7875 return false; 7876 7877 SmallVector<unsigned, 1> MismatchedParams; 7878 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7879 CDeclEnd = candidate.end(); 7880 CDecl != CDeclEnd; ++CDecl) { 7881 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7882 7883 if (FD && !FD->hasBody() && 7884 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7885 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7886 CXXRecordDecl *Parent = MD->getParent(); 7887 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7888 return true; 7889 } else if (!ExpectedParent) { 7890 return true; 7891 } 7892 } 7893 } 7894 7895 return false; 7896 } 7897 7898 std::unique_ptr<CorrectionCandidateCallback> clone() override { 7899 return std::make_unique<DifferentNameValidatorCCC>(*this); 7900 } 7901 7902 private: 7903 ASTContext &Context; 7904 FunctionDecl *OriginalFD; 7905 CXXRecordDecl *ExpectedParent; 7906 }; 7907 7908 } // end anonymous namespace 7909 7910 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7911 TypoCorrectedFunctionDefinitions.insert(F); 7912 } 7913 7914 /// Generate diagnostics for an invalid function redeclaration. 7915 /// 7916 /// This routine handles generating the diagnostic messages for an invalid 7917 /// function redeclaration, including finding possible similar declarations 7918 /// or performing typo correction if there are no previous declarations with 7919 /// the same name. 7920 /// 7921 /// Returns a NamedDecl iff typo correction was performed and substituting in 7922 /// the new declaration name does not cause new errors. 7923 static NamedDecl *DiagnoseInvalidRedeclaration( 7924 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7925 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7926 DeclarationName Name = NewFD->getDeclName(); 7927 DeclContext *NewDC = NewFD->getDeclContext(); 7928 SmallVector<unsigned, 1> MismatchedParams; 7929 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7930 TypoCorrection Correction; 7931 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7932 unsigned DiagMsg = 7933 IsLocalFriend ? diag::err_no_matching_local_friend : 7934 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 7935 diag::err_member_decl_does_not_match; 7936 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7937 IsLocalFriend ? Sema::LookupLocalFriendName 7938 : Sema::LookupOrdinaryName, 7939 Sema::ForVisibleRedeclaration); 7940 7941 NewFD->setInvalidDecl(); 7942 if (IsLocalFriend) 7943 SemaRef.LookupName(Prev, S); 7944 else 7945 SemaRef.LookupQualifiedName(Prev, NewDC); 7946 assert(!Prev.isAmbiguous() && 7947 "Cannot have an ambiguity in previous-declaration lookup"); 7948 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7949 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 7950 MD ? MD->getParent() : nullptr); 7951 if (!Prev.empty()) { 7952 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7953 Func != FuncEnd; ++Func) { 7954 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7955 if (FD && 7956 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7957 // Add 1 to the index so that 0 can mean the mismatch didn't 7958 // involve a parameter 7959 unsigned ParamNum = 7960 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7961 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7962 } 7963 } 7964 // If the qualified name lookup yielded nothing, try typo correction 7965 } else if ((Correction = SemaRef.CorrectTypo( 7966 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7967 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 7968 IsLocalFriend ? nullptr : NewDC))) { 7969 // Set up everything for the call to ActOnFunctionDeclarator 7970 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7971 ExtraArgs.D.getIdentifierLoc()); 7972 Previous.clear(); 7973 Previous.setLookupName(Correction.getCorrection()); 7974 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7975 CDeclEnd = Correction.end(); 7976 CDecl != CDeclEnd; ++CDecl) { 7977 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7978 if (FD && !FD->hasBody() && 7979 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7980 Previous.addDecl(FD); 7981 } 7982 } 7983 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7984 7985 NamedDecl *Result; 7986 // Retry building the function declaration with the new previous 7987 // declarations, and with errors suppressed. 7988 { 7989 // Trap errors. 7990 Sema::SFINAETrap Trap(SemaRef); 7991 7992 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7993 // pieces need to verify the typo-corrected C++ declaration and hopefully 7994 // eliminate the need for the parameter pack ExtraArgs. 7995 Result = SemaRef.ActOnFunctionDeclarator( 7996 ExtraArgs.S, ExtraArgs.D, 7997 Correction.getCorrectionDecl()->getDeclContext(), 7998 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7999 ExtraArgs.AddToScope); 8000 8001 if (Trap.hasErrorOccurred()) 8002 Result = nullptr; 8003 } 8004 8005 if (Result) { 8006 // Determine which correction we picked. 8007 Decl *Canonical = Result->getCanonicalDecl(); 8008 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8009 I != E; ++I) 8010 if ((*I)->getCanonicalDecl() == Canonical) 8011 Correction.setCorrectionDecl(*I); 8012 8013 // Let Sema know about the correction. 8014 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8015 SemaRef.diagnoseTypo( 8016 Correction, 8017 SemaRef.PDiag(IsLocalFriend 8018 ? diag::err_no_matching_local_friend_suggest 8019 : diag::err_member_decl_does_not_match_suggest) 8020 << Name << NewDC << IsDefinition); 8021 return Result; 8022 } 8023 8024 // Pretend the typo correction never occurred 8025 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8026 ExtraArgs.D.getIdentifierLoc()); 8027 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8028 Previous.clear(); 8029 Previous.setLookupName(Name); 8030 } 8031 8032 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8033 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8034 8035 bool NewFDisConst = false; 8036 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8037 NewFDisConst = NewMD->isConst(); 8038 8039 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8040 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8041 NearMatch != NearMatchEnd; ++NearMatch) { 8042 FunctionDecl *FD = NearMatch->first; 8043 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8044 bool FDisConst = MD && MD->isConst(); 8045 bool IsMember = MD || !IsLocalFriend; 8046 8047 // FIXME: These notes are poorly worded for the local friend case. 8048 if (unsigned Idx = NearMatch->second) { 8049 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8050 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8051 if (Loc.isInvalid()) Loc = FD->getLocation(); 8052 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8053 : diag::note_local_decl_close_param_match) 8054 << Idx << FDParam->getType() 8055 << NewFD->getParamDecl(Idx - 1)->getType(); 8056 } else if (FDisConst != NewFDisConst) { 8057 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8058 << NewFDisConst << FD->getSourceRange().getEnd(); 8059 } else 8060 SemaRef.Diag(FD->getLocation(), 8061 IsMember ? diag::note_member_def_close_match 8062 : diag::note_local_decl_close_match); 8063 } 8064 return nullptr; 8065 } 8066 8067 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8068 switch (D.getDeclSpec().getStorageClassSpec()) { 8069 default: llvm_unreachable("Unknown storage class!"); 8070 case DeclSpec::SCS_auto: 8071 case DeclSpec::SCS_register: 8072 case DeclSpec::SCS_mutable: 8073 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8074 diag::err_typecheck_sclass_func); 8075 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8076 D.setInvalidType(); 8077 break; 8078 case DeclSpec::SCS_unspecified: break; 8079 case DeclSpec::SCS_extern: 8080 if (D.getDeclSpec().isExternInLinkageSpec()) 8081 return SC_None; 8082 return SC_Extern; 8083 case DeclSpec::SCS_static: { 8084 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8085 // C99 6.7.1p5: 8086 // The declaration of an identifier for a function that has 8087 // block scope shall have no explicit storage-class specifier 8088 // other than extern 8089 // See also (C++ [dcl.stc]p4). 8090 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8091 diag::err_static_block_func); 8092 break; 8093 } else 8094 return SC_Static; 8095 } 8096 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8097 } 8098 8099 // No explicit storage class has already been returned 8100 return SC_None; 8101 } 8102 8103 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8104 DeclContext *DC, QualType &R, 8105 TypeSourceInfo *TInfo, 8106 StorageClass SC, 8107 bool &IsVirtualOkay) { 8108 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8109 DeclarationName Name = NameInfo.getName(); 8110 8111 FunctionDecl *NewFD = nullptr; 8112 bool isInline = D.getDeclSpec().isInlineSpecified(); 8113 8114 if (!SemaRef.getLangOpts().CPlusPlus) { 8115 // Determine whether the function was written with a 8116 // prototype. This true when: 8117 // - there is a prototype in the declarator, or 8118 // - the type R of the function is some kind of typedef or other non- 8119 // attributed reference to a type name (which eventually refers to a 8120 // function type). 8121 bool HasPrototype = 8122 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8123 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8124 8125 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8126 R, TInfo, SC, isInline, HasPrototype, 8127 CSK_unspecified); 8128 if (D.isInvalidType()) 8129 NewFD->setInvalidDecl(); 8130 8131 return NewFD; 8132 } 8133 8134 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8135 8136 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8137 if (ConstexprKind == CSK_constinit) { 8138 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8139 diag::err_constexpr_wrong_decl_kind) 8140 << ConstexprKind; 8141 ConstexprKind = CSK_unspecified; 8142 D.getMutableDeclSpec().ClearConstexprSpec(); 8143 } 8144 8145 // Check that the return type is not an abstract class type. 8146 // For record types, this is done by the AbstractClassUsageDiagnoser once 8147 // the class has been completely parsed. 8148 if (!DC->isRecord() && 8149 SemaRef.RequireNonAbstractType( 8150 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 8151 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8152 D.setInvalidType(); 8153 8154 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8155 // This is a C++ constructor declaration. 8156 assert(DC->isRecord() && 8157 "Constructors can only be declared in a member context"); 8158 8159 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8160 return CXXConstructorDecl::Create( 8161 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8162 TInfo, ExplicitSpecifier, isInline, 8163 /*isImplicitlyDeclared=*/false, ConstexprKind); 8164 8165 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8166 // This is a C++ destructor declaration. 8167 if (DC->isRecord()) { 8168 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8169 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8170 CXXDestructorDecl *NewDD = 8171 CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(), 8172 NameInfo, R, TInfo, isInline, 8173 /*isImplicitlyDeclared=*/false); 8174 8175 // If the destructor needs an implicit exception specification, set it 8176 // now. FIXME: It'd be nice to be able to create the right type to start 8177 // with, but the type needs to reference the destructor declaration. 8178 if (SemaRef.getLangOpts().CPlusPlus11) 8179 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8180 8181 IsVirtualOkay = true; 8182 return NewDD; 8183 8184 } else { 8185 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8186 D.setInvalidType(); 8187 8188 // Create a FunctionDecl to satisfy the function definition parsing 8189 // code path. 8190 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8191 D.getIdentifierLoc(), Name, R, TInfo, SC, 8192 isInline, 8193 /*hasPrototype=*/true, ConstexprKind); 8194 } 8195 8196 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8197 if (!DC->isRecord()) { 8198 SemaRef.Diag(D.getIdentifierLoc(), 8199 diag::err_conv_function_not_member); 8200 return nullptr; 8201 } 8202 8203 SemaRef.CheckConversionDeclarator(D, R, SC); 8204 IsVirtualOkay = true; 8205 return CXXConversionDecl::Create( 8206 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8207 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation()); 8208 8209 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8210 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8211 8212 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8213 ExplicitSpecifier, NameInfo, R, TInfo, 8214 D.getEndLoc()); 8215 } else if (DC->isRecord()) { 8216 // If the name of the function is the same as the name of the record, 8217 // then this must be an invalid constructor that has a return type. 8218 // (The parser checks for a return type and makes the declarator a 8219 // constructor if it has no return type). 8220 if (Name.getAsIdentifierInfo() && 8221 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8222 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8223 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8224 << SourceRange(D.getIdentifierLoc()); 8225 return nullptr; 8226 } 8227 8228 // This is a C++ method declaration. 8229 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8230 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8231 TInfo, SC, isInline, ConstexprKind, SourceLocation()); 8232 IsVirtualOkay = !Ret->isStatic(); 8233 return Ret; 8234 } else { 8235 bool isFriend = 8236 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8237 if (!isFriend && SemaRef.CurContext->isRecord()) 8238 return nullptr; 8239 8240 // Determine whether the function was written with a 8241 // prototype. This true when: 8242 // - we're in C++ (where every function has a prototype), 8243 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8244 R, TInfo, SC, isInline, true /*HasPrototype*/, 8245 ConstexprKind); 8246 } 8247 } 8248 8249 enum OpenCLParamType { 8250 ValidKernelParam, 8251 PtrPtrKernelParam, 8252 PtrKernelParam, 8253 InvalidAddrSpacePtrKernelParam, 8254 InvalidKernelParam, 8255 RecordKernelParam 8256 }; 8257 8258 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8259 // Size dependent types are just typedefs to normal integer types 8260 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8261 // integers other than by their names. 8262 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8263 8264 // Remove typedefs one by one until we reach a typedef 8265 // for a size dependent type. 8266 QualType DesugaredTy = Ty; 8267 do { 8268 ArrayRef<StringRef> Names(SizeTypeNames); 8269 auto Match = llvm::find(Names, DesugaredTy.getAsString()); 8270 if (Names.end() != Match) 8271 return true; 8272 8273 Ty = DesugaredTy; 8274 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8275 } while (DesugaredTy != Ty); 8276 8277 return false; 8278 } 8279 8280 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8281 if (PT->isPointerType()) { 8282 QualType PointeeType = PT->getPointeeType(); 8283 if (PointeeType->isPointerType()) 8284 return PtrPtrKernelParam; 8285 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8286 PointeeType.getAddressSpace() == LangAS::opencl_private || 8287 PointeeType.getAddressSpace() == LangAS::Default) 8288 return InvalidAddrSpacePtrKernelParam; 8289 return PtrKernelParam; 8290 } 8291 8292 // OpenCL v1.2 s6.9.k: 8293 // Arguments to kernel functions in a program cannot be declared with the 8294 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8295 // uintptr_t or a struct and/or union that contain fields declared to be one 8296 // of these built-in scalar types. 8297 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8298 return InvalidKernelParam; 8299 8300 if (PT->isImageType()) 8301 return PtrKernelParam; 8302 8303 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8304 return InvalidKernelParam; 8305 8306 // OpenCL extension spec v1.2 s9.5: 8307 // This extension adds support for half scalar and vector types as built-in 8308 // types that can be used for arithmetic operations, conversions etc. 8309 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8310 return InvalidKernelParam; 8311 8312 if (PT->isRecordType()) 8313 return RecordKernelParam; 8314 8315 // Look into an array argument to check if it has a forbidden type. 8316 if (PT->isArrayType()) { 8317 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8318 // Call ourself to check an underlying type of an array. Since the 8319 // getPointeeOrArrayElementType returns an innermost type which is not an 8320 // array, this recursive call only happens once. 8321 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8322 } 8323 8324 return ValidKernelParam; 8325 } 8326 8327 static void checkIsValidOpenCLKernelParameter( 8328 Sema &S, 8329 Declarator &D, 8330 ParmVarDecl *Param, 8331 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8332 QualType PT = Param->getType(); 8333 8334 // Cache the valid types we encounter to avoid rechecking structs that are 8335 // used again 8336 if (ValidTypes.count(PT.getTypePtr())) 8337 return; 8338 8339 switch (getOpenCLKernelParameterType(S, PT)) { 8340 case PtrPtrKernelParam: 8341 // OpenCL v1.2 s6.9.a: 8342 // A kernel function argument cannot be declared as a 8343 // pointer to a pointer type. 8344 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8345 D.setInvalidType(); 8346 return; 8347 8348 case InvalidAddrSpacePtrKernelParam: 8349 // OpenCL v1.0 s6.5: 8350 // __kernel function arguments declared to be a pointer of a type can point 8351 // to one of the following address spaces only : __global, __local or 8352 // __constant. 8353 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8354 D.setInvalidType(); 8355 return; 8356 8357 // OpenCL v1.2 s6.9.k: 8358 // Arguments to kernel functions in a program cannot be declared with the 8359 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8360 // uintptr_t or a struct and/or union that contain fields declared to be 8361 // one of these built-in scalar types. 8362 8363 case InvalidKernelParam: 8364 // OpenCL v1.2 s6.8 n: 8365 // A kernel function argument cannot be declared 8366 // of event_t type. 8367 // Do not diagnose half type since it is diagnosed as invalid argument 8368 // type for any function elsewhere. 8369 if (!PT->isHalfType()) { 8370 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8371 8372 // Explain what typedefs are involved. 8373 const TypedefType *Typedef = nullptr; 8374 while ((Typedef = PT->getAs<TypedefType>())) { 8375 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8376 // SourceLocation may be invalid for a built-in type. 8377 if (Loc.isValid()) 8378 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8379 PT = Typedef->desugar(); 8380 } 8381 } 8382 8383 D.setInvalidType(); 8384 return; 8385 8386 case PtrKernelParam: 8387 case ValidKernelParam: 8388 ValidTypes.insert(PT.getTypePtr()); 8389 return; 8390 8391 case RecordKernelParam: 8392 break; 8393 } 8394 8395 // Track nested structs we will inspect 8396 SmallVector<const Decl *, 4> VisitStack; 8397 8398 // Track where we are in the nested structs. Items will migrate from 8399 // VisitStack to HistoryStack as we do the DFS for bad field. 8400 SmallVector<const FieldDecl *, 4> HistoryStack; 8401 HistoryStack.push_back(nullptr); 8402 8403 // At this point we already handled everything except of a RecordType or 8404 // an ArrayType of a RecordType. 8405 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8406 const RecordType *RecTy = 8407 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8408 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8409 8410 VisitStack.push_back(RecTy->getDecl()); 8411 assert(VisitStack.back() && "First decl null?"); 8412 8413 do { 8414 const Decl *Next = VisitStack.pop_back_val(); 8415 if (!Next) { 8416 assert(!HistoryStack.empty()); 8417 // Found a marker, we have gone up a level 8418 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8419 ValidTypes.insert(Hist->getType().getTypePtr()); 8420 8421 continue; 8422 } 8423 8424 // Adds everything except the original parameter declaration (which is not a 8425 // field itself) to the history stack. 8426 const RecordDecl *RD; 8427 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8428 HistoryStack.push_back(Field); 8429 8430 QualType FieldTy = Field->getType(); 8431 // Other field types (known to be valid or invalid) are handled while we 8432 // walk around RecordDecl::fields(). 8433 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8434 "Unexpected type."); 8435 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8436 8437 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8438 } else { 8439 RD = cast<RecordDecl>(Next); 8440 } 8441 8442 // Add a null marker so we know when we've gone back up a level 8443 VisitStack.push_back(nullptr); 8444 8445 for (const auto *FD : RD->fields()) { 8446 QualType QT = FD->getType(); 8447 8448 if (ValidTypes.count(QT.getTypePtr())) 8449 continue; 8450 8451 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8452 if (ParamType == ValidKernelParam) 8453 continue; 8454 8455 if (ParamType == RecordKernelParam) { 8456 VisitStack.push_back(FD); 8457 continue; 8458 } 8459 8460 // OpenCL v1.2 s6.9.p: 8461 // Arguments to kernel functions that are declared to be a struct or union 8462 // do not allow OpenCL objects to be passed as elements of the struct or 8463 // union. 8464 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8465 ParamType == InvalidAddrSpacePtrKernelParam) { 8466 S.Diag(Param->getLocation(), 8467 diag::err_record_with_pointers_kernel_param) 8468 << PT->isUnionType() 8469 << PT; 8470 } else { 8471 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8472 } 8473 8474 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8475 << OrigRecDecl->getDeclName(); 8476 8477 // We have an error, now let's go back up through history and show where 8478 // the offending field came from 8479 for (ArrayRef<const FieldDecl *>::const_iterator 8480 I = HistoryStack.begin() + 1, 8481 E = HistoryStack.end(); 8482 I != E; ++I) { 8483 const FieldDecl *OuterField = *I; 8484 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8485 << OuterField->getType(); 8486 } 8487 8488 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8489 << QT->isPointerType() 8490 << QT; 8491 D.setInvalidType(); 8492 return; 8493 } 8494 } while (!VisitStack.empty()); 8495 } 8496 8497 /// Find the DeclContext in which a tag is implicitly declared if we see an 8498 /// elaborated type specifier in the specified context, and lookup finds 8499 /// nothing. 8500 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8501 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8502 DC = DC->getParent(); 8503 return DC; 8504 } 8505 8506 /// Find the Scope in which a tag is implicitly declared if we see an 8507 /// elaborated type specifier in the specified context, and lookup finds 8508 /// nothing. 8509 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8510 while (S->isClassScope() || 8511 (LangOpts.CPlusPlus && 8512 S->isFunctionPrototypeScope()) || 8513 ((S->getFlags() & Scope::DeclScope) == 0) || 8514 (S->getEntity() && S->getEntity()->isTransparentContext())) 8515 S = S->getParent(); 8516 return S; 8517 } 8518 8519 NamedDecl* 8520 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8521 TypeSourceInfo *TInfo, LookupResult &Previous, 8522 MultiTemplateParamsArg TemplateParamLists, 8523 bool &AddToScope) { 8524 QualType R = TInfo->getType(); 8525 8526 assert(R->isFunctionType()); 8527 8528 // TODO: consider using NameInfo for diagnostic. 8529 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8530 DeclarationName Name = NameInfo.getName(); 8531 StorageClass SC = getFunctionStorageClass(*this, D); 8532 8533 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8534 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8535 diag::err_invalid_thread) 8536 << DeclSpec::getSpecifierName(TSCS); 8537 8538 if (D.isFirstDeclarationOfMember()) 8539 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8540 D.getIdentifierLoc()); 8541 8542 bool isFriend = false; 8543 FunctionTemplateDecl *FunctionTemplate = nullptr; 8544 bool isMemberSpecialization = false; 8545 bool isFunctionTemplateSpecialization = false; 8546 8547 bool isDependentClassScopeExplicitSpecialization = false; 8548 bool HasExplicitTemplateArgs = false; 8549 TemplateArgumentListInfo TemplateArgs; 8550 8551 bool isVirtualOkay = false; 8552 8553 DeclContext *OriginalDC = DC; 8554 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8555 8556 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8557 isVirtualOkay); 8558 if (!NewFD) return nullptr; 8559 8560 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8561 NewFD->setTopLevelDeclInObjCContainer(); 8562 8563 // Set the lexical context. If this is a function-scope declaration, or has a 8564 // C++ scope specifier, or is the object of a friend declaration, the lexical 8565 // context will be different from the semantic context. 8566 NewFD->setLexicalDeclContext(CurContext); 8567 8568 if (IsLocalExternDecl) 8569 NewFD->setLocalExternDecl(); 8570 8571 if (getLangOpts().CPlusPlus) { 8572 bool isInline = D.getDeclSpec().isInlineSpecified(); 8573 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8574 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8575 isFriend = D.getDeclSpec().isFriendSpecified(); 8576 if (isFriend && !isInline && D.isFunctionDefinition()) { 8577 // C++ [class.friend]p5 8578 // A function can be defined in a friend declaration of a 8579 // class . . . . Such a function is implicitly inline. 8580 NewFD->setImplicitlyInline(); 8581 } 8582 8583 // If this is a method defined in an __interface, and is not a constructor 8584 // or an overloaded operator, then set the pure flag (isVirtual will already 8585 // return true). 8586 if (const CXXRecordDecl *Parent = 8587 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8588 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8589 NewFD->setPure(true); 8590 8591 // C++ [class.union]p2 8592 // A union can have member functions, but not virtual functions. 8593 if (isVirtual && Parent->isUnion()) 8594 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8595 } 8596 8597 SetNestedNameSpecifier(*this, NewFD, D); 8598 isMemberSpecialization = false; 8599 isFunctionTemplateSpecialization = false; 8600 if (D.isInvalidType()) 8601 NewFD->setInvalidDecl(); 8602 8603 // Match up the template parameter lists with the scope specifier, then 8604 // determine whether we have a template or a template specialization. 8605 bool Invalid = false; 8606 if (TemplateParameterList *TemplateParams = 8607 MatchTemplateParametersToScopeSpecifier( 8608 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8609 D.getCXXScopeSpec(), 8610 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8611 ? D.getName().TemplateId 8612 : nullptr, 8613 TemplateParamLists, isFriend, isMemberSpecialization, 8614 Invalid)) { 8615 if (TemplateParams->size() > 0) { 8616 // This is a function template 8617 8618 // Check that we can declare a template here. 8619 if (CheckTemplateDeclScope(S, TemplateParams)) 8620 NewFD->setInvalidDecl(); 8621 8622 // A destructor cannot be a template. 8623 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8624 Diag(NewFD->getLocation(), diag::err_destructor_template); 8625 NewFD->setInvalidDecl(); 8626 } 8627 8628 // If we're adding a template to a dependent context, we may need to 8629 // rebuilding some of the types used within the template parameter list, 8630 // now that we know what the current instantiation is. 8631 if (DC->isDependentContext()) { 8632 ContextRAII SavedContext(*this, DC); 8633 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8634 Invalid = true; 8635 } 8636 8637 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8638 NewFD->getLocation(), 8639 Name, TemplateParams, 8640 NewFD); 8641 FunctionTemplate->setLexicalDeclContext(CurContext); 8642 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8643 8644 // For source fidelity, store the other template param lists. 8645 if (TemplateParamLists.size() > 1) { 8646 NewFD->setTemplateParameterListsInfo(Context, 8647 TemplateParamLists.drop_back(1)); 8648 } 8649 } else { 8650 // This is a function template specialization. 8651 isFunctionTemplateSpecialization = true; 8652 // For source fidelity, store all the template param lists. 8653 if (TemplateParamLists.size() > 0) 8654 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8655 8656 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8657 if (isFriend) { 8658 // We want to remove the "template<>", found here. 8659 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8660 8661 // If we remove the template<> and the name is not a 8662 // template-id, we're actually silently creating a problem: 8663 // the friend declaration will refer to an untemplated decl, 8664 // and clearly the user wants a template specialization. So 8665 // we need to insert '<>' after the name. 8666 SourceLocation InsertLoc; 8667 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8668 InsertLoc = D.getName().getSourceRange().getEnd(); 8669 InsertLoc = getLocForEndOfToken(InsertLoc); 8670 } 8671 8672 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8673 << Name << RemoveRange 8674 << FixItHint::CreateRemoval(RemoveRange) 8675 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8676 } 8677 } 8678 } else { 8679 // All template param lists were matched against the scope specifier: 8680 // this is NOT (an explicit specialization of) a template. 8681 if (TemplateParamLists.size() > 0) 8682 // For source fidelity, store all the template param lists. 8683 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8684 } 8685 8686 if (Invalid) { 8687 NewFD->setInvalidDecl(); 8688 if (FunctionTemplate) 8689 FunctionTemplate->setInvalidDecl(); 8690 } 8691 8692 // C++ [dcl.fct.spec]p5: 8693 // The virtual specifier shall only be used in declarations of 8694 // nonstatic class member functions that appear within a 8695 // member-specification of a class declaration; see 10.3. 8696 // 8697 if (isVirtual && !NewFD->isInvalidDecl()) { 8698 if (!isVirtualOkay) { 8699 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8700 diag::err_virtual_non_function); 8701 } else if (!CurContext->isRecord()) { 8702 // 'virtual' was specified outside of the class. 8703 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8704 diag::err_virtual_out_of_class) 8705 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8706 } else if (NewFD->getDescribedFunctionTemplate()) { 8707 // C++ [temp.mem]p3: 8708 // A member function template shall not be virtual. 8709 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8710 diag::err_virtual_member_function_template) 8711 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8712 } else { 8713 // Okay: Add virtual to the method. 8714 NewFD->setVirtualAsWritten(true); 8715 } 8716 8717 if (getLangOpts().CPlusPlus14 && 8718 NewFD->getReturnType()->isUndeducedType()) 8719 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8720 } 8721 8722 if (getLangOpts().CPlusPlus14 && 8723 (NewFD->isDependentContext() || 8724 (isFriend && CurContext->isDependentContext())) && 8725 NewFD->getReturnType()->isUndeducedType()) { 8726 // If the function template is referenced directly (for instance, as a 8727 // member of the current instantiation), pretend it has a dependent type. 8728 // This is not really justified by the standard, but is the only sane 8729 // thing to do. 8730 // FIXME: For a friend function, we have not marked the function as being 8731 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8732 const FunctionProtoType *FPT = 8733 NewFD->getType()->castAs<FunctionProtoType>(); 8734 QualType Result = 8735 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8736 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8737 FPT->getExtProtoInfo())); 8738 } 8739 8740 // C++ [dcl.fct.spec]p3: 8741 // The inline specifier shall not appear on a block scope function 8742 // declaration. 8743 if (isInline && !NewFD->isInvalidDecl()) { 8744 if (CurContext->isFunctionOrMethod()) { 8745 // 'inline' is not allowed on block scope function declaration. 8746 Diag(D.getDeclSpec().getInlineSpecLoc(), 8747 diag::err_inline_declaration_block_scope) << Name 8748 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8749 } 8750 } 8751 8752 // C++ [dcl.fct.spec]p6: 8753 // The explicit specifier shall be used only in the declaration of a 8754 // constructor or conversion function within its class definition; 8755 // see 12.3.1 and 12.3.2. 8756 if (hasExplicit && !NewFD->isInvalidDecl() && 8757 !isa<CXXDeductionGuideDecl>(NewFD)) { 8758 if (!CurContext->isRecord()) { 8759 // 'explicit' was specified outside of the class. 8760 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8761 diag::err_explicit_out_of_class) 8762 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 8763 } else if (!isa<CXXConstructorDecl>(NewFD) && 8764 !isa<CXXConversionDecl>(NewFD)) { 8765 // 'explicit' was specified on a function that wasn't a constructor 8766 // or conversion function. 8767 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8768 diag::err_explicit_non_ctor_or_conv_function) 8769 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 8770 } 8771 } 8772 8773 if (ConstexprSpecKind ConstexprKind = 8774 D.getDeclSpec().getConstexprSpecifier()) { 8775 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8776 // are implicitly inline. 8777 NewFD->setImplicitlyInline(); 8778 8779 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8780 // be either constructors or to return a literal type. Therefore, 8781 // destructors cannot be declared constexpr. 8782 if (isa<CXXDestructorDecl>(NewFD)) { 8783 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 8784 << ConstexprKind; 8785 } 8786 } 8787 8788 // If __module_private__ was specified, mark the function accordingly. 8789 if (D.getDeclSpec().isModulePrivateSpecified()) { 8790 if (isFunctionTemplateSpecialization) { 8791 SourceLocation ModulePrivateLoc 8792 = D.getDeclSpec().getModulePrivateSpecLoc(); 8793 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8794 << 0 8795 << FixItHint::CreateRemoval(ModulePrivateLoc); 8796 } else { 8797 NewFD->setModulePrivate(); 8798 if (FunctionTemplate) 8799 FunctionTemplate->setModulePrivate(); 8800 } 8801 } 8802 8803 if (isFriend) { 8804 if (FunctionTemplate) { 8805 FunctionTemplate->setObjectOfFriendDecl(); 8806 FunctionTemplate->setAccess(AS_public); 8807 } 8808 NewFD->setObjectOfFriendDecl(); 8809 NewFD->setAccess(AS_public); 8810 } 8811 8812 // If a function is defined as defaulted or deleted, mark it as such now. 8813 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8814 // definition kind to FDK_Definition. 8815 switch (D.getFunctionDefinitionKind()) { 8816 case FDK_Declaration: 8817 case FDK_Definition: 8818 break; 8819 8820 case FDK_Defaulted: 8821 NewFD->setDefaulted(); 8822 break; 8823 8824 case FDK_Deleted: 8825 NewFD->setDeletedAsWritten(); 8826 break; 8827 } 8828 8829 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8830 D.isFunctionDefinition()) { 8831 // C++ [class.mfct]p2: 8832 // A member function may be defined (8.4) in its class definition, in 8833 // which case it is an inline member function (7.1.2) 8834 NewFD->setImplicitlyInline(); 8835 } 8836 8837 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8838 !CurContext->isRecord()) { 8839 // C++ [class.static]p1: 8840 // A data or function member of a class may be declared static 8841 // in a class definition, in which case it is a static member of 8842 // the class. 8843 8844 // Complain about the 'static' specifier if it's on an out-of-line 8845 // member function definition. 8846 8847 // MSVC permits the use of a 'static' storage specifier on an out-of-line 8848 // member function template declaration and class member template 8849 // declaration (MSVC versions before 2015), warn about this. 8850 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8851 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 8852 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 8853 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 8854 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 8855 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8856 } 8857 8858 // C++11 [except.spec]p15: 8859 // A deallocation function with no exception-specification is treated 8860 // as if it were specified with noexcept(true). 8861 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8862 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8863 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8864 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8865 NewFD->setType(Context.getFunctionType( 8866 FPT->getReturnType(), FPT->getParamTypes(), 8867 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8868 } 8869 8870 // Filter out previous declarations that don't match the scope. 8871 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8872 D.getCXXScopeSpec().isNotEmpty() || 8873 isMemberSpecialization || 8874 isFunctionTemplateSpecialization); 8875 8876 // Handle GNU asm-label extension (encoded as an attribute). 8877 if (Expr *E = (Expr*) D.getAsmLabel()) { 8878 // The parser guarantees this is a string. 8879 StringLiteral *SE = cast<StringLiteral>(E); 8880 NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getStrTokenLoc(0), 8881 SE->getString())); 8882 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8883 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8884 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8885 if (I != ExtnameUndeclaredIdentifiers.end()) { 8886 if (isDeclExternC(NewFD)) { 8887 NewFD->addAttr(I->second); 8888 ExtnameUndeclaredIdentifiers.erase(I); 8889 } else 8890 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8891 << /*Variable*/0 << NewFD; 8892 } 8893 } 8894 8895 // Copy the parameter declarations from the declarator D to the function 8896 // declaration NewFD, if they are available. First scavenge them into Params. 8897 SmallVector<ParmVarDecl*, 16> Params; 8898 unsigned FTIIdx; 8899 if (D.isFunctionDeclarator(FTIIdx)) { 8900 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8901 8902 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8903 // function that takes no arguments, not a function that takes a 8904 // single void argument. 8905 // We let through "const void" here because Sema::GetTypeForDeclarator 8906 // already checks for that case. 8907 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8908 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8909 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8910 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8911 Param->setDeclContext(NewFD); 8912 Params.push_back(Param); 8913 8914 if (Param->isInvalidDecl()) 8915 NewFD->setInvalidDecl(); 8916 } 8917 } 8918 8919 if (!getLangOpts().CPlusPlus) { 8920 // In C, find all the tag declarations from the prototype and move them 8921 // into the function DeclContext. Remove them from the surrounding tag 8922 // injection context of the function, which is typically but not always 8923 // the TU. 8924 DeclContext *PrototypeTagContext = 8925 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8926 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8927 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8928 8929 // We don't want to reparent enumerators. Look at their parent enum 8930 // instead. 8931 if (!TD) { 8932 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8933 TD = cast<EnumDecl>(ECD->getDeclContext()); 8934 } 8935 if (!TD) 8936 continue; 8937 DeclContext *TagDC = TD->getLexicalDeclContext(); 8938 if (!TagDC->containsDecl(TD)) 8939 continue; 8940 TagDC->removeDecl(TD); 8941 TD->setDeclContext(NewFD); 8942 NewFD->addDecl(TD); 8943 8944 // Preserve the lexical DeclContext if it is not the surrounding tag 8945 // injection context of the FD. In this example, the semantic context of 8946 // E will be f and the lexical context will be S, while both the 8947 // semantic and lexical contexts of S will be f: 8948 // void f(struct S { enum E { a } f; } s); 8949 if (TagDC != PrototypeTagContext) 8950 TD->setLexicalDeclContext(TagDC); 8951 } 8952 } 8953 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8954 // When we're declaring a function with a typedef, typeof, etc as in the 8955 // following example, we'll need to synthesize (unnamed) 8956 // parameters for use in the declaration. 8957 // 8958 // @code 8959 // typedef void fn(int); 8960 // fn f; 8961 // @endcode 8962 8963 // Synthesize a parameter for each argument type. 8964 for (const auto &AI : FT->param_types()) { 8965 ParmVarDecl *Param = 8966 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8967 Param->setScopeInfo(0, Params.size()); 8968 Params.push_back(Param); 8969 } 8970 } else { 8971 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8972 "Should not need args for typedef of non-prototype fn"); 8973 } 8974 8975 // Finally, we know we have the right number of parameters, install them. 8976 NewFD->setParams(Params); 8977 8978 if (D.getDeclSpec().isNoreturnSpecified()) 8979 NewFD->addAttr(C11NoReturnAttr::Create(Context, 8980 D.getDeclSpec().getNoreturnSpecLoc(), 8981 AttributeCommonInfo::AS_Keyword)); 8982 8983 // Functions returning a variably modified type violate C99 6.7.5.2p2 8984 // because all functions have linkage. 8985 if (!NewFD->isInvalidDecl() && 8986 NewFD->getReturnType()->isVariablyModifiedType()) { 8987 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8988 NewFD->setInvalidDecl(); 8989 } 8990 8991 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8992 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8993 !NewFD->hasAttr<SectionAttr>()) 8994 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 8995 Context, PragmaClangTextSection.SectionName, 8996 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 8997 8998 // Apply an implicit SectionAttr if #pragma code_seg is active. 8999 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9000 !NewFD->hasAttr<SectionAttr>()) { 9001 NewFD->addAttr(SectionAttr::CreateImplicit( 9002 Context, CodeSegStack.CurrentValue->getString(), 9003 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9004 SectionAttr::Declspec_allocate)); 9005 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9006 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9007 ASTContext::PSF_Read, 9008 NewFD)) 9009 NewFD->dropAttr<SectionAttr>(); 9010 } 9011 9012 // Apply an implicit CodeSegAttr from class declspec or 9013 // apply an implicit SectionAttr from #pragma code_seg if active. 9014 if (!NewFD->hasAttr<CodeSegAttr>()) { 9015 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9016 D.isFunctionDefinition())) { 9017 NewFD->addAttr(SAttr); 9018 } 9019 } 9020 9021 // Handle attributes. 9022 ProcessDeclAttributes(S, NewFD, D); 9023 9024 if (getLangOpts().OpenCL) { 9025 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9026 // type declaration will generate a compilation error. 9027 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9028 if (AddressSpace != LangAS::Default) { 9029 Diag(NewFD->getLocation(), 9030 diag::err_opencl_return_value_with_address_space); 9031 NewFD->setInvalidDecl(); 9032 } 9033 } 9034 9035 if (!getLangOpts().CPlusPlus) { 9036 // Perform semantic checking on the function declaration. 9037 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9038 CheckMain(NewFD, D.getDeclSpec()); 9039 9040 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9041 CheckMSVCRTEntryPoint(NewFD); 9042 9043 if (!NewFD->isInvalidDecl()) 9044 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9045 isMemberSpecialization)); 9046 else if (!Previous.empty()) 9047 // Recover gracefully from an invalid redeclaration. 9048 D.setRedeclaration(true); 9049 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9050 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9051 "previous declaration set still overloaded"); 9052 9053 // Diagnose no-prototype function declarations with calling conventions that 9054 // don't support variadic calls. Only do this in C and do it after merging 9055 // possibly prototyped redeclarations. 9056 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9057 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9058 CallingConv CC = FT->getExtInfo().getCC(); 9059 if (!supportsVariadicCall(CC)) { 9060 // Windows system headers sometimes accidentally use stdcall without 9061 // (void) parameters, so we relax this to a warning. 9062 int DiagID = 9063 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9064 Diag(NewFD->getLocation(), DiagID) 9065 << FunctionType::getNameForCallConv(CC); 9066 } 9067 } 9068 9069 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9070 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9071 checkNonTrivialCUnion(NewFD->getReturnType(), 9072 NewFD->getReturnTypeSourceRange().getBegin(), 9073 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9074 } else { 9075 // C++11 [replacement.functions]p3: 9076 // The program's definitions shall not be specified as inline. 9077 // 9078 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9079 // 9080 // Suppress the diagnostic if the function is __attribute__((used)), since 9081 // that forces an external definition to be emitted. 9082 if (D.getDeclSpec().isInlineSpecified() && 9083 NewFD->isReplaceableGlobalAllocationFunction() && 9084 !NewFD->hasAttr<UsedAttr>()) 9085 Diag(D.getDeclSpec().getInlineSpecLoc(), 9086 diag::ext_operator_new_delete_declared_inline) 9087 << NewFD->getDeclName(); 9088 9089 // If the declarator is a template-id, translate the parser's template 9090 // argument list into our AST format. 9091 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9092 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9093 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9094 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9095 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9096 TemplateId->NumArgs); 9097 translateTemplateArguments(TemplateArgsPtr, 9098 TemplateArgs); 9099 9100 HasExplicitTemplateArgs = true; 9101 9102 if (NewFD->isInvalidDecl()) { 9103 HasExplicitTemplateArgs = false; 9104 } else if (FunctionTemplate) { 9105 // Function template with explicit template arguments. 9106 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9107 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9108 9109 HasExplicitTemplateArgs = false; 9110 } else { 9111 assert((isFunctionTemplateSpecialization || 9112 D.getDeclSpec().isFriendSpecified()) && 9113 "should have a 'template<>' for this decl"); 9114 // "friend void foo<>(int);" is an implicit specialization decl. 9115 isFunctionTemplateSpecialization = true; 9116 } 9117 } else if (isFriend && isFunctionTemplateSpecialization) { 9118 // This combination is only possible in a recovery case; the user 9119 // wrote something like: 9120 // template <> friend void foo(int); 9121 // which we're recovering from as if the user had written: 9122 // friend void foo<>(int); 9123 // Go ahead and fake up a template id. 9124 HasExplicitTemplateArgs = true; 9125 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9126 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9127 } 9128 9129 // We do not add HD attributes to specializations here because 9130 // they may have different constexpr-ness compared to their 9131 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9132 // may end up with different effective targets. Instead, a 9133 // specialization inherits its target attributes from its template 9134 // in the CheckFunctionTemplateSpecialization() call below. 9135 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9136 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9137 9138 // If it's a friend (and only if it's a friend), it's possible 9139 // that either the specialized function type or the specialized 9140 // template is dependent, and therefore matching will fail. In 9141 // this case, don't check the specialization yet. 9142 bool InstantiationDependent = false; 9143 if (isFunctionTemplateSpecialization && isFriend && 9144 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9145 TemplateSpecializationType::anyDependentTemplateArguments( 9146 TemplateArgs, 9147 InstantiationDependent))) { 9148 assert(HasExplicitTemplateArgs && 9149 "friend function specialization without template args"); 9150 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9151 Previous)) 9152 NewFD->setInvalidDecl(); 9153 } else if (isFunctionTemplateSpecialization) { 9154 if (CurContext->isDependentContext() && CurContext->isRecord() 9155 && !isFriend) { 9156 isDependentClassScopeExplicitSpecialization = true; 9157 } else if (!NewFD->isInvalidDecl() && 9158 CheckFunctionTemplateSpecialization( 9159 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9160 Previous)) 9161 NewFD->setInvalidDecl(); 9162 9163 // C++ [dcl.stc]p1: 9164 // A storage-class-specifier shall not be specified in an explicit 9165 // specialization (14.7.3) 9166 FunctionTemplateSpecializationInfo *Info = 9167 NewFD->getTemplateSpecializationInfo(); 9168 if (Info && SC != SC_None) { 9169 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9170 Diag(NewFD->getLocation(), 9171 diag::err_explicit_specialization_inconsistent_storage_class) 9172 << SC 9173 << FixItHint::CreateRemoval( 9174 D.getDeclSpec().getStorageClassSpecLoc()); 9175 9176 else 9177 Diag(NewFD->getLocation(), 9178 diag::ext_explicit_specialization_storage_class) 9179 << FixItHint::CreateRemoval( 9180 D.getDeclSpec().getStorageClassSpecLoc()); 9181 } 9182 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9183 if (CheckMemberSpecialization(NewFD, Previous)) 9184 NewFD->setInvalidDecl(); 9185 } 9186 9187 // Perform semantic checking on the function declaration. 9188 if (!isDependentClassScopeExplicitSpecialization) { 9189 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9190 CheckMain(NewFD, D.getDeclSpec()); 9191 9192 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9193 CheckMSVCRTEntryPoint(NewFD); 9194 9195 if (!NewFD->isInvalidDecl()) 9196 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9197 isMemberSpecialization)); 9198 else if (!Previous.empty()) 9199 // Recover gracefully from an invalid redeclaration. 9200 D.setRedeclaration(true); 9201 } 9202 9203 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9204 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9205 "previous declaration set still overloaded"); 9206 9207 NamedDecl *PrincipalDecl = (FunctionTemplate 9208 ? cast<NamedDecl>(FunctionTemplate) 9209 : NewFD); 9210 9211 if (isFriend && NewFD->getPreviousDecl()) { 9212 AccessSpecifier Access = AS_public; 9213 if (!NewFD->isInvalidDecl()) 9214 Access = NewFD->getPreviousDecl()->getAccess(); 9215 9216 NewFD->setAccess(Access); 9217 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9218 } 9219 9220 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9221 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9222 PrincipalDecl->setNonMemberOperator(); 9223 9224 // If we have a function template, check the template parameter 9225 // list. This will check and merge default template arguments. 9226 if (FunctionTemplate) { 9227 FunctionTemplateDecl *PrevTemplate = 9228 FunctionTemplate->getPreviousDecl(); 9229 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9230 PrevTemplate ? PrevTemplate->getTemplateParameters() 9231 : nullptr, 9232 D.getDeclSpec().isFriendSpecified() 9233 ? (D.isFunctionDefinition() 9234 ? TPC_FriendFunctionTemplateDefinition 9235 : TPC_FriendFunctionTemplate) 9236 : (D.getCXXScopeSpec().isSet() && 9237 DC && DC->isRecord() && 9238 DC->isDependentContext()) 9239 ? TPC_ClassTemplateMember 9240 : TPC_FunctionTemplate); 9241 } 9242 9243 if (NewFD->isInvalidDecl()) { 9244 // Ignore all the rest of this. 9245 } else if (!D.isRedeclaration()) { 9246 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9247 AddToScope }; 9248 // Fake up an access specifier if it's supposed to be a class member. 9249 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9250 NewFD->setAccess(AS_public); 9251 9252 // Qualified decls generally require a previous declaration. 9253 if (D.getCXXScopeSpec().isSet()) { 9254 // ...with the major exception of templated-scope or 9255 // dependent-scope friend declarations. 9256 9257 // TODO: we currently also suppress this check in dependent 9258 // contexts because (1) the parameter depth will be off when 9259 // matching friend templates and (2) we might actually be 9260 // selecting a friend based on a dependent factor. But there 9261 // are situations where these conditions don't apply and we 9262 // can actually do this check immediately. 9263 // 9264 // Unless the scope is dependent, it's always an error if qualified 9265 // redeclaration lookup found nothing at all. Diagnose that now; 9266 // nothing will diagnose that error later. 9267 if (isFriend && 9268 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9269 (!Previous.empty() && CurContext->isDependentContext()))) { 9270 // ignore these 9271 } else { 9272 // The user tried to provide an out-of-line definition for a 9273 // function that is a member of a class or namespace, but there 9274 // was no such member function declared (C++ [class.mfct]p2, 9275 // C++ [namespace.memdef]p2). For example: 9276 // 9277 // class X { 9278 // void f() const; 9279 // }; 9280 // 9281 // void X::f() { } // ill-formed 9282 // 9283 // Complain about this problem, and attempt to suggest close 9284 // matches (e.g., those that differ only in cv-qualifiers and 9285 // whether the parameter types are references). 9286 9287 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9288 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9289 AddToScope = ExtraArgs.AddToScope; 9290 return Result; 9291 } 9292 } 9293 9294 // Unqualified local friend declarations are required to resolve 9295 // to something. 9296 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9297 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9298 *this, Previous, NewFD, ExtraArgs, true, S)) { 9299 AddToScope = ExtraArgs.AddToScope; 9300 return Result; 9301 } 9302 } 9303 } else if (!D.isFunctionDefinition() && 9304 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9305 !isFriend && !isFunctionTemplateSpecialization && 9306 !isMemberSpecialization) { 9307 // An out-of-line member function declaration must also be a 9308 // definition (C++ [class.mfct]p2). 9309 // Note that this is not the case for explicit specializations of 9310 // function templates or member functions of class templates, per 9311 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9312 // extension for compatibility with old SWIG code which likes to 9313 // generate them. 9314 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9315 << D.getCXXScopeSpec().getRange(); 9316 } 9317 } 9318 9319 ProcessPragmaWeak(S, NewFD); 9320 checkAttributesAfterMerging(*this, *NewFD); 9321 9322 AddKnownFunctionAttributes(NewFD); 9323 9324 if (NewFD->hasAttr<OverloadableAttr>() && 9325 !NewFD->getType()->getAs<FunctionProtoType>()) { 9326 Diag(NewFD->getLocation(), 9327 diag::err_attribute_overloadable_no_prototype) 9328 << NewFD; 9329 9330 // Turn this into a variadic function with no parameters. 9331 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9332 FunctionProtoType::ExtProtoInfo EPI( 9333 Context.getDefaultCallingConvention(true, false)); 9334 EPI.Variadic = true; 9335 EPI.ExtInfo = FT->getExtInfo(); 9336 9337 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9338 NewFD->setType(R); 9339 } 9340 9341 // If there's a #pragma GCC visibility in scope, and this isn't a class 9342 // member, set the visibility of this function. 9343 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9344 AddPushedVisibilityAttribute(NewFD); 9345 9346 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9347 // marking the function. 9348 AddCFAuditedAttribute(NewFD); 9349 9350 // If this is a function definition, check if we have to apply optnone due to 9351 // a pragma. 9352 if(D.isFunctionDefinition()) 9353 AddRangeBasedOptnone(NewFD); 9354 9355 // If this is the first declaration of an extern C variable, update 9356 // the map of such variables. 9357 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9358 isIncompleteDeclExternC(*this, NewFD)) 9359 RegisterLocallyScopedExternCDecl(NewFD, S); 9360 9361 // Set this FunctionDecl's range up to the right paren. 9362 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9363 9364 if (D.isRedeclaration() && !Previous.empty()) { 9365 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9366 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9367 isMemberSpecialization || 9368 isFunctionTemplateSpecialization, 9369 D.isFunctionDefinition()); 9370 } 9371 9372 if (getLangOpts().CUDA) { 9373 IdentifierInfo *II = NewFD->getIdentifier(); 9374 if (II && II->isStr(getCudaConfigureFuncName()) && 9375 !NewFD->isInvalidDecl() && 9376 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9377 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9378 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9379 << getCudaConfigureFuncName(); 9380 Context.setcudaConfigureCallDecl(NewFD); 9381 } 9382 9383 // Variadic functions, other than a *declaration* of printf, are not allowed 9384 // in device-side CUDA code, unless someone passed 9385 // -fcuda-allow-variadic-functions. 9386 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9387 (NewFD->hasAttr<CUDADeviceAttr>() || 9388 NewFD->hasAttr<CUDAGlobalAttr>()) && 9389 !(II && II->isStr("printf") && NewFD->isExternC() && 9390 !D.isFunctionDefinition())) { 9391 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9392 } 9393 } 9394 9395 MarkUnusedFileScopedDecl(NewFD); 9396 9397 9398 9399 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9400 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9401 if ((getLangOpts().OpenCLVersion >= 120) 9402 && (SC == SC_Static)) { 9403 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9404 D.setInvalidType(); 9405 } 9406 9407 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9408 if (!NewFD->getReturnType()->isVoidType()) { 9409 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9410 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9411 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9412 : FixItHint()); 9413 D.setInvalidType(); 9414 } 9415 9416 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9417 for (auto Param : NewFD->parameters()) 9418 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9419 9420 if (getLangOpts().OpenCLCPlusPlus) { 9421 if (DC->isRecord()) { 9422 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9423 D.setInvalidType(); 9424 } 9425 if (FunctionTemplate) { 9426 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9427 D.setInvalidType(); 9428 } 9429 } 9430 } 9431 9432 if (getLangOpts().CPlusPlus) { 9433 if (FunctionTemplate) { 9434 if (NewFD->isInvalidDecl()) 9435 FunctionTemplate->setInvalidDecl(); 9436 return FunctionTemplate; 9437 } 9438 9439 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9440 CompleteMemberSpecialization(NewFD, Previous); 9441 } 9442 9443 for (const ParmVarDecl *Param : NewFD->parameters()) { 9444 QualType PT = Param->getType(); 9445 9446 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9447 // types. 9448 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9449 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9450 QualType ElemTy = PipeTy->getElementType(); 9451 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9452 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9453 D.setInvalidType(); 9454 } 9455 } 9456 } 9457 } 9458 9459 // Here we have an function template explicit specialization at class scope. 9460 // The actual specialization will be postponed to template instatiation 9461 // time via the ClassScopeFunctionSpecializationDecl node. 9462 if (isDependentClassScopeExplicitSpecialization) { 9463 ClassScopeFunctionSpecializationDecl *NewSpec = 9464 ClassScopeFunctionSpecializationDecl::Create( 9465 Context, CurContext, NewFD->getLocation(), 9466 cast<CXXMethodDecl>(NewFD), 9467 HasExplicitTemplateArgs, TemplateArgs); 9468 CurContext->addDecl(NewSpec); 9469 AddToScope = false; 9470 } 9471 9472 // Diagnose availability attributes. Availability cannot be used on functions 9473 // that are run during load/unload. 9474 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9475 if (NewFD->hasAttr<ConstructorAttr>()) { 9476 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9477 << 1; 9478 NewFD->dropAttr<AvailabilityAttr>(); 9479 } 9480 if (NewFD->hasAttr<DestructorAttr>()) { 9481 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9482 << 2; 9483 NewFD->dropAttr<AvailabilityAttr>(); 9484 } 9485 } 9486 9487 return NewFD; 9488 } 9489 9490 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9491 /// when __declspec(code_seg) "is applied to a class, all member functions of 9492 /// the class and nested classes -- this includes compiler-generated special 9493 /// member functions -- are put in the specified segment." 9494 /// The actual behavior is a little more complicated. The Microsoft compiler 9495 /// won't check outer classes if there is an active value from #pragma code_seg. 9496 /// The CodeSeg is always applied from the direct parent but only from outer 9497 /// classes when the #pragma code_seg stack is empty. See: 9498 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9499 /// available since MS has removed the page. 9500 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9501 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9502 if (!Method) 9503 return nullptr; 9504 const CXXRecordDecl *Parent = Method->getParent(); 9505 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9506 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9507 NewAttr->setImplicit(true); 9508 return NewAttr; 9509 } 9510 9511 // The Microsoft compiler won't check outer classes for the CodeSeg 9512 // when the #pragma code_seg stack is active. 9513 if (S.CodeSegStack.CurrentValue) 9514 return nullptr; 9515 9516 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9517 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9518 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9519 NewAttr->setImplicit(true); 9520 return NewAttr; 9521 } 9522 } 9523 return nullptr; 9524 } 9525 9526 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9527 /// containing class. Otherwise it will return implicit SectionAttr if the 9528 /// function is a definition and there is an active value on CodeSegStack 9529 /// (from the current #pragma code-seg value). 9530 /// 9531 /// \param FD Function being declared. 9532 /// \param IsDefinition Whether it is a definition or just a declarartion. 9533 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9534 /// nullptr if no attribute should be added. 9535 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9536 bool IsDefinition) { 9537 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9538 return A; 9539 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9540 CodeSegStack.CurrentValue) 9541 return SectionAttr::CreateImplicit( 9542 getASTContext(), CodeSegStack.CurrentValue->getString(), 9543 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9544 SectionAttr::Declspec_allocate); 9545 return nullptr; 9546 } 9547 9548 /// Determines if we can perform a correct type check for \p D as a 9549 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9550 /// best-effort check. 9551 /// 9552 /// \param NewD The new declaration. 9553 /// \param OldD The old declaration. 9554 /// \param NewT The portion of the type of the new declaration to check. 9555 /// \param OldT The portion of the type of the old declaration to check. 9556 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9557 QualType NewT, QualType OldT) { 9558 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9559 return true; 9560 9561 // For dependently-typed local extern declarations and friends, we can't 9562 // perform a correct type check in general until instantiation: 9563 // 9564 // int f(); 9565 // template<typename T> void g() { T f(); } 9566 // 9567 // (valid if g() is only instantiated with T = int). 9568 if (NewT->isDependentType() && 9569 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9570 return false; 9571 9572 // Similarly, if the previous declaration was a dependent local extern 9573 // declaration, we don't really know its type yet. 9574 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9575 return false; 9576 9577 return true; 9578 } 9579 9580 /// Checks if the new declaration declared in dependent context must be 9581 /// put in the same redeclaration chain as the specified declaration. 9582 /// 9583 /// \param D Declaration that is checked. 9584 /// \param PrevDecl Previous declaration found with proper lookup method for the 9585 /// same declaration name. 9586 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9587 /// belongs to. 9588 /// 9589 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9590 if (!D->getLexicalDeclContext()->isDependentContext()) 9591 return true; 9592 9593 // Don't chain dependent friend function definitions until instantiation, to 9594 // permit cases like 9595 // 9596 // void func(); 9597 // template<typename T> class C1 { friend void func() {} }; 9598 // template<typename T> class C2 { friend void func() {} }; 9599 // 9600 // ... which is valid if only one of C1 and C2 is ever instantiated. 9601 // 9602 // FIXME: This need only apply to function definitions. For now, we proxy 9603 // this by checking for a file-scope function. We do not want this to apply 9604 // to friend declarations nominating member functions, because that gets in 9605 // the way of access checks. 9606 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9607 return false; 9608 9609 auto *VD = dyn_cast<ValueDecl>(D); 9610 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9611 return !VD || !PrevVD || 9612 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9613 PrevVD->getType()); 9614 } 9615 9616 /// Check the target attribute of the function for MultiVersion 9617 /// validity. 9618 /// 9619 /// Returns true if there was an error, false otherwise. 9620 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9621 const auto *TA = FD->getAttr<TargetAttr>(); 9622 assert(TA && "MultiVersion Candidate requires a target attribute"); 9623 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9624 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9625 enum ErrType { Feature = 0, Architecture = 1 }; 9626 9627 if (!ParseInfo.Architecture.empty() && 9628 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9629 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9630 << Architecture << ParseInfo.Architecture; 9631 return true; 9632 } 9633 9634 for (const auto &Feat : ParseInfo.Features) { 9635 auto BareFeat = StringRef{Feat}.substr(1); 9636 if (Feat[0] == '-') { 9637 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9638 << Feature << ("no-" + BareFeat).str(); 9639 return true; 9640 } 9641 9642 if (!TargetInfo.validateCpuSupports(BareFeat) || 9643 !TargetInfo.isValidFeatureName(BareFeat)) { 9644 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9645 << Feature << BareFeat; 9646 return true; 9647 } 9648 } 9649 return false; 9650 } 9651 9652 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9653 MultiVersionKind MVType) { 9654 for (const Attr *A : FD->attrs()) { 9655 switch (A->getKind()) { 9656 case attr::CPUDispatch: 9657 case attr::CPUSpecific: 9658 if (MVType != MultiVersionKind::CPUDispatch && 9659 MVType != MultiVersionKind::CPUSpecific) 9660 return true; 9661 break; 9662 case attr::Target: 9663 if (MVType != MultiVersionKind::Target) 9664 return true; 9665 break; 9666 default: 9667 return true; 9668 } 9669 } 9670 return false; 9671 } 9672 9673 bool Sema::areMultiversionVariantFunctionsCompatible( 9674 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 9675 const PartialDiagnostic &NoProtoDiagID, 9676 const PartialDiagnosticAt &NoteCausedDiagIDAt, 9677 const PartialDiagnosticAt &NoSupportDiagIDAt, 9678 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 9679 bool ConstexprSupported) { 9680 enum DoesntSupport { 9681 FuncTemplates = 0, 9682 VirtFuncs = 1, 9683 DeducedReturn = 2, 9684 Constructors = 3, 9685 Destructors = 4, 9686 DeletedFuncs = 5, 9687 DefaultedFuncs = 6, 9688 ConstexprFuncs = 7, 9689 ConstevalFuncs = 8, 9690 }; 9691 enum Different { 9692 CallingConv = 0, 9693 ReturnType = 1, 9694 ConstexprSpec = 2, 9695 InlineSpec = 3, 9696 StorageClass = 4, 9697 Linkage = 5, 9698 }; 9699 9700 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { 9701 Diag(OldFD->getLocation(), NoProtoDiagID); 9702 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 9703 return true; 9704 } 9705 9706 if (!NewFD->getType()->getAs<FunctionProtoType>()) 9707 return Diag(NewFD->getLocation(), NoProtoDiagID); 9708 9709 if (!TemplatesSupported && 9710 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9711 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9712 << FuncTemplates; 9713 9714 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9715 if (NewCXXFD->isVirtual()) 9716 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9717 << VirtFuncs; 9718 9719 if (isa<CXXConstructorDecl>(NewCXXFD)) 9720 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9721 << Constructors; 9722 9723 if (isa<CXXDestructorDecl>(NewCXXFD)) 9724 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9725 << Destructors; 9726 } 9727 9728 if (NewFD->isDeleted()) 9729 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9730 << DeletedFuncs; 9731 9732 if (NewFD->isDefaulted()) 9733 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9734 << DefaultedFuncs; 9735 9736 if (!ConstexprSupported && NewFD->isConstexpr()) 9737 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9738 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 9739 9740 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 9741 const auto *NewType = cast<FunctionType>(NewQType); 9742 QualType NewReturnType = NewType->getReturnType(); 9743 9744 if (NewReturnType->isUndeducedType()) 9745 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 9746 << DeducedReturn; 9747 9748 // Ensure the return type is identical. 9749 if (OldFD) { 9750 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 9751 const auto *OldType = cast<FunctionType>(OldQType); 9752 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9753 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9754 9755 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9756 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 9757 9758 QualType OldReturnType = OldType->getReturnType(); 9759 9760 if (OldReturnType != NewReturnType) 9761 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 9762 9763 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 9764 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 9765 9766 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9767 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 9768 9769 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9770 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 9771 9772 if (OldFD->isExternC() != NewFD->isExternC()) 9773 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 9774 9775 if (CheckEquivalentExceptionSpec( 9776 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9777 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9778 return true; 9779 } 9780 return false; 9781 } 9782 9783 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9784 const FunctionDecl *NewFD, 9785 bool CausesMV, 9786 MultiVersionKind MVType) { 9787 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9788 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9789 if (OldFD) 9790 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9791 return true; 9792 } 9793 9794 bool IsCPUSpecificCPUDispatchMVType = 9795 MVType == MultiVersionKind::CPUDispatch || 9796 MVType == MultiVersionKind::CPUSpecific; 9797 9798 // For now, disallow all other attributes. These should be opt-in, but 9799 // an analysis of all of them is a future FIXME. 9800 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 9801 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 9802 << IsCPUSpecificCPUDispatchMVType; 9803 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9804 return true; 9805 } 9806 9807 if (HasNonMultiVersionAttributes(NewFD, MVType)) 9808 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 9809 << IsCPUSpecificCPUDispatchMVType; 9810 9811 // Only allow transition to MultiVersion if it hasn't been used. 9812 if (OldFD && CausesMV && OldFD->isUsed(false)) 9813 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9814 9815 return S.areMultiversionVariantFunctionsCompatible( 9816 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 9817 PartialDiagnosticAt(NewFD->getLocation(), 9818 S.PDiag(diag::note_multiversioning_caused_here)), 9819 PartialDiagnosticAt(NewFD->getLocation(), 9820 S.PDiag(diag::err_multiversion_doesnt_support) 9821 << IsCPUSpecificCPUDispatchMVType), 9822 PartialDiagnosticAt(NewFD->getLocation(), 9823 S.PDiag(diag::err_multiversion_diff)), 9824 /*TemplatesSupported=*/false, 9825 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType); 9826 } 9827 9828 /// Check the validity of a multiversion function declaration that is the 9829 /// first of its kind. Also sets the multiversion'ness' of the function itself. 9830 /// 9831 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9832 /// 9833 /// Returns true if there was an error, false otherwise. 9834 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 9835 MultiVersionKind MVType, 9836 const TargetAttr *TA) { 9837 assert(MVType != MultiVersionKind::None && 9838 "Function lacks multiversion attribute"); 9839 9840 // Target only causes MV if it is default, otherwise this is a normal 9841 // function. 9842 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 9843 return false; 9844 9845 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 9846 FD->setInvalidDecl(); 9847 return true; 9848 } 9849 9850 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 9851 FD->setInvalidDecl(); 9852 return true; 9853 } 9854 9855 FD->setIsMultiVersion(); 9856 return false; 9857 } 9858 9859 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 9860 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 9861 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 9862 return true; 9863 } 9864 9865 return false; 9866 } 9867 9868 static bool CheckTargetCausesMultiVersioning( 9869 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 9870 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9871 LookupResult &Previous) { 9872 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9873 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9874 // Sort order doesn't matter, it just needs to be consistent. 9875 llvm::sort(NewParsed.Features); 9876 9877 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9878 // to change, this is a simple redeclaration. 9879 if (!NewTA->isDefaultVersion() && 9880 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 9881 return false; 9882 9883 // Otherwise, this decl causes MultiVersioning. 9884 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9885 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9886 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9887 NewFD->setInvalidDecl(); 9888 return true; 9889 } 9890 9891 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 9892 MultiVersionKind::Target)) { 9893 NewFD->setInvalidDecl(); 9894 return true; 9895 } 9896 9897 if (CheckMultiVersionValue(S, NewFD)) { 9898 NewFD->setInvalidDecl(); 9899 return true; 9900 } 9901 9902 // If this is 'default', permit the forward declaration. 9903 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 9904 Redeclaration = true; 9905 OldDecl = OldFD; 9906 OldFD->setIsMultiVersion(); 9907 NewFD->setIsMultiVersion(); 9908 return false; 9909 } 9910 9911 if (CheckMultiVersionValue(S, OldFD)) { 9912 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9913 NewFD->setInvalidDecl(); 9914 return true; 9915 } 9916 9917 TargetAttr::ParsedTargetAttr OldParsed = 9918 OldTA->parse(std::less<std::string>()); 9919 9920 if (OldParsed == NewParsed) { 9921 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9922 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9923 NewFD->setInvalidDecl(); 9924 return true; 9925 } 9926 9927 for (const auto *FD : OldFD->redecls()) { 9928 const auto *CurTA = FD->getAttr<TargetAttr>(); 9929 // We allow forward declarations before ANY multiversioning attributes, but 9930 // nothing after the fact. 9931 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 9932 (!CurTA || CurTA->isInherited())) { 9933 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 9934 << 0; 9935 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9936 NewFD->setInvalidDecl(); 9937 return true; 9938 } 9939 } 9940 9941 OldFD->setIsMultiVersion(); 9942 NewFD->setIsMultiVersion(); 9943 Redeclaration = false; 9944 MergeTypeWithPrevious = false; 9945 OldDecl = nullptr; 9946 Previous.clear(); 9947 return false; 9948 } 9949 9950 /// Check the validity of a new function declaration being added to an existing 9951 /// multiversioned declaration collection. 9952 static bool CheckMultiVersionAdditionalDecl( 9953 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 9954 MultiVersionKind NewMVType, const TargetAttr *NewTA, 9955 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 9956 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9957 LookupResult &Previous) { 9958 9959 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 9960 // Disallow mixing of multiversioning types. 9961 if ((OldMVType == MultiVersionKind::Target && 9962 NewMVType != MultiVersionKind::Target) || 9963 (NewMVType == MultiVersionKind::Target && 9964 OldMVType != MultiVersionKind::Target)) { 9965 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9966 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9967 NewFD->setInvalidDecl(); 9968 return true; 9969 } 9970 9971 TargetAttr::ParsedTargetAttr NewParsed; 9972 if (NewTA) { 9973 NewParsed = NewTA->parse(); 9974 llvm::sort(NewParsed.Features); 9975 } 9976 9977 bool UseMemberUsingDeclRules = 9978 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9979 9980 // Next, check ALL non-overloads to see if this is a redeclaration of a 9981 // previous member of the MultiVersion set. 9982 for (NamedDecl *ND : Previous) { 9983 FunctionDecl *CurFD = ND->getAsFunction(); 9984 if (!CurFD) 9985 continue; 9986 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9987 continue; 9988 9989 if (NewMVType == MultiVersionKind::Target) { 9990 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9991 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9992 NewFD->setIsMultiVersion(); 9993 Redeclaration = true; 9994 OldDecl = ND; 9995 return false; 9996 } 9997 9998 TargetAttr::ParsedTargetAttr CurParsed = 9999 CurTA->parse(std::less<std::string>()); 10000 if (CurParsed == NewParsed) { 10001 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10002 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10003 NewFD->setInvalidDecl(); 10004 return true; 10005 } 10006 } else { 10007 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10008 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10009 // Handle CPUDispatch/CPUSpecific versions. 10010 // Only 1 CPUDispatch function is allowed, this will make it go through 10011 // the redeclaration errors. 10012 if (NewMVType == MultiVersionKind::CPUDispatch && 10013 CurFD->hasAttr<CPUDispatchAttr>()) { 10014 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10015 std::equal( 10016 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10017 NewCPUDisp->cpus_begin(), 10018 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10019 return Cur->getName() == New->getName(); 10020 })) { 10021 NewFD->setIsMultiVersion(); 10022 Redeclaration = true; 10023 OldDecl = ND; 10024 return false; 10025 } 10026 10027 // If the declarations don't match, this is an error condition. 10028 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10029 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10030 NewFD->setInvalidDecl(); 10031 return true; 10032 } 10033 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10034 10035 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10036 std::equal( 10037 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10038 NewCPUSpec->cpus_begin(), 10039 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10040 return Cur->getName() == New->getName(); 10041 })) { 10042 NewFD->setIsMultiVersion(); 10043 Redeclaration = true; 10044 OldDecl = ND; 10045 return false; 10046 } 10047 10048 // Only 1 version of CPUSpecific is allowed for each CPU. 10049 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10050 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10051 if (CurII == NewII) { 10052 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10053 << NewII; 10054 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10055 NewFD->setInvalidDecl(); 10056 return true; 10057 } 10058 } 10059 } 10060 } 10061 // If the two decls aren't the same MVType, there is no possible error 10062 // condition. 10063 } 10064 } 10065 10066 // Else, this is simply a non-redecl case. Checking the 'value' is only 10067 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10068 // handled in the attribute adding step. 10069 if (NewMVType == MultiVersionKind::Target && 10070 CheckMultiVersionValue(S, NewFD)) { 10071 NewFD->setInvalidDecl(); 10072 return true; 10073 } 10074 10075 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10076 !OldFD->isMultiVersion(), NewMVType)) { 10077 NewFD->setInvalidDecl(); 10078 return true; 10079 } 10080 10081 // Permit forward declarations in the case where these two are compatible. 10082 if (!OldFD->isMultiVersion()) { 10083 OldFD->setIsMultiVersion(); 10084 NewFD->setIsMultiVersion(); 10085 Redeclaration = true; 10086 OldDecl = OldFD; 10087 return false; 10088 } 10089 10090 NewFD->setIsMultiVersion(); 10091 Redeclaration = false; 10092 MergeTypeWithPrevious = false; 10093 OldDecl = nullptr; 10094 Previous.clear(); 10095 return false; 10096 } 10097 10098 10099 /// Check the validity of a mulitversion function declaration. 10100 /// Also sets the multiversion'ness' of the function itself. 10101 /// 10102 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10103 /// 10104 /// Returns true if there was an error, false otherwise. 10105 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10106 bool &Redeclaration, NamedDecl *&OldDecl, 10107 bool &MergeTypeWithPrevious, 10108 LookupResult &Previous) { 10109 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10110 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10111 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10112 10113 // Mixing Multiversioning types is prohibited. 10114 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10115 (NewCPUDisp && NewCPUSpec)) { 10116 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10117 NewFD->setInvalidDecl(); 10118 return true; 10119 } 10120 10121 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10122 10123 // Main isn't allowed to become a multiversion function, however it IS 10124 // permitted to have 'main' be marked with the 'target' optimization hint. 10125 if (NewFD->isMain()) { 10126 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10127 MVType == MultiVersionKind::CPUDispatch || 10128 MVType == MultiVersionKind::CPUSpecific) { 10129 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10130 NewFD->setInvalidDecl(); 10131 return true; 10132 } 10133 return false; 10134 } 10135 10136 if (!OldDecl || !OldDecl->getAsFunction() || 10137 OldDecl->getDeclContext()->getRedeclContext() != 10138 NewFD->getDeclContext()->getRedeclContext()) { 10139 // If there's no previous declaration, AND this isn't attempting to cause 10140 // multiversioning, this isn't an error condition. 10141 if (MVType == MultiVersionKind::None) 10142 return false; 10143 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10144 } 10145 10146 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10147 10148 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10149 return false; 10150 10151 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10152 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10153 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10154 NewFD->setInvalidDecl(); 10155 return true; 10156 } 10157 10158 // Handle the target potentially causes multiversioning case. 10159 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10160 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10161 Redeclaration, OldDecl, 10162 MergeTypeWithPrevious, Previous); 10163 10164 // At this point, we have a multiversion function decl (in OldFD) AND an 10165 // appropriate attribute in the current function decl. Resolve that these are 10166 // still compatible with previous declarations. 10167 return CheckMultiVersionAdditionalDecl( 10168 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10169 OldDecl, MergeTypeWithPrevious, Previous); 10170 } 10171 10172 /// Perform semantic checking of a new function declaration. 10173 /// 10174 /// Performs semantic analysis of the new function declaration 10175 /// NewFD. This routine performs all semantic checking that does not 10176 /// require the actual declarator involved in the declaration, and is 10177 /// used both for the declaration of functions as they are parsed 10178 /// (called via ActOnDeclarator) and for the declaration of functions 10179 /// that have been instantiated via C++ template instantiation (called 10180 /// via InstantiateDecl). 10181 /// 10182 /// \param IsMemberSpecialization whether this new function declaration is 10183 /// a member specialization (that replaces any definition provided by the 10184 /// previous declaration). 10185 /// 10186 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10187 /// 10188 /// \returns true if the function declaration is a redeclaration. 10189 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10190 LookupResult &Previous, 10191 bool IsMemberSpecialization) { 10192 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10193 "Variably modified return types are not handled here"); 10194 10195 // Determine whether the type of this function should be merged with 10196 // a previous visible declaration. This never happens for functions in C++, 10197 // and always happens in C if the previous declaration was visible. 10198 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10199 !Previous.isShadowed(); 10200 10201 bool Redeclaration = false; 10202 NamedDecl *OldDecl = nullptr; 10203 bool MayNeedOverloadableChecks = false; 10204 10205 // Merge or overload the declaration with an existing declaration of 10206 // the same name, if appropriate. 10207 if (!Previous.empty()) { 10208 // Determine whether NewFD is an overload of PrevDecl or 10209 // a declaration that requires merging. If it's an overload, 10210 // there's no more work to do here; we'll just add the new 10211 // function to the scope. 10212 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10213 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10214 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10215 Redeclaration = true; 10216 OldDecl = Candidate; 10217 } 10218 } else { 10219 MayNeedOverloadableChecks = true; 10220 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10221 /*NewIsUsingDecl*/ false)) { 10222 case Ovl_Match: 10223 Redeclaration = true; 10224 break; 10225 10226 case Ovl_NonFunction: 10227 Redeclaration = true; 10228 break; 10229 10230 case Ovl_Overload: 10231 Redeclaration = false; 10232 break; 10233 } 10234 } 10235 } 10236 10237 // Check for a previous extern "C" declaration with this name. 10238 if (!Redeclaration && 10239 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10240 if (!Previous.empty()) { 10241 // This is an extern "C" declaration with the same name as a previous 10242 // declaration, and thus redeclares that entity... 10243 Redeclaration = true; 10244 OldDecl = Previous.getFoundDecl(); 10245 MergeTypeWithPrevious = false; 10246 10247 // ... except in the presence of __attribute__((overloadable)). 10248 if (OldDecl->hasAttr<OverloadableAttr>() || 10249 NewFD->hasAttr<OverloadableAttr>()) { 10250 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10251 MayNeedOverloadableChecks = true; 10252 Redeclaration = false; 10253 OldDecl = nullptr; 10254 } 10255 } 10256 } 10257 } 10258 10259 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10260 MergeTypeWithPrevious, Previous)) 10261 return Redeclaration; 10262 10263 // C++11 [dcl.constexpr]p8: 10264 // A constexpr specifier for a non-static member function that is not 10265 // a constructor declares that member function to be const. 10266 // 10267 // This needs to be delayed until we know whether this is an out-of-line 10268 // definition of a static member function. 10269 // 10270 // This rule is not present in C++1y, so we produce a backwards 10271 // compatibility warning whenever it happens in C++11. 10272 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10273 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10274 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10275 !MD->getMethodQualifiers().hasConst()) { 10276 CXXMethodDecl *OldMD = nullptr; 10277 if (OldDecl) 10278 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10279 if (!OldMD || !OldMD->isStatic()) { 10280 const FunctionProtoType *FPT = 10281 MD->getType()->castAs<FunctionProtoType>(); 10282 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10283 EPI.TypeQuals.addConst(); 10284 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10285 FPT->getParamTypes(), EPI)); 10286 10287 // Warn that we did this, if we're not performing template instantiation. 10288 // In that case, we'll have warned already when the template was defined. 10289 if (!inTemplateInstantiation()) { 10290 SourceLocation AddConstLoc; 10291 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10292 .IgnoreParens().getAs<FunctionTypeLoc>()) 10293 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10294 10295 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10296 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10297 } 10298 } 10299 } 10300 10301 if (Redeclaration) { 10302 // NewFD and OldDecl represent declarations that need to be 10303 // merged. 10304 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10305 NewFD->setInvalidDecl(); 10306 return Redeclaration; 10307 } 10308 10309 Previous.clear(); 10310 Previous.addDecl(OldDecl); 10311 10312 if (FunctionTemplateDecl *OldTemplateDecl = 10313 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10314 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10315 FunctionTemplateDecl *NewTemplateDecl 10316 = NewFD->getDescribedFunctionTemplate(); 10317 assert(NewTemplateDecl && "Template/non-template mismatch"); 10318 10319 // The call to MergeFunctionDecl above may have created some state in 10320 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10321 // can add it as a redeclaration. 10322 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10323 10324 NewFD->setPreviousDeclaration(OldFD); 10325 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10326 if (NewFD->isCXXClassMember()) { 10327 NewFD->setAccess(OldTemplateDecl->getAccess()); 10328 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10329 } 10330 10331 // If this is an explicit specialization of a member that is a function 10332 // template, mark it as a member specialization. 10333 if (IsMemberSpecialization && 10334 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10335 NewTemplateDecl->setMemberSpecialization(); 10336 assert(OldTemplateDecl->isMemberSpecialization()); 10337 // Explicit specializations of a member template do not inherit deleted 10338 // status from the parent member template that they are specializing. 10339 if (OldFD->isDeleted()) { 10340 // FIXME: This assert will not hold in the presence of modules. 10341 assert(OldFD->getCanonicalDecl() == OldFD); 10342 // FIXME: We need an update record for this AST mutation. 10343 OldFD->setDeletedAsWritten(false); 10344 } 10345 } 10346 10347 } else { 10348 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10349 auto *OldFD = cast<FunctionDecl>(OldDecl); 10350 // This needs to happen first so that 'inline' propagates. 10351 NewFD->setPreviousDeclaration(OldFD); 10352 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10353 if (NewFD->isCXXClassMember()) 10354 NewFD->setAccess(OldFD->getAccess()); 10355 } 10356 } 10357 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10358 !NewFD->getAttr<OverloadableAttr>()) { 10359 assert((Previous.empty() || 10360 llvm::any_of(Previous, 10361 [](const NamedDecl *ND) { 10362 return ND->hasAttr<OverloadableAttr>(); 10363 })) && 10364 "Non-redecls shouldn't happen without overloadable present"); 10365 10366 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10367 const auto *FD = dyn_cast<FunctionDecl>(ND); 10368 return FD && !FD->hasAttr<OverloadableAttr>(); 10369 }); 10370 10371 if (OtherUnmarkedIter != Previous.end()) { 10372 Diag(NewFD->getLocation(), 10373 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10374 Diag((*OtherUnmarkedIter)->getLocation(), 10375 diag::note_attribute_overloadable_prev_overload) 10376 << false; 10377 10378 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10379 } 10380 } 10381 10382 // Semantic checking for this function declaration (in isolation). 10383 10384 if (getLangOpts().CPlusPlus) { 10385 // C++-specific checks. 10386 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10387 CheckConstructor(Constructor); 10388 } else if (CXXDestructorDecl *Destructor = 10389 dyn_cast<CXXDestructorDecl>(NewFD)) { 10390 CXXRecordDecl *Record = Destructor->getParent(); 10391 QualType ClassType = Context.getTypeDeclType(Record); 10392 10393 // FIXME: Shouldn't we be able to perform this check even when the class 10394 // type is dependent? Both gcc and edg can handle that. 10395 if (!ClassType->isDependentType()) { 10396 DeclarationName Name 10397 = Context.DeclarationNames.getCXXDestructorName( 10398 Context.getCanonicalType(ClassType)); 10399 if (NewFD->getDeclName() != Name) { 10400 Diag(NewFD->getLocation(), diag::err_destructor_name); 10401 NewFD->setInvalidDecl(); 10402 return Redeclaration; 10403 } 10404 } 10405 } else if (CXXConversionDecl *Conversion 10406 = dyn_cast<CXXConversionDecl>(NewFD)) { 10407 ActOnConversionDeclarator(Conversion); 10408 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10409 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10410 CheckDeductionGuideTemplate(TD); 10411 10412 // A deduction guide is not on the list of entities that can be 10413 // explicitly specialized. 10414 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10415 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10416 << /*explicit specialization*/ 1; 10417 } 10418 10419 // Find any virtual functions that this function overrides. 10420 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10421 if (!Method->isFunctionTemplateSpecialization() && 10422 !Method->getDescribedFunctionTemplate() && 10423 Method->isCanonicalDecl()) { 10424 if (AddOverriddenMethods(Method->getParent(), Method)) { 10425 // If the function was marked as "static", we have a problem. 10426 if (NewFD->getStorageClass() == SC_Static) { 10427 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10428 } 10429 } 10430 } 10431 10432 if (Method->isStatic()) 10433 checkThisInStaticMemberFunctionType(Method); 10434 } 10435 10436 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10437 if (NewFD->isOverloadedOperator() && 10438 CheckOverloadedOperatorDeclaration(NewFD)) { 10439 NewFD->setInvalidDecl(); 10440 return Redeclaration; 10441 } 10442 10443 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10444 if (NewFD->getLiteralIdentifier() && 10445 CheckLiteralOperatorDeclaration(NewFD)) { 10446 NewFD->setInvalidDecl(); 10447 return Redeclaration; 10448 } 10449 10450 // In C++, check default arguments now that we have merged decls. Unless 10451 // the lexical context is the class, because in this case this is done 10452 // during delayed parsing anyway. 10453 if (!CurContext->isRecord()) 10454 CheckCXXDefaultArguments(NewFD); 10455 10456 // If this function declares a builtin function, check the type of this 10457 // declaration against the expected type for the builtin. 10458 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10459 ASTContext::GetBuiltinTypeError Error; 10460 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10461 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10462 // If the type of the builtin differs only in its exception 10463 // specification, that's OK. 10464 // FIXME: If the types do differ in this way, it would be better to 10465 // retain the 'noexcept' form of the type. 10466 if (!T.isNull() && 10467 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10468 NewFD->getType())) 10469 // The type of this function differs from the type of the builtin, 10470 // so forget about the builtin entirely. 10471 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10472 } 10473 10474 // If this function is declared as being extern "C", then check to see if 10475 // the function returns a UDT (class, struct, or union type) that is not C 10476 // compatible, and if it does, warn the user. 10477 // But, issue any diagnostic on the first declaration only. 10478 if (Previous.empty() && NewFD->isExternC()) { 10479 QualType R = NewFD->getReturnType(); 10480 if (R->isIncompleteType() && !R->isVoidType()) 10481 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10482 << NewFD << R; 10483 else if (!R.isPODType(Context) && !R->isVoidType() && 10484 !R->isObjCObjectPointerType()) 10485 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10486 } 10487 10488 // C++1z [dcl.fct]p6: 10489 // [...] whether the function has a non-throwing exception-specification 10490 // [is] part of the function type 10491 // 10492 // This results in an ABI break between C++14 and C++17 for functions whose 10493 // declared type includes an exception-specification in a parameter or 10494 // return type. (Exception specifications on the function itself are OK in 10495 // most cases, and exception specifications are not permitted in most other 10496 // contexts where they could make it into a mangling.) 10497 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10498 auto HasNoexcept = [&](QualType T) -> bool { 10499 // Strip off declarator chunks that could be between us and a function 10500 // type. We don't need to look far, exception specifications are very 10501 // restricted prior to C++17. 10502 if (auto *RT = T->getAs<ReferenceType>()) 10503 T = RT->getPointeeType(); 10504 else if (T->isAnyPointerType()) 10505 T = T->getPointeeType(); 10506 else if (auto *MPT = T->getAs<MemberPointerType>()) 10507 T = MPT->getPointeeType(); 10508 if (auto *FPT = T->getAs<FunctionProtoType>()) 10509 if (FPT->isNothrow()) 10510 return true; 10511 return false; 10512 }; 10513 10514 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10515 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10516 for (QualType T : FPT->param_types()) 10517 AnyNoexcept |= HasNoexcept(T); 10518 if (AnyNoexcept) 10519 Diag(NewFD->getLocation(), 10520 diag::warn_cxx17_compat_exception_spec_in_signature) 10521 << NewFD; 10522 } 10523 10524 if (!Redeclaration && LangOpts.CUDA) 10525 checkCUDATargetOverload(NewFD, Previous); 10526 } 10527 return Redeclaration; 10528 } 10529 10530 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10531 // C++11 [basic.start.main]p3: 10532 // A program that [...] declares main to be inline, static or 10533 // constexpr is ill-formed. 10534 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10535 // appear in a declaration of main. 10536 // static main is not an error under C99, but we should warn about it. 10537 // We accept _Noreturn main as an extension. 10538 if (FD->getStorageClass() == SC_Static) 10539 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10540 ? diag::err_static_main : diag::warn_static_main) 10541 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10542 if (FD->isInlineSpecified()) 10543 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10544 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10545 if (DS.isNoreturnSpecified()) { 10546 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10547 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10548 Diag(NoreturnLoc, diag::ext_noreturn_main); 10549 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10550 << FixItHint::CreateRemoval(NoreturnRange); 10551 } 10552 if (FD->isConstexpr()) { 10553 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10554 << FD->isConsteval() 10555 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10556 FD->setConstexprKind(CSK_unspecified); 10557 } 10558 10559 if (getLangOpts().OpenCL) { 10560 Diag(FD->getLocation(), diag::err_opencl_no_main) 10561 << FD->hasAttr<OpenCLKernelAttr>(); 10562 FD->setInvalidDecl(); 10563 return; 10564 } 10565 10566 QualType T = FD->getType(); 10567 assert(T->isFunctionType() && "function decl is not of function type"); 10568 const FunctionType* FT = T->castAs<FunctionType>(); 10569 10570 // Set default calling convention for main() 10571 if (FT->getCallConv() != CC_C) { 10572 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10573 FD->setType(QualType(FT, 0)); 10574 T = Context.getCanonicalType(FD->getType()); 10575 } 10576 10577 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10578 // In C with GNU extensions we allow main() to have non-integer return 10579 // type, but we should warn about the extension, and we disable the 10580 // implicit-return-zero rule. 10581 10582 // GCC in C mode accepts qualified 'int'. 10583 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10584 FD->setHasImplicitReturnZero(true); 10585 else { 10586 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10587 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10588 if (RTRange.isValid()) 10589 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10590 << FixItHint::CreateReplacement(RTRange, "int"); 10591 } 10592 } else { 10593 // In C and C++, main magically returns 0 if you fall off the end; 10594 // set the flag which tells us that. 10595 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10596 10597 // All the standards say that main() should return 'int'. 10598 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10599 FD->setHasImplicitReturnZero(true); 10600 else { 10601 // Otherwise, this is just a flat-out error. 10602 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10603 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10604 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10605 : FixItHint()); 10606 FD->setInvalidDecl(true); 10607 } 10608 } 10609 10610 // Treat protoless main() as nullary. 10611 if (isa<FunctionNoProtoType>(FT)) return; 10612 10613 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10614 unsigned nparams = FTP->getNumParams(); 10615 assert(FD->getNumParams() == nparams); 10616 10617 bool HasExtraParameters = (nparams > 3); 10618 10619 if (FTP->isVariadic()) { 10620 Diag(FD->getLocation(), diag::ext_variadic_main); 10621 // FIXME: if we had information about the location of the ellipsis, we 10622 // could add a FixIt hint to remove it as a parameter. 10623 } 10624 10625 // Darwin passes an undocumented fourth argument of type char**. If 10626 // other platforms start sprouting these, the logic below will start 10627 // getting shifty. 10628 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10629 HasExtraParameters = false; 10630 10631 if (HasExtraParameters) { 10632 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10633 FD->setInvalidDecl(true); 10634 nparams = 3; 10635 } 10636 10637 // FIXME: a lot of the following diagnostics would be improved 10638 // if we had some location information about types. 10639 10640 QualType CharPP = 10641 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10642 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10643 10644 for (unsigned i = 0; i < nparams; ++i) { 10645 QualType AT = FTP->getParamType(i); 10646 10647 bool mismatch = true; 10648 10649 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10650 mismatch = false; 10651 else if (Expected[i] == CharPP) { 10652 // As an extension, the following forms are okay: 10653 // char const ** 10654 // char const * const * 10655 // char * const * 10656 10657 QualifierCollector qs; 10658 const PointerType* PT; 10659 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10660 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10661 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10662 Context.CharTy)) { 10663 qs.removeConst(); 10664 mismatch = !qs.empty(); 10665 } 10666 } 10667 10668 if (mismatch) { 10669 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10670 // TODO: suggest replacing given type with expected type 10671 FD->setInvalidDecl(true); 10672 } 10673 } 10674 10675 if (nparams == 1 && !FD->isInvalidDecl()) { 10676 Diag(FD->getLocation(), diag::warn_main_one_arg); 10677 } 10678 10679 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10680 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10681 FD->setInvalidDecl(); 10682 } 10683 } 10684 10685 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10686 QualType T = FD->getType(); 10687 assert(T->isFunctionType() && "function decl is not of function type"); 10688 const FunctionType *FT = T->castAs<FunctionType>(); 10689 10690 // Set an implicit return of 'zero' if the function can return some integral, 10691 // enumeration, pointer or nullptr type. 10692 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10693 FT->getReturnType()->isAnyPointerType() || 10694 FT->getReturnType()->isNullPtrType()) 10695 // DllMain is exempt because a return value of zero means it failed. 10696 if (FD->getName() != "DllMain") 10697 FD->setHasImplicitReturnZero(true); 10698 10699 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10700 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10701 FD->setInvalidDecl(); 10702 } 10703 } 10704 10705 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10706 // FIXME: Need strict checking. In C89, we need to check for 10707 // any assignment, increment, decrement, function-calls, or 10708 // commas outside of a sizeof. In C99, it's the same list, 10709 // except that the aforementioned are allowed in unevaluated 10710 // expressions. Everything else falls under the 10711 // "may accept other forms of constant expressions" exception. 10712 // (We never end up here for C++, so the constant expression 10713 // rules there don't matter.) 10714 const Expr *Culprit; 10715 if (Init->isConstantInitializer(Context, false, &Culprit)) 10716 return false; 10717 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10718 << Culprit->getSourceRange(); 10719 return true; 10720 } 10721 10722 namespace { 10723 // Visits an initialization expression to see if OrigDecl is evaluated in 10724 // its own initialization and throws a warning if it does. 10725 class SelfReferenceChecker 10726 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10727 Sema &S; 10728 Decl *OrigDecl; 10729 bool isRecordType; 10730 bool isPODType; 10731 bool isReferenceType; 10732 10733 bool isInitList; 10734 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10735 10736 public: 10737 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10738 10739 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10740 S(S), OrigDecl(OrigDecl) { 10741 isPODType = false; 10742 isRecordType = false; 10743 isReferenceType = false; 10744 isInitList = false; 10745 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10746 isPODType = VD->getType().isPODType(S.Context); 10747 isRecordType = VD->getType()->isRecordType(); 10748 isReferenceType = VD->getType()->isReferenceType(); 10749 } 10750 } 10751 10752 // For most expressions, just call the visitor. For initializer lists, 10753 // track the index of the field being initialized since fields are 10754 // initialized in order allowing use of previously initialized fields. 10755 void CheckExpr(Expr *E) { 10756 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10757 if (!InitList) { 10758 Visit(E); 10759 return; 10760 } 10761 10762 // Track and increment the index here. 10763 isInitList = true; 10764 InitFieldIndex.push_back(0); 10765 for (auto Child : InitList->children()) { 10766 CheckExpr(cast<Expr>(Child)); 10767 ++InitFieldIndex.back(); 10768 } 10769 InitFieldIndex.pop_back(); 10770 } 10771 10772 // Returns true if MemberExpr is checked and no further checking is needed. 10773 // Returns false if additional checking is required. 10774 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10775 llvm::SmallVector<FieldDecl*, 4> Fields; 10776 Expr *Base = E; 10777 bool ReferenceField = false; 10778 10779 // Get the field members used. 10780 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10781 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10782 if (!FD) 10783 return false; 10784 Fields.push_back(FD); 10785 if (FD->getType()->isReferenceType()) 10786 ReferenceField = true; 10787 Base = ME->getBase()->IgnoreParenImpCasts(); 10788 } 10789 10790 // Keep checking only if the base Decl is the same. 10791 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10792 if (!DRE || DRE->getDecl() != OrigDecl) 10793 return false; 10794 10795 // A reference field can be bound to an unininitialized field. 10796 if (CheckReference && !ReferenceField) 10797 return true; 10798 10799 // Convert FieldDecls to their index number. 10800 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10801 for (const FieldDecl *I : llvm::reverse(Fields)) 10802 UsedFieldIndex.push_back(I->getFieldIndex()); 10803 10804 // See if a warning is needed by checking the first difference in index 10805 // numbers. If field being used has index less than the field being 10806 // initialized, then the use is safe. 10807 for (auto UsedIter = UsedFieldIndex.begin(), 10808 UsedEnd = UsedFieldIndex.end(), 10809 OrigIter = InitFieldIndex.begin(), 10810 OrigEnd = InitFieldIndex.end(); 10811 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10812 if (*UsedIter < *OrigIter) 10813 return true; 10814 if (*UsedIter > *OrigIter) 10815 break; 10816 } 10817 10818 // TODO: Add a different warning which will print the field names. 10819 HandleDeclRefExpr(DRE); 10820 return true; 10821 } 10822 10823 // For most expressions, the cast is directly above the DeclRefExpr. 10824 // For conditional operators, the cast can be outside the conditional 10825 // operator if both expressions are DeclRefExpr's. 10826 void HandleValue(Expr *E) { 10827 E = E->IgnoreParens(); 10828 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10829 HandleDeclRefExpr(DRE); 10830 return; 10831 } 10832 10833 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10834 Visit(CO->getCond()); 10835 HandleValue(CO->getTrueExpr()); 10836 HandleValue(CO->getFalseExpr()); 10837 return; 10838 } 10839 10840 if (BinaryConditionalOperator *BCO = 10841 dyn_cast<BinaryConditionalOperator>(E)) { 10842 Visit(BCO->getCond()); 10843 HandleValue(BCO->getFalseExpr()); 10844 return; 10845 } 10846 10847 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10848 HandleValue(OVE->getSourceExpr()); 10849 return; 10850 } 10851 10852 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10853 if (BO->getOpcode() == BO_Comma) { 10854 Visit(BO->getLHS()); 10855 HandleValue(BO->getRHS()); 10856 return; 10857 } 10858 } 10859 10860 if (isa<MemberExpr>(E)) { 10861 if (isInitList) { 10862 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10863 false /*CheckReference*/)) 10864 return; 10865 } 10866 10867 Expr *Base = E->IgnoreParenImpCasts(); 10868 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10869 // Check for static member variables and don't warn on them. 10870 if (!isa<FieldDecl>(ME->getMemberDecl())) 10871 return; 10872 Base = ME->getBase()->IgnoreParenImpCasts(); 10873 } 10874 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10875 HandleDeclRefExpr(DRE); 10876 return; 10877 } 10878 10879 Visit(E); 10880 } 10881 10882 // Reference types not handled in HandleValue are handled here since all 10883 // uses of references are bad, not just r-value uses. 10884 void VisitDeclRefExpr(DeclRefExpr *E) { 10885 if (isReferenceType) 10886 HandleDeclRefExpr(E); 10887 } 10888 10889 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10890 if (E->getCastKind() == CK_LValueToRValue) { 10891 HandleValue(E->getSubExpr()); 10892 return; 10893 } 10894 10895 Inherited::VisitImplicitCastExpr(E); 10896 } 10897 10898 void VisitMemberExpr(MemberExpr *E) { 10899 if (isInitList) { 10900 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10901 return; 10902 } 10903 10904 // Don't warn on arrays since they can be treated as pointers. 10905 if (E->getType()->canDecayToPointerType()) return; 10906 10907 // Warn when a non-static method call is followed by non-static member 10908 // field accesses, which is followed by a DeclRefExpr. 10909 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10910 bool Warn = (MD && !MD->isStatic()); 10911 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10912 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10913 if (!isa<FieldDecl>(ME->getMemberDecl())) 10914 Warn = false; 10915 Base = ME->getBase()->IgnoreParenImpCasts(); 10916 } 10917 10918 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10919 if (Warn) 10920 HandleDeclRefExpr(DRE); 10921 return; 10922 } 10923 10924 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10925 // Visit that expression. 10926 Visit(Base); 10927 } 10928 10929 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10930 Expr *Callee = E->getCallee(); 10931 10932 if (isa<UnresolvedLookupExpr>(Callee)) 10933 return Inherited::VisitCXXOperatorCallExpr(E); 10934 10935 Visit(Callee); 10936 for (auto Arg: E->arguments()) 10937 HandleValue(Arg->IgnoreParenImpCasts()); 10938 } 10939 10940 void VisitUnaryOperator(UnaryOperator *E) { 10941 // For POD record types, addresses of its own members are well-defined. 10942 if (E->getOpcode() == UO_AddrOf && isRecordType && 10943 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10944 if (!isPODType) 10945 HandleValue(E->getSubExpr()); 10946 return; 10947 } 10948 10949 if (E->isIncrementDecrementOp()) { 10950 HandleValue(E->getSubExpr()); 10951 return; 10952 } 10953 10954 Inherited::VisitUnaryOperator(E); 10955 } 10956 10957 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10958 10959 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10960 if (E->getConstructor()->isCopyConstructor()) { 10961 Expr *ArgExpr = E->getArg(0); 10962 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10963 if (ILE->getNumInits() == 1) 10964 ArgExpr = ILE->getInit(0); 10965 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10966 if (ICE->getCastKind() == CK_NoOp) 10967 ArgExpr = ICE->getSubExpr(); 10968 HandleValue(ArgExpr); 10969 return; 10970 } 10971 Inherited::VisitCXXConstructExpr(E); 10972 } 10973 10974 void VisitCallExpr(CallExpr *E) { 10975 // Treat std::move as a use. 10976 if (E->isCallToStdMove()) { 10977 HandleValue(E->getArg(0)); 10978 return; 10979 } 10980 10981 Inherited::VisitCallExpr(E); 10982 } 10983 10984 void VisitBinaryOperator(BinaryOperator *E) { 10985 if (E->isCompoundAssignmentOp()) { 10986 HandleValue(E->getLHS()); 10987 Visit(E->getRHS()); 10988 return; 10989 } 10990 10991 Inherited::VisitBinaryOperator(E); 10992 } 10993 10994 // A custom visitor for BinaryConditionalOperator is needed because the 10995 // regular visitor would check the condition and true expression separately 10996 // but both point to the same place giving duplicate diagnostics. 10997 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10998 Visit(E->getCond()); 10999 Visit(E->getFalseExpr()); 11000 } 11001 11002 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11003 Decl* ReferenceDecl = DRE->getDecl(); 11004 if (OrigDecl != ReferenceDecl) return; 11005 unsigned diag; 11006 if (isReferenceType) { 11007 diag = diag::warn_uninit_self_reference_in_reference_init; 11008 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11009 diag = diag::warn_static_self_reference_in_init; 11010 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11011 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11012 DRE->getDecl()->getType()->isRecordType()) { 11013 diag = diag::warn_uninit_self_reference_in_init; 11014 } else { 11015 // Local variables will be handled by the CFG analysis. 11016 return; 11017 } 11018 11019 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11020 S.PDiag(diag) 11021 << DRE->getDecl() << OrigDecl->getLocation() 11022 << DRE->getSourceRange()); 11023 } 11024 }; 11025 11026 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11027 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11028 bool DirectInit) { 11029 // Parameters arguments are occassionially constructed with itself, 11030 // for instance, in recursive functions. Skip them. 11031 if (isa<ParmVarDecl>(OrigDecl)) 11032 return; 11033 11034 E = E->IgnoreParens(); 11035 11036 // Skip checking T a = a where T is not a record or reference type. 11037 // Doing so is a way to silence uninitialized warnings. 11038 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11039 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11040 if (ICE->getCastKind() == CK_LValueToRValue) 11041 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11042 if (DRE->getDecl() == OrigDecl) 11043 return; 11044 11045 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11046 } 11047 } // end anonymous namespace 11048 11049 namespace { 11050 // Simple wrapper to add the name of a variable or (if no variable is 11051 // available) a DeclarationName into a diagnostic. 11052 struct VarDeclOrName { 11053 VarDecl *VDecl; 11054 DeclarationName Name; 11055 11056 friend const Sema::SemaDiagnosticBuilder & 11057 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11058 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11059 } 11060 }; 11061 } // end anonymous namespace 11062 11063 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11064 DeclarationName Name, QualType Type, 11065 TypeSourceInfo *TSI, 11066 SourceRange Range, bool DirectInit, 11067 Expr *Init) { 11068 bool IsInitCapture = !VDecl; 11069 assert((!VDecl || !VDecl->isInitCapture()) && 11070 "init captures are expected to be deduced prior to initialization"); 11071 11072 VarDeclOrName VN{VDecl, Name}; 11073 11074 DeducedType *Deduced = Type->getContainedDeducedType(); 11075 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11076 11077 // C++11 [dcl.spec.auto]p3 11078 if (!Init) { 11079 assert(VDecl && "no init for init capture deduction?"); 11080 11081 // Except for class argument deduction, and then for an initializing 11082 // declaration only, i.e. no static at class scope or extern. 11083 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11084 VDecl->hasExternalStorage() || 11085 VDecl->isStaticDataMember()) { 11086 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11087 << VDecl->getDeclName() << Type; 11088 return QualType(); 11089 } 11090 } 11091 11092 ArrayRef<Expr*> DeduceInits; 11093 if (Init) 11094 DeduceInits = Init; 11095 11096 if (DirectInit) { 11097 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11098 DeduceInits = PL->exprs(); 11099 } 11100 11101 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11102 assert(VDecl && "non-auto type for init capture deduction?"); 11103 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11104 InitializationKind Kind = InitializationKind::CreateForInit( 11105 VDecl->getLocation(), DirectInit, Init); 11106 // FIXME: Initialization should not be taking a mutable list of inits. 11107 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11108 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11109 InitsCopy); 11110 } 11111 11112 if (DirectInit) { 11113 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11114 DeduceInits = IL->inits(); 11115 } 11116 11117 // Deduction only works if we have exactly one source expression. 11118 if (DeduceInits.empty()) { 11119 // It isn't possible to write this directly, but it is possible to 11120 // end up in this situation with "auto x(some_pack...);" 11121 Diag(Init->getBeginLoc(), IsInitCapture 11122 ? diag::err_init_capture_no_expression 11123 : diag::err_auto_var_init_no_expression) 11124 << VN << Type << Range; 11125 return QualType(); 11126 } 11127 11128 if (DeduceInits.size() > 1) { 11129 Diag(DeduceInits[1]->getBeginLoc(), 11130 IsInitCapture ? diag::err_init_capture_multiple_expressions 11131 : diag::err_auto_var_init_multiple_expressions) 11132 << VN << Type << Range; 11133 return QualType(); 11134 } 11135 11136 Expr *DeduceInit = DeduceInits[0]; 11137 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11138 Diag(Init->getBeginLoc(), IsInitCapture 11139 ? diag::err_init_capture_paren_braces 11140 : diag::err_auto_var_init_paren_braces) 11141 << isa<InitListExpr>(Init) << VN << Type << Range; 11142 return QualType(); 11143 } 11144 11145 // Expressions default to 'id' when we're in a debugger. 11146 bool DefaultedAnyToId = false; 11147 if (getLangOpts().DebuggerCastResultToId && 11148 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11149 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11150 if (Result.isInvalid()) { 11151 return QualType(); 11152 } 11153 Init = Result.get(); 11154 DefaultedAnyToId = true; 11155 } 11156 11157 // C++ [dcl.decomp]p1: 11158 // If the assignment-expression [...] has array type A and no ref-qualifier 11159 // is present, e has type cv A 11160 if (VDecl && isa<DecompositionDecl>(VDecl) && 11161 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11162 DeduceInit->getType()->isConstantArrayType()) 11163 return Context.getQualifiedType(DeduceInit->getType(), 11164 Type.getQualifiers()); 11165 11166 QualType DeducedType; 11167 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11168 if (!IsInitCapture) 11169 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11170 else if (isa<InitListExpr>(Init)) 11171 Diag(Range.getBegin(), 11172 diag::err_init_capture_deduction_failure_from_init_list) 11173 << VN 11174 << (DeduceInit->getType().isNull() ? TSI->getType() 11175 : DeduceInit->getType()) 11176 << DeduceInit->getSourceRange(); 11177 else 11178 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11179 << VN << TSI->getType() 11180 << (DeduceInit->getType().isNull() ? TSI->getType() 11181 : DeduceInit->getType()) 11182 << DeduceInit->getSourceRange(); 11183 } 11184 11185 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11186 // 'id' instead of a specific object type prevents most of our usual 11187 // checks. 11188 // We only want to warn outside of template instantiations, though: 11189 // inside a template, the 'id' could have come from a parameter. 11190 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11191 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11192 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11193 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11194 } 11195 11196 return DeducedType; 11197 } 11198 11199 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11200 Expr *Init) { 11201 QualType DeducedType = deduceVarTypeFromInitializer( 11202 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11203 VDecl->getSourceRange(), DirectInit, Init); 11204 if (DeducedType.isNull()) { 11205 VDecl->setInvalidDecl(); 11206 return true; 11207 } 11208 11209 VDecl->setType(DeducedType); 11210 assert(VDecl->isLinkageValid()); 11211 11212 // In ARC, infer lifetime. 11213 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11214 VDecl->setInvalidDecl(); 11215 11216 // If this is a redeclaration, check that the type we just deduced matches 11217 // the previously declared type. 11218 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11219 // We never need to merge the type, because we cannot form an incomplete 11220 // array of auto, nor deduce such a type. 11221 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11222 } 11223 11224 // Check the deduced type is valid for a variable declaration. 11225 CheckVariableDeclarationType(VDecl); 11226 return VDecl->isInvalidDecl(); 11227 } 11228 11229 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11230 SourceLocation Loc) { 11231 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11232 Init = CE->getSubExpr(); 11233 11234 QualType InitType = Init->getType(); 11235 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11236 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11237 "shouldn't be called if type doesn't have a non-trivial C struct"); 11238 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11239 for (auto I : ILE->inits()) { 11240 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11241 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11242 continue; 11243 SourceLocation SL = I->getExprLoc(); 11244 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11245 } 11246 return; 11247 } 11248 11249 if (isa<ImplicitValueInitExpr>(Init)) { 11250 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11251 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11252 NTCUK_Init); 11253 } else { 11254 // Assume all other explicit initializers involving copying some existing 11255 // object. 11256 // TODO: ignore any explicit initializers where we can guarantee 11257 // copy-elision. 11258 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11259 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11260 } 11261 } 11262 11263 namespace { 11264 11265 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11266 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11267 // in the source code or implicitly by the compiler if it is in a union 11268 // defined in a system header and has non-trivial ObjC ownership 11269 // qualifications. We don't want those fields to participate in determining 11270 // whether the containing union is non-trivial. 11271 return FD->hasAttr<UnavailableAttr>(); 11272 } 11273 11274 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11275 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11276 void> { 11277 using Super = 11278 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11279 void>; 11280 11281 DiagNonTrivalCUnionDefaultInitializeVisitor( 11282 QualType OrigTy, SourceLocation OrigLoc, 11283 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11284 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11285 11286 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11287 const FieldDecl *FD, bool InNonTrivialUnion) { 11288 if (const auto *AT = S.Context.getAsArrayType(QT)) 11289 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11290 InNonTrivialUnion); 11291 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11292 } 11293 11294 void visitARCStrong(QualType QT, const FieldDecl *FD, 11295 bool InNonTrivialUnion) { 11296 if (InNonTrivialUnion) 11297 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11298 << 1 << 0 << QT << FD->getName(); 11299 } 11300 11301 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11302 if (InNonTrivialUnion) 11303 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11304 << 1 << 0 << QT << FD->getName(); 11305 } 11306 11307 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11308 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11309 if (RD->isUnion()) { 11310 if (OrigLoc.isValid()) { 11311 bool IsUnion = false; 11312 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11313 IsUnion = OrigRD->isUnion(); 11314 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11315 << 0 << OrigTy << IsUnion << UseContext; 11316 // Reset OrigLoc so that this diagnostic is emitted only once. 11317 OrigLoc = SourceLocation(); 11318 } 11319 InNonTrivialUnion = true; 11320 } 11321 11322 if (InNonTrivialUnion) 11323 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11324 << 0 << 0 << QT.getUnqualifiedType() << ""; 11325 11326 for (const FieldDecl *FD : RD->fields()) 11327 if (!shouldIgnoreForRecordTriviality(FD)) 11328 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11329 } 11330 11331 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11332 11333 // The non-trivial C union type or the struct/union type that contains a 11334 // non-trivial C union. 11335 QualType OrigTy; 11336 SourceLocation OrigLoc; 11337 Sema::NonTrivialCUnionContext UseContext; 11338 Sema &S; 11339 }; 11340 11341 struct DiagNonTrivalCUnionDestructedTypeVisitor 11342 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11343 using Super = 11344 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11345 11346 DiagNonTrivalCUnionDestructedTypeVisitor( 11347 QualType OrigTy, SourceLocation OrigLoc, 11348 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11349 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11350 11351 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11352 const FieldDecl *FD, bool InNonTrivialUnion) { 11353 if (const auto *AT = S.Context.getAsArrayType(QT)) 11354 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11355 InNonTrivialUnion); 11356 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11357 } 11358 11359 void visitARCStrong(QualType QT, const FieldDecl *FD, 11360 bool InNonTrivialUnion) { 11361 if (InNonTrivialUnion) 11362 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11363 << 1 << 1 << QT << FD->getName(); 11364 } 11365 11366 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11367 if (InNonTrivialUnion) 11368 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11369 << 1 << 1 << QT << FD->getName(); 11370 } 11371 11372 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11373 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11374 if (RD->isUnion()) { 11375 if (OrigLoc.isValid()) { 11376 bool IsUnion = false; 11377 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11378 IsUnion = OrigRD->isUnion(); 11379 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11380 << 1 << OrigTy << IsUnion << UseContext; 11381 // Reset OrigLoc so that this diagnostic is emitted only once. 11382 OrigLoc = SourceLocation(); 11383 } 11384 InNonTrivialUnion = true; 11385 } 11386 11387 if (InNonTrivialUnion) 11388 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11389 << 0 << 1 << QT.getUnqualifiedType() << ""; 11390 11391 for (const FieldDecl *FD : RD->fields()) 11392 if (!shouldIgnoreForRecordTriviality(FD)) 11393 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11394 } 11395 11396 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11397 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11398 bool InNonTrivialUnion) {} 11399 11400 // The non-trivial C union type or the struct/union type that contains a 11401 // non-trivial C union. 11402 QualType OrigTy; 11403 SourceLocation OrigLoc; 11404 Sema::NonTrivialCUnionContext UseContext; 11405 Sema &S; 11406 }; 11407 11408 struct DiagNonTrivalCUnionCopyVisitor 11409 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11410 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11411 11412 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11413 Sema::NonTrivialCUnionContext UseContext, 11414 Sema &S) 11415 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11416 11417 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11418 const FieldDecl *FD, bool InNonTrivialUnion) { 11419 if (const auto *AT = S.Context.getAsArrayType(QT)) 11420 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11421 InNonTrivialUnion); 11422 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11423 } 11424 11425 void visitARCStrong(QualType QT, const FieldDecl *FD, 11426 bool InNonTrivialUnion) { 11427 if (InNonTrivialUnion) 11428 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11429 << 1 << 2 << QT << FD->getName(); 11430 } 11431 11432 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11433 if (InNonTrivialUnion) 11434 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11435 << 1 << 2 << QT << FD->getName(); 11436 } 11437 11438 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11439 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11440 if (RD->isUnion()) { 11441 if (OrigLoc.isValid()) { 11442 bool IsUnion = false; 11443 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11444 IsUnion = OrigRD->isUnion(); 11445 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11446 << 2 << OrigTy << IsUnion << UseContext; 11447 // Reset OrigLoc so that this diagnostic is emitted only once. 11448 OrigLoc = SourceLocation(); 11449 } 11450 InNonTrivialUnion = true; 11451 } 11452 11453 if (InNonTrivialUnion) 11454 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11455 << 0 << 2 << QT.getUnqualifiedType() << ""; 11456 11457 for (const FieldDecl *FD : RD->fields()) 11458 if (!shouldIgnoreForRecordTriviality(FD)) 11459 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11460 } 11461 11462 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11463 const FieldDecl *FD, bool InNonTrivialUnion) {} 11464 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11465 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11466 bool InNonTrivialUnion) {} 11467 11468 // The non-trivial C union type or the struct/union type that contains a 11469 // non-trivial C union. 11470 QualType OrigTy; 11471 SourceLocation OrigLoc; 11472 Sema::NonTrivialCUnionContext UseContext; 11473 Sema &S; 11474 }; 11475 11476 } // namespace 11477 11478 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11479 NonTrivialCUnionContext UseContext, 11480 unsigned NonTrivialKind) { 11481 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11482 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11483 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11484 "shouldn't be called if type doesn't have a non-trivial C union"); 11485 11486 if ((NonTrivialKind & NTCUK_Init) && 11487 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11488 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11489 .visit(QT, nullptr, false); 11490 if ((NonTrivialKind & NTCUK_Destruct) && 11491 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11492 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11493 .visit(QT, nullptr, false); 11494 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11495 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11496 .visit(QT, nullptr, false); 11497 } 11498 11499 /// AddInitializerToDecl - Adds the initializer Init to the 11500 /// declaration dcl. If DirectInit is true, this is C++ direct 11501 /// initialization rather than copy initialization. 11502 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11503 // If there is no declaration, there was an error parsing it. Just ignore 11504 // the initializer. 11505 if (!RealDecl || RealDecl->isInvalidDecl()) { 11506 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11507 return; 11508 } 11509 11510 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11511 // Pure-specifiers are handled in ActOnPureSpecifier. 11512 Diag(Method->getLocation(), diag::err_member_function_initialization) 11513 << Method->getDeclName() << Init->getSourceRange(); 11514 Method->setInvalidDecl(); 11515 return; 11516 } 11517 11518 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11519 if (!VDecl) { 11520 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11521 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11522 RealDecl->setInvalidDecl(); 11523 return; 11524 } 11525 11526 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11527 if (VDecl->getType()->isUndeducedType()) { 11528 // Attempt typo correction early so that the type of the init expression can 11529 // be deduced based on the chosen correction if the original init contains a 11530 // TypoExpr. 11531 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11532 if (!Res.isUsable()) { 11533 RealDecl->setInvalidDecl(); 11534 return; 11535 } 11536 Init = Res.get(); 11537 11538 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11539 return; 11540 } 11541 11542 // dllimport cannot be used on variable definitions. 11543 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11544 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11545 VDecl->setInvalidDecl(); 11546 return; 11547 } 11548 11549 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11550 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11551 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11552 VDecl->setInvalidDecl(); 11553 return; 11554 } 11555 11556 if (!VDecl->getType()->isDependentType()) { 11557 // A definition must end up with a complete type, which means it must be 11558 // complete with the restriction that an array type might be completed by 11559 // the initializer; note that later code assumes this restriction. 11560 QualType BaseDeclType = VDecl->getType(); 11561 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11562 BaseDeclType = Array->getElementType(); 11563 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11564 diag::err_typecheck_decl_incomplete_type)) { 11565 RealDecl->setInvalidDecl(); 11566 return; 11567 } 11568 11569 // The variable can not have an abstract class type. 11570 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11571 diag::err_abstract_type_in_decl, 11572 AbstractVariableType)) 11573 VDecl->setInvalidDecl(); 11574 } 11575 11576 // If adding the initializer will turn this declaration into a definition, 11577 // and we already have a definition for this variable, diagnose or otherwise 11578 // handle the situation. 11579 VarDecl *Def; 11580 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11581 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11582 !VDecl->isThisDeclarationADemotedDefinition() && 11583 checkVarDeclRedefinition(Def, VDecl)) 11584 return; 11585 11586 if (getLangOpts().CPlusPlus) { 11587 // C++ [class.static.data]p4 11588 // If a static data member is of const integral or const 11589 // enumeration type, its declaration in the class definition can 11590 // specify a constant-initializer which shall be an integral 11591 // constant expression (5.19). In that case, the member can appear 11592 // in integral constant expressions. The member shall still be 11593 // defined in a namespace scope if it is used in the program and the 11594 // namespace scope definition shall not contain an initializer. 11595 // 11596 // We already performed a redefinition check above, but for static 11597 // data members we also need to check whether there was an in-class 11598 // declaration with an initializer. 11599 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11600 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11601 << VDecl->getDeclName(); 11602 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11603 diag::note_previous_initializer) 11604 << 0; 11605 return; 11606 } 11607 11608 if (VDecl->hasLocalStorage()) 11609 setFunctionHasBranchProtectedScope(); 11610 11611 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11612 VDecl->setInvalidDecl(); 11613 return; 11614 } 11615 } 11616 11617 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11618 // a kernel function cannot be initialized." 11619 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11620 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11621 VDecl->setInvalidDecl(); 11622 return; 11623 } 11624 11625 // Get the decls type and save a reference for later, since 11626 // CheckInitializerTypes may change it. 11627 QualType DclT = VDecl->getType(), SavT = DclT; 11628 11629 // Expressions default to 'id' when we're in a debugger 11630 // and we are assigning it to a variable of Objective-C pointer type. 11631 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11632 Init->getType() == Context.UnknownAnyTy) { 11633 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11634 if (Result.isInvalid()) { 11635 VDecl->setInvalidDecl(); 11636 return; 11637 } 11638 Init = Result.get(); 11639 } 11640 11641 // Perform the initialization. 11642 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11643 if (!VDecl->isInvalidDecl()) { 11644 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11645 InitializationKind Kind = InitializationKind::CreateForInit( 11646 VDecl->getLocation(), DirectInit, Init); 11647 11648 MultiExprArg Args = Init; 11649 if (CXXDirectInit) 11650 Args = MultiExprArg(CXXDirectInit->getExprs(), 11651 CXXDirectInit->getNumExprs()); 11652 11653 // Try to correct any TypoExprs in the initialization arguments. 11654 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11655 ExprResult Res = CorrectDelayedTyposInExpr( 11656 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11657 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11658 return Init.Failed() ? ExprError() : E; 11659 }); 11660 if (Res.isInvalid()) { 11661 VDecl->setInvalidDecl(); 11662 } else if (Res.get() != Args[Idx]) { 11663 Args[Idx] = Res.get(); 11664 } 11665 } 11666 if (VDecl->isInvalidDecl()) 11667 return; 11668 11669 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11670 /*TopLevelOfInitList=*/false, 11671 /*TreatUnavailableAsInvalid=*/false); 11672 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11673 if (Result.isInvalid()) { 11674 VDecl->setInvalidDecl(); 11675 return; 11676 } 11677 11678 Init = Result.getAs<Expr>(); 11679 } 11680 11681 // Check for self-references within variable initializers. 11682 // Variables declared within a function/method body (except for references) 11683 // are handled by a dataflow analysis. 11684 // This is undefined behavior in C++, but valid in C. 11685 if (getLangOpts().CPlusPlus) { 11686 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11687 VDecl->getType()->isReferenceType()) { 11688 CheckSelfReference(*this, RealDecl, Init, DirectInit); 11689 } 11690 } 11691 11692 // If the type changed, it means we had an incomplete type that was 11693 // completed by the initializer. For example: 11694 // int ary[] = { 1, 3, 5 }; 11695 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 11696 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 11697 VDecl->setType(DclT); 11698 11699 if (!VDecl->isInvalidDecl()) { 11700 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 11701 11702 if (VDecl->hasAttr<BlocksAttr>()) 11703 checkRetainCycles(VDecl, Init); 11704 11705 // It is safe to assign a weak reference into a strong variable. 11706 // Although this code can still have problems: 11707 // id x = self.weakProp; 11708 // id y = self.weakProp; 11709 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11710 // paths through the function. This should be revisited if 11711 // -Wrepeated-use-of-weak is made flow-sensitive. 11712 if (FunctionScopeInfo *FSI = getCurFunction()) 11713 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 11714 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 11715 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11716 Init->getBeginLoc())) 11717 FSI->markSafeWeakUse(Init); 11718 } 11719 11720 // The initialization is usually a full-expression. 11721 // 11722 // FIXME: If this is a braced initialization of an aggregate, it is not 11723 // an expression, and each individual field initializer is a separate 11724 // full-expression. For instance, in: 11725 // 11726 // struct Temp { ~Temp(); }; 11727 // struct S { S(Temp); }; 11728 // struct T { S a, b; } t = { Temp(), Temp() } 11729 // 11730 // we should destroy the first Temp before constructing the second. 11731 ExprResult Result = 11732 ActOnFinishFullExpr(Init, VDecl->getLocation(), 11733 /*DiscardedValue*/ false, VDecl->isConstexpr()); 11734 if (Result.isInvalid()) { 11735 VDecl->setInvalidDecl(); 11736 return; 11737 } 11738 Init = Result.get(); 11739 11740 // Attach the initializer to the decl. 11741 VDecl->setInit(Init); 11742 11743 if (VDecl->isLocalVarDecl()) { 11744 // Don't check the initializer if the declaration is malformed. 11745 if (VDecl->isInvalidDecl()) { 11746 // do nothing 11747 11748 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 11749 // This is true even in C++ for OpenCL. 11750 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 11751 CheckForConstantInitializer(Init, DclT); 11752 11753 // Otherwise, C++ does not restrict the initializer. 11754 } else if (getLangOpts().CPlusPlus) { 11755 // do nothing 11756 11757 // C99 6.7.8p4: All the expressions in an initializer for an object that has 11758 // static storage duration shall be constant expressions or string literals. 11759 } else if (VDecl->getStorageClass() == SC_Static) { 11760 CheckForConstantInitializer(Init, DclT); 11761 11762 // C89 is stricter than C99 for aggregate initializers. 11763 // C89 6.5.7p3: All the expressions [...] in an initializer list 11764 // for an object that has aggregate or union type shall be 11765 // constant expressions. 11766 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 11767 isa<InitListExpr>(Init)) { 11768 const Expr *Culprit; 11769 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 11770 Diag(Culprit->getExprLoc(), 11771 diag::ext_aggregate_init_not_constant) 11772 << Culprit->getSourceRange(); 11773 } 11774 } 11775 11776 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 11777 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 11778 if (VDecl->hasLocalStorage()) 11779 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 11780 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 11781 VDecl->getLexicalDeclContext()->isRecord()) { 11782 // This is an in-class initialization for a static data member, e.g., 11783 // 11784 // struct S { 11785 // static const int value = 17; 11786 // }; 11787 11788 // C++ [class.mem]p4: 11789 // A member-declarator can contain a constant-initializer only 11790 // if it declares a static member (9.4) of const integral or 11791 // const enumeration type, see 9.4.2. 11792 // 11793 // C++11 [class.static.data]p3: 11794 // If a non-volatile non-inline const static data member is of integral 11795 // or enumeration type, its declaration in the class definition can 11796 // specify a brace-or-equal-initializer in which every initializer-clause 11797 // that is an assignment-expression is a constant expression. A static 11798 // data member of literal type can be declared in the class definition 11799 // with the constexpr specifier; if so, its declaration shall specify a 11800 // brace-or-equal-initializer in which every initializer-clause that is 11801 // an assignment-expression is a constant expression. 11802 11803 // Do nothing on dependent types. 11804 if (DclT->isDependentType()) { 11805 11806 // Allow any 'static constexpr' members, whether or not they are of literal 11807 // type. We separately check that every constexpr variable is of literal 11808 // type. 11809 } else if (VDecl->isConstexpr()) { 11810 11811 // Require constness. 11812 } else if (!DclT.isConstQualified()) { 11813 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 11814 << Init->getSourceRange(); 11815 VDecl->setInvalidDecl(); 11816 11817 // We allow integer constant expressions in all cases. 11818 } else if (DclT->isIntegralOrEnumerationType()) { 11819 // Check whether the expression is a constant expression. 11820 SourceLocation Loc; 11821 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 11822 // In C++11, a non-constexpr const static data member with an 11823 // in-class initializer cannot be volatile. 11824 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 11825 else if (Init->isValueDependent()) 11826 ; // Nothing to check. 11827 else if (Init->isIntegerConstantExpr(Context, &Loc)) 11828 ; // Ok, it's an ICE! 11829 else if (Init->getType()->isScopedEnumeralType() && 11830 Init->isCXX11ConstantExpr(Context)) 11831 ; // Ok, it is a scoped-enum constant expression. 11832 else if (Init->isEvaluatable(Context)) { 11833 // If we can constant fold the initializer through heroics, accept it, 11834 // but report this as a use of an extension for -pedantic. 11835 Diag(Loc, diag::ext_in_class_initializer_non_constant) 11836 << Init->getSourceRange(); 11837 } else { 11838 // Otherwise, this is some crazy unknown case. Report the issue at the 11839 // location provided by the isIntegerConstantExpr failed check. 11840 Diag(Loc, diag::err_in_class_initializer_non_constant) 11841 << Init->getSourceRange(); 11842 VDecl->setInvalidDecl(); 11843 } 11844 11845 // We allow foldable floating-point constants as an extension. 11846 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 11847 // In C++98, this is a GNU extension. In C++11, it is not, but we support 11848 // it anyway and provide a fixit to add the 'constexpr'. 11849 if (getLangOpts().CPlusPlus11) { 11850 Diag(VDecl->getLocation(), 11851 diag::ext_in_class_initializer_float_type_cxx11) 11852 << DclT << Init->getSourceRange(); 11853 Diag(VDecl->getBeginLoc(), 11854 diag::note_in_class_initializer_float_type_cxx11) 11855 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11856 } else { 11857 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 11858 << DclT << Init->getSourceRange(); 11859 11860 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 11861 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 11862 << Init->getSourceRange(); 11863 VDecl->setInvalidDecl(); 11864 } 11865 } 11866 11867 // Suggest adding 'constexpr' in C++11 for literal types. 11868 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 11869 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 11870 << DclT << Init->getSourceRange() 11871 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11872 VDecl->setConstexpr(true); 11873 11874 } else { 11875 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 11876 << DclT << Init->getSourceRange(); 11877 VDecl->setInvalidDecl(); 11878 } 11879 } else if (VDecl->isFileVarDecl()) { 11880 // In C, extern is typically used to avoid tentative definitions when 11881 // declaring variables in headers, but adding an intializer makes it a 11882 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 11883 // In C++, extern is often used to give implictly static const variables 11884 // external linkage, so don't warn in that case. If selectany is present, 11885 // this might be header code intended for C and C++ inclusion, so apply the 11886 // C++ rules. 11887 if (VDecl->getStorageClass() == SC_Extern && 11888 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 11889 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 11890 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 11891 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 11892 Diag(VDecl->getLocation(), diag::warn_extern_init); 11893 11894 // In Microsoft C++ mode, a const variable defined in namespace scope has 11895 // external linkage by default if the variable is declared with 11896 // __declspec(dllexport). 11897 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 11898 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 11899 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 11900 VDecl->setStorageClass(SC_Extern); 11901 11902 // C99 6.7.8p4. All file scoped initializers need to be constant. 11903 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 11904 CheckForConstantInitializer(Init, DclT); 11905 } 11906 11907 QualType InitType = Init->getType(); 11908 if (!InitType.isNull() && 11909 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11910 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 11911 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 11912 11913 // We will represent direct-initialization similarly to copy-initialization: 11914 // int x(1); -as-> int x = 1; 11915 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 11916 // 11917 // Clients that want to distinguish between the two forms, can check for 11918 // direct initializer using VarDecl::getInitStyle(). 11919 // A major benefit is that clients that don't particularly care about which 11920 // exactly form was it (like the CodeGen) can handle both cases without 11921 // special case code. 11922 11923 // C++ 8.5p11: 11924 // The form of initialization (using parentheses or '=') is generally 11925 // insignificant, but does matter when the entity being initialized has a 11926 // class type. 11927 if (CXXDirectInit) { 11928 assert(DirectInit && "Call-style initializer must be direct init."); 11929 VDecl->setInitStyle(VarDecl::CallInit); 11930 } else if (DirectInit) { 11931 // This must be list-initialization. No other way is direct-initialization. 11932 VDecl->setInitStyle(VarDecl::ListInit); 11933 } 11934 11935 CheckCompleteVariableDeclaration(VDecl); 11936 } 11937 11938 /// ActOnInitializerError - Given that there was an error parsing an 11939 /// initializer for the given declaration, try to return to some form 11940 /// of sanity. 11941 void Sema::ActOnInitializerError(Decl *D) { 11942 // Our main concern here is re-establishing invariants like "a 11943 // variable's type is either dependent or complete". 11944 if (!D || D->isInvalidDecl()) return; 11945 11946 VarDecl *VD = dyn_cast<VarDecl>(D); 11947 if (!VD) return; 11948 11949 // Bindings are not usable if we can't make sense of the initializer. 11950 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11951 for (auto *BD : DD->bindings()) 11952 BD->setInvalidDecl(); 11953 11954 // Auto types are meaningless if we can't make sense of the initializer. 11955 if (ParsingInitForAutoVars.count(D)) { 11956 D->setInvalidDecl(); 11957 return; 11958 } 11959 11960 QualType Ty = VD->getType(); 11961 if (Ty->isDependentType()) return; 11962 11963 // Require a complete type. 11964 if (RequireCompleteType(VD->getLocation(), 11965 Context.getBaseElementType(Ty), 11966 diag::err_typecheck_decl_incomplete_type)) { 11967 VD->setInvalidDecl(); 11968 return; 11969 } 11970 11971 // Require a non-abstract type. 11972 if (RequireNonAbstractType(VD->getLocation(), Ty, 11973 diag::err_abstract_type_in_decl, 11974 AbstractVariableType)) { 11975 VD->setInvalidDecl(); 11976 return; 11977 } 11978 11979 // Don't bother complaining about constructors or destructors, 11980 // though. 11981 } 11982 11983 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11984 // If there is no declaration, there was an error parsing it. Just ignore it. 11985 if (!RealDecl) 11986 return; 11987 11988 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11989 QualType Type = Var->getType(); 11990 11991 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11992 if (isa<DecompositionDecl>(RealDecl)) { 11993 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11994 Var->setInvalidDecl(); 11995 return; 11996 } 11997 11998 if (Type->isUndeducedType() && 11999 DeduceVariableDeclarationType(Var, false, nullptr)) 12000 return; 12001 12002 // C++11 [class.static.data]p3: A static data member can be declared with 12003 // the constexpr specifier; if so, its declaration shall specify 12004 // a brace-or-equal-initializer. 12005 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12006 // the definition of a variable [...] or the declaration of a static data 12007 // member. 12008 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12009 !Var->isThisDeclarationADemotedDefinition()) { 12010 if (Var->isStaticDataMember()) { 12011 // C++1z removes the relevant rule; the in-class declaration is always 12012 // a definition there. 12013 if (!getLangOpts().CPlusPlus17 && 12014 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12015 Diag(Var->getLocation(), 12016 diag::err_constexpr_static_mem_var_requires_init) 12017 << Var->getDeclName(); 12018 Var->setInvalidDecl(); 12019 return; 12020 } 12021 } else { 12022 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12023 Var->setInvalidDecl(); 12024 return; 12025 } 12026 } 12027 12028 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12029 // be initialized. 12030 if (!Var->isInvalidDecl() && 12031 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12032 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12033 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12034 Var->setInvalidDecl(); 12035 return; 12036 } 12037 12038 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12039 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12040 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12041 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12042 NTCUC_DefaultInitializedObject, NTCUK_Init); 12043 12044 12045 switch (DefKind) { 12046 case VarDecl::Definition: 12047 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12048 break; 12049 12050 // We have an out-of-line definition of a static data member 12051 // that has an in-class initializer, so we type-check this like 12052 // a declaration. 12053 // 12054 LLVM_FALLTHROUGH; 12055 12056 case VarDecl::DeclarationOnly: 12057 // It's only a declaration. 12058 12059 // Block scope. C99 6.7p7: If an identifier for an object is 12060 // declared with no linkage (C99 6.2.2p6), the type for the 12061 // object shall be complete. 12062 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12063 !Var->hasLinkage() && !Var->isInvalidDecl() && 12064 RequireCompleteType(Var->getLocation(), Type, 12065 diag::err_typecheck_decl_incomplete_type)) 12066 Var->setInvalidDecl(); 12067 12068 // Make sure that the type is not abstract. 12069 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12070 RequireNonAbstractType(Var->getLocation(), Type, 12071 diag::err_abstract_type_in_decl, 12072 AbstractVariableType)) 12073 Var->setInvalidDecl(); 12074 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12075 Var->getStorageClass() == SC_PrivateExtern) { 12076 Diag(Var->getLocation(), diag::warn_private_extern); 12077 Diag(Var->getLocation(), diag::note_private_extern); 12078 } 12079 12080 return; 12081 12082 case VarDecl::TentativeDefinition: 12083 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12084 // object that has file scope without an initializer, and without a 12085 // storage-class specifier or with the storage-class specifier "static", 12086 // constitutes a tentative definition. Note: A tentative definition with 12087 // external linkage is valid (C99 6.2.2p5). 12088 if (!Var->isInvalidDecl()) { 12089 if (const IncompleteArrayType *ArrayT 12090 = Context.getAsIncompleteArrayType(Type)) { 12091 if (RequireCompleteType(Var->getLocation(), 12092 ArrayT->getElementType(), 12093 diag::err_illegal_decl_array_incomplete_type)) 12094 Var->setInvalidDecl(); 12095 } else if (Var->getStorageClass() == SC_Static) { 12096 // C99 6.9.2p3: If the declaration of an identifier for an object is 12097 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12098 // declared type shall not be an incomplete type. 12099 // NOTE: code such as the following 12100 // static struct s; 12101 // struct s { int a; }; 12102 // is accepted by gcc. Hence here we issue a warning instead of 12103 // an error and we do not invalidate the static declaration. 12104 // NOTE: to avoid multiple warnings, only check the first declaration. 12105 if (Var->isFirstDecl()) 12106 RequireCompleteType(Var->getLocation(), Type, 12107 diag::ext_typecheck_decl_incomplete_type); 12108 } 12109 } 12110 12111 // Record the tentative definition; we're done. 12112 if (!Var->isInvalidDecl()) 12113 TentativeDefinitions.push_back(Var); 12114 return; 12115 } 12116 12117 // Provide a specific diagnostic for uninitialized variable 12118 // definitions with incomplete array type. 12119 if (Type->isIncompleteArrayType()) { 12120 Diag(Var->getLocation(), 12121 diag::err_typecheck_incomplete_array_needs_initializer); 12122 Var->setInvalidDecl(); 12123 return; 12124 } 12125 12126 // Provide a specific diagnostic for uninitialized variable 12127 // definitions with reference type. 12128 if (Type->isReferenceType()) { 12129 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12130 << Var->getDeclName() 12131 << SourceRange(Var->getLocation(), Var->getLocation()); 12132 Var->setInvalidDecl(); 12133 return; 12134 } 12135 12136 // Do not attempt to type-check the default initializer for a 12137 // variable with dependent type. 12138 if (Type->isDependentType()) 12139 return; 12140 12141 if (Var->isInvalidDecl()) 12142 return; 12143 12144 if (!Var->hasAttr<AliasAttr>()) { 12145 if (RequireCompleteType(Var->getLocation(), 12146 Context.getBaseElementType(Type), 12147 diag::err_typecheck_decl_incomplete_type)) { 12148 Var->setInvalidDecl(); 12149 return; 12150 } 12151 } else { 12152 return; 12153 } 12154 12155 // The variable can not have an abstract class type. 12156 if (RequireNonAbstractType(Var->getLocation(), Type, 12157 diag::err_abstract_type_in_decl, 12158 AbstractVariableType)) { 12159 Var->setInvalidDecl(); 12160 return; 12161 } 12162 12163 // Check for jumps past the implicit initializer. C++0x 12164 // clarifies that this applies to a "variable with automatic 12165 // storage duration", not a "local variable". 12166 // C++11 [stmt.dcl]p3 12167 // A program that jumps from a point where a variable with automatic 12168 // storage duration is not in scope to a point where it is in scope is 12169 // ill-formed unless the variable has scalar type, class type with a 12170 // trivial default constructor and a trivial destructor, a cv-qualified 12171 // version of one of these types, or an array of one of the preceding 12172 // types and is declared without an initializer. 12173 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12174 if (const RecordType *Record 12175 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12176 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12177 // Mark the function (if we're in one) for further checking even if the 12178 // looser rules of C++11 do not require such checks, so that we can 12179 // diagnose incompatibilities with C++98. 12180 if (!CXXRecord->isPOD()) 12181 setFunctionHasBranchProtectedScope(); 12182 } 12183 } 12184 // In OpenCL, we can't initialize objects in the __local address space, 12185 // even implicitly, so don't synthesize an implicit initializer. 12186 if (getLangOpts().OpenCL && 12187 Var->getType().getAddressSpace() == LangAS::opencl_local) 12188 return; 12189 // C++03 [dcl.init]p9: 12190 // If no initializer is specified for an object, and the 12191 // object is of (possibly cv-qualified) non-POD class type (or 12192 // array thereof), the object shall be default-initialized; if 12193 // the object is of const-qualified type, the underlying class 12194 // type shall have a user-declared default 12195 // constructor. Otherwise, if no initializer is specified for 12196 // a non- static object, the object and its subobjects, if 12197 // any, have an indeterminate initial value); if the object 12198 // or any of its subobjects are of const-qualified type, the 12199 // program is ill-formed. 12200 // C++0x [dcl.init]p11: 12201 // If no initializer is specified for an object, the object is 12202 // default-initialized; [...]. 12203 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12204 InitializationKind Kind 12205 = InitializationKind::CreateDefault(Var->getLocation()); 12206 12207 InitializationSequence InitSeq(*this, Entity, Kind, None); 12208 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12209 if (Init.isInvalid()) 12210 Var->setInvalidDecl(); 12211 else if (Init.get()) { 12212 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12213 // This is important for template substitution. 12214 Var->setInitStyle(VarDecl::CallInit); 12215 } 12216 12217 CheckCompleteVariableDeclaration(Var); 12218 } 12219 } 12220 12221 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12222 // If there is no declaration, there was an error parsing it. Ignore it. 12223 if (!D) 12224 return; 12225 12226 VarDecl *VD = dyn_cast<VarDecl>(D); 12227 if (!VD) { 12228 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12229 D->setInvalidDecl(); 12230 return; 12231 } 12232 12233 VD->setCXXForRangeDecl(true); 12234 12235 // for-range-declaration cannot be given a storage class specifier. 12236 int Error = -1; 12237 switch (VD->getStorageClass()) { 12238 case SC_None: 12239 break; 12240 case SC_Extern: 12241 Error = 0; 12242 break; 12243 case SC_Static: 12244 Error = 1; 12245 break; 12246 case SC_PrivateExtern: 12247 Error = 2; 12248 break; 12249 case SC_Auto: 12250 Error = 3; 12251 break; 12252 case SC_Register: 12253 Error = 4; 12254 break; 12255 } 12256 if (Error != -1) { 12257 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12258 << VD->getDeclName() << Error; 12259 D->setInvalidDecl(); 12260 } 12261 } 12262 12263 StmtResult 12264 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12265 IdentifierInfo *Ident, 12266 ParsedAttributes &Attrs, 12267 SourceLocation AttrEnd) { 12268 // C++1y [stmt.iter]p1: 12269 // A range-based for statement of the form 12270 // for ( for-range-identifier : for-range-initializer ) statement 12271 // is equivalent to 12272 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12273 DeclSpec DS(Attrs.getPool().getFactory()); 12274 12275 const char *PrevSpec; 12276 unsigned DiagID; 12277 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12278 getPrintingPolicy()); 12279 12280 Declarator D(DS, DeclaratorContext::ForContext); 12281 D.SetIdentifier(Ident, IdentLoc); 12282 D.takeAttributes(Attrs, AttrEnd); 12283 12284 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12285 IdentLoc); 12286 Decl *Var = ActOnDeclarator(S, D); 12287 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12288 FinalizeDeclaration(Var); 12289 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12290 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12291 } 12292 12293 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12294 if (var->isInvalidDecl()) return; 12295 12296 if (getLangOpts().OpenCL) { 12297 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12298 // initialiser 12299 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12300 !var->hasInit()) { 12301 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12302 << 1 /*Init*/; 12303 var->setInvalidDecl(); 12304 return; 12305 } 12306 } 12307 12308 // In Objective-C, don't allow jumps past the implicit initialization of a 12309 // local retaining variable. 12310 if (getLangOpts().ObjC && 12311 var->hasLocalStorage()) { 12312 switch (var->getType().getObjCLifetime()) { 12313 case Qualifiers::OCL_None: 12314 case Qualifiers::OCL_ExplicitNone: 12315 case Qualifiers::OCL_Autoreleasing: 12316 break; 12317 12318 case Qualifiers::OCL_Weak: 12319 case Qualifiers::OCL_Strong: 12320 setFunctionHasBranchProtectedScope(); 12321 break; 12322 } 12323 } 12324 12325 if (var->hasLocalStorage() && 12326 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12327 setFunctionHasBranchProtectedScope(); 12328 12329 // Warn about externally-visible variables being defined without a 12330 // prior declaration. We only want to do this for global 12331 // declarations, but we also specifically need to avoid doing it for 12332 // class members because the linkage of an anonymous class can 12333 // change if it's later given a typedef name. 12334 if (var->isThisDeclarationADefinition() && 12335 var->getDeclContext()->getRedeclContext()->isFileContext() && 12336 var->isExternallyVisible() && var->hasLinkage() && 12337 !var->isInline() && !var->getDescribedVarTemplate() && 12338 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12339 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12340 var->getLocation())) { 12341 // Find a previous declaration that's not a definition. 12342 VarDecl *prev = var->getPreviousDecl(); 12343 while (prev && prev->isThisDeclarationADefinition()) 12344 prev = prev->getPreviousDecl(); 12345 12346 if (!prev) { 12347 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12348 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12349 << /* variable */ 0; 12350 } 12351 } 12352 12353 // Cache the result of checking for constant initialization. 12354 Optional<bool> CacheHasConstInit; 12355 const Expr *CacheCulprit = nullptr; 12356 auto checkConstInit = [&]() mutable { 12357 if (!CacheHasConstInit) 12358 CacheHasConstInit = var->getInit()->isConstantInitializer( 12359 Context, var->getType()->isReferenceType(), &CacheCulprit); 12360 return *CacheHasConstInit; 12361 }; 12362 12363 if (var->getTLSKind() == VarDecl::TLS_Static) { 12364 if (var->getType().isDestructedType()) { 12365 // GNU C++98 edits for __thread, [basic.start.term]p3: 12366 // The type of an object with thread storage duration shall not 12367 // have a non-trivial destructor. 12368 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12369 if (getLangOpts().CPlusPlus11) 12370 Diag(var->getLocation(), diag::note_use_thread_local); 12371 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12372 if (!checkConstInit()) { 12373 // GNU C++98 edits for __thread, [basic.start.init]p4: 12374 // An object of thread storage duration shall not require dynamic 12375 // initialization. 12376 // FIXME: Need strict checking here. 12377 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12378 << CacheCulprit->getSourceRange(); 12379 if (getLangOpts().CPlusPlus11) 12380 Diag(var->getLocation(), diag::note_use_thread_local); 12381 } 12382 } 12383 } 12384 12385 // Apply section attributes and pragmas to global variables. 12386 bool GlobalStorage = var->hasGlobalStorage(); 12387 if (GlobalStorage && var->isThisDeclarationADefinition() && 12388 !inTemplateInstantiation()) { 12389 PragmaStack<StringLiteral *> *Stack = nullptr; 12390 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 12391 if (var->getType().isConstQualified()) 12392 Stack = &ConstSegStack; 12393 else if (!var->getInit()) { 12394 Stack = &BSSSegStack; 12395 SectionFlags |= ASTContext::PSF_Write; 12396 } else { 12397 Stack = &DataSegStack; 12398 SectionFlags |= ASTContext::PSF_Write; 12399 } 12400 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) 12401 var->addAttr(SectionAttr::CreateImplicit( 12402 Context, Stack->CurrentValue->getString(), 12403 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 12404 SectionAttr::Declspec_allocate)); 12405 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 12406 if (UnifySection(SA->getName(), SectionFlags, var)) 12407 var->dropAttr<SectionAttr>(); 12408 12409 // Apply the init_seg attribute if this has an initializer. If the 12410 // initializer turns out to not be dynamic, we'll end up ignoring this 12411 // attribute. 12412 if (CurInitSeg && var->getInit()) 12413 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12414 CurInitSegLoc, 12415 AttributeCommonInfo::AS_Pragma)); 12416 } 12417 12418 // All the following checks are C++ only. 12419 if (!getLangOpts().CPlusPlus) { 12420 // If this variable must be emitted, add it as an initializer for the 12421 // current module. 12422 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12423 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12424 return; 12425 } 12426 12427 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12428 CheckCompleteDecompositionDeclaration(DD); 12429 12430 QualType type = var->getType(); 12431 if (type->isDependentType()) return; 12432 12433 if (var->hasAttr<BlocksAttr>()) 12434 getCurFunction()->addByrefBlockVar(var); 12435 12436 Expr *Init = var->getInit(); 12437 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12438 QualType baseType = Context.getBaseElementType(type); 12439 12440 if (Init && !Init->isValueDependent()) { 12441 if (var->isConstexpr()) { 12442 SmallVector<PartialDiagnosticAt, 8> Notes; 12443 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12444 SourceLocation DiagLoc = var->getLocation(); 12445 // If the note doesn't add any useful information other than a source 12446 // location, fold it into the primary diagnostic. 12447 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12448 diag::note_invalid_subexpr_in_const_expr) { 12449 DiagLoc = Notes[0].first; 12450 Notes.clear(); 12451 } 12452 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12453 << var << Init->getSourceRange(); 12454 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12455 Diag(Notes[I].first, Notes[I].second); 12456 } 12457 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12458 // Check whether the initializer of a const variable of integral or 12459 // enumeration type is an ICE now, since we can't tell whether it was 12460 // initialized by a constant expression if we check later. 12461 var->checkInitIsICE(); 12462 } 12463 12464 // Don't emit further diagnostics about constexpr globals since they 12465 // were just diagnosed. 12466 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12467 // FIXME: Need strict checking in C++03 here. 12468 bool DiagErr = getLangOpts().CPlusPlus11 12469 ? !var->checkInitIsICE() : !checkConstInit(); 12470 if (DiagErr) { 12471 auto *Attr = var->getAttr<ConstInitAttr>(); 12472 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12473 << Init->getSourceRange(); 12474 Diag(Attr->getLocation(), 12475 diag::note_declared_required_constant_init_here) 12476 << Attr->getRange() << Attr->isConstinit(); 12477 if (getLangOpts().CPlusPlus11) { 12478 APValue Value; 12479 SmallVector<PartialDiagnosticAt, 8> Notes; 12480 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12481 for (auto &it : Notes) 12482 Diag(it.first, it.second); 12483 } else { 12484 Diag(CacheCulprit->getExprLoc(), 12485 diag::note_invalid_subexpr_in_const_expr) 12486 << CacheCulprit->getSourceRange(); 12487 } 12488 } 12489 } 12490 else if (!var->isConstexpr() && IsGlobal && 12491 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12492 var->getLocation())) { 12493 // Warn about globals which don't have a constant initializer. Don't 12494 // warn about globals with a non-trivial destructor because we already 12495 // warned about them. 12496 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12497 if (!(RD && !RD->hasTrivialDestructor())) { 12498 if (!checkConstInit()) 12499 Diag(var->getLocation(), diag::warn_global_constructor) 12500 << Init->getSourceRange(); 12501 } 12502 } 12503 } 12504 12505 // Require the destructor. 12506 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12507 FinalizeVarWithDestructor(var, recordType); 12508 12509 // If this variable must be emitted, add it as an initializer for the current 12510 // module. 12511 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12512 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12513 } 12514 12515 /// Determines if a variable's alignment is dependent. 12516 static bool hasDependentAlignment(VarDecl *VD) { 12517 if (VD->getType()->isDependentType()) 12518 return true; 12519 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12520 if (I->isAlignmentDependent()) 12521 return true; 12522 return false; 12523 } 12524 12525 /// Check if VD needs to be dllexport/dllimport due to being in a 12526 /// dllexport/import function. 12527 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12528 assert(VD->isStaticLocal()); 12529 12530 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12531 12532 // Find outermost function when VD is in lambda function. 12533 while (FD && !getDLLAttr(FD) && 12534 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12535 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12536 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12537 } 12538 12539 if (!FD) 12540 return; 12541 12542 // Static locals inherit dll attributes from their function. 12543 if (Attr *A = getDLLAttr(FD)) { 12544 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12545 NewAttr->setInherited(true); 12546 VD->addAttr(NewAttr); 12547 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12548 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12549 NewAttr->setInherited(true); 12550 VD->addAttr(NewAttr); 12551 12552 // Export this function to enforce exporting this static variable even 12553 // if it is not used in this compilation unit. 12554 if (!FD->hasAttr<DLLExportAttr>()) 12555 FD->addAttr(NewAttr); 12556 12557 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12558 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12559 NewAttr->setInherited(true); 12560 VD->addAttr(NewAttr); 12561 } 12562 } 12563 12564 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12565 /// any semantic actions necessary after any initializer has been attached. 12566 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12567 // Note that we are no longer parsing the initializer for this declaration. 12568 ParsingInitForAutoVars.erase(ThisDecl); 12569 12570 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12571 if (!VD) 12572 return; 12573 12574 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12575 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12576 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12577 if (PragmaClangBSSSection.Valid) 12578 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12579 Context, PragmaClangBSSSection.SectionName, 12580 PragmaClangBSSSection.PragmaLocation, 12581 AttributeCommonInfo::AS_Pragma)); 12582 if (PragmaClangDataSection.Valid) 12583 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12584 Context, PragmaClangDataSection.SectionName, 12585 PragmaClangDataSection.PragmaLocation, 12586 AttributeCommonInfo::AS_Pragma)); 12587 if (PragmaClangRodataSection.Valid) 12588 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12589 Context, PragmaClangRodataSection.SectionName, 12590 PragmaClangRodataSection.PragmaLocation, 12591 AttributeCommonInfo::AS_Pragma)); 12592 } 12593 12594 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12595 for (auto *BD : DD->bindings()) { 12596 FinalizeDeclaration(BD); 12597 } 12598 } 12599 12600 checkAttributesAfterMerging(*this, *VD); 12601 12602 // Perform TLS alignment check here after attributes attached to the variable 12603 // which may affect the alignment have been processed. Only perform the check 12604 // if the target has a maximum TLS alignment (zero means no constraints). 12605 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12606 // Protect the check so that it's not performed on dependent types and 12607 // dependent alignments (we can't determine the alignment in that case). 12608 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12609 !VD->isInvalidDecl()) { 12610 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12611 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12612 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12613 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12614 << (unsigned)MaxAlignChars.getQuantity(); 12615 } 12616 } 12617 } 12618 12619 if (VD->isStaticLocal()) { 12620 CheckStaticLocalForDllExport(VD); 12621 12622 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12623 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12624 // function, only __shared__ variables or variables without any device 12625 // memory qualifiers may be declared with static storage class. 12626 // Note: It is unclear how a function-scope non-const static variable 12627 // without device memory qualifier is implemented, therefore only static 12628 // const variable without device memory qualifier is allowed. 12629 [&]() { 12630 if (!getLangOpts().CUDA) 12631 return; 12632 if (VD->hasAttr<CUDASharedAttr>()) 12633 return; 12634 if (VD->getType().isConstQualified() && 12635 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12636 return; 12637 if (CUDADiagIfDeviceCode(VD->getLocation(), 12638 diag::err_device_static_local_var) 12639 << CurrentCUDATarget()) 12640 VD->setInvalidDecl(); 12641 }(); 12642 } 12643 } 12644 12645 // Perform check for initializers of device-side global variables. 12646 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12647 // 7.5). We must also apply the same checks to all __shared__ 12648 // variables whether they are local or not. CUDA also allows 12649 // constant initializers for __constant__ and __device__ variables. 12650 if (getLangOpts().CUDA) 12651 checkAllowedCUDAInitializer(VD); 12652 12653 // Grab the dllimport or dllexport attribute off of the VarDecl. 12654 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12655 12656 // Imported static data members cannot be defined out-of-line. 12657 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12658 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12659 VD->isThisDeclarationADefinition()) { 12660 // We allow definitions of dllimport class template static data members 12661 // with a warning. 12662 CXXRecordDecl *Context = 12663 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12664 bool IsClassTemplateMember = 12665 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12666 Context->getDescribedClassTemplate(); 12667 12668 Diag(VD->getLocation(), 12669 IsClassTemplateMember 12670 ? diag::warn_attribute_dllimport_static_field_definition 12671 : diag::err_attribute_dllimport_static_field_definition); 12672 Diag(IA->getLocation(), diag::note_attribute); 12673 if (!IsClassTemplateMember) 12674 VD->setInvalidDecl(); 12675 } 12676 } 12677 12678 // dllimport/dllexport variables cannot be thread local, their TLS index 12679 // isn't exported with the variable. 12680 if (DLLAttr && VD->getTLSKind()) { 12681 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12682 if (F && getDLLAttr(F)) { 12683 assert(VD->isStaticLocal()); 12684 // But if this is a static local in a dlimport/dllexport function, the 12685 // function will never be inlined, which means the var would never be 12686 // imported, so having it marked import/export is safe. 12687 } else { 12688 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 12689 << DLLAttr; 12690 VD->setInvalidDecl(); 12691 } 12692 } 12693 12694 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 12695 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 12696 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 12697 VD->dropAttr<UsedAttr>(); 12698 } 12699 } 12700 12701 const DeclContext *DC = VD->getDeclContext(); 12702 // If there's a #pragma GCC visibility in scope, and this isn't a class 12703 // member, set the visibility of this variable. 12704 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 12705 AddPushedVisibilityAttribute(VD); 12706 12707 // FIXME: Warn on unused var template partial specializations. 12708 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 12709 MarkUnusedFileScopedDecl(VD); 12710 12711 // Now we have parsed the initializer and can update the table of magic 12712 // tag values. 12713 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 12714 !VD->getType()->isIntegralOrEnumerationType()) 12715 return; 12716 12717 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 12718 const Expr *MagicValueExpr = VD->getInit(); 12719 if (!MagicValueExpr) { 12720 continue; 12721 } 12722 llvm::APSInt MagicValueInt; 12723 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 12724 Diag(I->getRange().getBegin(), 12725 diag::err_type_tag_for_datatype_not_ice) 12726 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12727 continue; 12728 } 12729 if (MagicValueInt.getActiveBits() > 64) { 12730 Diag(I->getRange().getBegin(), 12731 diag::err_type_tag_for_datatype_too_large) 12732 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12733 continue; 12734 } 12735 uint64_t MagicValue = MagicValueInt.getZExtValue(); 12736 RegisterTypeTagForDatatype(I->getArgumentKind(), 12737 MagicValue, 12738 I->getMatchingCType(), 12739 I->getLayoutCompatible(), 12740 I->getMustBeNull()); 12741 } 12742 } 12743 12744 static bool hasDeducedAuto(DeclaratorDecl *DD) { 12745 auto *VD = dyn_cast<VarDecl>(DD); 12746 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 12747 } 12748 12749 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 12750 ArrayRef<Decl *> Group) { 12751 SmallVector<Decl*, 8> Decls; 12752 12753 if (DS.isTypeSpecOwned()) 12754 Decls.push_back(DS.getRepAsDecl()); 12755 12756 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 12757 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 12758 bool DiagnosedMultipleDecomps = false; 12759 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 12760 bool DiagnosedNonDeducedAuto = false; 12761 12762 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12763 if (Decl *D = Group[i]) { 12764 // For declarators, there are some additional syntactic-ish checks we need 12765 // to perform. 12766 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 12767 if (!FirstDeclaratorInGroup) 12768 FirstDeclaratorInGroup = DD; 12769 if (!FirstDecompDeclaratorInGroup) 12770 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 12771 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 12772 !hasDeducedAuto(DD)) 12773 FirstNonDeducedAutoInGroup = DD; 12774 12775 if (FirstDeclaratorInGroup != DD) { 12776 // A decomposition declaration cannot be combined with any other 12777 // declaration in the same group. 12778 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 12779 Diag(FirstDecompDeclaratorInGroup->getLocation(), 12780 diag::err_decomp_decl_not_alone) 12781 << FirstDeclaratorInGroup->getSourceRange() 12782 << DD->getSourceRange(); 12783 DiagnosedMultipleDecomps = true; 12784 } 12785 12786 // A declarator that uses 'auto' in any way other than to declare a 12787 // variable with a deduced type cannot be combined with any other 12788 // declarator in the same group. 12789 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 12790 Diag(FirstNonDeducedAutoInGroup->getLocation(), 12791 diag::err_auto_non_deduced_not_alone) 12792 << FirstNonDeducedAutoInGroup->getType() 12793 ->hasAutoForTrailingReturnType() 12794 << FirstDeclaratorInGroup->getSourceRange() 12795 << DD->getSourceRange(); 12796 DiagnosedNonDeducedAuto = true; 12797 } 12798 } 12799 } 12800 12801 Decls.push_back(D); 12802 } 12803 } 12804 12805 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 12806 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 12807 handleTagNumbering(Tag, S); 12808 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 12809 getLangOpts().CPlusPlus) 12810 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 12811 } 12812 } 12813 12814 return BuildDeclaratorGroup(Decls); 12815 } 12816 12817 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 12818 /// group, performing any necessary semantic checking. 12819 Sema::DeclGroupPtrTy 12820 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 12821 // C++14 [dcl.spec.auto]p7: (DR1347) 12822 // If the type that replaces the placeholder type is not the same in each 12823 // deduction, the program is ill-formed. 12824 if (Group.size() > 1) { 12825 QualType Deduced; 12826 VarDecl *DeducedDecl = nullptr; 12827 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12828 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 12829 if (!D || D->isInvalidDecl()) 12830 break; 12831 DeducedType *DT = D->getType()->getContainedDeducedType(); 12832 if (!DT || DT->getDeducedType().isNull()) 12833 continue; 12834 if (Deduced.isNull()) { 12835 Deduced = DT->getDeducedType(); 12836 DeducedDecl = D; 12837 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 12838 auto *AT = dyn_cast<AutoType>(DT); 12839 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 12840 diag::err_auto_different_deductions) 12841 << (AT ? (unsigned)AT->getKeyword() : 3) 12842 << Deduced << DeducedDecl->getDeclName() 12843 << DT->getDeducedType() << D->getDeclName() 12844 << DeducedDecl->getInit()->getSourceRange() 12845 << D->getInit()->getSourceRange(); 12846 D->setInvalidDecl(); 12847 break; 12848 } 12849 } 12850 } 12851 12852 ActOnDocumentableDecls(Group); 12853 12854 return DeclGroupPtrTy::make( 12855 DeclGroupRef::Create(Context, Group.data(), Group.size())); 12856 } 12857 12858 void Sema::ActOnDocumentableDecl(Decl *D) { 12859 ActOnDocumentableDecls(D); 12860 } 12861 12862 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 12863 // Don't parse the comment if Doxygen diagnostics are ignored. 12864 if (Group.empty() || !Group[0]) 12865 return; 12866 12867 if (Diags.isIgnored(diag::warn_doc_param_not_found, 12868 Group[0]->getLocation()) && 12869 Diags.isIgnored(diag::warn_unknown_comment_command_name, 12870 Group[0]->getLocation())) 12871 return; 12872 12873 if (Group.size() >= 2) { 12874 // This is a decl group. Normally it will contain only declarations 12875 // produced from declarator list. But in case we have any definitions or 12876 // additional declaration references: 12877 // 'typedef struct S {} S;' 12878 // 'typedef struct S *S;' 12879 // 'struct S *pS;' 12880 // FinalizeDeclaratorGroup adds these as separate declarations. 12881 Decl *MaybeTagDecl = Group[0]; 12882 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 12883 Group = Group.slice(1); 12884 } 12885 } 12886 12887 // FIMXE: We assume every Decl in the group is in the same file. 12888 // This is false when preprocessor constructs the group from decls in 12889 // different files (e. g. macros or #include). 12890 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 12891 } 12892 12893 /// Common checks for a parameter-declaration that should apply to both function 12894 /// parameters and non-type template parameters. 12895 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 12896 // Check that there are no default arguments inside the type of this 12897 // parameter. 12898 if (getLangOpts().CPlusPlus) 12899 CheckExtraCXXDefaultArguments(D); 12900 12901 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12902 if (D.getCXXScopeSpec().isSet()) { 12903 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12904 << D.getCXXScopeSpec().getRange(); 12905 } 12906 12907 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 12908 // simple identifier except [...irrelevant cases...]. 12909 switch (D.getName().getKind()) { 12910 case UnqualifiedIdKind::IK_Identifier: 12911 break; 12912 12913 case UnqualifiedIdKind::IK_OperatorFunctionId: 12914 case UnqualifiedIdKind::IK_ConversionFunctionId: 12915 case UnqualifiedIdKind::IK_LiteralOperatorId: 12916 case UnqualifiedIdKind::IK_ConstructorName: 12917 case UnqualifiedIdKind::IK_DestructorName: 12918 case UnqualifiedIdKind::IK_ImplicitSelfParam: 12919 case UnqualifiedIdKind::IK_DeductionGuideName: 12920 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12921 << GetNameForDeclarator(D).getName(); 12922 break; 12923 12924 case UnqualifiedIdKind::IK_TemplateId: 12925 case UnqualifiedIdKind::IK_ConstructorTemplateId: 12926 // GetNameForDeclarator would not produce a useful name in this case. 12927 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 12928 break; 12929 } 12930 } 12931 12932 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 12933 /// to introduce parameters into function prototype scope. 12934 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 12935 const DeclSpec &DS = D.getDeclSpec(); 12936 12937 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 12938 12939 // C++03 [dcl.stc]p2 also permits 'auto'. 12940 StorageClass SC = SC_None; 12941 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 12942 SC = SC_Register; 12943 // In C++11, the 'register' storage class specifier is deprecated. 12944 // In C++17, it is not allowed, but we tolerate it as an extension. 12945 if (getLangOpts().CPlusPlus11) { 12946 Diag(DS.getStorageClassSpecLoc(), 12947 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 12948 : diag::warn_deprecated_register) 12949 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12950 } 12951 } else if (getLangOpts().CPlusPlus && 12952 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 12953 SC = SC_Auto; 12954 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 12955 Diag(DS.getStorageClassSpecLoc(), 12956 diag::err_invalid_storage_class_in_func_decl); 12957 D.getMutableDeclSpec().ClearStorageClassSpecs(); 12958 } 12959 12960 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12961 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12962 << DeclSpec::getSpecifierName(TSCS); 12963 if (DS.isInlineSpecified()) 12964 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12965 << getLangOpts().CPlusPlus17; 12966 if (DS.hasConstexprSpecifier()) 12967 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12968 << 0 << D.getDeclSpec().getConstexprSpecifier(); 12969 12970 DiagnoseFunctionSpecifiers(DS); 12971 12972 CheckFunctionOrTemplateParamDeclarator(S, D); 12973 12974 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12975 QualType parmDeclType = TInfo->getType(); 12976 12977 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12978 IdentifierInfo *II = D.getIdentifier(); 12979 if (II) { 12980 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12981 ForVisibleRedeclaration); 12982 LookupName(R, S); 12983 if (R.isSingleResult()) { 12984 NamedDecl *PrevDecl = R.getFoundDecl(); 12985 if (PrevDecl->isTemplateParameter()) { 12986 // Maybe we will complain about the shadowed template parameter. 12987 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12988 // Just pretend that we didn't see the previous declaration. 12989 PrevDecl = nullptr; 12990 } else if (S->isDeclScope(PrevDecl)) { 12991 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12992 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12993 12994 // Recover by removing the name 12995 II = nullptr; 12996 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12997 D.setInvalidType(true); 12998 } 12999 } 13000 } 13001 13002 // Temporarily put parameter variables in the translation unit, not 13003 // the enclosing context. This prevents them from accidentally 13004 // looking like class members in C++. 13005 ParmVarDecl *New = 13006 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13007 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13008 13009 if (D.isInvalidType()) 13010 New->setInvalidDecl(); 13011 13012 assert(S->isFunctionPrototypeScope()); 13013 assert(S->getFunctionPrototypeDepth() >= 1); 13014 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13015 S->getNextFunctionPrototypeIndex()); 13016 13017 // Add the parameter declaration into this scope. 13018 S->AddDecl(New); 13019 if (II) 13020 IdResolver.AddDecl(New); 13021 13022 ProcessDeclAttributes(S, New, D); 13023 13024 if (D.getDeclSpec().isModulePrivateSpecified()) 13025 Diag(New->getLocation(), diag::err_module_private_local) 13026 << 1 << New->getDeclName() 13027 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13028 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13029 13030 if (New->hasAttr<BlocksAttr>()) { 13031 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13032 } 13033 return New; 13034 } 13035 13036 /// Synthesizes a variable for a parameter arising from a 13037 /// typedef. 13038 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13039 SourceLocation Loc, 13040 QualType T) { 13041 /* FIXME: setting StartLoc == Loc. 13042 Would it be worth to modify callers so as to provide proper source 13043 location for the unnamed parameters, embedding the parameter's type? */ 13044 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13045 T, Context.getTrivialTypeSourceInfo(T, Loc), 13046 SC_None, nullptr); 13047 Param->setImplicit(); 13048 return Param; 13049 } 13050 13051 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13052 // Don't diagnose unused-parameter errors in template instantiations; we 13053 // will already have done so in the template itself. 13054 if (inTemplateInstantiation()) 13055 return; 13056 13057 for (const ParmVarDecl *Parameter : Parameters) { 13058 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13059 !Parameter->hasAttr<UnusedAttr>()) { 13060 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13061 << Parameter->getDeclName(); 13062 } 13063 } 13064 } 13065 13066 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13067 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13068 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13069 return; 13070 13071 // Warn if the return value is pass-by-value and larger than the specified 13072 // threshold. 13073 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13074 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13075 if (Size > LangOpts.NumLargeByValueCopy) 13076 Diag(D->getLocation(), diag::warn_return_value_size) 13077 << D->getDeclName() << Size; 13078 } 13079 13080 // Warn if any parameter is pass-by-value and larger than the specified 13081 // threshold. 13082 for (const ParmVarDecl *Parameter : Parameters) { 13083 QualType T = Parameter->getType(); 13084 if (T->isDependentType() || !T.isPODType(Context)) 13085 continue; 13086 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13087 if (Size > LangOpts.NumLargeByValueCopy) 13088 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13089 << Parameter->getDeclName() << Size; 13090 } 13091 } 13092 13093 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13094 SourceLocation NameLoc, IdentifierInfo *Name, 13095 QualType T, TypeSourceInfo *TSInfo, 13096 StorageClass SC) { 13097 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13098 if (getLangOpts().ObjCAutoRefCount && 13099 T.getObjCLifetime() == Qualifiers::OCL_None && 13100 T->isObjCLifetimeType()) { 13101 13102 Qualifiers::ObjCLifetime lifetime; 13103 13104 // Special cases for arrays: 13105 // - if it's const, use __unsafe_unretained 13106 // - otherwise, it's an error 13107 if (T->isArrayType()) { 13108 if (!T.isConstQualified()) { 13109 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13110 DelayedDiagnostics.add( 13111 sema::DelayedDiagnostic::makeForbiddenType( 13112 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13113 else 13114 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13115 << TSInfo->getTypeLoc().getSourceRange(); 13116 } 13117 lifetime = Qualifiers::OCL_ExplicitNone; 13118 } else { 13119 lifetime = T->getObjCARCImplicitLifetime(); 13120 } 13121 T = Context.getLifetimeQualifiedType(T, lifetime); 13122 } 13123 13124 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13125 Context.getAdjustedParameterType(T), 13126 TSInfo, SC, nullptr); 13127 13128 // Make a note if we created a new pack in the scope of a lambda, so that 13129 // we know that references to that pack must also be expanded within the 13130 // lambda scope. 13131 if (New->isParameterPack()) 13132 if (auto *LSI = getEnclosingLambda()) 13133 LSI->LocalPacks.push_back(New); 13134 13135 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13136 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13137 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13138 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13139 13140 // Parameters can not be abstract class types. 13141 // For record types, this is done by the AbstractClassUsageDiagnoser once 13142 // the class has been completely parsed. 13143 if (!CurContext->isRecord() && 13144 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13145 AbstractParamType)) 13146 New->setInvalidDecl(); 13147 13148 // Parameter declarators cannot be interface types. All ObjC objects are 13149 // passed by reference. 13150 if (T->isObjCObjectType()) { 13151 SourceLocation TypeEndLoc = 13152 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13153 Diag(NameLoc, 13154 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13155 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13156 T = Context.getObjCObjectPointerType(T); 13157 New->setType(T); 13158 } 13159 13160 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13161 // duration shall not be qualified by an address-space qualifier." 13162 // Since all parameters have automatic store duration, they can not have 13163 // an address space. 13164 if (T.getAddressSpace() != LangAS::Default && 13165 // OpenCL allows function arguments declared to be an array of a type 13166 // to be qualified with an address space. 13167 !(getLangOpts().OpenCL && 13168 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13169 Diag(NameLoc, diag::err_arg_with_address_space); 13170 New->setInvalidDecl(); 13171 } 13172 13173 return New; 13174 } 13175 13176 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13177 SourceLocation LocAfterDecls) { 13178 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13179 13180 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13181 // for a K&R function. 13182 if (!FTI.hasPrototype) { 13183 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13184 --i; 13185 if (FTI.Params[i].Param == nullptr) { 13186 SmallString<256> Code; 13187 llvm::raw_svector_ostream(Code) 13188 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13189 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13190 << FTI.Params[i].Ident 13191 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13192 13193 // Implicitly declare the argument as type 'int' for lack of a better 13194 // type. 13195 AttributeFactory attrs; 13196 DeclSpec DS(attrs); 13197 const char* PrevSpec; // unused 13198 unsigned DiagID; // unused 13199 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13200 DiagID, Context.getPrintingPolicy()); 13201 // Use the identifier location for the type source range. 13202 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13203 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13204 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13205 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13206 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13207 } 13208 } 13209 } 13210 } 13211 13212 Decl * 13213 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13214 MultiTemplateParamsArg TemplateParameterLists, 13215 SkipBodyInfo *SkipBody) { 13216 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13217 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13218 Scope *ParentScope = FnBodyScope->getParent(); 13219 13220 D.setFunctionDefinitionKind(FDK_Definition); 13221 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13222 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13223 } 13224 13225 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13226 Consumer.HandleInlineFunctionDefinition(D); 13227 } 13228 13229 static bool 13230 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13231 const FunctionDecl *&PossiblePrototype) { 13232 // Don't warn about invalid declarations. 13233 if (FD->isInvalidDecl()) 13234 return false; 13235 13236 // Or declarations that aren't global. 13237 if (!FD->isGlobal()) 13238 return false; 13239 13240 // Don't warn about C++ member functions. 13241 if (isa<CXXMethodDecl>(FD)) 13242 return false; 13243 13244 // Don't warn about 'main'. 13245 if (FD->isMain()) 13246 return false; 13247 13248 // Don't warn about inline functions. 13249 if (FD->isInlined()) 13250 return false; 13251 13252 // Don't warn about function templates. 13253 if (FD->getDescribedFunctionTemplate()) 13254 return false; 13255 13256 // Don't warn about function template specializations. 13257 if (FD->isFunctionTemplateSpecialization()) 13258 return false; 13259 13260 // Don't warn for OpenCL kernels. 13261 if (FD->hasAttr<OpenCLKernelAttr>()) 13262 return false; 13263 13264 // Don't warn on explicitly deleted functions. 13265 if (FD->isDeleted()) 13266 return false; 13267 13268 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13269 Prev; Prev = Prev->getPreviousDecl()) { 13270 // Ignore any declarations that occur in function or method 13271 // scope, because they aren't visible from the header. 13272 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13273 continue; 13274 13275 PossiblePrototype = Prev; 13276 return Prev->getType()->isFunctionNoProtoType(); 13277 } 13278 13279 return true; 13280 } 13281 13282 void 13283 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13284 const FunctionDecl *EffectiveDefinition, 13285 SkipBodyInfo *SkipBody) { 13286 const FunctionDecl *Definition = EffectiveDefinition; 13287 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13288 // If this is a friend function defined in a class template, it does not 13289 // have a body until it is used, nevertheless it is a definition, see 13290 // [temp.inst]p2: 13291 // 13292 // ... for the purpose of determining whether an instantiated redeclaration 13293 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13294 // corresponds to a definition in the template is considered to be a 13295 // definition. 13296 // 13297 // The following code must produce redefinition error: 13298 // 13299 // template<typename T> struct C20 { friend void func_20() {} }; 13300 // C20<int> c20i; 13301 // void func_20() {} 13302 // 13303 for (auto I : FD->redecls()) { 13304 if (I != FD && !I->isInvalidDecl() && 13305 I->getFriendObjectKind() != Decl::FOK_None) { 13306 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13307 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13308 // A merged copy of the same function, instantiated as a member of 13309 // the same class, is OK. 13310 if (declaresSameEntity(OrigFD, Original) && 13311 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13312 cast<Decl>(FD->getLexicalDeclContext()))) 13313 continue; 13314 } 13315 13316 if (Original->isThisDeclarationADefinition()) { 13317 Definition = I; 13318 break; 13319 } 13320 } 13321 } 13322 } 13323 } 13324 13325 if (!Definition) 13326 // Similar to friend functions a friend function template may be a 13327 // definition and do not have a body if it is instantiated in a class 13328 // template. 13329 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13330 for (auto I : FTD->redecls()) { 13331 auto D = cast<FunctionTemplateDecl>(I); 13332 if (D != FTD) { 13333 assert(!D->isThisDeclarationADefinition() && 13334 "More than one definition in redeclaration chain"); 13335 if (D->getFriendObjectKind() != Decl::FOK_None) 13336 if (FunctionTemplateDecl *FT = 13337 D->getInstantiatedFromMemberTemplate()) { 13338 if (FT->isThisDeclarationADefinition()) { 13339 Definition = D->getTemplatedDecl(); 13340 break; 13341 } 13342 } 13343 } 13344 } 13345 } 13346 13347 if (!Definition) 13348 return; 13349 13350 if (canRedefineFunction(Definition, getLangOpts())) 13351 return; 13352 13353 // Don't emit an error when this is redefinition of a typo-corrected 13354 // definition. 13355 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13356 return; 13357 13358 // If we don't have a visible definition of the function, and it's inline or 13359 // a template, skip the new definition. 13360 if (SkipBody && !hasVisibleDefinition(Definition) && 13361 (Definition->getFormalLinkage() == InternalLinkage || 13362 Definition->isInlined() || 13363 Definition->getDescribedFunctionTemplate() || 13364 Definition->getNumTemplateParameterLists())) { 13365 SkipBody->ShouldSkip = true; 13366 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13367 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13368 makeMergedDefinitionVisible(TD); 13369 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13370 return; 13371 } 13372 13373 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13374 Definition->getStorageClass() == SC_Extern) 13375 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13376 << FD->getDeclName() << getLangOpts().CPlusPlus; 13377 else 13378 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13379 13380 Diag(Definition->getLocation(), diag::note_previous_definition); 13381 FD->setInvalidDecl(); 13382 } 13383 13384 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13385 Sema &S) { 13386 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13387 13388 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13389 LSI->CallOperator = CallOperator; 13390 LSI->Lambda = LambdaClass; 13391 LSI->ReturnType = CallOperator->getReturnType(); 13392 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13393 13394 if (LCD == LCD_None) 13395 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13396 else if (LCD == LCD_ByCopy) 13397 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13398 else if (LCD == LCD_ByRef) 13399 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13400 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13401 13402 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13403 LSI->Mutable = !CallOperator->isConst(); 13404 13405 // Add the captures to the LSI so they can be noted as already 13406 // captured within tryCaptureVar. 13407 auto I = LambdaClass->field_begin(); 13408 for (const auto &C : LambdaClass->captures()) { 13409 if (C.capturesVariable()) { 13410 VarDecl *VD = C.getCapturedVar(); 13411 if (VD->isInitCapture()) 13412 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13413 QualType CaptureType = VD->getType(); 13414 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13415 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13416 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13417 /*EllipsisLoc*/C.isPackExpansion() 13418 ? C.getEllipsisLoc() : SourceLocation(), 13419 CaptureType, /*Invalid*/false); 13420 13421 } else if (C.capturesThis()) { 13422 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13423 C.getCaptureKind() == LCK_StarThis); 13424 } else { 13425 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13426 I->getType()); 13427 } 13428 ++I; 13429 } 13430 } 13431 13432 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13433 SkipBodyInfo *SkipBody) { 13434 if (!D) { 13435 // Parsing the function declaration failed in some way. Push on a fake scope 13436 // anyway so we can try to parse the function body. 13437 PushFunctionScope(); 13438 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13439 return D; 13440 } 13441 13442 FunctionDecl *FD = nullptr; 13443 13444 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13445 FD = FunTmpl->getTemplatedDecl(); 13446 else 13447 FD = cast<FunctionDecl>(D); 13448 13449 // Do not push if it is a lambda because one is already pushed when building 13450 // the lambda in ActOnStartOfLambdaDefinition(). 13451 if (!isLambdaCallOperator(FD)) 13452 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13453 13454 // Check for defining attributes before the check for redefinition. 13455 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13456 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13457 FD->dropAttr<AliasAttr>(); 13458 FD->setInvalidDecl(); 13459 } 13460 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13461 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13462 FD->dropAttr<IFuncAttr>(); 13463 FD->setInvalidDecl(); 13464 } 13465 13466 // See if this is a redefinition. If 'will have body' is already set, then 13467 // these checks were already performed when it was set. 13468 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13469 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13470 13471 // If we're skipping the body, we're done. Don't enter the scope. 13472 if (SkipBody && SkipBody->ShouldSkip) 13473 return D; 13474 } 13475 13476 // Mark this function as "will have a body eventually". This lets users to 13477 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13478 // this function. 13479 FD->setWillHaveBody(); 13480 13481 // If we are instantiating a generic lambda call operator, push 13482 // a LambdaScopeInfo onto the function stack. But use the information 13483 // that's already been calculated (ActOnLambdaExpr) to prime the current 13484 // LambdaScopeInfo. 13485 // When the template operator is being specialized, the LambdaScopeInfo, 13486 // has to be properly restored so that tryCaptureVariable doesn't try 13487 // and capture any new variables. In addition when calculating potential 13488 // captures during transformation of nested lambdas, it is necessary to 13489 // have the LSI properly restored. 13490 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13491 assert(inTemplateInstantiation() && 13492 "There should be an active template instantiation on the stack " 13493 "when instantiating a generic lambda!"); 13494 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13495 } else { 13496 // Enter a new function scope 13497 PushFunctionScope(); 13498 } 13499 13500 // Builtin functions cannot be defined. 13501 if (unsigned BuiltinID = FD->getBuiltinID()) { 13502 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13503 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13504 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13505 FD->setInvalidDecl(); 13506 } 13507 } 13508 13509 // The return type of a function definition must be complete 13510 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13511 QualType ResultType = FD->getReturnType(); 13512 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13513 !FD->isInvalidDecl() && 13514 RequireCompleteType(FD->getLocation(), ResultType, 13515 diag::err_func_def_incomplete_result)) 13516 FD->setInvalidDecl(); 13517 13518 if (FnBodyScope) 13519 PushDeclContext(FnBodyScope, FD); 13520 13521 // Check the validity of our function parameters 13522 CheckParmsForFunctionDef(FD->parameters(), 13523 /*CheckParameterNames=*/true); 13524 13525 // Add non-parameter declarations already in the function to the current 13526 // scope. 13527 if (FnBodyScope) { 13528 for (Decl *NPD : FD->decls()) { 13529 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13530 if (!NonParmDecl) 13531 continue; 13532 assert(!isa<ParmVarDecl>(NonParmDecl) && 13533 "parameters should not be in newly created FD yet"); 13534 13535 // If the decl has a name, make it accessible in the current scope. 13536 if (NonParmDecl->getDeclName()) 13537 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13538 13539 // Similarly, dive into enums and fish their constants out, making them 13540 // accessible in this scope. 13541 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13542 for (auto *EI : ED->enumerators()) 13543 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13544 } 13545 } 13546 } 13547 13548 // Introduce our parameters into the function scope 13549 for (auto Param : FD->parameters()) { 13550 Param->setOwningFunction(FD); 13551 13552 // If this has an identifier, add it to the scope stack. 13553 if (Param->getIdentifier() && FnBodyScope) { 13554 CheckShadow(FnBodyScope, Param); 13555 13556 PushOnScopeChains(Param, FnBodyScope); 13557 } 13558 } 13559 13560 // Ensure that the function's exception specification is instantiated. 13561 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13562 ResolveExceptionSpec(D->getLocation(), FPT); 13563 13564 // dllimport cannot be applied to non-inline function definitions. 13565 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13566 !FD->isTemplateInstantiation()) { 13567 assert(!FD->hasAttr<DLLExportAttr>()); 13568 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13569 FD->setInvalidDecl(); 13570 return D; 13571 } 13572 // We want to attach documentation to original Decl (which might be 13573 // a function template). 13574 ActOnDocumentableDecl(D); 13575 if (getCurLexicalContext()->isObjCContainer() && 13576 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13577 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13578 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13579 13580 return D; 13581 } 13582 13583 /// Given the set of return statements within a function body, 13584 /// compute the variables that are subject to the named return value 13585 /// optimization. 13586 /// 13587 /// Each of the variables that is subject to the named return value 13588 /// optimization will be marked as NRVO variables in the AST, and any 13589 /// return statement that has a marked NRVO variable as its NRVO candidate can 13590 /// use the named return value optimization. 13591 /// 13592 /// This function applies a very simplistic algorithm for NRVO: if every return 13593 /// statement in the scope of a variable has the same NRVO candidate, that 13594 /// candidate is an NRVO variable. 13595 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13596 ReturnStmt **Returns = Scope->Returns.data(); 13597 13598 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13599 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13600 if (!NRVOCandidate->isNRVOVariable()) 13601 Returns[I]->setNRVOCandidate(nullptr); 13602 } 13603 } 13604 } 13605 13606 bool Sema::canDelayFunctionBody(const Declarator &D) { 13607 // We can't delay parsing the body of a constexpr function template (yet). 13608 if (D.getDeclSpec().hasConstexprSpecifier()) 13609 return false; 13610 13611 // We can't delay parsing the body of a function template with a deduced 13612 // return type (yet). 13613 if (D.getDeclSpec().hasAutoTypeSpec()) { 13614 // If the placeholder introduces a non-deduced trailing return type, 13615 // we can still delay parsing it. 13616 if (D.getNumTypeObjects()) { 13617 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13618 if (Outer.Kind == DeclaratorChunk::Function && 13619 Outer.Fun.hasTrailingReturnType()) { 13620 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13621 return Ty.isNull() || !Ty->isUndeducedType(); 13622 } 13623 } 13624 return false; 13625 } 13626 13627 return true; 13628 } 13629 13630 bool Sema::canSkipFunctionBody(Decl *D) { 13631 // We cannot skip the body of a function (or function template) which is 13632 // constexpr, since we may need to evaluate its body in order to parse the 13633 // rest of the file. 13634 // We cannot skip the body of a function with an undeduced return type, 13635 // because any callers of that function need to know the type. 13636 if (const FunctionDecl *FD = D->getAsFunction()) { 13637 if (FD->isConstexpr()) 13638 return false; 13639 // We can't simply call Type::isUndeducedType here, because inside template 13640 // auto can be deduced to a dependent type, which is not considered 13641 // "undeduced". 13642 if (FD->getReturnType()->getContainedDeducedType()) 13643 return false; 13644 } 13645 return Consumer.shouldSkipFunctionBody(D); 13646 } 13647 13648 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13649 if (!Decl) 13650 return nullptr; 13651 if (FunctionDecl *FD = Decl->getAsFunction()) 13652 FD->setHasSkippedBody(); 13653 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13654 MD->setHasSkippedBody(); 13655 return Decl; 13656 } 13657 13658 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13659 return ActOnFinishFunctionBody(D, BodyArg, false); 13660 } 13661 13662 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13663 /// body. 13664 class ExitFunctionBodyRAII { 13665 public: 13666 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13667 ~ExitFunctionBodyRAII() { 13668 if (!IsLambda) 13669 S.PopExpressionEvaluationContext(); 13670 } 13671 13672 private: 13673 Sema &S; 13674 bool IsLambda = false; 13675 }; 13676 13677 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 13678 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 13679 13680 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 13681 if (EscapeInfo.count(BD)) 13682 return EscapeInfo[BD]; 13683 13684 bool R = false; 13685 const BlockDecl *CurBD = BD; 13686 13687 do { 13688 R = !CurBD->doesNotEscape(); 13689 if (R) 13690 break; 13691 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 13692 } while (CurBD); 13693 13694 return EscapeInfo[BD] = R; 13695 }; 13696 13697 // If the location where 'self' is implicitly retained is inside a escaping 13698 // block, emit a diagnostic. 13699 for (const std::pair<SourceLocation, const BlockDecl *> &P : 13700 S.ImplicitlyRetainedSelfLocs) 13701 if (IsOrNestedInEscapingBlock(P.second)) 13702 S.Diag(P.first, diag::warn_implicitly_retains_self) 13703 << FixItHint::CreateInsertion(P.first, "self->"); 13704 } 13705 13706 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 13707 bool IsInstantiation) { 13708 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 13709 13710 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13711 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 13712 13713 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 13714 CheckCompletedCoroutineBody(FD, Body); 13715 13716 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 13717 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 13718 // meant to pop the context added in ActOnStartOfFunctionDef(). 13719 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 13720 13721 if (FD) { 13722 FD->setBody(Body); 13723 FD->setWillHaveBody(false); 13724 13725 if (getLangOpts().CPlusPlus14) { 13726 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 13727 FD->getReturnType()->isUndeducedType()) { 13728 // If the function has a deduced result type but contains no 'return' 13729 // statements, the result type as written must be exactly 'auto', and 13730 // the deduced result type is 'void'. 13731 if (!FD->getReturnType()->getAs<AutoType>()) { 13732 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 13733 << FD->getReturnType(); 13734 FD->setInvalidDecl(); 13735 } else { 13736 // Substitute 'void' for the 'auto' in the type. 13737 TypeLoc ResultType = getReturnTypeLoc(FD); 13738 Context.adjustDeducedFunctionResultType( 13739 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 13740 } 13741 } 13742 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 13743 // In C++11, we don't use 'auto' deduction rules for lambda call 13744 // operators because we don't support return type deduction. 13745 auto *LSI = getCurLambda(); 13746 if (LSI->HasImplicitReturnType) { 13747 deduceClosureReturnType(*LSI); 13748 13749 // C++11 [expr.prim.lambda]p4: 13750 // [...] if there are no return statements in the compound-statement 13751 // [the deduced type is] the type void 13752 QualType RetType = 13753 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 13754 13755 // Update the return type to the deduced type. 13756 const FunctionProtoType *Proto = 13757 FD->getType()->getAs<FunctionProtoType>(); 13758 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 13759 Proto->getExtProtoInfo())); 13760 } 13761 } 13762 13763 // If the function implicitly returns zero (like 'main') or is naked, 13764 // don't complain about missing return statements. 13765 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 13766 WP.disableCheckFallThrough(); 13767 13768 // MSVC permits the use of pure specifier (=0) on function definition, 13769 // defined at class scope, warn about this non-standard construct. 13770 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 13771 Diag(FD->getLocation(), diag::ext_pure_function_definition); 13772 13773 if (!FD->isInvalidDecl()) { 13774 // Don't diagnose unused parameters of defaulted or deleted functions. 13775 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 13776 DiagnoseUnusedParameters(FD->parameters()); 13777 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 13778 FD->getReturnType(), FD); 13779 13780 // If this is a structor, we need a vtable. 13781 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 13782 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 13783 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 13784 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 13785 13786 // Try to apply the named return value optimization. We have to check 13787 // if we can do this here because lambdas keep return statements around 13788 // to deduce an implicit return type. 13789 if (FD->getReturnType()->isRecordType() && 13790 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 13791 computeNRVO(Body, getCurFunction()); 13792 } 13793 13794 // GNU warning -Wmissing-prototypes: 13795 // Warn if a global function is defined without a previous 13796 // prototype declaration. This warning is issued even if the 13797 // definition itself provides a prototype. The aim is to detect 13798 // global functions that fail to be declared in header files. 13799 const FunctionDecl *PossiblePrototype = nullptr; 13800 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 13801 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 13802 13803 if (PossiblePrototype) { 13804 // We found a declaration that is not a prototype, 13805 // but that could be a zero-parameter prototype 13806 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 13807 TypeLoc TL = TI->getTypeLoc(); 13808 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 13809 Diag(PossiblePrototype->getLocation(), 13810 diag::note_declaration_not_a_prototype) 13811 << (FD->getNumParams() != 0) 13812 << (FD->getNumParams() == 0 13813 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 13814 : FixItHint{}); 13815 } 13816 } else { 13817 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13818 << /* function */ 1 13819 << (FD->getStorageClass() == SC_None 13820 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 13821 "static ") 13822 : FixItHint{}); 13823 } 13824 13825 // GNU warning -Wstrict-prototypes 13826 // Warn if K&R function is defined without a previous declaration. 13827 // This warning is issued only if the definition itself does not provide 13828 // a prototype. Only K&R definitions do not provide a prototype. 13829 // An empty list in a function declarator that is part of a definition 13830 // of that function specifies that the function has no parameters 13831 // (C99 6.7.5.3p14) 13832 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 13833 !LangOpts.CPlusPlus) { 13834 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 13835 TypeLoc TL = TI->getTypeLoc(); 13836 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 13837 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 13838 } 13839 } 13840 13841 // Warn on CPUDispatch with an actual body. 13842 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 13843 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 13844 if (!CmpndBody->body_empty()) 13845 Diag(CmpndBody->body_front()->getBeginLoc(), 13846 diag::warn_dispatch_body_ignored); 13847 13848 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 13849 const CXXMethodDecl *KeyFunction; 13850 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 13851 MD->isVirtual() && 13852 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 13853 MD == KeyFunction->getCanonicalDecl()) { 13854 // Update the key-function state if necessary for this ABI. 13855 if (FD->isInlined() && 13856 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 13857 Context.setNonKeyFunction(MD); 13858 13859 // If the newly-chosen key function is already defined, then we 13860 // need to mark the vtable as used retroactively. 13861 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 13862 const FunctionDecl *Definition; 13863 if (KeyFunction && KeyFunction->isDefined(Definition)) 13864 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 13865 } else { 13866 // We just defined they key function; mark the vtable as used. 13867 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 13868 } 13869 } 13870 } 13871 13872 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 13873 "Function parsing confused"); 13874 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 13875 assert(MD == getCurMethodDecl() && "Method parsing confused"); 13876 MD->setBody(Body); 13877 if (!MD->isInvalidDecl()) { 13878 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 13879 MD->getReturnType(), MD); 13880 13881 if (Body) 13882 computeNRVO(Body, getCurFunction()); 13883 } 13884 if (getCurFunction()->ObjCShouldCallSuper) { 13885 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 13886 << MD->getSelector().getAsString(); 13887 getCurFunction()->ObjCShouldCallSuper = false; 13888 } 13889 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 13890 const ObjCMethodDecl *InitMethod = nullptr; 13891 bool isDesignated = 13892 MD->isDesignatedInitializerForTheInterface(&InitMethod); 13893 assert(isDesignated && InitMethod); 13894 (void)isDesignated; 13895 13896 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 13897 auto IFace = MD->getClassInterface(); 13898 if (!IFace) 13899 return false; 13900 auto SuperD = IFace->getSuperClass(); 13901 if (!SuperD) 13902 return false; 13903 return SuperD->getIdentifier() == 13904 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 13905 }; 13906 // Don't issue this warning for unavailable inits or direct subclasses 13907 // of NSObject. 13908 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 13909 Diag(MD->getLocation(), 13910 diag::warn_objc_designated_init_missing_super_call); 13911 Diag(InitMethod->getLocation(), 13912 diag::note_objc_designated_init_marked_here); 13913 } 13914 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 13915 } 13916 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 13917 // Don't issue this warning for unavaialable inits. 13918 if (!MD->isUnavailable()) 13919 Diag(MD->getLocation(), 13920 diag::warn_objc_secondary_init_missing_init_call); 13921 getCurFunction()->ObjCWarnForNoInitDelegation = false; 13922 } 13923 13924 diagnoseImplicitlyRetainedSelf(*this); 13925 } else { 13926 // Parsing the function declaration failed in some way. Pop the fake scope 13927 // we pushed on. 13928 PopFunctionScopeInfo(ActivePolicy, dcl); 13929 return nullptr; 13930 } 13931 13932 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13933 DiagnoseUnguardedAvailabilityViolations(dcl); 13934 13935 assert(!getCurFunction()->ObjCShouldCallSuper && 13936 "This should only be set for ObjC methods, which should have been " 13937 "handled in the block above."); 13938 13939 // Verify and clean out per-function state. 13940 if (Body && (!FD || !FD->isDefaulted())) { 13941 // C++ constructors that have function-try-blocks can't have return 13942 // statements in the handlers of that block. (C++ [except.handle]p14) 13943 // Verify this. 13944 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 13945 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 13946 13947 // Verify that gotos and switch cases don't jump into scopes illegally. 13948 if (getCurFunction()->NeedsScopeChecking() && 13949 !PP.isCodeCompletionEnabled()) 13950 DiagnoseInvalidJumps(Body); 13951 13952 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 13953 if (!Destructor->getParent()->isDependentType()) 13954 CheckDestructor(Destructor); 13955 13956 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13957 Destructor->getParent()); 13958 } 13959 13960 // If any errors have occurred, clear out any temporaries that may have 13961 // been leftover. This ensures that these temporaries won't be picked up for 13962 // deletion in some later function. 13963 if (getDiagnostics().hasErrorOccurred() || 13964 getDiagnostics().getSuppressAllDiagnostics()) { 13965 DiscardCleanupsInEvaluationContext(); 13966 } 13967 if (!getDiagnostics().hasUncompilableErrorOccurred() && 13968 !isa<FunctionTemplateDecl>(dcl)) { 13969 // Since the body is valid, issue any analysis-based warnings that are 13970 // enabled. 13971 ActivePolicy = &WP; 13972 } 13973 13974 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 13975 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 13976 FD->setInvalidDecl(); 13977 13978 if (FD && FD->hasAttr<NakedAttr>()) { 13979 for (const Stmt *S : Body->children()) { 13980 // Allow local register variables without initializer as they don't 13981 // require prologue. 13982 bool RegisterVariables = false; 13983 if (auto *DS = dyn_cast<DeclStmt>(S)) { 13984 for (const auto *Decl : DS->decls()) { 13985 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 13986 RegisterVariables = 13987 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 13988 if (!RegisterVariables) 13989 break; 13990 } 13991 } 13992 } 13993 if (RegisterVariables) 13994 continue; 13995 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 13996 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 13997 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 13998 FD->setInvalidDecl(); 13999 break; 14000 } 14001 } 14002 } 14003 14004 assert(ExprCleanupObjects.size() == 14005 ExprEvalContexts.back().NumCleanupObjects && 14006 "Leftover temporaries in function"); 14007 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14008 assert(MaybeODRUseExprs.empty() && 14009 "Leftover expressions for odr-use checking"); 14010 } 14011 14012 if (!IsInstantiation) 14013 PopDeclContext(); 14014 14015 PopFunctionScopeInfo(ActivePolicy, dcl); 14016 // If any errors have occurred, clear out any temporaries that may have 14017 // been leftover. This ensures that these temporaries won't be picked up for 14018 // deletion in some later function. 14019 if (getDiagnostics().hasErrorOccurred()) { 14020 DiscardCleanupsInEvaluationContext(); 14021 } 14022 14023 return dcl; 14024 } 14025 14026 /// When we finish delayed parsing of an attribute, we must attach it to the 14027 /// relevant Decl. 14028 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14029 ParsedAttributes &Attrs) { 14030 // Always attach attributes to the underlying decl. 14031 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14032 D = TD->getTemplatedDecl(); 14033 ProcessDeclAttributeList(S, D, Attrs); 14034 14035 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14036 if (Method->isStatic()) 14037 checkThisInStaticMemberFunctionAttributes(Method); 14038 } 14039 14040 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14041 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14042 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14043 IdentifierInfo &II, Scope *S) { 14044 // Find the scope in which the identifier is injected and the corresponding 14045 // DeclContext. 14046 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14047 // In that case, we inject the declaration into the translation unit scope 14048 // instead. 14049 Scope *BlockScope = S; 14050 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14051 BlockScope = BlockScope->getParent(); 14052 14053 Scope *ContextScope = BlockScope; 14054 while (!ContextScope->getEntity()) 14055 ContextScope = ContextScope->getParent(); 14056 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14057 14058 // Before we produce a declaration for an implicitly defined 14059 // function, see whether there was a locally-scoped declaration of 14060 // this name as a function or variable. If so, use that 14061 // (non-visible) declaration, and complain about it. 14062 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14063 if (ExternCPrev) { 14064 // We still need to inject the function into the enclosing block scope so 14065 // that later (non-call) uses can see it. 14066 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14067 14068 // C89 footnote 38: 14069 // If in fact it is not defined as having type "function returning int", 14070 // the behavior is undefined. 14071 if (!isa<FunctionDecl>(ExternCPrev) || 14072 !Context.typesAreCompatible( 14073 cast<FunctionDecl>(ExternCPrev)->getType(), 14074 Context.getFunctionNoProtoType(Context.IntTy))) { 14075 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14076 << ExternCPrev << !getLangOpts().C99; 14077 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14078 return ExternCPrev; 14079 } 14080 } 14081 14082 // Extension in C99. Legal in C90, but warn about it. 14083 unsigned diag_id; 14084 if (II.getName().startswith("__builtin_")) 14085 diag_id = diag::warn_builtin_unknown; 14086 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14087 else if (getLangOpts().OpenCL) 14088 diag_id = diag::err_opencl_implicit_function_decl; 14089 else if (getLangOpts().C99) 14090 diag_id = diag::ext_implicit_function_decl; 14091 else 14092 diag_id = diag::warn_implicit_function_decl; 14093 Diag(Loc, diag_id) << &II; 14094 14095 // If we found a prior declaration of this function, don't bother building 14096 // another one. We've already pushed that one into scope, so there's nothing 14097 // more to do. 14098 if (ExternCPrev) 14099 return ExternCPrev; 14100 14101 // Because typo correction is expensive, only do it if the implicit 14102 // function declaration is going to be treated as an error. 14103 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14104 TypoCorrection Corrected; 14105 DeclFilterCCC<FunctionDecl> CCC{}; 14106 if (S && (Corrected = 14107 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14108 S, nullptr, CCC, CTK_NonError))) 14109 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14110 /*ErrorRecovery*/false); 14111 } 14112 14113 // Set a Declarator for the implicit definition: int foo(); 14114 const char *Dummy; 14115 AttributeFactory attrFactory; 14116 DeclSpec DS(attrFactory); 14117 unsigned DiagID; 14118 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14119 Context.getPrintingPolicy()); 14120 (void)Error; // Silence warning. 14121 assert(!Error && "Error setting up implicit decl!"); 14122 SourceLocation NoLoc; 14123 Declarator D(DS, DeclaratorContext::BlockContext); 14124 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14125 /*IsAmbiguous=*/false, 14126 /*LParenLoc=*/NoLoc, 14127 /*Params=*/nullptr, 14128 /*NumParams=*/0, 14129 /*EllipsisLoc=*/NoLoc, 14130 /*RParenLoc=*/NoLoc, 14131 /*RefQualifierIsLvalueRef=*/true, 14132 /*RefQualifierLoc=*/NoLoc, 14133 /*MutableLoc=*/NoLoc, EST_None, 14134 /*ESpecRange=*/SourceRange(), 14135 /*Exceptions=*/nullptr, 14136 /*ExceptionRanges=*/nullptr, 14137 /*NumExceptions=*/0, 14138 /*NoexceptExpr=*/nullptr, 14139 /*ExceptionSpecTokens=*/nullptr, 14140 /*DeclsInPrototype=*/None, Loc, 14141 Loc, D), 14142 std::move(DS.getAttributes()), SourceLocation()); 14143 D.SetIdentifier(&II, Loc); 14144 14145 // Insert this function into the enclosing block scope. 14146 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14147 FD->setImplicit(); 14148 14149 AddKnownFunctionAttributes(FD); 14150 14151 return FD; 14152 } 14153 14154 /// Adds any function attributes that we know a priori based on 14155 /// the declaration of this function. 14156 /// 14157 /// These attributes can apply both to implicitly-declared builtins 14158 /// (like __builtin___printf_chk) or to library-declared functions 14159 /// like NSLog or printf. 14160 /// 14161 /// We need to check for duplicate attributes both here and where user-written 14162 /// attributes are applied to declarations. 14163 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14164 if (FD->isInvalidDecl()) 14165 return; 14166 14167 // If this is a built-in function, map its builtin attributes to 14168 // actual attributes. 14169 if (unsigned BuiltinID = FD->getBuiltinID()) { 14170 // Handle printf-formatting attributes. 14171 unsigned FormatIdx; 14172 bool HasVAListArg; 14173 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14174 if (!FD->hasAttr<FormatAttr>()) { 14175 const char *fmt = "printf"; 14176 unsigned int NumParams = FD->getNumParams(); 14177 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14178 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14179 fmt = "NSString"; 14180 FD->addAttr(FormatAttr::CreateImplicit(Context, 14181 &Context.Idents.get(fmt), 14182 FormatIdx+1, 14183 HasVAListArg ? 0 : FormatIdx+2, 14184 FD->getLocation())); 14185 } 14186 } 14187 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14188 HasVAListArg)) { 14189 if (!FD->hasAttr<FormatAttr>()) 14190 FD->addAttr(FormatAttr::CreateImplicit(Context, 14191 &Context.Idents.get("scanf"), 14192 FormatIdx+1, 14193 HasVAListArg ? 0 : FormatIdx+2, 14194 FD->getLocation())); 14195 } 14196 14197 // Handle automatically recognized callbacks. 14198 SmallVector<int, 4> Encoding; 14199 if (!FD->hasAttr<CallbackAttr>() && 14200 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14201 FD->addAttr(CallbackAttr::CreateImplicit( 14202 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14203 14204 // Mark const if we don't care about errno and that is the only thing 14205 // preventing the function from being const. This allows IRgen to use LLVM 14206 // intrinsics for such functions. 14207 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14208 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14209 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14210 14211 // We make "fma" on some platforms const because we know it does not set 14212 // errno in those environments even though it could set errno based on the 14213 // C standard. 14214 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14215 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14216 !FD->hasAttr<ConstAttr>()) { 14217 switch (BuiltinID) { 14218 case Builtin::BI__builtin_fma: 14219 case Builtin::BI__builtin_fmaf: 14220 case Builtin::BI__builtin_fmal: 14221 case Builtin::BIfma: 14222 case Builtin::BIfmaf: 14223 case Builtin::BIfmal: 14224 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14225 break; 14226 default: 14227 break; 14228 } 14229 } 14230 14231 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14232 !FD->hasAttr<ReturnsTwiceAttr>()) 14233 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14234 FD->getLocation())); 14235 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14236 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14237 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14238 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14239 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14240 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14241 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14242 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14243 // Add the appropriate attribute, depending on the CUDA compilation mode 14244 // and which target the builtin belongs to. For example, during host 14245 // compilation, aux builtins are __device__, while the rest are __host__. 14246 if (getLangOpts().CUDAIsDevice != 14247 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14248 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14249 else 14250 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14251 } 14252 } 14253 14254 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14255 // throw, add an implicit nothrow attribute to any extern "C" function we come 14256 // across. 14257 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14258 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14259 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14260 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14261 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14262 } 14263 14264 IdentifierInfo *Name = FD->getIdentifier(); 14265 if (!Name) 14266 return; 14267 if ((!getLangOpts().CPlusPlus && 14268 FD->getDeclContext()->isTranslationUnit()) || 14269 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14270 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14271 LinkageSpecDecl::lang_c)) { 14272 // Okay: this could be a libc/libm/Objective-C function we know 14273 // about. 14274 } else 14275 return; 14276 14277 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14278 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14279 // target-specific builtins, perhaps? 14280 if (!FD->hasAttr<FormatAttr>()) 14281 FD->addAttr(FormatAttr::CreateImplicit(Context, 14282 &Context.Idents.get("printf"), 2, 14283 Name->isStr("vasprintf") ? 0 : 3, 14284 FD->getLocation())); 14285 } 14286 14287 if (Name->isStr("__CFStringMakeConstantString")) { 14288 // We already have a __builtin___CFStringMakeConstantString, 14289 // but builds that use -fno-constant-cfstrings don't go through that. 14290 if (!FD->hasAttr<FormatArgAttr>()) 14291 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14292 FD->getLocation())); 14293 } 14294 } 14295 14296 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14297 TypeSourceInfo *TInfo) { 14298 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14299 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14300 14301 if (!TInfo) { 14302 assert(D.isInvalidType() && "no declarator info for valid type"); 14303 TInfo = Context.getTrivialTypeSourceInfo(T); 14304 } 14305 14306 // Scope manipulation handled by caller. 14307 TypedefDecl *NewTD = 14308 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14309 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14310 14311 // Bail out immediately if we have an invalid declaration. 14312 if (D.isInvalidType()) { 14313 NewTD->setInvalidDecl(); 14314 return NewTD; 14315 } 14316 14317 if (D.getDeclSpec().isModulePrivateSpecified()) { 14318 if (CurContext->isFunctionOrMethod()) 14319 Diag(NewTD->getLocation(), diag::err_module_private_local) 14320 << 2 << NewTD->getDeclName() 14321 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14322 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14323 else 14324 NewTD->setModulePrivate(); 14325 } 14326 14327 // C++ [dcl.typedef]p8: 14328 // If the typedef declaration defines an unnamed class (or 14329 // enum), the first typedef-name declared by the declaration 14330 // to be that class type (or enum type) is used to denote the 14331 // class type (or enum type) for linkage purposes only. 14332 // We need to check whether the type was declared in the declaration. 14333 switch (D.getDeclSpec().getTypeSpecType()) { 14334 case TST_enum: 14335 case TST_struct: 14336 case TST_interface: 14337 case TST_union: 14338 case TST_class: { 14339 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14340 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14341 break; 14342 } 14343 14344 default: 14345 break; 14346 } 14347 14348 return NewTD; 14349 } 14350 14351 /// Check that this is a valid underlying type for an enum declaration. 14352 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14353 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14354 QualType T = TI->getType(); 14355 14356 if (T->isDependentType()) 14357 return false; 14358 14359 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14360 if (BT->isInteger()) 14361 return false; 14362 14363 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14364 return true; 14365 } 14366 14367 /// Check whether this is a valid redeclaration of a previous enumeration. 14368 /// \return true if the redeclaration was invalid. 14369 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14370 QualType EnumUnderlyingTy, bool IsFixed, 14371 const EnumDecl *Prev) { 14372 if (IsScoped != Prev->isScoped()) { 14373 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14374 << Prev->isScoped(); 14375 Diag(Prev->getLocation(), diag::note_previous_declaration); 14376 return true; 14377 } 14378 14379 if (IsFixed && Prev->isFixed()) { 14380 if (!EnumUnderlyingTy->isDependentType() && 14381 !Prev->getIntegerType()->isDependentType() && 14382 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14383 Prev->getIntegerType())) { 14384 // TODO: Highlight the underlying type of the redeclaration. 14385 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14386 << EnumUnderlyingTy << Prev->getIntegerType(); 14387 Diag(Prev->getLocation(), diag::note_previous_declaration) 14388 << Prev->getIntegerTypeRange(); 14389 return true; 14390 } 14391 } else if (IsFixed != Prev->isFixed()) { 14392 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14393 << Prev->isFixed(); 14394 Diag(Prev->getLocation(), diag::note_previous_declaration); 14395 return true; 14396 } 14397 14398 return false; 14399 } 14400 14401 /// Get diagnostic %select index for tag kind for 14402 /// redeclaration diagnostic message. 14403 /// WARNING: Indexes apply to particular diagnostics only! 14404 /// 14405 /// \returns diagnostic %select index. 14406 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14407 switch (Tag) { 14408 case TTK_Struct: return 0; 14409 case TTK_Interface: return 1; 14410 case TTK_Class: return 2; 14411 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14412 } 14413 } 14414 14415 /// Determine if tag kind is a class-key compatible with 14416 /// class for redeclaration (class, struct, or __interface). 14417 /// 14418 /// \returns true iff the tag kind is compatible. 14419 static bool isClassCompatTagKind(TagTypeKind Tag) 14420 { 14421 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14422 } 14423 14424 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14425 TagTypeKind TTK) { 14426 if (isa<TypedefDecl>(PrevDecl)) 14427 return NTK_Typedef; 14428 else if (isa<TypeAliasDecl>(PrevDecl)) 14429 return NTK_TypeAlias; 14430 else if (isa<ClassTemplateDecl>(PrevDecl)) 14431 return NTK_Template; 14432 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14433 return NTK_TypeAliasTemplate; 14434 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14435 return NTK_TemplateTemplateArgument; 14436 switch (TTK) { 14437 case TTK_Struct: 14438 case TTK_Interface: 14439 case TTK_Class: 14440 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14441 case TTK_Union: 14442 return NTK_NonUnion; 14443 case TTK_Enum: 14444 return NTK_NonEnum; 14445 } 14446 llvm_unreachable("invalid TTK"); 14447 } 14448 14449 /// Determine whether a tag with a given kind is acceptable 14450 /// as a redeclaration of the given tag declaration. 14451 /// 14452 /// \returns true if the new tag kind is acceptable, false otherwise. 14453 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14454 TagTypeKind NewTag, bool isDefinition, 14455 SourceLocation NewTagLoc, 14456 const IdentifierInfo *Name) { 14457 // C++ [dcl.type.elab]p3: 14458 // The class-key or enum keyword present in the 14459 // elaborated-type-specifier shall agree in kind with the 14460 // declaration to which the name in the elaborated-type-specifier 14461 // refers. This rule also applies to the form of 14462 // elaborated-type-specifier that declares a class-name or 14463 // friend class since it can be construed as referring to the 14464 // definition of the class. Thus, in any 14465 // elaborated-type-specifier, the enum keyword shall be used to 14466 // refer to an enumeration (7.2), the union class-key shall be 14467 // used to refer to a union (clause 9), and either the class or 14468 // struct class-key shall be used to refer to a class (clause 9) 14469 // declared using the class or struct class-key. 14470 TagTypeKind OldTag = Previous->getTagKind(); 14471 if (OldTag != NewTag && 14472 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14473 return false; 14474 14475 // Tags are compatible, but we might still want to warn on mismatched tags. 14476 // Non-class tags can't be mismatched at this point. 14477 if (!isClassCompatTagKind(NewTag)) 14478 return true; 14479 14480 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14481 // by our warning analysis. We don't want to warn about mismatches with (eg) 14482 // declarations in system headers that are designed to be specialized, but if 14483 // a user asks us to warn, we should warn if their code contains mismatched 14484 // declarations. 14485 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14486 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14487 Loc); 14488 }; 14489 if (IsIgnoredLoc(NewTagLoc)) 14490 return true; 14491 14492 auto IsIgnored = [&](const TagDecl *Tag) { 14493 return IsIgnoredLoc(Tag->getLocation()); 14494 }; 14495 while (IsIgnored(Previous)) { 14496 Previous = Previous->getPreviousDecl(); 14497 if (!Previous) 14498 return true; 14499 OldTag = Previous->getTagKind(); 14500 } 14501 14502 bool isTemplate = false; 14503 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 14504 isTemplate = Record->getDescribedClassTemplate(); 14505 14506 if (inTemplateInstantiation()) { 14507 if (OldTag != NewTag) { 14508 // In a template instantiation, do not offer fix-its for tag mismatches 14509 // since they usually mess up the template instead of fixing the problem. 14510 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14511 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14512 << getRedeclDiagFromTagKind(OldTag); 14513 // FIXME: Note previous location? 14514 } 14515 return true; 14516 } 14517 14518 if (isDefinition) { 14519 // On definitions, check all previous tags and issue a fix-it for each 14520 // one that doesn't match the current tag. 14521 if (Previous->getDefinition()) { 14522 // Don't suggest fix-its for redefinitions. 14523 return true; 14524 } 14525 14526 bool previousMismatch = false; 14527 for (const TagDecl *I : Previous->redecls()) { 14528 if (I->getTagKind() != NewTag) { 14529 // Ignore previous declarations for which the warning was disabled. 14530 if (IsIgnored(I)) 14531 continue; 14532 14533 if (!previousMismatch) { 14534 previousMismatch = true; 14535 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 14536 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14537 << getRedeclDiagFromTagKind(I->getTagKind()); 14538 } 14539 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 14540 << getRedeclDiagFromTagKind(NewTag) 14541 << FixItHint::CreateReplacement(I->getInnerLocStart(), 14542 TypeWithKeyword::getTagTypeKindName(NewTag)); 14543 } 14544 } 14545 return true; 14546 } 14547 14548 // Identify the prevailing tag kind: this is the kind of the definition (if 14549 // there is a non-ignored definition), or otherwise the kind of the prior 14550 // (non-ignored) declaration. 14551 const TagDecl *PrevDef = Previous->getDefinition(); 14552 if (PrevDef && IsIgnored(PrevDef)) 14553 PrevDef = nullptr; 14554 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 14555 if (Redecl->getTagKind() != NewTag) { 14556 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14557 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14558 << getRedeclDiagFromTagKind(OldTag); 14559 Diag(Redecl->getLocation(), diag::note_previous_use); 14560 14561 // If there is a previous definition, suggest a fix-it. 14562 if (PrevDef) { 14563 Diag(NewTagLoc, diag::note_struct_class_suggestion) 14564 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 14565 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 14566 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 14567 } 14568 } 14569 14570 return true; 14571 } 14572 14573 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 14574 /// from an outer enclosing namespace or file scope inside a friend declaration. 14575 /// This should provide the commented out code in the following snippet: 14576 /// namespace N { 14577 /// struct X; 14578 /// namespace M { 14579 /// struct Y { friend struct /*N::*/ X; }; 14580 /// } 14581 /// } 14582 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 14583 SourceLocation NameLoc) { 14584 // While the decl is in a namespace, do repeated lookup of that name and see 14585 // if we get the same namespace back. If we do not, continue until 14586 // translation unit scope, at which point we have a fully qualified NNS. 14587 SmallVector<IdentifierInfo *, 4> Namespaces; 14588 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14589 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 14590 // This tag should be declared in a namespace, which can only be enclosed by 14591 // other namespaces. Bail if there's an anonymous namespace in the chain. 14592 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 14593 if (!Namespace || Namespace->isAnonymousNamespace()) 14594 return FixItHint(); 14595 IdentifierInfo *II = Namespace->getIdentifier(); 14596 Namespaces.push_back(II); 14597 NamedDecl *Lookup = SemaRef.LookupSingleName( 14598 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 14599 if (Lookup == Namespace) 14600 break; 14601 } 14602 14603 // Once we have all the namespaces, reverse them to go outermost first, and 14604 // build an NNS. 14605 SmallString<64> Insertion; 14606 llvm::raw_svector_ostream OS(Insertion); 14607 if (DC->isTranslationUnit()) 14608 OS << "::"; 14609 std::reverse(Namespaces.begin(), Namespaces.end()); 14610 for (auto *II : Namespaces) 14611 OS << II->getName() << "::"; 14612 return FixItHint::CreateInsertion(NameLoc, Insertion); 14613 } 14614 14615 /// Determine whether a tag originally declared in context \p OldDC can 14616 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 14617 /// found a declaration in \p OldDC as a previous decl, perhaps through a 14618 /// using-declaration). 14619 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 14620 DeclContext *NewDC) { 14621 OldDC = OldDC->getRedeclContext(); 14622 NewDC = NewDC->getRedeclContext(); 14623 14624 if (OldDC->Equals(NewDC)) 14625 return true; 14626 14627 // In MSVC mode, we allow a redeclaration if the contexts are related (either 14628 // encloses the other). 14629 if (S.getLangOpts().MSVCCompat && 14630 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 14631 return true; 14632 14633 return false; 14634 } 14635 14636 /// This is invoked when we see 'struct foo' or 'struct {'. In the 14637 /// former case, Name will be non-null. In the later case, Name will be null. 14638 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 14639 /// reference/declaration/definition of a tag. 14640 /// 14641 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 14642 /// trailing-type-specifier) other than one in an alias-declaration. 14643 /// 14644 /// \param SkipBody If non-null, will be set to indicate if the caller should 14645 /// skip the definition of this tag and treat it as if it were a declaration. 14646 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 14647 SourceLocation KWLoc, CXXScopeSpec &SS, 14648 IdentifierInfo *Name, SourceLocation NameLoc, 14649 const ParsedAttributesView &Attrs, AccessSpecifier AS, 14650 SourceLocation ModulePrivateLoc, 14651 MultiTemplateParamsArg TemplateParameterLists, 14652 bool &OwnedDecl, bool &IsDependent, 14653 SourceLocation ScopedEnumKWLoc, 14654 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 14655 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 14656 SkipBodyInfo *SkipBody) { 14657 // If this is not a definition, it must have a name. 14658 IdentifierInfo *OrigName = Name; 14659 assert((Name != nullptr || TUK == TUK_Definition) && 14660 "Nameless record must be a definition!"); 14661 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 14662 14663 OwnedDecl = false; 14664 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14665 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 14666 14667 // FIXME: Check member specializations more carefully. 14668 bool isMemberSpecialization = false; 14669 bool Invalid = false; 14670 14671 // We only need to do this matching if we have template parameters 14672 // or a scope specifier, which also conveniently avoids this work 14673 // for non-C++ cases. 14674 if (TemplateParameterLists.size() > 0 || 14675 (SS.isNotEmpty() && TUK != TUK_Reference)) { 14676 if (TemplateParameterList *TemplateParams = 14677 MatchTemplateParametersToScopeSpecifier( 14678 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 14679 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 14680 if (Kind == TTK_Enum) { 14681 Diag(KWLoc, diag::err_enum_template); 14682 return nullptr; 14683 } 14684 14685 if (TemplateParams->size() > 0) { 14686 // This is a declaration or definition of a class template (which may 14687 // be a member of another template). 14688 14689 if (Invalid) 14690 return nullptr; 14691 14692 OwnedDecl = false; 14693 DeclResult Result = CheckClassTemplate( 14694 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 14695 AS, ModulePrivateLoc, 14696 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 14697 TemplateParameterLists.data(), SkipBody); 14698 return Result.get(); 14699 } else { 14700 // The "template<>" header is extraneous. 14701 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14702 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14703 isMemberSpecialization = true; 14704 } 14705 } 14706 } 14707 14708 // Figure out the underlying type if this a enum declaration. We need to do 14709 // this early, because it's needed to detect if this is an incompatible 14710 // redeclaration. 14711 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 14712 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 14713 14714 if (Kind == TTK_Enum) { 14715 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 14716 // No underlying type explicitly specified, or we failed to parse the 14717 // type, default to int. 14718 EnumUnderlying = Context.IntTy.getTypePtr(); 14719 } else if (UnderlyingType.get()) { 14720 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 14721 // integral type; any cv-qualification is ignored. 14722 TypeSourceInfo *TI = nullptr; 14723 GetTypeFromParser(UnderlyingType.get(), &TI); 14724 EnumUnderlying = TI; 14725 14726 if (CheckEnumUnderlyingType(TI)) 14727 // Recover by falling back to int. 14728 EnumUnderlying = Context.IntTy.getTypePtr(); 14729 14730 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 14731 UPPC_FixedUnderlyingType)) 14732 EnumUnderlying = Context.IntTy.getTypePtr(); 14733 14734 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 14735 // For MSVC ABI compatibility, unfixed enums must use an underlying type 14736 // of 'int'. However, if this is an unfixed forward declaration, don't set 14737 // the underlying type unless the user enables -fms-compatibility. This 14738 // makes unfixed forward declared enums incomplete and is more conforming. 14739 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 14740 EnumUnderlying = Context.IntTy.getTypePtr(); 14741 } 14742 } 14743 14744 DeclContext *SearchDC = CurContext; 14745 DeclContext *DC = CurContext; 14746 bool isStdBadAlloc = false; 14747 bool isStdAlignValT = false; 14748 14749 RedeclarationKind Redecl = forRedeclarationInCurContext(); 14750 if (TUK == TUK_Friend || TUK == TUK_Reference) 14751 Redecl = NotForRedeclaration; 14752 14753 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 14754 /// implemented asks for structural equivalence checking, the returned decl 14755 /// here is passed back to the parser, allowing the tag body to be parsed. 14756 auto createTagFromNewDecl = [&]() -> TagDecl * { 14757 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 14758 // If there is an identifier, use the location of the identifier as the 14759 // location of the decl, otherwise use the location of the struct/union 14760 // keyword. 14761 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14762 TagDecl *New = nullptr; 14763 14764 if (Kind == TTK_Enum) { 14765 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 14766 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 14767 // If this is an undefined enum, bail. 14768 if (TUK != TUK_Definition && !Invalid) 14769 return nullptr; 14770 if (EnumUnderlying) { 14771 EnumDecl *ED = cast<EnumDecl>(New); 14772 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 14773 ED->setIntegerTypeSourceInfo(TI); 14774 else 14775 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 14776 ED->setPromotionType(ED->getIntegerType()); 14777 } 14778 } else { // struct/union 14779 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14780 nullptr); 14781 } 14782 14783 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14784 // Add alignment attributes if necessary; these attributes are checked 14785 // when the ASTContext lays out the structure. 14786 // 14787 // It is important for implementing the correct semantics that this 14788 // happen here (in ActOnTag). The #pragma pack stack is 14789 // maintained as a result of parser callbacks which can occur at 14790 // many points during the parsing of a struct declaration (because 14791 // the #pragma tokens are effectively skipped over during the 14792 // parsing of the struct). 14793 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14794 AddAlignmentAttributesForRecord(RD); 14795 AddMsStructLayoutForRecord(RD); 14796 } 14797 } 14798 New->setLexicalDeclContext(CurContext); 14799 return New; 14800 }; 14801 14802 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 14803 if (Name && SS.isNotEmpty()) { 14804 // We have a nested-name tag ('struct foo::bar'). 14805 14806 // Check for invalid 'foo::'. 14807 if (SS.isInvalid()) { 14808 Name = nullptr; 14809 goto CreateNewDecl; 14810 } 14811 14812 // If this is a friend or a reference to a class in a dependent 14813 // context, don't try to make a decl for it. 14814 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14815 DC = computeDeclContext(SS, false); 14816 if (!DC) { 14817 IsDependent = true; 14818 return nullptr; 14819 } 14820 } else { 14821 DC = computeDeclContext(SS, true); 14822 if (!DC) { 14823 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 14824 << SS.getRange(); 14825 return nullptr; 14826 } 14827 } 14828 14829 if (RequireCompleteDeclContext(SS, DC)) 14830 return nullptr; 14831 14832 SearchDC = DC; 14833 // Look-up name inside 'foo::'. 14834 LookupQualifiedName(Previous, DC); 14835 14836 if (Previous.isAmbiguous()) 14837 return nullptr; 14838 14839 if (Previous.empty()) { 14840 // Name lookup did not find anything. However, if the 14841 // nested-name-specifier refers to the current instantiation, 14842 // and that current instantiation has any dependent base 14843 // classes, we might find something at instantiation time: treat 14844 // this as a dependent elaborated-type-specifier. 14845 // But this only makes any sense for reference-like lookups. 14846 if (Previous.wasNotFoundInCurrentInstantiation() && 14847 (TUK == TUK_Reference || TUK == TUK_Friend)) { 14848 IsDependent = true; 14849 return nullptr; 14850 } 14851 14852 // A tag 'foo::bar' must already exist. 14853 Diag(NameLoc, diag::err_not_tag_in_scope) 14854 << Kind << Name << DC << SS.getRange(); 14855 Name = nullptr; 14856 Invalid = true; 14857 goto CreateNewDecl; 14858 } 14859 } else if (Name) { 14860 // C++14 [class.mem]p14: 14861 // If T is the name of a class, then each of the following shall have a 14862 // name different from T: 14863 // -- every member of class T that is itself a type 14864 if (TUK != TUK_Reference && TUK != TUK_Friend && 14865 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 14866 return nullptr; 14867 14868 // If this is a named struct, check to see if there was a previous forward 14869 // declaration or definition. 14870 // FIXME: We're looking into outer scopes here, even when we 14871 // shouldn't be. Doing so can result in ambiguities that we 14872 // shouldn't be diagnosing. 14873 LookupName(Previous, S); 14874 14875 // When declaring or defining a tag, ignore ambiguities introduced 14876 // by types using'ed into this scope. 14877 if (Previous.isAmbiguous() && 14878 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 14879 LookupResult::Filter F = Previous.makeFilter(); 14880 while (F.hasNext()) { 14881 NamedDecl *ND = F.next(); 14882 if (!ND->getDeclContext()->getRedeclContext()->Equals( 14883 SearchDC->getRedeclContext())) 14884 F.erase(); 14885 } 14886 F.done(); 14887 } 14888 14889 // C++11 [namespace.memdef]p3: 14890 // If the name in a friend declaration is neither qualified nor 14891 // a template-id and the declaration is a function or an 14892 // elaborated-type-specifier, the lookup to determine whether 14893 // the entity has been previously declared shall not consider 14894 // any scopes outside the innermost enclosing namespace. 14895 // 14896 // MSVC doesn't implement the above rule for types, so a friend tag 14897 // declaration may be a redeclaration of a type declared in an enclosing 14898 // scope. They do implement this rule for friend functions. 14899 // 14900 // Does it matter that this should be by scope instead of by 14901 // semantic context? 14902 if (!Previous.empty() && TUK == TUK_Friend) { 14903 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 14904 LookupResult::Filter F = Previous.makeFilter(); 14905 bool FriendSawTagOutsideEnclosingNamespace = false; 14906 while (F.hasNext()) { 14907 NamedDecl *ND = F.next(); 14908 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14909 if (DC->isFileContext() && 14910 !EnclosingNS->Encloses(ND->getDeclContext())) { 14911 if (getLangOpts().MSVCCompat) 14912 FriendSawTagOutsideEnclosingNamespace = true; 14913 else 14914 F.erase(); 14915 } 14916 } 14917 F.done(); 14918 14919 // Diagnose this MSVC extension in the easy case where lookup would have 14920 // unambiguously found something outside the enclosing namespace. 14921 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 14922 NamedDecl *ND = Previous.getFoundDecl(); 14923 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 14924 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 14925 } 14926 } 14927 14928 // Note: there used to be some attempt at recovery here. 14929 if (Previous.isAmbiguous()) 14930 return nullptr; 14931 14932 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 14933 // FIXME: This makes sure that we ignore the contexts associated 14934 // with C structs, unions, and enums when looking for a matching 14935 // tag declaration or definition. See the similar lookup tweak 14936 // in Sema::LookupName; is there a better way to deal with this? 14937 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 14938 SearchDC = SearchDC->getParent(); 14939 } 14940 } 14941 14942 if (Previous.isSingleResult() && 14943 Previous.getFoundDecl()->isTemplateParameter()) { 14944 // Maybe we will complain about the shadowed template parameter. 14945 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 14946 // Just pretend that we didn't see the previous declaration. 14947 Previous.clear(); 14948 } 14949 14950 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 14951 DC->Equals(getStdNamespace())) { 14952 if (Name->isStr("bad_alloc")) { 14953 // This is a declaration of or a reference to "std::bad_alloc". 14954 isStdBadAlloc = true; 14955 14956 // If std::bad_alloc has been implicitly declared (but made invisible to 14957 // name lookup), fill in this implicit declaration as the previous 14958 // declaration, so that the declarations get chained appropriately. 14959 if (Previous.empty() && StdBadAlloc) 14960 Previous.addDecl(getStdBadAlloc()); 14961 } else if (Name->isStr("align_val_t")) { 14962 isStdAlignValT = true; 14963 if (Previous.empty() && StdAlignValT) 14964 Previous.addDecl(getStdAlignValT()); 14965 } 14966 } 14967 14968 // If we didn't find a previous declaration, and this is a reference 14969 // (or friend reference), move to the correct scope. In C++, we 14970 // also need to do a redeclaration lookup there, just in case 14971 // there's a shadow friend decl. 14972 if (Name && Previous.empty() && 14973 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 14974 if (Invalid) goto CreateNewDecl; 14975 assert(SS.isEmpty()); 14976 14977 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 14978 // C++ [basic.scope.pdecl]p5: 14979 // -- for an elaborated-type-specifier of the form 14980 // 14981 // class-key identifier 14982 // 14983 // if the elaborated-type-specifier is used in the 14984 // decl-specifier-seq or parameter-declaration-clause of a 14985 // function defined in namespace scope, the identifier is 14986 // declared as a class-name in the namespace that contains 14987 // the declaration; otherwise, except as a friend 14988 // declaration, the identifier is declared in the smallest 14989 // non-class, non-function-prototype scope that contains the 14990 // declaration. 14991 // 14992 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 14993 // C structs and unions. 14994 // 14995 // It is an error in C++ to declare (rather than define) an enum 14996 // type, including via an elaborated type specifier. We'll 14997 // diagnose that later; for now, declare the enum in the same 14998 // scope as we would have picked for any other tag type. 14999 // 15000 // GNU C also supports this behavior as part of its incomplete 15001 // enum types extension, while GNU C++ does not. 15002 // 15003 // Find the context where we'll be declaring the tag. 15004 // FIXME: We would like to maintain the current DeclContext as the 15005 // lexical context, 15006 SearchDC = getTagInjectionContext(SearchDC); 15007 15008 // Find the scope where we'll be declaring the tag. 15009 S = getTagInjectionScope(S, getLangOpts()); 15010 } else { 15011 assert(TUK == TUK_Friend); 15012 // C++ [namespace.memdef]p3: 15013 // If a friend declaration in a non-local class first declares a 15014 // class or function, the friend class or function is a member of 15015 // the innermost enclosing namespace. 15016 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15017 } 15018 15019 // In C++, we need to do a redeclaration lookup to properly 15020 // diagnose some problems. 15021 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15022 // hidden declaration so that we don't get ambiguity errors when using a 15023 // type declared by an elaborated-type-specifier. In C that is not correct 15024 // and we should instead merge compatible types found by lookup. 15025 if (getLangOpts().CPlusPlus) { 15026 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15027 LookupQualifiedName(Previous, SearchDC); 15028 } else { 15029 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15030 LookupName(Previous, S); 15031 } 15032 } 15033 15034 // If we have a known previous declaration to use, then use it. 15035 if (Previous.empty() && SkipBody && SkipBody->Previous) 15036 Previous.addDecl(SkipBody->Previous); 15037 15038 if (!Previous.empty()) { 15039 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15040 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15041 15042 // It's okay to have a tag decl in the same scope as a typedef 15043 // which hides a tag decl in the same scope. Finding this 15044 // insanity with a redeclaration lookup can only actually happen 15045 // in C++. 15046 // 15047 // This is also okay for elaborated-type-specifiers, which is 15048 // technically forbidden by the current standard but which is 15049 // okay according to the likely resolution of an open issue; 15050 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15051 if (getLangOpts().CPlusPlus) { 15052 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15053 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15054 TagDecl *Tag = TT->getDecl(); 15055 if (Tag->getDeclName() == Name && 15056 Tag->getDeclContext()->getRedeclContext() 15057 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15058 PrevDecl = Tag; 15059 Previous.clear(); 15060 Previous.addDecl(Tag); 15061 Previous.resolveKind(); 15062 } 15063 } 15064 } 15065 } 15066 15067 // If this is a redeclaration of a using shadow declaration, it must 15068 // declare a tag in the same context. In MSVC mode, we allow a 15069 // redefinition if either context is within the other. 15070 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15071 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15072 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15073 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15074 !(OldTag && isAcceptableTagRedeclContext( 15075 *this, OldTag->getDeclContext(), SearchDC))) { 15076 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15077 Diag(Shadow->getTargetDecl()->getLocation(), 15078 diag::note_using_decl_target); 15079 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15080 << 0; 15081 // Recover by ignoring the old declaration. 15082 Previous.clear(); 15083 goto CreateNewDecl; 15084 } 15085 } 15086 15087 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15088 // If this is a use of a previous tag, or if the tag is already declared 15089 // in the same scope (so that the definition/declaration completes or 15090 // rementions the tag), reuse the decl. 15091 if (TUK == TUK_Reference || TUK == TUK_Friend || 15092 isDeclInScope(DirectPrevDecl, SearchDC, S, 15093 SS.isNotEmpty() || isMemberSpecialization)) { 15094 // Make sure that this wasn't declared as an enum and now used as a 15095 // struct or something similar. 15096 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15097 TUK == TUK_Definition, KWLoc, 15098 Name)) { 15099 bool SafeToContinue 15100 = (PrevTagDecl->getTagKind() != TTK_Enum && 15101 Kind != TTK_Enum); 15102 if (SafeToContinue) 15103 Diag(KWLoc, diag::err_use_with_wrong_tag) 15104 << Name 15105 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15106 PrevTagDecl->getKindName()); 15107 else 15108 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15109 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15110 15111 if (SafeToContinue) 15112 Kind = PrevTagDecl->getTagKind(); 15113 else { 15114 // Recover by making this an anonymous redefinition. 15115 Name = nullptr; 15116 Previous.clear(); 15117 Invalid = true; 15118 } 15119 } 15120 15121 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15122 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15123 15124 // If this is an elaborated-type-specifier for a scoped enumeration, 15125 // the 'class' keyword is not necessary and not permitted. 15126 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15127 if (ScopedEnum) 15128 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 15129 << PrevEnum->isScoped() 15130 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 15131 return PrevTagDecl; 15132 } 15133 15134 QualType EnumUnderlyingTy; 15135 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15136 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15137 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15138 EnumUnderlyingTy = QualType(T, 0); 15139 15140 // All conflicts with previous declarations are recovered by 15141 // returning the previous declaration, unless this is a definition, 15142 // in which case we want the caller to bail out. 15143 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15144 ScopedEnum, EnumUnderlyingTy, 15145 IsFixed, PrevEnum)) 15146 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15147 } 15148 15149 // C++11 [class.mem]p1: 15150 // A member shall not be declared twice in the member-specification, 15151 // except that a nested class or member class template can be declared 15152 // and then later defined. 15153 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15154 S->isDeclScope(PrevDecl)) { 15155 Diag(NameLoc, diag::ext_member_redeclared); 15156 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15157 } 15158 15159 if (!Invalid) { 15160 // If this is a use, just return the declaration we found, unless 15161 // we have attributes. 15162 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15163 if (!Attrs.empty()) { 15164 // FIXME: Diagnose these attributes. For now, we create a new 15165 // declaration to hold them. 15166 } else if (TUK == TUK_Reference && 15167 (PrevTagDecl->getFriendObjectKind() == 15168 Decl::FOK_Undeclared || 15169 PrevDecl->getOwningModule() != getCurrentModule()) && 15170 SS.isEmpty()) { 15171 // This declaration is a reference to an existing entity, but 15172 // has different visibility from that entity: it either makes 15173 // a friend visible or it makes a type visible in a new module. 15174 // In either case, create a new declaration. We only do this if 15175 // the declaration would have meant the same thing if no prior 15176 // declaration were found, that is, if it was found in the same 15177 // scope where we would have injected a declaration. 15178 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15179 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15180 return PrevTagDecl; 15181 // This is in the injected scope, create a new declaration in 15182 // that scope. 15183 S = getTagInjectionScope(S, getLangOpts()); 15184 } else { 15185 return PrevTagDecl; 15186 } 15187 } 15188 15189 // Diagnose attempts to redefine a tag. 15190 if (TUK == TUK_Definition) { 15191 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15192 // If we're defining a specialization and the previous definition 15193 // is from an implicit instantiation, don't emit an error 15194 // here; we'll catch this in the general case below. 15195 bool IsExplicitSpecializationAfterInstantiation = false; 15196 if (isMemberSpecialization) { 15197 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15198 IsExplicitSpecializationAfterInstantiation = 15199 RD->getTemplateSpecializationKind() != 15200 TSK_ExplicitSpecialization; 15201 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15202 IsExplicitSpecializationAfterInstantiation = 15203 ED->getTemplateSpecializationKind() != 15204 TSK_ExplicitSpecialization; 15205 } 15206 15207 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15208 // not keep more that one definition around (merge them). However, 15209 // ensure the decl passes the structural compatibility check in 15210 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15211 NamedDecl *Hidden = nullptr; 15212 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15213 // There is a definition of this tag, but it is not visible. We 15214 // explicitly make use of C++'s one definition rule here, and 15215 // assume that this definition is identical to the hidden one 15216 // we already have. Make the existing definition visible and 15217 // use it in place of this one. 15218 if (!getLangOpts().CPlusPlus) { 15219 // Postpone making the old definition visible until after we 15220 // complete parsing the new one and do the structural 15221 // comparison. 15222 SkipBody->CheckSameAsPrevious = true; 15223 SkipBody->New = createTagFromNewDecl(); 15224 SkipBody->Previous = Def; 15225 return Def; 15226 } else { 15227 SkipBody->ShouldSkip = true; 15228 SkipBody->Previous = Def; 15229 makeMergedDefinitionVisible(Hidden); 15230 // Carry on and handle it like a normal definition. We'll 15231 // skip starting the definitiion later. 15232 } 15233 } else if (!IsExplicitSpecializationAfterInstantiation) { 15234 // A redeclaration in function prototype scope in C isn't 15235 // visible elsewhere, so merely issue a warning. 15236 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15237 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15238 else 15239 Diag(NameLoc, diag::err_redefinition) << Name; 15240 notePreviousDefinition(Def, 15241 NameLoc.isValid() ? NameLoc : KWLoc); 15242 // If this is a redefinition, recover by making this 15243 // struct be anonymous, which will make any later 15244 // references get the previous definition. 15245 Name = nullptr; 15246 Previous.clear(); 15247 Invalid = true; 15248 } 15249 } else { 15250 // If the type is currently being defined, complain 15251 // about a nested redefinition. 15252 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15253 if (TD->isBeingDefined()) { 15254 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15255 Diag(PrevTagDecl->getLocation(), 15256 diag::note_previous_definition); 15257 Name = nullptr; 15258 Previous.clear(); 15259 Invalid = true; 15260 } 15261 } 15262 15263 // Okay, this is definition of a previously declared or referenced 15264 // tag. We're going to create a new Decl for it. 15265 } 15266 15267 // Okay, we're going to make a redeclaration. If this is some kind 15268 // of reference, make sure we build the redeclaration in the same DC 15269 // as the original, and ignore the current access specifier. 15270 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15271 SearchDC = PrevTagDecl->getDeclContext(); 15272 AS = AS_none; 15273 } 15274 } 15275 // If we get here we have (another) forward declaration or we 15276 // have a definition. Just create a new decl. 15277 15278 } else { 15279 // If we get here, this is a definition of a new tag type in a nested 15280 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15281 // new decl/type. We set PrevDecl to NULL so that the entities 15282 // have distinct types. 15283 Previous.clear(); 15284 } 15285 // If we get here, we're going to create a new Decl. If PrevDecl 15286 // is non-NULL, it's a definition of the tag declared by 15287 // PrevDecl. If it's NULL, we have a new definition. 15288 15289 // Otherwise, PrevDecl is not a tag, but was found with tag 15290 // lookup. This is only actually possible in C++, where a few 15291 // things like templates still live in the tag namespace. 15292 } else { 15293 // Use a better diagnostic if an elaborated-type-specifier 15294 // found the wrong kind of type on the first 15295 // (non-redeclaration) lookup. 15296 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15297 !Previous.isForRedeclaration()) { 15298 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15299 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15300 << Kind; 15301 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15302 Invalid = true; 15303 15304 // Otherwise, only diagnose if the declaration is in scope. 15305 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15306 SS.isNotEmpty() || isMemberSpecialization)) { 15307 // do nothing 15308 15309 // Diagnose implicit declarations introduced by elaborated types. 15310 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15311 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15312 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15313 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15314 Invalid = true; 15315 15316 // Otherwise it's a declaration. Call out a particularly common 15317 // case here. 15318 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15319 unsigned Kind = 0; 15320 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15321 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15322 << Name << Kind << TND->getUnderlyingType(); 15323 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15324 Invalid = true; 15325 15326 // Otherwise, diagnose. 15327 } else { 15328 // The tag name clashes with something else in the target scope, 15329 // issue an error and recover by making this tag be anonymous. 15330 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15331 notePreviousDefinition(PrevDecl, NameLoc); 15332 Name = nullptr; 15333 Invalid = true; 15334 } 15335 15336 // The existing declaration isn't relevant to us; we're in a 15337 // new scope, so clear out the previous declaration. 15338 Previous.clear(); 15339 } 15340 } 15341 15342 CreateNewDecl: 15343 15344 TagDecl *PrevDecl = nullptr; 15345 if (Previous.isSingleResult()) 15346 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15347 15348 // If there is an identifier, use the location of the identifier as the 15349 // location of the decl, otherwise use the location of the struct/union 15350 // keyword. 15351 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15352 15353 // Otherwise, create a new declaration. If there is a previous 15354 // declaration of the same entity, the two will be linked via 15355 // PrevDecl. 15356 TagDecl *New; 15357 15358 if (Kind == TTK_Enum) { 15359 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15360 // enum X { A, B, C } D; D should chain to X. 15361 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15362 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15363 ScopedEnumUsesClassTag, IsFixed); 15364 15365 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15366 StdAlignValT = cast<EnumDecl>(New); 15367 15368 // If this is an undefined enum, warn. 15369 if (TUK != TUK_Definition && !Invalid) { 15370 TagDecl *Def; 15371 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15372 // C++0x: 7.2p2: opaque-enum-declaration. 15373 // Conflicts are diagnosed above. Do nothing. 15374 } 15375 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15376 Diag(Loc, diag::ext_forward_ref_enum_def) 15377 << New; 15378 Diag(Def->getLocation(), diag::note_previous_definition); 15379 } else { 15380 unsigned DiagID = diag::ext_forward_ref_enum; 15381 if (getLangOpts().MSVCCompat) 15382 DiagID = diag::ext_ms_forward_ref_enum; 15383 else if (getLangOpts().CPlusPlus) 15384 DiagID = diag::err_forward_ref_enum; 15385 Diag(Loc, DiagID); 15386 } 15387 } 15388 15389 if (EnumUnderlying) { 15390 EnumDecl *ED = cast<EnumDecl>(New); 15391 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15392 ED->setIntegerTypeSourceInfo(TI); 15393 else 15394 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15395 ED->setPromotionType(ED->getIntegerType()); 15396 assert(ED->isComplete() && "enum with type should be complete"); 15397 } 15398 } else { 15399 // struct/union/class 15400 15401 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15402 // struct X { int A; } D; D should chain to X. 15403 if (getLangOpts().CPlusPlus) { 15404 // FIXME: Look for a way to use RecordDecl for simple structs. 15405 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15406 cast_or_null<CXXRecordDecl>(PrevDecl)); 15407 15408 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15409 StdBadAlloc = cast<CXXRecordDecl>(New); 15410 } else 15411 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15412 cast_or_null<RecordDecl>(PrevDecl)); 15413 } 15414 15415 // C++11 [dcl.type]p3: 15416 // A type-specifier-seq shall not define a class or enumeration [...]. 15417 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15418 TUK == TUK_Definition) { 15419 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15420 << Context.getTagDeclType(New); 15421 Invalid = true; 15422 } 15423 15424 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15425 DC->getDeclKind() == Decl::Enum) { 15426 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15427 << Context.getTagDeclType(New); 15428 Invalid = true; 15429 } 15430 15431 // Maybe add qualifier info. 15432 if (SS.isNotEmpty()) { 15433 if (SS.isSet()) { 15434 // If this is either a declaration or a definition, check the 15435 // nested-name-specifier against the current context. 15436 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15437 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15438 isMemberSpecialization)) 15439 Invalid = true; 15440 15441 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15442 if (TemplateParameterLists.size() > 0) { 15443 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15444 } 15445 } 15446 else 15447 Invalid = true; 15448 } 15449 15450 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15451 // Add alignment attributes if necessary; these attributes are checked when 15452 // the ASTContext lays out the structure. 15453 // 15454 // It is important for implementing the correct semantics that this 15455 // happen here (in ActOnTag). The #pragma pack stack is 15456 // maintained as a result of parser callbacks which can occur at 15457 // many points during the parsing of a struct declaration (because 15458 // the #pragma tokens are effectively skipped over during the 15459 // parsing of the struct). 15460 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15461 AddAlignmentAttributesForRecord(RD); 15462 AddMsStructLayoutForRecord(RD); 15463 } 15464 } 15465 15466 if (ModulePrivateLoc.isValid()) { 15467 if (isMemberSpecialization) 15468 Diag(New->getLocation(), diag::err_module_private_specialization) 15469 << 2 15470 << FixItHint::CreateRemoval(ModulePrivateLoc); 15471 // __module_private__ does not apply to local classes. However, we only 15472 // diagnose this as an error when the declaration specifiers are 15473 // freestanding. Here, we just ignore the __module_private__. 15474 else if (!SearchDC->isFunctionOrMethod()) 15475 New->setModulePrivate(); 15476 } 15477 15478 // If this is a specialization of a member class (of a class template), 15479 // check the specialization. 15480 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15481 Invalid = true; 15482 15483 // If we're declaring or defining a tag in function prototype scope in C, 15484 // note that this type can only be used within the function and add it to 15485 // the list of decls to inject into the function definition scope. 15486 if ((Name || Kind == TTK_Enum) && 15487 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15488 if (getLangOpts().CPlusPlus) { 15489 // C++ [dcl.fct]p6: 15490 // Types shall not be defined in return or parameter types. 15491 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15492 Diag(Loc, diag::err_type_defined_in_param_type) 15493 << Name; 15494 Invalid = true; 15495 } 15496 } else if (!PrevDecl) { 15497 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15498 } 15499 } 15500 15501 if (Invalid) 15502 New->setInvalidDecl(); 15503 15504 // Set the lexical context. If the tag has a C++ scope specifier, the 15505 // lexical context will be different from the semantic context. 15506 New->setLexicalDeclContext(CurContext); 15507 15508 // Mark this as a friend decl if applicable. 15509 // In Microsoft mode, a friend declaration also acts as a forward 15510 // declaration so we always pass true to setObjectOfFriendDecl to make 15511 // the tag name visible. 15512 if (TUK == TUK_Friend) 15513 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 15514 15515 // Set the access specifier. 15516 if (!Invalid && SearchDC->isRecord()) 15517 SetMemberAccessSpecifier(New, PrevDecl, AS); 15518 15519 if (PrevDecl) 15520 CheckRedeclarationModuleOwnership(New, PrevDecl); 15521 15522 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 15523 New->startDefinition(); 15524 15525 ProcessDeclAttributeList(S, New, Attrs); 15526 AddPragmaAttributes(S, New); 15527 15528 // If this has an identifier, add it to the scope stack. 15529 if (TUK == TUK_Friend) { 15530 // We might be replacing an existing declaration in the lookup tables; 15531 // if so, borrow its access specifier. 15532 if (PrevDecl) 15533 New->setAccess(PrevDecl->getAccess()); 15534 15535 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 15536 DC->makeDeclVisibleInContext(New); 15537 if (Name) // can be null along some error paths 15538 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15539 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 15540 } else if (Name) { 15541 S = getNonFieldDeclScope(S); 15542 PushOnScopeChains(New, S, true); 15543 } else { 15544 CurContext->addDecl(New); 15545 } 15546 15547 // If this is the C FILE type, notify the AST context. 15548 if (IdentifierInfo *II = New->getIdentifier()) 15549 if (!New->isInvalidDecl() && 15550 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 15551 II->isStr("FILE")) 15552 Context.setFILEDecl(New); 15553 15554 if (PrevDecl) 15555 mergeDeclAttributes(New, PrevDecl); 15556 15557 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 15558 inferGslOwnerPointerAttribute(CXXRD); 15559 15560 // If there's a #pragma GCC visibility in scope, set the visibility of this 15561 // record. 15562 AddPushedVisibilityAttribute(New); 15563 15564 if (isMemberSpecialization && !New->isInvalidDecl()) 15565 CompleteMemberSpecialization(New, Previous); 15566 15567 OwnedDecl = true; 15568 // In C++, don't return an invalid declaration. We can't recover well from 15569 // the cases where we make the type anonymous. 15570 if (Invalid && getLangOpts().CPlusPlus) { 15571 if (New->isBeingDefined()) 15572 if (auto RD = dyn_cast<RecordDecl>(New)) 15573 RD->completeDefinition(); 15574 return nullptr; 15575 } else if (SkipBody && SkipBody->ShouldSkip) { 15576 return SkipBody->Previous; 15577 } else { 15578 return New; 15579 } 15580 } 15581 15582 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 15583 AdjustDeclIfTemplate(TagD); 15584 TagDecl *Tag = cast<TagDecl>(TagD); 15585 15586 // Enter the tag context. 15587 PushDeclContext(S, Tag); 15588 15589 ActOnDocumentableDecl(TagD); 15590 15591 // If there's a #pragma GCC visibility in scope, set the visibility of this 15592 // record. 15593 AddPushedVisibilityAttribute(Tag); 15594 } 15595 15596 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 15597 SkipBodyInfo &SkipBody) { 15598 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 15599 return false; 15600 15601 // Make the previous decl visible. 15602 makeMergedDefinitionVisible(SkipBody.Previous); 15603 return true; 15604 } 15605 15606 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 15607 assert(isa<ObjCContainerDecl>(IDecl) && 15608 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 15609 DeclContext *OCD = cast<DeclContext>(IDecl); 15610 assert(getContainingDC(OCD) == CurContext && 15611 "The next DeclContext should be lexically contained in the current one."); 15612 CurContext = OCD; 15613 return IDecl; 15614 } 15615 15616 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 15617 SourceLocation FinalLoc, 15618 bool IsFinalSpelledSealed, 15619 SourceLocation LBraceLoc) { 15620 AdjustDeclIfTemplate(TagD); 15621 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 15622 15623 FieldCollector->StartClass(); 15624 15625 if (!Record->getIdentifier()) 15626 return; 15627 15628 if (FinalLoc.isValid()) 15629 Record->addAttr(FinalAttr::Create( 15630 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 15631 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 15632 15633 // C++ [class]p2: 15634 // [...] The class-name is also inserted into the scope of the 15635 // class itself; this is known as the injected-class-name. For 15636 // purposes of access checking, the injected-class-name is treated 15637 // as if it were a public member name. 15638 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 15639 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 15640 Record->getLocation(), Record->getIdentifier(), 15641 /*PrevDecl=*/nullptr, 15642 /*DelayTypeCreation=*/true); 15643 Context.getTypeDeclType(InjectedClassName, Record); 15644 InjectedClassName->setImplicit(); 15645 InjectedClassName->setAccess(AS_public); 15646 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 15647 InjectedClassName->setDescribedClassTemplate(Template); 15648 PushOnScopeChains(InjectedClassName, S); 15649 assert(InjectedClassName->isInjectedClassName() && 15650 "Broken injected-class-name"); 15651 } 15652 15653 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 15654 SourceRange BraceRange) { 15655 AdjustDeclIfTemplate(TagD); 15656 TagDecl *Tag = cast<TagDecl>(TagD); 15657 Tag->setBraceRange(BraceRange); 15658 15659 // Make sure we "complete" the definition even it is invalid. 15660 if (Tag->isBeingDefined()) { 15661 assert(Tag->isInvalidDecl() && "We should already have completed it"); 15662 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15663 RD->completeDefinition(); 15664 } 15665 15666 if (isa<CXXRecordDecl>(Tag)) { 15667 FieldCollector->FinishClass(); 15668 } 15669 15670 // Exit this scope of this tag's definition. 15671 PopDeclContext(); 15672 15673 if (getCurLexicalContext()->isObjCContainer() && 15674 Tag->getDeclContext()->isFileContext()) 15675 Tag->setTopLevelDeclInObjCContainer(); 15676 15677 // Notify the consumer that we've defined a tag. 15678 if (!Tag->isInvalidDecl()) 15679 Consumer.HandleTagDeclDefinition(Tag); 15680 } 15681 15682 void Sema::ActOnObjCContainerFinishDefinition() { 15683 // Exit this scope of this interface definition. 15684 PopDeclContext(); 15685 } 15686 15687 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 15688 assert(DC == CurContext && "Mismatch of container contexts"); 15689 OriginalLexicalContext = DC; 15690 ActOnObjCContainerFinishDefinition(); 15691 } 15692 15693 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 15694 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 15695 OriginalLexicalContext = nullptr; 15696 } 15697 15698 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 15699 AdjustDeclIfTemplate(TagD); 15700 TagDecl *Tag = cast<TagDecl>(TagD); 15701 Tag->setInvalidDecl(); 15702 15703 // Make sure we "complete" the definition even it is invalid. 15704 if (Tag->isBeingDefined()) { 15705 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15706 RD->completeDefinition(); 15707 } 15708 15709 // We're undoing ActOnTagStartDefinition here, not 15710 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 15711 // the FieldCollector. 15712 15713 PopDeclContext(); 15714 } 15715 15716 // Note that FieldName may be null for anonymous bitfields. 15717 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 15718 IdentifierInfo *FieldName, 15719 QualType FieldTy, bool IsMsStruct, 15720 Expr *BitWidth, bool *ZeroWidth) { 15721 // Default to true; that shouldn't confuse checks for emptiness 15722 if (ZeroWidth) 15723 *ZeroWidth = true; 15724 15725 // C99 6.7.2.1p4 - verify the field type. 15726 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 15727 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 15728 // Handle incomplete types with specific error. 15729 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 15730 return ExprError(); 15731 if (FieldName) 15732 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 15733 << FieldName << FieldTy << BitWidth->getSourceRange(); 15734 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 15735 << FieldTy << BitWidth->getSourceRange(); 15736 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 15737 UPPC_BitFieldWidth)) 15738 return ExprError(); 15739 15740 // If the bit-width is type- or value-dependent, don't try to check 15741 // it now. 15742 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 15743 return BitWidth; 15744 15745 llvm::APSInt Value; 15746 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 15747 if (ICE.isInvalid()) 15748 return ICE; 15749 BitWidth = ICE.get(); 15750 15751 if (Value != 0 && ZeroWidth) 15752 *ZeroWidth = false; 15753 15754 // Zero-width bitfield is ok for anonymous field. 15755 if (Value == 0 && FieldName) 15756 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 15757 15758 if (Value.isSigned() && Value.isNegative()) { 15759 if (FieldName) 15760 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 15761 << FieldName << Value.toString(10); 15762 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 15763 << Value.toString(10); 15764 } 15765 15766 if (!FieldTy->isDependentType()) { 15767 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 15768 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 15769 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 15770 15771 // Over-wide bitfields are an error in C or when using the MSVC bitfield 15772 // ABI. 15773 bool CStdConstraintViolation = 15774 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 15775 bool MSBitfieldViolation = 15776 Value.ugt(TypeStorageSize) && 15777 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 15778 if (CStdConstraintViolation || MSBitfieldViolation) { 15779 unsigned DiagWidth = 15780 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 15781 if (FieldName) 15782 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 15783 << FieldName << (unsigned)Value.getZExtValue() 15784 << !CStdConstraintViolation << DiagWidth; 15785 15786 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 15787 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 15788 << DiagWidth; 15789 } 15790 15791 // Warn on types where the user might conceivably expect to get all 15792 // specified bits as value bits: that's all integral types other than 15793 // 'bool'. 15794 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 15795 if (FieldName) 15796 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 15797 << FieldName << (unsigned)Value.getZExtValue() 15798 << (unsigned)TypeWidth; 15799 else 15800 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 15801 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 15802 } 15803 } 15804 15805 return BitWidth; 15806 } 15807 15808 /// ActOnField - Each field of a C struct/union is passed into this in order 15809 /// to create a FieldDecl object for it. 15810 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 15811 Declarator &D, Expr *BitfieldWidth) { 15812 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 15813 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 15814 /*InitStyle=*/ICIS_NoInit, AS_public); 15815 return Res; 15816 } 15817 15818 /// HandleField - Analyze a field of a C struct or a C++ data member. 15819 /// 15820 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 15821 SourceLocation DeclStart, 15822 Declarator &D, Expr *BitWidth, 15823 InClassInitStyle InitStyle, 15824 AccessSpecifier AS) { 15825 if (D.isDecompositionDeclarator()) { 15826 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 15827 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 15828 << Decomp.getSourceRange(); 15829 return nullptr; 15830 } 15831 15832 IdentifierInfo *II = D.getIdentifier(); 15833 SourceLocation Loc = DeclStart; 15834 if (II) Loc = D.getIdentifierLoc(); 15835 15836 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15837 QualType T = TInfo->getType(); 15838 if (getLangOpts().CPlusPlus) { 15839 CheckExtraCXXDefaultArguments(D); 15840 15841 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15842 UPPC_DataMemberType)) { 15843 D.setInvalidType(); 15844 T = Context.IntTy; 15845 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15846 } 15847 } 15848 15849 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15850 15851 if (D.getDeclSpec().isInlineSpecified()) 15852 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15853 << getLangOpts().CPlusPlus17; 15854 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15855 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15856 diag::err_invalid_thread) 15857 << DeclSpec::getSpecifierName(TSCS); 15858 15859 // Check to see if this name was declared as a member previously 15860 NamedDecl *PrevDecl = nullptr; 15861 LookupResult Previous(*this, II, Loc, LookupMemberName, 15862 ForVisibleRedeclaration); 15863 LookupName(Previous, S); 15864 switch (Previous.getResultKind()) { 15865 case LookupResult::Found: 15866 case LookupResult::FoundUnresolvedValue: 15867 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15868 break; 15869 15870 case LookupResult::FoundOverloaded: 15871 PrevDecl = Previous.getRepresentativeDecl(); 15872 break; 15873 15874 case LookupResult::NotFound: 15875 case LookupResult::NotFoundInCurrentInstantiation: 15876 case LookupResult::Ambiguous: 15877 break; 15878 } 15879 Previous.suppressDiagnostics(); 15880 15881 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15882 // Maybe we will complain about the shadowed template parameter. 15883 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15884 // Just pretend that we didn't see the previous declaration. 15885 PrevDecl = nullptr; 15886 } 15887 15888 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15889 PrevDecl = nullptr; 15890 15891 bool Mutable 15892 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 15893 SourceLocation TSSL = D.getBeginLoc(); 15894 FieldDecl *NewFD 15895 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 15896 TSSL, AS, PrevDecl, &D); 15897 15898 if (NewFD->isInvalidDecl()) 15899 Record->setInvalidDecl(); 15900 15901 if (D.getDeclSpec().isModulePrivateSpecified()) 15902 NewFD->setModulePrivate(); 15903 15904 if (NewFD->isInvalidDecl() && PrevDecl) { 15905 // Don't introduce NewFD into scope; there's already something 15906 // with the same name in the same scope. 15907 } else if (II) { 15908 PushOnScopeChains(NewFD, S); 15909 } else 15910 Record->addDecl(NewFD); 15911 15912 return NewFD; 15913 } 15914 15915 /// Build a new FieldDecl and check its well-formedness. 15916 /// 15917 /// This routine builds a new FieldDecl given the fields name, type, 15918 /// record, etc. \p PrevDecl should refer to any previous declaration 15919 /// with the same name and in the same scope as the field to be 15920 /// created. 15921 /// 15922 /// \returns a new FieldDecl. 15923 /// 15924 /// \todo The Declarator argument is a hack. It will be removed once 15925 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 15926 TypeSourceInfo *TInfo, 15927 RecordDecl *Record, SourceLocation Loc, 15928 bool Mutable, Expr *BitWidth, 15929 InClassInitStyle InitStyle, 15930 SourceLocation TSSL, 15931 AccessSpecifier AS, NamedDecl *PrevDecl, 15932 Declarator *D) { 15933 IdentifierInfo *II = Name.getAsIdentifierInfo(); 15934 bool InvalidDecl = false; 15935 if (D) InvalidDecl = D->isInvalidType(); 15936 15937 // If we receive a broken type, recover by assuming 'int' and 15938 // marking this declaration as invalid. 15939 if (T.isNull()) { 15940 InvalidDecl = true; 15941 T = Context.IntTy; 15942 } 15943 15944 QualType EltTy = Context.getBaseElementType(T); 15945 if (!EltTy->isDependentType()) { 15946 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 15947 // Fields of incomplete type force their record to be invalid. 15948 Record->setInvalidDecl(); 15949 InvalidDecl = true; 15950 } else { 15951 NamedDecl *Def; 15952 EltTy->isIncompleteType(&Def); 15953 if (Def && Def->isInvalidDecl()) { 15954 Record->setInvalidDecl(); 15955 InvalidDecl = true; 15956 } 15957 } 15958 } 15959 15960 // TR 18037 does not allow fields to be declared with address space 15961 if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || 15962 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 15963 Diag(Loc, diag::err_field_with_address_space); 15964 Record->setInvalidDecl(); 15965 InvalidDecl = true; 15966 } 15967 15968 if (LangOpts.OpenCL) { 15969 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 15970 // used as structure or union field: image, sampler, event or block types. 15971 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 15972 T->isBlockPointerType()) { 15973 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 15974 Record->setInvalidDecl(); 15975 InvalidDecl = true; 15976 } 15977 // OpenCL v1.2 s6.9.c: bitfields are not supported. 15978 if (BitWidth) { 15979 Diag(Loc, diag::err_opencl_bitfields); 15980 InvalidDecl = true; 15981 } 15982 } 15983 15984 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 15985 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 15986 T.hasQualifiers()) { 15987 InvalidDecl = true; 15988 Diag(Loc, diag::err_anon_bitfield_qualifiers); 15989 } 15990 15991 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15992 // than a variably modified type. 15993 if (!InvalidDecl && T->isVariablyModifiedType()) { 15994 bool SizeIsNegative; 15995 llvm::APSInt Oversized; 15996 15997 TypeSourceInfo *FixedTInfo = 15998 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 15999 SizeIsNegative, 16000 Oversized); 16001 if (FixedTInfo) { 16002 Diag(Loc, diag::warn_illegal_constant_array_size); 16003 TInfo = FixedTInfo; 16004 T = FixedTInfo->getType(); 16005 } else { 16006 if (SizeIsNegative) 16007 Diag(Loc, diag::err_typecheck_negative_array_size); 16008 else if (Oversized.getBoolValue()) 16009 Diag(Loc, diag::err_array_too_large) 16010 << Oversized.toString(10); 16011 else 16012 Diag(Loc, diag::err_typecheck_field_variable_size); 16013 InvalidDecl = true; 16014 } 16015 } 16016 16017 // Fields can not have abstract class types 16018 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16019 diag::err_abstract_type_in_decl, 16020 AbstractFieldType)) 16021 InvalidDecl = true; 16022 16023 bool ZeroWidth = false; 16024 if (InvalidDecl) 16025 BitWidth = nullptr; 16026 // If this is declared as a bit-field, check the bit-field. 16027 if (BitWidth) { 16028 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16029 &ZeroWidth).get(); 16030 if (!BitWidth) { 16031 InvalidDecl = true; 16032 BitWidth = nullptr; 16033 ZeroWidth = false; 16034 } 16035 } 16036 16037 // Check that 'mutable' is consistent with the type of the declaration. 16038 if (!InvalidDecl && Mutable) { 16039 unsigned DiagID = 0; 16040 if (T->isReferenceType()) 16041 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16042 : diag::err_mutable_reference; 16043 else if (T.isConstQualified()) 16044 DiagID = diag::err_mutable_const; 16045 16046 if (DiagID) { 16047 SourceLocation ErrLoc = Loc; 16048 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16049 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16050 Diag(ErrLoc, DiagID); 16051 if (DiagID != diag::ext_mutable_reference) { 16052 Mutable = false; 16053 InvalidDecl = true; 16054 } 16055 } 16056 } 16057 16058 // C++11 [class.union]p8 (DR1460): 16059 // At most one variant member of a union may have a 16060 // brace-or-equal-initializer. 16061 if (InitStyle != ICIS_NoInit) 16062 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16063 16064 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16065 BitWidth, Mutable, InitStyle); 16066 if (InvalidDecl) 16067 NewFD->setInvalidDecl(); 16068 16069 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16070 Diag(Loc, diag::err_duplicate_member) << II; 16071 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16072 NewFD->setInvalidDecl(); 16073 } 16074 16075 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16076 if (Record->isUnion()) { 16077 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16078 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16079 if (RDecl->getDefinition()) { 16080 // C++ [class.union]p1: An object of a class with a non-trivial 16081 // constructor, a non-trivial copy constructor, a non-trivial 16082 // destructor, or a non-trivial copy assignment operator 16083 // cannot be a member of a union, nor can an array of such 16084 // objects. 16085 if (CheckNontrivialField(NewFD)) 16086 NewFD->setInvalidDecl(); 16087 } 16088 } 16089 16090 // C++ [class.union]p1: If a union contains a member of reference type, 16091 // the program is ill-formed, except when compiling with MSVC extensions 16092 // enabled. 16093 if (EltTy->isReferenceType()) { 16094 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16095 diag::ext_union_member_of_reference_type : 16096 diag::err_union_member_of_reference_type) 16097 << NewFD->getDeclName() << EltTy; 16098 if (!getLangOpts().MicrosoftExt) 16099 NewFD->setInvalidDecl(); 16100 } 16101 } 16102 } 16103 16104 // FIXME: We need to pass in the attributes given an AST 16105 // representation, not a parser representation. 16106 if (D) { 16107 // FIXME: The current scope is almost... but not entirely... correct here. 16108 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16109 16110 if (NewFD->hasAttrs()) 16111 CheckAlignasUnderalignment(NewFD); 16112 } 16113 16114 // In auto-retain/release, infer strong retension for fields of 16115 // retainable type. 16116 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16117 NewFD->setInvalidDecl(); 16118 16119 if (T.isObjCGCWeak()) 16120 Diag(Loc, diag::warn_attribute_weak_on_field); 16121 16122 NewFD->setAccess(AS); 16123 return NewFD; 16124 } 16125 16126 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16127 assert(FD); 16128 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16129 16130 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16131 return false; 16132 16133 QualType EltTy = Context.getBaseElementType(FD->getType()); 16134 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16135 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16136 if (RDecl->getDefinition()) { 16137 // We check for copy constructors before constructors 16138 // because otherwise we'll never get complaints about 16139 // copy constructors. 16140 16141 CXXSpecialMember member = CXXInvalid; 16142 // We're required to check for any non-trivial constructors. Since the 16143 // implicit default constructor is suppressed if there are any 16144 // user-declared constructors, we just need to check that there is a 16145 // trivial default constructor and a trivial copy constructor. (We don't 16146 // worry about move constructors here, since this is a C++98 check.) 16147 if (RDecl->hasNonTrivialCopyConstructor()) 16148 member = CXXCopyConstructor; 16149 else if (!RDecl->hasTrivialDefaultConstructor()) 16150 member = CXXDefaultConstructor; 16151 else if (RDecl->hasNonTrivialCopyAssignment()) 16152 member = CXXCopyAssignment; 16153 else if (RDecl->hasNonTrivialDestructor()) 16154 member = CXXDestructor; 16155 16156 if (member != CXXInvalid) { 16157 if (!getLangOpts().CPlusPlus11 && 16158 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16159 // Objective-C++ ARC: it is an error to have a non-trivial field of 16160 // a union. However, system headers in Objective-C programs 16161 // occasionally have Objective-C lifetime objects within unions, 16162 // and rather than cause the program to fail, we make those 16163 // members unavailable. 16164 SourceLocation Loc = FD->getLocation(); 16165 if (getSourceManager().isInSystemHeader(Loc)) { 16166 if (!FD->hasAttr<UnavailableAttr>()) 16167 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16168 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16169 return false; 16170 } 16171 } 16172 16173 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16174 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16175 diag::err_illegal_union_or_anon_struct_member) 16176 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16177 DiagnoseNontrivial(RDecl, member); 16178 return !getLangOpts().CPlusPlus11; 16179 } 16180 } 16181 } 16182 16183 return false; 16184 } 16185 16186 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16187 /// AST enum value. 16188 static ObjCIvarDecl::AccessControl 16189 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16190 switch (ivarVisibility) { 16191 default: llvm_unreachable("Unknown visitibility kind"); 16192 case tok::objc_private: return ObjCIvarDecl::Private; 16193 case tok::objc_public: return ObjCIvarDecl::Public; 16194 case tok::objc_protected: return ObjCIvarDecl::Protected; 16195 case tok::objc_package: return ObjCIvarDecl::Package; 16196 } 16197 } 16198 16199 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16200 /// in order to create an IvarDecl object for it. 16201 Decl *Sema::ActOnIvar(Scope *S, 16202 SourceLocation DeclStart, 16203 Declarator &D, Expr *BitfieldWidth, 16204 tok::ObjCKeywordKind Visibility) { 16205 16206 IdentifierInfo *II = D.getIdentifier(); 16207 Expr *BitWidth = (Expr*)BitfieldWidth; 16208 SourceLocation Loc = DeclStart; 16209 if (II) Loc = D.getIdentifierLoc(); 16210 16211 // FIXME: Unnamed fields can be handled in various different ways, for 16212 // example, unnamed unions inject all members into the struct namespace! 16213 16214 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16215 QualType T = TInfo->getType(); 16216 16217 if (BitWidth) { 16218 // 6.7.2.1p3, 6.7.2.1p4 16219 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16220 if (!BitWidth) 16221 D.setInvalidType(); 16222 } else { 16223 // Not a bitfield. 16224 16225 // validate II. 16226 16227 } 16228 if (T->isReferenceType()) { 16229 Diag(Loc, diag::err_ivar_reference_type); 16230 D.setInvalidType(); 16231 } 16232 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16233 // than a variably modified type. 16234 else if (T->isVariablyModifiedType()) { 16235 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16236 D.setInvalidType(); 16237 } 16238 16239 // Get the visibility (access control) for this ivar. 16240 ObjCIvarDecl::AccessControl ac = 16241 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16242 : ObjCIvarDecl::None; 16243 // Must set ivar's DeclContext to its enclosing interface. 16244 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16245 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16246 return nullptr; 16247 ObjCContainerDecl *EnclosingContext; 16248 if (ObjCImplementationDecl *IMPDecl = 16249 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16250 if (LangOpts.ObjCRuntime.isFragile()) { 16251 // Case of ivar declared in an implementation. Context is that of its class. 16252 EnclosingContext = IMPDecl->getClassInterface(); 16253 assert(EnclosingContext && "Implementation has no class interface!"); 16254 } 16255 else 16256 EnclosingContext = EnclosingDecl; 16257 } else { 16258 if (ObjCCategoryDecl *CDecl = 16259 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16260 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16261 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16262 return nullptr; 16263 } 16264 } 16265 EnclosingContext = EnclosingDecl; 16266 } 16267 16268 // Construct the decl. 16269 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16270 DeclStart, Loc, II, T, 16271 TInfo, ac, (Expr *)BitfieldWidth); 16272 16273 if (II) { 16274 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16275 ForVisibleRedeclaration); 16276 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16277 && !isa<TagDecl>(PrevDecl)) { 16278 Diag(Loc, diag::err_duplicate_member) << II; 16279 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16280 NewID->setInvalidDecl(); 16281 } 16282 } 16283 16284 // Process attributes attached to the ivar. 16285 ProcessDeclAttributes(S, NewID, D); 16286 16287 if (D.isInvalidType()) 16288 NewID->setInvalidDecl(); 16289 16290 // In ARC, infer 'retaining' for ivars of retainable type. 16291 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16292 NewID->setInvalidDecl(); 16293 16294 if (D.getDeclSpec().isModulePrivateSpecified()) 16295 NewID->setModulePrivate(); 16296 16297 if (II) { 16298 // FIXME: When interfaces are DeclContexts, we'll need to add 16299 // these to the interface. 16300 S->AddDecl(NewID); 16301 IdResolver.AddDecl(NewID); 16302 } 16303 16304 if (LangOpts.ObjCRuntime.isNonFragile() && 16305 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16306 Diag(Loc, diag::warn_ivars_in_interface); 16307 16308 return NewID; 16309 } 16310 16311 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16312 /// class and class extensions. For every class \@interface and class 16313 /// extension \@interface, if the last ivar is a bitfield of any type, 16314 /// then add an implicit `char :0` ivar to the end of that interface. 16315 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16316 SmallVectorImpl<Decl *> &AllIvarDecls) { 16317 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16318 return; 16319 16320 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16321 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16322 16323 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16324 return; 16325 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16326 if (!ID) { 16327 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16328 if (!CD->IsClassExtension()) 16329 return; 16330 } 16331 // No need to add this to end of @implementation. 16332 else 16333 return; 16334 } 16335 // All conditions are met. Add a new bitfield to the tail end of ivars. 16336 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16337 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16338 16339 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16340 DeclLoc, DeclLoc, nullptr, 16341 Context.CharTy, 16342 Context.getTrivialTypeSourceInfo(Context.CharTy, 16343 DeclLoc), 16344 ObjCIvarDecl::Private, BW, 16345 true); 16346 AllIvarDecls.push_back(Ivar); 16347 } 16348 16349 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16350 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16351 SourceLocation RBrac, 16352 const ParsedAttributesView &Attrs) { 16353 assert(EnclosingDecl && "missing record or interface decl"); 16354 16355 // If this is an Objective-C @implementation or category and we have 16356 // new fields here we should reset the layout of the interface since 16357 // it will now change. 16358 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16359 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16360 switch (DC->getKind()) { 16361 default: break; 16362 case Decl::ObjCCategory: 16363 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16364 break; 16365 case Decl::ObjCImplementation: 16366 Context. 16367 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16368 break; 16369 } 16370 } 16371 16372 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16373 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16374 16375 // Start counting up the number of named members; make sure to include 16376 // members of anonymous structs and unions in the total. 16377 unsigned NumNamedMembers = 0; 16378 if (Record) { 16379 for (const auto *I : Record->decls()) { 16380 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16381 if (IFD->getDeclName()) 16382 ++NumNamedMembers; 16383 } 16384 } 16385 16386 // Verify that all the fields are okay. 16387 SmallVector<FieldDecl*, 32> RecFields; 16388 16389 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16390 i != end; ++i) { 16391 FieldDecl *FD = cast<FieldDecl>(*i); 16392 16393 // Get the type for the field. 16394 const Type *FDTy = FD->getType().getTypePtr(); 16395 16396 if (!FD->isAnonymousStructOrUnion()) { 16397 // Remember all fields written by the user. 16398 RecFields.push_back(FD); 16399 } 16400 16401 // If the field is already invalid for some reason, don't emit more 16402 // diagnostics about it. 16403 if (FD->isInvalidDecl()) { 16404 EnclosingDecl->setInvalidDecl(); 16405 continue; 16406 } 16407 16408 // C99 6.7.2.1p2: 16409 // A structure or union shall not contain a member with 16410 // incomplete or function type (hence, a structure shall not 16411 // contain an instance of itself, but may contain a pointer to 16412 // an instance of itself), except that the last member of a 16413 // structure with more than one named member may have incomplete 16414 // array type; such a structure (and any union containing, 16415 // possibly recursively, a member that is such a structure) 16416 // shall not be a member of a structure or an element of an 16417 // array. 16418 bool IsLastField = (i + 1 == Fields.end()); 16419 if (FDTy->isFunctionType()) { 16420 // Field declared as a function. 16421 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16422 << FD->getDeclName(); 16423 FD->setInvalidDecl(); 16424 EnclosingDecl->setInvalidDecl(); 16425 continue; 16426 } else if (FDTy->isIncompleteArrayType() && 16427 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16428 if (Record) { 16429 // Flexible array member. 16430 // Microsoft and g++ is more permissive regarding flexible array. 16431 // It will accept flexible array in union and also 16432 // as the sole element of a struct/class. 16433 unsigned DiagID = 0; 16434 if (!Record->isUnion() && !IsLastField) { 16435 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16436 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16437 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16438 FD->setInvalidDecl(); 16439 EnclosingDecl->setInvalidDecl(); 16440 continue; 16441 } else if (Record->isUnion()) 16442 DiagID = getLangOpts().MicrosoftExt 16443 ? diag::ext_flexible_array_union_ms 16444 : getLangOpts().CPlusPlus 16445 ? diag::ext_flexible_array_union_gnu 16446 : diag::err_flexible_array_union; 16447 else if (NumNamedMembers < 1) 16448 DiagID = getLangOpts().MicrosoftExt 16449 ? diag::ext_flexible_array_empty_aggregate_ms 16450 : getLangOpts().CPlusPlus 16451 ? diag::ext_flexible_array_empty_aggregate_gnu 16452 : diag::err_flexible_array_empty_aggregate; 16453 16454 if (DiagID) 16455 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16456 << Record->getTagKind(); 16457 // While the layout of types that contain virtual bases is not specified 16458 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16459 // virtual bases after the derived members. This would make a flexible 16460 // array member declared at the end of an object not adjacent to the end 16461 // of the type. 16462 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16463 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16464 << FD->getDeclName() << Record->getTagKind(); 16465 if (!getLangOpts().C99) 16466 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16467 << FD->getDeclName() << Record->getTagKind(); 16468 16469 // If the element type has a non-trivial destructor, we would not 16470 // implicitly destroy the elements, so disallow it for now. 16471 // 16472 // FIXME: GCC allows this. We should probably either implicitly delete 16473 // the destructor of the containing class, or just allow this. 16474 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16475 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16476 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16477 << FD->getDeclName() << FD->getType(); 16478 FD->setInvalidDecl(); 16479 EnclosingDecl->setInvalidDecl(); 16480 continue; 16481 } 16482 // Okay, we have a legal flexible array member at the end of the struct. 16483 Record->setHasFlexibleArrayMember(true); 16484 } else { 16485 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16486 // unless they are followed by another ivar. That check is done 16487 // elsewhere, after synthesized ivars are known. 16488 } 16489 } else if (!FDTy->isDependentType() && 16490 RequireCompleteType(FD->getLocation(), FD->getType(), 16491 diag::err_field_incomplete)) { 16492 // Incomplete type 16493 FD->setInvalidDecl(); 16494 EnclosingDecl->setInvalidDecl(); 16495 continue; 16496 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 16497 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 16498 // A type which contains a flexible array member is considered to be a 16499 // flexible array member. 16500 Record->setHasFlexibleArrayMember(true); 16501 if (!Record->isUnion()) { 16502 // If this is a struct/class and this is not the last element, reject 16503 // it. Note that GCC supports variable sized arrays in the middle of 16504 // structures. 16505 if (!IsLastField) 16506 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 16507 << FD->getDeclName() << FD->getType(); 16508 else { 16509 // We support flexible arrays at the end of structs in 16510 // other structs as an extension. 16511 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 16512 << FD->getDeclName(); 16513 } 16514 } 16515 } 16516 if (isa<ObjCContainerDecl>(EnclosingDecl) && 16517 RequireNonAbstractType(FD->getLocation(), FD->getType(), 16518 diag::err_abstract_type_in_decl, 16519 AbstractIvarType)) { 16520 // Ivars can not have abstract class types 16521 FD->setInvalidDecl(); 16522 } 16523 if (Record && FDTTy->getDecl()->hasObjectMember()) 16524 Record->setHasObjectMember(true); 16525 if (Record && FDTTy->getDecl()->hasVolatileMember()) 16526 Record->setHasVolatileMember(true); 16527 } else if (FDTy->isObjCObjectType()) { 16528 /// A field cannot be an Objective-c object 16529 Diag(FD->getLocation(), diag::err_statically_allocated_object) 16530 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 16531 QualType T = Context.getObjCObjectPointerType(FD->getType()); 16532 FD->setType(T); 16533 } else if (Record && Record->isUnion() && 16534 FD->getType().hasNonTrivialObjCLifetime() && 16535 getSourceManager().isInSystemHeader(FD->getLocation()) && 16536 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 16537 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 16538 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 16539 // For backward compatibility, fields of C unions declared in system 16540 // headers that have non-trivial ObjC ownership qualifications are marked 16541 // as unavailable unless the qualifier is explicit and __strong. This can 16542 // break ABI compatibility between programs compiled with ARC and MRR, but 16543 // is a better option than rejecting programs using those unions under 16544 // ARC. 16545 FD->addAttr(UnavailableAttr::CreateImplicit( 16546 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 16547 FD->getLocation())); 16548 } else if (getLangOpts().ObjC && 16549 getLangOpts().getGC() != LangOptions::NonGC && 16550 Record && !Record->hasObjectMember()) { 16551 if (FD->getType()->isObjCObjectPointerType() || 16552 FD->getType().isObjCGCStrong()) 16553 Record->setHasObjectMember(true); 16554 else if (Context.getAsArrayType(FD->getType())) { 16555 QualType BaseType = Context.getBaseElementType(FD->getType()); 16556 if (BaseType->isRecordType() && 16557 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 16558 Record->setHasObjectMember(true); 16559 else if (BaseType->isObjCObjectPointerType() || 16560 BaseType.isObjCGCStrong()) 16561 Record->setHasObjectMember(true); 16562 } 16563 } 16564 16565 if (Record && !getLangOpts().CPlusPlus && 16566 !shouldIgnoreForRecordTriviality(FD)) { 16567 QualType FT = FD->getType(); 16568 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 16569 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 16570 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 16571 Record->isUnion()) 16572 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 16573 } 16574 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 16575 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 16576 Record->setNonTrivialToPrimitiveCopy(true); 16577 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 16578 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 16579 } 16580 if (FT.isDestructedType()) { 16581 Record->setNonTrivialToPrimitiveDestroy(true); 16582 Record->setParamDestroyedInCallee(true); 16583 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 16584 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 16585 } 16586 16587 if (const auto *RT = FT->getAs<RecordType>()) { 16588 if (RT->getDecl()->getArgPassingRestrictions() == 16589 RecordDecl::APK_CanNeverPassInRegs) 16590 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16591 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 16592 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16593 } 16594 16595 if (Record && FD->getType().isVolatileQualified()) 16596 Record->setHasVolatileMember(true); 16597 // Keep track of the number of named members. 16598 if (FD->getIdentifier()) 16599 ++NumNamedMembers; 16600 } 16601 16602 // Okay, we successfully defined 'Record'. 16603 if (Record) { 16604 bool Completed = false; 16605 if (CXXRecord) { 16606 if (!CXXRecord->isInvalidDecl()) { 16607 // Set access bits correctly on the directly-declared conversions. 16608 for (CXXRecordDecl::conversion_iterator 16609 I = CXXRecord->conversion_begin(), 16610 E = CXXRecord->conversion_end(); I != E; ++I) 16611 I.setAccess((*I)->getAccess()); 16612 } 16613 16614 if (!CXXRecord->isDependentType()) { 16615 // Add any implicitly-declared members to this class. 16616 AddImplicitlyDeclaredMembersToClass(CXXRecord); 16617 16618 if (!CXXRecord->isInvalidDecl()) { 16619 // If we have virtual base classes, we may end up finding multiple 16620 // final overriders for a given virtual function. Check for this 16621 // problem now. 16622 if (CXXRecord->getNumVBases()) { 16623 CXXFinalOverriderMap FinalOverriders; 16624 CXXRecord->getFinalOverriders(FinalOverriders); 16625 16626 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 16627 MEnd = FinalOverriders.end(); 16628 M != MEnd; ++M) { 16629 for (OverridingMethods::iterator SO = M->second.begin(), 16630 SOEnd = M->second.end(); 16631 SO != SOEnd; ++SO) { 16632 assert(SO->second.size() > 0 && 16633 "Virtual function without overriding functions?"); 16634 if (SO->second.size() == 1) 16635 continue; 16636 16637 // C++ [class.virtual]p2: 16638 // In a derived class, if a virtual member function of a base 16639 // class subobject has more than one final overrider the 16640 // program is ill-formed. 16641 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 16642 << (const NamedDecl *)M->first << Record; 16643 Diag(M->first->getLocation(), 16644 diag::note_overridden_virtual_function); 16645 for (OverridingMethods::overriding_iterator 16646 OM = SO->second.begin(), 16647 OMEnd = SO->second.end(); 16648 OM != OMEnd; ++OM) 16649 Diag(OM->Method->getLocation(), diag::note_final_overrider) 16650 << (const NamedDecl *)M->first << OM->Method->getParent(); 16651 16652 Record->setInvalidDecl(); 16653 } 16654 } 16655 CXXRecord->completeDefinition(&FinalOverriders); 16656 Completed = true; 16657 } 16658 } 16659 } 16660 } 16661 16662 if (!Completed) 16663 Record->completeDefinition(); 16664 16665 // Handle attributes before checking the layout. 16666 ProcessDeclAttributeList(S, Record, Attrs); 16667 16668 // We may have deferred checking for a deleted destructor. Check now. 16669 if (CXXRecord) { 16670 auto *Dtor = CXXRecord->getDestructor(); 16671 if (Dtor && Dtor->isImplicit() && 16672 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 16673 CXXRecord->setImplicitDestructorIsDeleted(); 16674 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 16675 } 16676 } 16677 16678 if (Record->hasAttrs()) { 16679 CheckAlignasUnderalignment(Record); 16680 16681 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 16682 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 16683 IA->getRange(), IA->getBestCase(), 16684 IA->getSemanticSpelling()); 16685 } 16686 16687 // Check if the structure/union declaration is a type that can have zero 16688 // size in C. For C this is a language extension, for C++ it may cause 16689 // compatibility problems. 16690 bool CheckForZeroSize; 16691 if (!getLangOpts().CPlusPlus) { 16692 CheckForZeroSize = true; 16693 } else { 16694 // For C++ filter out types that cannot be referenced in C code. 16695 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 16696 CheckForZeroSize = 16697 CXXRecord->getLexicalDeclContext()->isExternCContext() && 16698 !CXXRecord->isDependentType() && 16699 CXXRecord->isCLike(); 16700 } 16701 if (CheckForZeroSize) { 16702 bool ZeroSize = true; 16703 bool IsEmpty = true; 16704 unsigned NonBitFields = 0; 16705 for (RecordDecl::field_iterator I = Record->field_begin(), 16706 E = Record->field_end(); 16707 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 16708 IsEmpty = false; 16709 if (I->isUnnamedBitfield()) { 16710 if (!I->isZeroLengthBitField(Context)) 16711 ZeroSize = false; 16712 } else { 16713 ++NonBitFields; 16714 QualType FieldType = I->getType(); 16715 if (FieldType->isIncompleteType() || 16716 !Context.getTypeSizeInChars(FieldType).isZero()) 16717 ZeroSize = false; 16718 } 16719 } 16720 16721 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 16722 // allowed in C++, but warn if its declaration is inside 16723 // extern "C" block. 16724 if (ZeroSize) { 16725 Diag(RecLoc, getLangOpts().CPlusPlus ? 16726 diag::warn_zero_size_struct_union_in_extern_c : 16727 diag::warn_zero_size_struct_union_compat) 16728 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 16729 } 16730 16731 // Structs without named members are extension in C (C99 6.7.2.1p7), 16732 // but are accepted by GCC. 16733 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 16734 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 16735 diag::ext_no_named_members_in_struct_union) 16736 << Record->isUnion(); 16737 } 16738 } 16739 } else { 16740 ObjCIvarDecl **ClsFields = 16741 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 16742 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 16743 ID->setEndOfDefinitionLoc(RBrac); 16744 // Add ivar's to class's DeclContext. 16745 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16746 ClsFields[i]->setLexicalDeclContext(ID); 16747 ID->addDecl(ClsFields[i]); 16748 } 16749 // Must enforce the rule that ivars in the base classes may not be 16750 // duplicates. 16751 if (ID->getSuperClass()) 16752 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 16753 } else if (ObjCImplementationDecl *IMPDecl = 16754 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16755 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 16756 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 16757 // Ivar declared in @implementation never belongs to the implementation. 16758 // Only it is in implementation's lexical context. 16759 ClsFields[I]->setLexicalDeclContext(IMPDecl); 16760 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 16761 IMPDecl->setIvarLBraceLoc(LBrac); 16762 IMPDecl->setIvarRBraceLoc(RBrac); 16763 } else if (ObjCCategoryDecl *CDecl = 16764 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16765 // case of ivars in class extension; all other cases have been 16766 // reported as errors elsewhere. 16767 // FIXME. Class extension does not have a LocEnd field. 16768 // CDecl->setLocEnd(RBrac); 16769 // Add ivar's to class extension's DeclContext. 16770 // Diagnose redeclaration of private ivars. 16771 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 16772 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16773 if (IDecl) { 16774 if (const ObjCIvarDecl *ClsIvar = 16775 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 16776 Diag(ClsFields[i]->getLocation(), 16777 diag::err_duplicate_ivar_declaration); 16778 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 16779 continue; 16780 } 16781 for (const auto *Ext : IDecl->known_extensions()) { 16782 if (const ObjCIvarDecl *ClsExtIvar 16783 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 16784 Diag(ClsFields[i]->getLocation(), 16785 diag::err_duplicate_ivar_declaration); 16786 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 16787 continue; 16788 } 16789 } 16790 } 16791 ClsFields[i]->setLexicalDeclContext(CDecl); 16792 CDecl->addDecl(ClsFields[i]); 16793 } 16794 CDecl->setIvarLBraceLoc(LBrac); 16795 CDecl->setIvarRBraceLoc(RBrac); 16796 } 16797 } 16798 } 16799 16800 /// Determine whether the given integral value is representable within 16801 /// the given type T. 16802 static bool isRepresentableIntegerValue(ASTContext &Context, 16803 llvm::APSInt &Value, 16804 QualType T) { 16805 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 16806 "Integral type required!"); 16807 unsigned BitWidth = Context.getIntWidth(T); 16808 16809 if (Value.isUnsigned() || Value.isNonNegative()) { 16810 if (T->isSignedIntegerOrEnumerationType()) 16811 --BitWidth; 16812 return Value.getActiveBits() <= BitWidth; 16813 } 16814 return Value.getMinSignedBits() <= BitWidth; 16815 } 16816 16817 // Given an integral type, return the next larger integral type 16818 // (or a NULL type of no such type exists). 16819 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 16820 // FIXME: Int128/UInt128 support, which also needs to be introduced into 16821 // enum checking below. 16822 assert((T->isIntegralType(Context) || 16823 T->isEnumeralType()) && "Integral type required!"); 16824 const unsigned NumTypes = 4; 16825 QualType SignedIntegralTypes[NumTypes] = { 16826 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 16827 }; 16828 QualType UnsignedIntegralTypes[NumTypes] = { 16829 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 16830 Context.UnsignedLongLongTy 16831 }; 16832 16833 unsigned BitWidth = Context.getTypeSize(T); 16834 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 16835 : UnsignedIntegralTypes; 16836 for (unsigned I = 0; I != NumTypes; ++I) 16837 if (Context.getTypeSize(Types[I]) > BitWidth) 16838 return Types[I]; 16839 16840 return QualType(); 16841 } 16842 16843 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 16844 EnumConstantDecl *LastEnumConst, 16845 SourceLocation IdLoc, 16846 IdentifierInfo *Id, 16847 Expr *Val) { 16848 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16849 llvm::APSInt EnumVal(IntWidth); 16850 QualType EltTy; 16851 16852 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 16853 Val = nullptr; 16854 16855 if (Val) 16856 Val = DefaultLvalueConversion(Val).get(); 16857 16858 if (Val) { 16859 if (Enum->isDependentType() || Val->isTypeDependent()) 16860 EltTy = Context.DependentTy; 16861 else { 16862 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 16863 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 16864 // constant-expression in the enumerator-definition shall be a converted 16865 // constant expression of the underlying type. 16866 EltTy = Enum->getIntegerType(); 16867 ExprResult Converted = 16868 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 16869 CCEK_Enumerator); 16870 if (Converted.isInvalid()) 16871 Val = nullptr; 16872 else 16873 Val = Converted.get(); 16874 } else if (!Val->isValueDependent() && 16875 !(Val = VerifyIntegerConstantExpression(Val, 16876 &EnumVal).get())) { 16877 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 16878 } else { 16879 if (Enum->isComplete()) { 16880 EltTy = Enum->getIntegerType(); 16881 16882 // In Obj-C and Microsoft mode, require the enumeration value to be 16883 // representable in the underlying type of the enumeration. In C++11, 16884 // we perform a non-narrowing conversion as part of converted constant 16885 // expression checking. 16886 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16887 if (Context.getTargetInfo() 16888 .getTriple() 16889 .isWindowsMSVCEnvironment()) { 16890 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 16891 } else { 16892 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 16893 } 16894 } 16895 16896 // Cast to the underlying type. 16897 Val = ImpCastExprToType(Val, EltTy, 16898 EltTy->isBooleanType() ? CK_IntegralToBoolean 16899 : CK_IntegralCast) 16900 .get(); 16901 } else if (getLangOpts().CPlusPlus) { 16902 // C++11 [dcl.enum]p5: 16903 // If the underlying type is not fixed, the type of each enumerator 16904 // is the type of its initializing value: 16905 // - If an initializer is specified for an enumerator, the 16906 // initializing value has the same type as the expression. 16907 EltTy = Val->getType(); 16908 } else { 16909 // C99 6.7.2.2p2: 16910 // The expression that defines the value of an enumeration constant 16911 // shall be an integer constant expression that has a value 16912 // representable as an int. 16913 16914 // Complain if the value is not representable in an int. 16915 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 16916 Diag(IdLoc, diag::ext_enum_value_not_int) 16917 << EnumVal.toString(10) << Val->getSourceRange() 16918 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 16919 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 16920 // Force the type of the expression to 'int'. 16921 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 16922 } 16923 EltTy = Val->getType(); 16924 } 16925 } 16926 } 16927 } 16928 16929 if (!Val) { 16930 if (Enum->isDependentType()) 16931 EltTy = Context.DependentTy; 16932 else if (!LastEnumConst) { 16933 // C++0x [dcl.enum]p5: 16934 // If the underlying type is not fixed, the type of each enumerator 16935 // is the type of its initializing value: 16936 // - If no initializer is specified for the first enumerator, the 16937 // initializing value has an unspecified integral type. 16938 // 16939 // GCC uses 'int' for its unspecified integral type, as does 16940 // C99 6.7.2.2p3. 16941 if (Enum->isFixed()) { 16942 EltTy = Enum->getIntegerType(); 16943 } 16944 else { 16945 EltTy = Context.IntTy; 16946 } 16947 } else { 16948 // Assign the last value + 1. 16949 EnumVal = LastEnumConst->getInitVal(); 16950 ++EnumVal; 16951 EltTy = LastEnumConst->getType(); 16952 16953 // Check for overflow on increment. 16954 if (EnumVal < LastEnumConst->getInitVal()) { 16955 // C++0x [dcl.enum]p5: 16956 // If the underlying type is not fixed, the type of each enumerator 16957 // is the type of its initializing value: 16958 // 16959 // - Otherwise the type of the initializing value is the same as 16960 // the type of the initializing value of the preceding enumerator 16961 // unless the incremented value is not representable in that type, 16962 // in which case the type is an unspecified integral type 16963 // sufficient to contain the incremented value. If no such type 16964 // exists, the program is ill-formed. 16965 QualType T = getNextLargerIntegralType(Context, EltTy); 16966 if (T.isNull() || Enum->isFixed()) { 16967 // There is no integral type larger enough to represent this 16968 // value. Complain, then allow the value to wrap around. 16969 EnumVal = LastEnumConst->getInitVal(); 16970 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 16971 ++EnumVal; 16972 if (Enum->isFixed()) 16973 // When the underlying type is fixed, this is ill-formed. 16974 Diag(IdLoc, diag::err_enumerator_wrapped) 16975 << EnumVal.toString(10) 16976 << EltTy; 16977 else 16978 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 16979 << EnumVal.toString(10); 16980 } else { 16981 EltTy = T; 16982 } 16983 16984 // Retrieve the last enumerator's value, extent that type to the 16985 // type that is supposed to be large enough to represent the incremented 16986 // value, then increment. 16987 EnumVal = LastEnumConst->getInitVal(); 16988 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16989 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 16990 ++EnumVal; 16991 16992 // If we're not in C++, diagnose the overflow of enumerator values, 16993 // which in C99 means that the enumerator value is not representable in 16994 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 16995 // permits enumerator values that are representable in some larger 16996 // integral type. 16997 if (!getLangOpts().CPlusPlus && !T.isNull()) 16998 Diag(IdLoc, diag::warn_enum_value_overflow); 16999 } else if (!getLangOpts().CPlusPlus && 17000 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17001 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17002 Diag(IdLoc, diag::ext_enum_value_not_int) 17003 << EnumVal.toString(10) << 1; 17004 } 17005 } 17006 } 17007 17008 if (!EltTy->isDependentType()) { 17009 // Make the enumerator value match the signedness and size of the 17010 // enumerator's type. 17011 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17012 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17013 } 17014 17015 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17016 Val, EnumVal); 17017 } 17018 17019 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17020 SourceLocation IILoc) { 17021 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17022 !getLangOpts().CPlusPlus) 17023 return SkipBodyInfo(); 17024 17025 // We have an anonymous enum definition. Look up the first enumerator to 17026 // determine if we should merge the definition with an existing one and 17027 // skip the body. 17028 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17029 forRedeclarationInCurContext()); 17030 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17031 if (!PrevECD) 17032 return SkipBodyInfo(); 17033 17034 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17035 NamedDecl *Hidden; 17036 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17037 SkipBodyInfo Skip; 17038 Skip.Previous = Hidden; 17039 return Skip; 17040 } 17041 17042 return SkipBodyInfo(); 17043 } 17044 17045 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17046 SourceLocation IdLoc, IdentifierInfo *Id, 17047 const ParsedAttributesView &Attrs, 17048 SourceLocation EqualLoc, Expr *Val) { 17049 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17050 EnumConstantDecl *LastEnumConst = 17051 cast_or_null<EnumConstantDecl>(lastEnumConst); 17052 17053 // The scope passed in may not be a decl scope. Zip up the scope tree until 17054 // we find one that is. 17055 S = getNonFieldDeclScope(S); 17056 17057 // Verify that there isn't already something declared with this name in this 17058 // scope. 17059 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17060 LookupName(R, S); 17061 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17062 17063 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17064 // Maybe we will complain about the shadowed template parameter. 17065 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17066 // Just pretend that we didn't see the previous declaration. 17067 PrevDecl = nullptr; 17068 } 17069 17070 // C++ [class.mem]p15: 17071 // If T is the name of a class, then each of the following shall have a name 17072 // different from T: 17073 // - every enumerator of every member of class T that is an unscoped 17074 // enumerated type 17075 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17076 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17077 DeclarationNameInfo(Id, IdLoc)); 17078 17079 EnumConstantDecl *New = 17080 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17081 if (!New) 17082 return nullptr; 17083 17084 if (PrevDecl) { 17085 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17086 // Check for other kinds of shadowing not already handled. 17087 CheckShadow(New, PrevDecl, R); 17088 } 17089 17090 // When in C++, we may get a TagDecl with the same name; in this case the 17091 // enum constant will 'hide' the tag. 17092 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17093 "Received TagDecl when not in C++!"); 17094 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17095 if (isa<EnumConstantDecl>(PrevDecl)) 17096 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17097 else 17098 Diag(IdLoc, diag::err_redefinition) << Id; 17099 notePreviousDefinition(PrevDecl, IdLoc); 17100 return nullptr; 17101 } 17102 } 17103 17104 // Process attributes. 17105 ProcessDeclAttributeList(S, New, Attrs); 17106 AddPragmaAttributes(S, New); 17107 17108 // Register this decl in the current scope stack. 17109 New->setAccess(TheEnumDecl->getAccess()); 17110 PushOnScopeChains(New, S); 17111 17112 ActOnDocumentableDecl(New); 17113 17114 return New; 17115 } 17116 17117 // Returns true when the enum initial expression does not trigger the 17118 // duplicate enum warning. A few common cases are exempted as follows: 17119 // Element2 = Element1 17120 // Element2 = Element1 + 1 17121 // Element2 = Element1 - 1 17122 // Where Element2 and Element1 are from the same enum. 17123 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17124 Expr *InitExpr = ECD->getInitExpr(); 17125 if (!InitExpr) 17126 return true; 17127 InitExpr = InitExpr->IgnoreImpCasts(); 17128 17129 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17130 if (!BO->isAdditiveOp()) 17131 return true; 17132 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17133 if (!IL) 17134 return true; 17135 if (IL->getValue() != 1) 17136 return true; 17137 17138 InitExpr = BO->getLHS(); 17139 } 17140 17141 // This checks if the elements are from the same enum. 17142 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17143 if (!DRE) 17144 return true; 17145 17146 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17147 if (!EnumConstant) 17148 return true; 17149 17150 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17151 Enum) 17152 return true; 17153 17154 return false; 17155 } 17156 17157 // Emits a warning when an element is implicitly set a value that 17158 // a previous element has already been set to. 17159 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17160 EnumDecl *Enum, QualType EnumType) { 17161 // Avoid anonymous enums 17162 if (!Enum->getIdentifier()) 17163 return; 17164 17165 // Only check for small enums. 17166 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17167 return; 17168 17169 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17170 return; 17171 17172 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17173 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17174 17175 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17176 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17177 17178 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 17179 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17180 llvm::APSInt Val = D->getInitVal(); 17181 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17182 }; 17183 17184 DuplicatesVector DupVector; 17185 ValueToVectorMap EnumMap; 17186 17187 // Populate the EnumMap with all values represented by enum constants without 17188 // an initializer. 17189 for (auto *Element : Elements) { 17190 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17191 17192 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17193 // this constant. Skip this enum since it may be ill-formed. 17194 if (!ECD) { 17195 return; 17196 } 17197 17198 // Constants with initalizers are handled in the next loop. 17199 if (ECD->getInitExpr()) 17200 continue; 17201 17202 // Duplicate values are handled in the next loop. 17203 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17204 } 17205 17206 if (EnumMap.size() == 0) 17207 return; 17208 17209 // Create vectors for any values that has duplicates. 17210 for (auto *Element : Elements) { 17211 // The last loop returned if any constant was null. 17212 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17213 if (!ValidDuplicateEnum(ECD, Enum)) 17214 continue; 17215 17216 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17217 if (Iter == EnumMap.end()) 17218 continue; 17219 17220 DeclOrVector& Entry = Iter->second; 17221 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17222 // Ensure constants are different. 17223 if (D == ECD) 17224 continue; 17225 17226 // Create new vector and push values onto it. 17227 auto Vec = std::make_unique<ECDVector>(); 17228 Vec->push_back(D); 17229 Vec->push_back(ECD); 17230 17231 // Update entry to point to the duplicates vector. 17232 Entry = Vec.get(); 17233 17234 // Store the vector somewhere we can consult later for quick emission of 17235 // diagnostics. 17236 DupVector.emplace_back(std::move(Vec)); 17237 continue; 17238 } 17239 17240 ECDVector *Vec = Entry.get<ECDVector*>(); 17241 // Make sure constants are not added more than once. 17242 if (*Vec->begin() == ECD) 17243 continue; 17244 17245 Vec->push_back(ECD); 17246 } 17247 17248 // Emit diagnostics. 17249 for (const auto &Vec : DupVector) { 17250 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17251 17252 // Emit warning for one enum constant. 17253 auto *FirstECD = Vec->front(); 17254 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17255 << FirstECD << FirstECD->getInitVal().toString(10) 17256 << FirstECD->getSourceRange(); 17257 17258 // Emit one note for each of the remaining enum constants with 17259 // the same value. 17260 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17261 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17262 << ECD << ECD->getInitVal().toString(10) 17263 << ECD->getSourceRange(); 17264 } 17265 } 17266 17267 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17268 bool AllowMask) const { 17269 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17270 assert(ED->isCompleteDefinition() && "expected enum definition"); 17271 17272 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17273 llvm::APInt &FlagBits = R.first->second; 17274 17275 if (R.second) { 17276 for (auto *E : ED->enumerators()) { 17277 const auto &EVal = E->getInitVal(); 17278 // Only single-bit enumerators introduce new flag values. 17279 if (EVal.isPowerOf2()) 17280 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17281 } 17282 } 17283 17284 // A value is in a flag enum if either its bits are a subset of the enum's 17285 // flag bits (the first condition) or we are allowing masks and the same is 17286 // true of its complement (the second condition). When masks are allowed, we 17287 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17288 // 17289 // While it's true that any value could be used as a mask, the assumption is 17290 // that a mask will have all of the insignificant bits set. Anything else is 17291 // likely a logic error. 17292 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17293 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17294 } 17295 17296 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17297 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17298 const ParsedAttributesView &Attrs) { 17299 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17300 QualType EnumType = Context.getTypeDeclType(Enum); 17301 17302 ProcessDeclAttributeList(S, Enum, Attrs); 17303 17304 if (Enum->isDependentType()) { 17305 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17306 EnumConstantDecl *ECD = 17307 cast_or_null<EnumConstantDecl>(Elements[i]); 17308 if (!ECD) continue; 17309 17310 ECD->setType(EnumType); 17311 } 17312 17313 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17314 return; 17315 } 17316 17317 // TODO: If the result value doesn't fit in an int, it must be a long or long 17318 // long value. ISO C does not support this, but GCC does as an extension, 17319 // emit a warning. 17320 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17321 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17322 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17323 17324 // Verify that all the values are okay, compute the size of the values, and 17325 // reverse the list. 17326 unsigned NumNegativeBits = 0; 17327 unsigned NumPositiveBits = 0; 17328 17329 // Keep track of whether all elements have type int. 17330 bool AllElementsInt = true; 17331 17332 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17333 EnumConstantDecl *ECD = 17334 cast_or_null<EnumConstantDecl>(Elements[i]); 17335 if (!ECD) continue; // Already issued a diagnostic. 17336 17337 const llvm::APSInt &InitVal = ECD->getInitVal(); 17338 17339 // Keep track of the size of positive and negative values. 17340 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17341 NumPositiveBits = std::max(NumPositiveBits, 17342 (unsigned)InitVal.getActiveBits()); 17343 else 17344 NumNegativeBits = std::max(NumNegativeBits, 17345 (unsigned)InitVal.getMinSignedBits()); 17346 17347 // Keep track of whether every enum element has type int (very common). 17348 if (AllElementsInt) 17349 AllElementsInt = ECD->getType() == Context.IntTy; 17350 } 17351 17352 // Figure out the type that should be used for this enum. 17353 QualType BestType; 17354 unsigned BestWidth; 17355 17356 // C++0x N3000 [conv.prom]p3: 17357 // An rvalue of an unscoped enumeration type whose underlying 17358 // type is not fixed can be converted to an rvalue of the first 17359 // of the following types that can represent all the values of 17360 // the enumeration: int, unsigned int, long int, unsigned long 17361 // int, long long int, or unsigned long long int. 17362 // C99 6.4.4.3p2: 17363 // An identifier declared as an enumeration constant has type int. 17364 // The C99 rule is modified by a gcc extension 17365 QualType BestPromotionType; 17366 17367 bool Packed = Enum->hasAttr<PackedAttr>(); 17368 // -fshort-enums is the equivalent to specifying the packed attribute on all 17369 // enum definitions. 17370 if (LangOpts.ShortEnums) 17371 Packed = true; 17372 17373 // If the enum already has a type because it is fixed or dictated by the 17374 // target, promote that type instead of analyzing the enumerators. 17375 if (Enum->isComplete()) { 17376 BestType = Enum->getIntegerType(); 17377 if (BestType->isPromotableIntegerType()) 17378 BestPromotionType = Context.getPromotedIntegerType(BestType); 17379 else 17380 BestPromotionType = BestType; 17381 17382 BestWidth = Context.getIntWidth(BestType); 17383 } 17384 else if (NumNegativeBits) { 17385 // If there is a negative value, figure out the smallest integer type (of 17386 // int/long/longlong) that fits. 17387 // If it's packed, check also if it fits a char or a short. 17388 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17389 BestType = Context.SignedCharTy; 17390 BestWidth = CharWidth; 17391 } else if (Packed && NumNegativeBits <= ShortWidth && 17392 NumPositiveBits < ShortWidth) { 17393 BestType = Context.ShortTy; 17394 BestWidth = ShortWidth; 17395 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17396 BestType = Context.IntTy; 17397 BestWidth = IntWidth; 17398 } else { 17399 BestWidth = Context.getTargetInfo().getLongWidth(); 17400 17401 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17402 BestType = Context.LongTy; 17403 } else { 17404 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17405 17406 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17407 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17408 BestType = Context.LongLongTy; 17409 } 17410 } 17411 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17412 } else { 17413 // If there is no negative value, figure out the smallest type that fits 17414 // all of the enumerator values. 17415 // If it's packed, check also if it fits a char or a short. 17416 if (Packed && NumPositiveBits <= CharWidth) { 17417 BestType = Context.UnsignedCharTy; 17418 BestPromotionType = Context.IntTy; 17419 BestWidth = CharWidth; 17420 } else if (Packed && NumPositiveBits <= ShortWidth) { 17421 BestType = Context.UnsignedShortTy; 17422 BestPromotionType = Context.IntTy; 17423 BestWidth = ShortWidth; 17424 } else if (NumPositiveBits <= IntWidth) { 17425 BestType = Context.UnsignedIntTy; 17426 BestWidth = IntWidth; 17427 BestPromotionType 17428 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17429 ? Context.UnsignedIntTy : Context.IntTy; 17430 } else if (NumPositiveBits <= 17431 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17432 BestType = Context.UnsignedLongTy; 17433 BestPromotionType 17434 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17435 ? Context.UnsignedLongTy : Context.LongTy; 17436 } else { 17437 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17438 assert(NumPositiveBits <= BestWidth && 17439 "How could an initializer get larger than ULL?"); 17440 BestType = Context.UnsignedLongLongTy; 17441 BestPromotionType 17442 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17443 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17444 } 17445 } 17446 17447 // Loop over all of the enumerator constants, changing their types to match 17448 // the type of the enum if needed. 17449 for (auto *D : Elements) { 17450 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17451 if (!ECD) continue; // Already issued a diagnostic. 17452 17453 // Standard C says the enumerators have int type, but we allow, as an 17454 // extension, the enumerators to be larger than int size. If each 17455 // enumerator value fits in an int, type it as an int, otherwise type it the 17456 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17457 // that X has type 'int', not 'unsigned'. 17458 17459 // Determine whether the value fits into an int. 17460 llvm::APSInt InitVal = ECD->getInitVal(); 17461 17462 // If it fits into an integer type, force it. Otherwise force it to match 17463 // the enum decl type. 17464 QualType NewTy; 17465 unsigned NewWidth; 17466 bool NewSign; 17467 if (!getLangOpts().CPlusPlus && 17468 !Enum->isFixed() && 17469 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17470 NewTy = Context.IntTy; 17471 NewWidth = IntWidth; 17472 NewSign = true; 17473 } else if (ECD->getType() == BestType) { 17474 // Already the right type! 17475 if (getLangOpts().CPlusPlus) 17476 // C++ [dcl.enum]p4: Following the closing brace of an 17477 // enum-specifier, each enumerator has the type of its 17478 // enumeration. 17479 ECD->setType(EnumType); 17480 continue; 17481 } else { 17482 NewTy = BestType; 17483 NewWidth = BestWidth; 17484 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17485 } 17486 17487 // Adjust the APSInt value. 17488 InitVal = InitVal.extOrTrunc(NewWidth); 17489 InitVal.setIsSigned(NewSign); 17490 ECD->setInitVal(InitVal); 17491 17492 // Adjust the Expr initializer and type. 17493 if (ECD->getInitExpr() && 17494 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 17495 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 17496 CK_IntegralCast, 17497 ECD->getInitExpr(), 17498 /*base paths*/ nullptr, 17499 VK_RValue)); 17500 if (getLangOpts().CPlusPlus) 17501 // C++ [dcl.enum]p4: Following the closing brace of an 17502 // enum-specifier, each enumerator has the type of its 17503 // enumeration. 17504 ECD->setType(EnumType); 17505 else 17506 ECD->setType(NewTy); 17507 } 17508 17509 Enum->completeDefinition(BestType, BestPromotionType, 17510 NumPositiveBits, NumNegativeBits); 17511 17512 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 17513 17514 if (Enum->isClosedFlag()) { 17515 for (Decl *D : Elements) { 17516 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 17517 if (!ECD) continue; // Already issued a diagnostic. 17518 17519 llvm::APSInt InitVal = ECD->getInitVal(); 17520 if (InitVal != 0 && !InitVal.isPowerOf2() && 17521 !IsValueInFlagEnum(Enum, InitVal, true)) 17522 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 17523 << ECD << Enum; 17524 } 17525 } 17526 17527 // Now that the enum type is defined, ensure it's not been underaligned. 17528 if (Enum->hasAttrs()) 17529 CheckAlignasUnderalignment(Enum); 17530 } 17531 17532 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 17533 SourceLocation StartLoc, 17534 SourceLocation EndLoc) { 17535 StringLiteral *AsmString = cast<StringLiteral>(expr); 17536 17537 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 17538 AsmString, StartLoc, 17539 EndLoc); 17540 CurContext->addDecl(New); 17541 return New; 17542 } 17543 17544 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17545 IdentifierInfo* AliasName, 17546 SourceLocation PragmaLoc, 17547 SourceLocation NameLoc, 17548 SourceLocation AliasNameLoc) { 17549 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17550 LookupOrdinaryName); 17551 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 17552 AttributeCommonInfo::AS_Pragma); 17553 AsmLabelAttr *Attr = 17554 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info); 17555 17556 // If a declaration that: 17557 // 1) declares a function or a variable 17558 // 2) has external linkage 17559 // already exists, add a label attribute to it. 17560 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17561 if (isDeclExternC(PrevDecl)) 17562 PrevDecl->addAttr(Attr); 17563 else 17564 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17565 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17566 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17567 } else 17568 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17569 } 17570 17571 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17572 SourceLocation PragmaLoc, 17573 SourceLocation NameLoc) { 17574 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17575 17576 if (PrevDecl) { 17577 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 17578 } else { 17579 (void)WeakUndeclaredIdentifiers.insert( 17580 std::pair<IdentifierInfo*,WeakInfo> 17581 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17582 } 17583 } 17584 17585 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17586 IdentifierInfo* AliasName, 17587 SourceLocation PragmaLoc, 17588 SourceLocation NameLoc, 17589 SourceLocation AliasNameLoc) { 17590 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17591 LookupOrdinaryName); 17592 WeakInfo W = WeakInfo(Name, NameLoc); 17593 17594 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17595 if (!PrevDecl->hasAttr<AliasAttr>()) 17596 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17597 DeclApplyPragmaWeak(TUScope, ND, W); 17598 } else { 17599 (void)WeakUndeclaredIdentifiers.insert( 17600 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 17601 } 17602 } 17603 17604 Decl *Sema::getObjCDeclContext() const { 17605 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 17606 } 17607