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/StmtCXX.h" 26 #include "clang/Basic/Builtins.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 32 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 34 #include "clang/Sema/CXXFieldCollector.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Initialization.h" 38 #include "clang/Sema/Lookup.h" 39 #include "clang/Sema/ParsedTemplate.h" 40 #include "clang/Sema/Scope.h" 41 #include "clang/Sema/ScopeInfo.h" 42 #include "clang/Sema/SemaInternal.h" 43 #include "clang/Sema/Template.h" 44 #include "llvm/ADT/SmallString.h" 45 #include "llvm/ADT/Triple.h" 46 #include <algorithm> 47 #include <cstring> 48 #include <functional> 49 50 using namespace clang; 51 using namespace sema; 52 53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 54 if (OwnedType) { 55 Decl *Group[2] = { OwnedType, Ptr }; 56 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 57 } 58 59 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 60 } 61 62 namespace { 63 64 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 65 public: 66 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 67 bool AllowTemplates = false, 68 bool AllowNonTemplates = true) 69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 70 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 71 WantExpressionKeywords = false; 72 WantCXXNamedCasts = false; 73 WantRemainingKeywords = false; 74 } 75 76 bool ValidateCandidate(const TypoCorrection &candidate) override { 77 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 78 if (!AllowInvalidDecl && ND->isInvalidDecl()) 79 return false; 80 81 if (getAsTypeTemplateDecl(ND)) 82 return AllowTemplates; 83 84 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 85 if (!IsType) 86 return false; 87 88 if (AllowNonTemplates) 89 return true; 90 91 // An injected-class-name of a class template (specialization) is valid 92 // as a template or as a non-template. 93 if (AllowTemplates) { 94 auto *RD = dyn_cast<CXXRecordDecl>(ND); 95 if (!RD || !RD->isInjectedClassName()) 96 return false; 97 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 98 return RD->getDescribedClassTemplate() || 99 isa<ClassTemplateSpecializationDecl>(RD); 100 } 101 102 return false; 103 } 104 105 return !WantClassName && candidate.isKeyword(); 106 } 107 108 std::unique_ptr<CorrectionCandidateCallback> clone() override { 109 return llvm::make_unique<TypeNameValidatorCCC>(*this); 110 } 111 112 private: 113 bool AllowInvalidDecl; 114 bool WantClassName; 115 bool AllowTemplates; 116 bool AllowNonTemplates; 117 }; 118 119 } // end anonymous namespace 120 121 /// Determine whether the token kind starts a simple-type-specifier. 122 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 123 switch (Kind) { 124 // FIXME: Take into account the current language when deciding whether a 125 // token kind is a valid type specifier 126 case tok::kw_short: 127 case tok::kw_long: 128 case tok::kw___int64: 129 case tok::kw___int128: 130 case tok::kw_signed: 131 case tok::kw_unsigned: 132 case tok::kw_void: 133 case tok::kw_char: 134 case tok::kw_int: 135 case tok::kw_half: 136 case tok::kw_float: 137 case tok::kw_double: 138 case tok::kw__Float16: 139 case tok::kw___float128: 140 case tok::kw_wchar_t: 141 case tok::kw_bool: 142 case tok::kw___underlying_type: 143 case tok::kw___auto_type: 144 return true; 145 146 case tok::annot_typename: 147 case tok::kw_char16_t: 148 case tok::kw_char32_t: 149 case tok::kw_typeof: 150 case tok::annot_decltype: 151 case tok::kw_decltype: 152 return getLangOpts().CPlusPlus; 153 154 case tok::kw_char8_t: 155 return getLangOpts().Char8; 156 157 default: 158 break; 159 } 160 161 return false; 162 } 163 164 namespace { 165 enum class UnqualifiedTypeNameLookupResult { 166 NotFound, 167 FoundNonType, 168 FoundType 169 }; 170 } // end anonymous namespace 171 172 /// Tries to perform unqualified lookup of the type decls in bases for 173 /// dependent class. 174 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 175 /// type decl, \a FoundType if only type decls are found. 176 static UnqualifiedTypeNameLookupResult 177 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 178 SourceLocation NameLoc, 179 const CXXRecordDecl *RD) { 180 if (!RD->hasDefinition()) 181 return UnqualifiedTypeNameLookupResult::NotFound; 182 // Look for type decls in base classes. 183 UnqualifiedTypeNameLookupResult FoundTypeDecl = 184 UnqualifiedTypeNameLookupResult::NotFound; 185 for (const auto &Base : RD->bases()) { 186 const CXXRecordDecl *BaseRD = nullptr; 187 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 188 BaseRD = BaseTT->getAsCXXRecordDecl(); 189 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 190 // Look for type decls in dependent base classes that have known primary 191 // templates. 192 if (!TST || !TST->isDependentType()) 193 continue; 194 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 195 if (!TD) 196 continue; 197 if (auto *BasePrimaryTemplate = 198 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 199 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 200 BaseRD = BasePrimaryTemplate; 201 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 202 if (const ClassTemplatePartialSpecializationDecl *PS = 203 CTD->findPartialSpecialization(Base.getType())) 204 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 205 BaseRD = PS; 206 } 207 } 208 } 209 if (BaseRD) { 210 for (NamedDecl *ND : BaseRD->lookup(&II)) { 211 if (!isa<TypeDecl>(ND)) 212 return UnqualifiedTypeNameLookupResult::FoundNonType; 213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 214 } 215 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 216 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 217 case UnqualifiedTypeNameLookupResult::FoundNonType: 218 return UnqualifiedTypeNameLookupResult::FoundNonType; 219 case UnqualifiedTypeNameLookupResult::FoundType: 220 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 221 break; 222 case UnqualifiedTypeNameLookupResult::NotFound: 223 break; 224 } 225 } 226 } 227 } 228 229 return FoundTypeDecl; 230 } 231 232 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 233 const IdentifierInfo &II, 234 SourceLocation NameLoc) { 235 // Lookup in the parent class template context, if any. 236 const CXXRecordDecl *RD = nullptr; 237 UnqualifiedTypeNameLookupResult FoundTypeDecl = 238 UnqualifiedTypeNameLookupResult::NotFound; 239 for (DeclContext *DC = S.CurContext; 240 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 241 DC = DC->getParent()) { 242 // Look for type decls in dependent base classes that have known primary 243 // templates. 244 RD = dyn_cast<CXXRecordDecl>(DC); 245 if (RD && RD->getDescribedClassTemplate()) 246 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 247 } 248 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 249 return nullptr; 250 251 // We found some types in dependent base classes. Recover as if the user 252 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 253 // lookup during template instantiation. 254 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 255 256 ASTContext &Context = S.Context; 257 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 258 cast<Type>(Context.getRecordType(RD))); 259 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 260 261 CXXScopeSpec SS; 262 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 263 264 TypeLocBuilder Builder; 265 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 266 DepTL.setNameLoc(NameLoc); 267 DepTL.setElaboratedKeywordLoc(SourceLocation()); 268 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 269 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 270 } 271 272 /// If the identifier refers to a type name within this scope, 273 /// return the declaration of that type. 274 /// 275 /// This routine performs ordinary name lookup of the identifier II 276 /// within the given scope, with optional C++ scope specifier SS, to 277 /// determine whether the name refers to a type. If so, returns an 278 /// opaque pointer (actually a QualType) corresponding to that 279 /// type. Otherwise, returns NULL. 280 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 281 Scope *S, CXXScopeSpec *SS, 282 bool isClassName, bool HasTrailingDot, 283 ParsedType ObjectTypePtr, 284 bool IsCtorOrDtorName, 285 bool WantNontrivialTypeSourceInfo, 286 bool IsClassTemplateDeductionContext, 287 IdentifierInfo **CorrectedII) { 288 // FIXME: Consider allowing this outside C++1z mode as an extension. 289 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 290 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 291 !isClassName && !HasTrailingDot; 292 293 // Determine where we will perform name lookup. 294 DeclContext *LookupCtx = nullptr; 295 if (ObjectTypePtr) { 296 QualType ObjectType = ObjectTypePtr.get(); 297 if (ObjectType->isRecordType()) 298 LookupCtx = computeDeclContext(ObjectType); 299 } else if (SS && SS->isNotEmpty()) { 300 LookupCtx = computeDeclContext(*SS, false); 301 302 if (!LookupCtx) { 303 if (isDependentScopeSpecifier(*SS)) { 304 // C++ [temp.res]p3: 305 // A qualified-id that refers to a type and in which the 306 // nested-name-specifier depends on a template-parameter (14.6.2) 307 // shall be prefixed by the keyword typename to indicate that the 308 // qualified-id denotes a type, forming an 309 // elaborated-type-specifier (7.1.5.3). 310 // 311 // We therefore do not perform any name lookup if the result would 312 // refer to a member of an unknown specialization. 313 if (!isClassName && !IsCtorOrDtorName) 314 return nullptr; 315 316 // We know from the grammar that this name refers to a type, 317 // so build a dependent node to describe the type. 318 if (WantNontrivialTypeSourceInfo) 319 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 320 321 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 322 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 323 II, NameLoc); 324 return ParsedType::make(T); 325 } 326 327 return nullptr; 328 } 329 330 if (!LookupCtx->isDependentContext() && 331 RequireCompleteDeclContext(*SS, LookupCtx)) 332 return nullptr; 333 } 334 335 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 336 // lookup for class-names. 337 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 338 LookupOrdinaryName; 339 LookupResult Result(*this, &II, NameLoc, Kind); 340 if (LookupCtx) { 341 // Perform "qualified" name lookup into the declaration context we 342 // computed, which is either the type of the base of a member access 343 // expression or the declaration context associated with a prior 344 // nested-name-specifier. 345 LookupQualifiedName(Result, LookupCtx); 346 347 if (ObjectTypePtr && Result.empty()) { 348 // C++ [basic.lookup.classref]p3: 349 // If the unqualified-id is ~type-name, the type-name is looked up 350 // in the context of the entire postfix-expression. If the type T of 351 // the object expression is of a class type C, the type-name is also 352 // looked up in the scope of class C. At least one of the lookups shall 353 // find a name that refers to (possibly cv-qualified) T. 354 LookupName(Result, S); 355 } 356 } else { 357 // Perform unqualified name lookup. 358 LookupName(Result, S); 359 360 // For unqualified lookup in a class template in MSVC mode, look into 361 // dependent base classes where the primary class template is known. 362 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 363 if (ParsedType TypeInBase = 364 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 365 return TypeInBase; 366 } 367 } 368 369 NamedDecl *IIDecl = nullptr; 370 switch (Result.getResultKind()) { 371 case LookupResult::NotFound: 372 case LookupResult::NotFoundInCurrentInstantiation: 373 if (CorrectedII) { 374 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 375 AllowDeducedTemplate); 376 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 377 S, SS, CCC, CTK_ErrorRecovery); 378 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 379 TemplateTy Template; 380 bool MemberOfUnknownSpecialization; 381 UnqualifiedId TemplateName; 382 TemplateName.setIdentifier(NewII, NameLoc); 383 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 384 CXXScopeSpec NewSS, *NewSSPtr = SS; 385 if (SS && NNS) { 386 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 387 NewSSPtr = &NewSS; 388 } 389 if (Correction && (NNS || NewII != &II) && 390 // Ignore a correction to a template type as the to-be-corrected 391 // identifier is not a template (typo correction for template names 392 // is handled elsewhere). 393 !(getLangOpts().CPlusPlus && NewSSPtr && 394 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 395 Template, MemberOfUnknownSpecialization))) { 396 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 397 isClassName, HasTrailingDot, ObjectTypePtr, 398 IsCtorOrDtorName, 399 WantNontrivialTypeSourceInfo, 400 IsClassTemplateDeductionContext); 401 if (Ty) { 402 diagnoseTypo(Correction, 403 PDiag(diag::err_unknown_type_or_class_name_suggest) 404 << Result.getLookupName() << isClassName); 405 if (SS && NNS) 406 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 407 *CorrectedII = NewII; 408 return Ty; 409 } 410 } 411 } 412 // If typo correction failed or was not performed, fall through 413 LLVM_FALLTHROUGH; 414 case LookupResult::FoundOverloaded: 415 case LookupResult::FoundUnresolvedValue: 416 Result.suppressDiagnostics(); 417 return nullptr; 418 419 case LookupResult::Ambiguous: 420 // Recover from type-hiding ambiguities by hiding the type. We'll 421 // do the lookup again when looking for an object, and we can 422 // diagnose the error then. If we don't do this, then the error 423 // about hiding the type will be immediately followed by an error 424 // that only makes sense if the identifier was treated like a type. 425 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 426 Result.suppressDiagnostics(); 427 return nullptr; 428 } 429 430 // Look to see if we have a type anywhere in the list of results. 431 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 432 Res != ResEnd; ++Res) { 433 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 434 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 435 if (!IIDecl || 436 (*Res)->getLocation().getRawEncoding() < 437 IIDecl->getLocation().getRawEncoding()) 438 IIDecl = *Res; 439 } 440 } 441 442 if (!IIDecl) { 443 // None of the entities we found is a type, so there is no way 444 // to even assume that the result is a type. In this case, don't 445 // complain about the ambiguity. The parser will either try to 446 // perform this lookup again (e.g., as an object name), which 447 // will produce the ambiguity, or will complain that it expected 448 // a type name. 449 Result.suppressDiagnostics(); 450 return nullptr; 451 } 452 453 // We found a type within the ambiguous lookup; diagnose the 454 // ambiguity and then return that type. This might be the right 455 // answer, or it might not be, but it suppresses any attempt to 456 // perform the name lookup again. 457 break; 458 459 case LookupResult::Found: 460 IIDecl = Result.getFoundDecl(); 461 break; 462 } 463 464 assert(IIDecl && "Didn't find decl"); 465 466 QualType T; 467 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 468 // C++ [class.qual]p2: A lookup that would find the injected-class-name 469 // instead names the constructors of the class, except when naming a class. 470 // This is ill-formed when we're not actually forming a ctor or dtor name. 471 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 472 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 473 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 474 FoundRD->isInjectedClassName() && 475 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 476 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 477 << &II << /*Type*/1; 478 479 DiagnoseUseOfDecl(IIDecl, NameLoc); 480 481 T = Context.getTypeDeclType(TD); 482 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 483 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 484 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 485 if (!HasTrailingDot) 486 T = Context.getObjCInterfaceType(IDecl); 487 } else if (AllowDeducedTemplate) { 488 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 489 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 490 QualType(), false); 491 } 492 493 if (T.isNull()) { 494 // If it's not plausibly a type, suppress diagnostics. 495 Result.suppressDiagnostics(); 496 return nullptr; 497 } 498 499 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 500 // constructor or destructor name (in such a case, the scope specifier 501 // will be attached to the enclosing Expr or Decl node). 502 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 503 !isa<ObjCInterfaceDecl>(IIDecl)) { 504 if (WantNontrivialTypeSourceInfo) { 505 // Construct a type with type-source information. 506 TypeLocBuilder Builder; 507 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 508 509 T = getElaboratedType(ETK_None, *SS, T); 510 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 511 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 512 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 513 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 514 } else { 515 T = getElaboratedType(ETK_None, *SS, T); 516 } 517 } 518 519 return ParsedType::make(T); 520 } 521 522 // Builds a fake NNS for the given decl context. 523 static NestedNameSpecifier * 524 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 525 for (;; DC = DC->getLookupParent()) { 526 DC = DC->getPrimaryContext(); 527 auto *ND = dyn_cast<NamespaceDecl>(DC); 528 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 529 return NestedNameSpecifier::Create(Context, nullptr, ND); 530 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 531 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 532 RD->getTypeForDecl()); 533 else if (isa<TranslationUnitDecl>(DC)) 534 return NestedNameSpecifier::GlobalSpecifier(Context); 535 } 536 llvm_unreachable("something isn't in TU scope?"); 537 } 538 539 /// Find the parent class with dependent bases of the innermost enclosing method 540 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 541 /// up allowing unqualified dependent type names at class-level, which MSVC 542 /// correctly rejects. 543 static const CXXRecordDecl * 544 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 545 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 546 DC = DC->getPrimaryContext(); 547 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 548 if (MD->getParent()->hasAnyDependentBases()) 549 return MD->getParent(); 550 } 551 return nullptr; 552 } 553 554 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 555 SourceLocation NameLoc, 556 bool IsTemplateTypeArg) { 557 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 558 559 NestedNameSpecifier *NNS = nullptr; 560 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 561 // If we weren't able to parse a default template argument, delay lookup 562 // until instantiation time by making a non-dependent DependentTypeName. We 563 // pretend we saw a NestedNameSpecifier referring to the current scope, and 564 // lookup is retried. 565 // FIXME: This hurts our diagnostic quality, since we get errors like "no 566 // type named 'Foo' in 'current_namespace'" when the user didn't write any 567 // name specifiers. 568 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 569 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 570 } else if (const CXXRecordDecl *RD = 571 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 572 // Build a DependentNameType that will perform lookup into RD at 573 // instantiation time. 574 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 575 RD->getTypeForDecl()); 576 577 // Diagnose that this identifier was undeclared, and retry the lookup during 578 // template instantiation. 579 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 580 << RD; 581 } else { 582 // This is not a situation that we should recover from. 583 return ParsedType(); 584 } 585 586 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 587 588 // Build type location information. We synthesized the qualifier, so we have 589 // to build a fake NestedNameSpecifierLoc. 590 NestedNameSpecifierLocBuilder NNSLocBuilder; 591 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 592 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 593 594 TypeLocBuilder Builder; 595 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 596 DepTL.setNameLoc(NameLoc); 597 DepTL.setElaboratedKeywordLoc(SourceLocation()); 598 DepTL.setQualifierLoc(QualifierLoc); 599 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 600 } 601 602 /// isTagName() - This method is called *for error recovery purposes only* 603 /// to determine if the specified name is a valid tag name ("struct foo"). If 604 /// so, this returns the TST for the tag corresponding to it (TST_enum, 605 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 606 /// cases in C where the user forgot to specify the tag. 607 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 608 // Do a tag name lookup in this scope. 609 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 610 LookupName(R, S, false); 611 R.suppressDiagnostics(); 612 if (R.getResultKind() == LookupResult::Found) 613 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 614 switch (TD->getTagKind()) { 615 case TTK_Struct: return DeclSpec::TST_struct; 616 case TTK_Interface: return DeclSpec::TST_interface; 617 case TTK_Union: return DeclSpec::TST_union; 618 case TTK_Class: return DeclSpec::TST_class; 619 case TTK_Enum: return DeclSpec::TST_enum; 620 } 621 } 622 623 return DeclSpec::TST_unspecified; 624 } 625 626 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 627 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 628 /// then downgrade the missing typename error to a warning. 629 /// This is needed for MSVC compatibility; Example: 630 /// @code 631 /// template<class T> class A { 632 /// public: 633 /// typedef int TYPE; 634 /// }; 635 /// template<class T> class B : public A<T> { 636 /// public: 637 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 638 /// }; 639 /// @endcode 640 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 641 if (CurContext->isRecord()) { 642 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 643 return true; 644 645 const Type *Ty = SS->getScopeRep()->getAsType(); 646 647 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 648 for (const auto &Base : RD->bases()) 649 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 650 return true; 651 return S->isFunctionPrototypeScope(); 652 } 653 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 654 } 655 656 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 657 SourceLocation IILoc, 658 Scope *S, 659 CXXScopeSpec *SS, 660 ParsedType &SuggestedType, 661 bool IsTemplateName) { 662 // Don't report typename errors for editor placeholders. 663 if (II->isEditorPlaceholder()) 664 return; 665 // We don't have anything to suggest (yet). 666 SuggestedType = nullptr; 667 668 // There may have been a typo in the name of the type. Look up typo 669 // results, in case we have something that we can suggest. 670 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 671 /*AllowTemplates=*/IsTemplateName, 672 /*AllowNonTemplates=*/!IsTemplateName); 673 if (TypoCorrection Corrected = 674 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 675 CCC, CTK_ErrorRecovery)) { 676 // FIXME: Support error recovery for the template-name case. 677 bool CanRecover = !IsTemplateName; 678 if (Corrected.isKeyword()) { 679 // We corrected to a keyword. 680 diagnoseTypo(Corrected, 681 PDiag(IsTemplateName ? diag::err_no_template_suggest 682 : diag::err_unknown_typename_suggest) 683 << II); 684 II = Corrected.getCorrectionAsIdentifierInfo(); 685 } else { 686 // We found a similarly-named type or interface; suggest that. 687 if (!SS || !SS->isSet()) { 688 diagnoseTypo(Corrected, 689 PDiag(IsTemplateName ? diag::err_no_template_suggest 690 : diag::err_unknown_typename_suggest) 691 << II, CanRecover); 692 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 693 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 694 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 695 II->getName().equals(CorrectedStr); 696 diagnoseTypo(Corrected, 697 PDiag(IsTemplateName 698 ? diag::err_no_member_template_suggest 699 : diag::err_unknown_nested_typename_suggest) 700 << II << DC << DroppedSpecifier << SS->getRange(), 701 CanRecover); 702 } else { 703 llvm_unreachable("could not have corrected a typo here"); 704 } 705 706 if (!CanRecover) 707 return; 708 709 CXXScopeSpec tmpSS; 710 if (Corrected.getCorrectionSpecifier()) 711 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 712 SourceRange(IILoc)); 713 // FIXME: Support class template argument deduction here. 714 SuggestedType = 715 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 716 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 717 /*IsCtorOrDtorName=*/false, 718 /*NonTrivialTypeSourceInfo=*/true); 719 } 720 return; 721 } 722 723 if (getLangOpts().CPlusPlus && !IsTemplateName) { 724 // See if II is a class template that the user forgot to pass arguments to. 725 UnqualifiedId Name; 726 Name.setIdentifier(II, IILoc); 727 CXXScopeSpec EmptySS; 728 TemplateTy TemplateResult; 729 bool MemberOfUnknownSpecialization; 730 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 731 Name, nullptr, true, TemplateResult, 732 MemberOfUnknownSpecialization) == TNK_Type_template) { 733 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 734 return; 735 } 736 } 737 738 // FIXME: Should we move the logic that tries to recover from a missing tag 739 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 740 741 if (!SS || (!SS->isSet() && !SS->isInvalid())) 742 Diag(IILoc, IsTemplateName ? diag::err_no_template 743 : diag::err_unknown_typename) 744 << II; 745 else if (DeclContext *DC = computeDeclContext(*SS, false)) 746 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 747 : diag::err_typename_nested_not_found) 748 << II << DC << SS->getRange(); 749 else if (isDependentScopeSpecifier(*SS)) { 750 unsigned DiagID = diag::err_typename_missing; 751 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 752 DiagID = diag::ext_typename_missing; 753 754 Diag(SS->getRange().getBegin(), DiagID) 755 << SS->getScopeRep() << II->getName() 756 << SourceRange(SS->getRange().getBegin(), IILoc) 757 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 758 SuggestedType = ActOnTypenameType(S, SourceLocation(), 759 *SS, *II, IILoc).get(); 760 } else { 761 assert(SS && SS->isInvalid() && 762 "Invalid scope specifier has already been diagnosed"); 763 } 764 } 765 766 /// Determine whether the given result set contains either a type name 767 /// or 768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 769 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 770 NextToken.is(tok::less); 771 772 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 773 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 774 return true; 775 776 if (CheckTemplate && isa<TemplateDecl>(*I)) 777 return true; 778 } 779 780 return false; 781 } 782 783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 784 Scope *S, CXXScopeSpec &SS, 785 IdentifierInfo *&Name, 786 SourceLocation NameLoc) { 787 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 788 SemaRef.LookupParsedName(R, S, &SS); 789 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 790 StringRef FixItTagName; 791 switch (Tag->getTagKind()) { 792 case TTK_Class: 793 FixItTagName = "class "; 794 break; 795 796 case TTK_Enum: 797 FixItTagName = "enum "; 798 break; 799 800 case TTK_Struct: 801 FixItTagName = "struct "; 802 break; 803 804 case TTK_Interface: 805 FixItTagName = "__interface "; 806 break; 807 808 case TTK_Union: 809 FixItTagName = "union "; 810 break; 811 } 812 813 StringRef TagName = FixItTagName.drop_back(); 814 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 815 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 816 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 817 818 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 819 I != IEnd; ++I) 820 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 821 << Name << TagName; 822 823 // Replace lookup results with just the tag decl. 824 Result.clear(Sema::LookupTagName); 825 SemaRef.LookupParsedName(Result, S, &SS); 826 return true; 827 } 828 829 return false; 830 } 831 832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 834 QualType T, SourceLocation NameLoc) { 835 ASTContext &Context = S.Context; 836 837 TypeLocBuilder Builder; 838 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 839 840 T = S.getElaboratedType(ETK_None, SS, T); 841 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 842 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 843 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 844 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 845 } 846 847 Sema::NameClassification 848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 849 SourceLocation NameLoc, const Token &NextToken, 850 bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) { 851 DeclarationNameInfo NameInfo(Name, NameLoc); 852 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 853 854 if (NextToken.is(tok::coloncolon)) { 855 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 856 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 857 } else if (getLangOpts().CPlusPlus && SS.isSet() && 858 isCurrentClassName(*Name, S, &SS)) { 859 // Per [class.qual]p2, this names the constructors of SS, not the 860 // injected-class-name. We don't have a classification for that. 861 // There's not much point caching this result, since the parser 862 // will reject it later. 863 return NameClassification::Unknown(); 864 } 865 866 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 867 LookupParsedName(Result, S, &SS, !CurMethod); 868 869 // For unqualified lookup in a class template in MSVC mode, look into 870 // dependent base classes where the primary class template is known. 871 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 872 if (ParsedType TypeInBase = 873 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 874 return TypeInBase; 875 } 876 877 // Perform lookup for Objective-C instance variables (including automatically 878 // synthesized instance variables), if we're in an Objective-C method. 879 // FIXME: This lookup really, really needs to be folded in to the normal 880 // unqualified lookup mechanism. 881 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 882 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 883 if (E.get() || E.isInvalid()) 884 return E; 885 } 886 887 bool SecondTry = false; 888 bool IsFilteredTemplateName = false; 889 890 Corrected: 891 switch (Result.getResultKind()) { 892 case LookupResult::NotFound: 893 // If an unqualified-id is followed by a '(', then we have a function 894 // call. 895 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 896 // In C++, this is an ADL-only call. 897 // FIXME: Reference? 898 if (getLangOpts().CPlusPlus) 899 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 900 901 // C90 6.3.2.2: 902 // If the expression that precedes the parenthesized argument list in a 903 // function call consists solely of an identifier, and if no 904 // declaration is visible for this identifier, the identifier is 905 // implicitly declared exactly as if, in the innermost block containing 906 // the function call, the declaration 907 // 908 // extern int identifier (); 909 // 910 // appeared. 911 // 912 // We also allow this in C99 as an extension. 913 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 914 Result.addDecl(D); 915 Result.resolveKind(); 916 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 917 } 918 } 919 920 if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) { 921 // In C++20 onwards, this could be an ADL-only call to a function 922 // template, and we're required to assume that this is a template name. 923 // 924 // FIXME: Find a way to still do typo correction in this case. 925 TemplateName Template = 926 Context.getAssumedTemplateName(NameInfo.getName()); 927 return NameClassification::UndeclaredTemplate(Template); 928 } 929 930 // In C, we first see whether there is a tag type by the same name, in 931 // which case it's likely that the user just forgot to write "enum", 932 // "struct", or "union". 933 if (!getLangOpts().CPlusPlus && !SecondTry && 934 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 935 break; 936 } 937 938 // Perform typo correction to determine if there is another name that is 939 // close to this name. 940 if (!SecondTry && CCC) { 941 SecondTry = true; 942 if (TypoCorrection Corrected = 943 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 944 &SS, *CCC, CTK_ErrorRecovery)) { 945 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 946 unsigned QualifiedDiag = diag::err_no_member_suggest; 947 948 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 949 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 950 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 951 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 952 UnqualifiedDiag = diag::err_no_template_suggest; 953 QualifiedDiag = diag::err_no_member_template_suggest; 954 } else if (UnderlyingFirstDecl && 955 (isa<TypeDecl>(UnderlyingFirstDecl) || 956 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 957 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 958 UnqualifiedDiag = diag::err_unknown_typename_suggest; 959 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 960 } 961 962 if (SS.isEmpty()) { 963 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 964 } else {// FIXME: is this even reachable? Test it. 965 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 966 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 967 Name->getName().equals(CorrectedStr); 968 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 969 << Name << computeDeclContext(SS, false) 970 << DroppedSpecifier << SS.getRange()); 971 } 972 973 // Update the name, so that the caller has the new name. 974 Name = Corrected.getCorrectionAsIdentifierInfo(); 975 976 // Typo correction corrected to a keyword. 977 if (Corrected.isKeyword()) 978 return Name; 979 980 // Also update the LookupResult... 981 // FIXME: This should probably go away at some point 982 Result.clear(); 983 Result.setLookupName(Corrected.getCorrection()); 984 if (FirstDecl) 985 Result.addDecl(FirstDecl); 986 987 // If we found an Objective-C instance variable, let 988 // LookupInObjCMethod build the appropriate expression to 989 // reference the ivar. 990 // FIXME: This is a gross hack. 991 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 992 Result.clear(); 993 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 994 return E; 995 } 996 997 goto Corrected; 998 } 999 } 1000 1001 // We failed to correct; just fall through and let the parser deal with it. 1002 Result.suppressDiagnostics(); 1003 return NameClassification::Unknown(); 1004 1005 case LookupResult::NotFoundInCurrentInstantiation: { 1006 // We performed name lookup into the current instantiation, and there were 1007 // dependent bases, so we treat this result the same way as any other 1008 // dependent nested-name-specifier. 1009 1010 // C++ [temp.res]p2: 1011 // A name used in a template declaration or definition and that is 1012 // dependent on a template-parameter is assumed not to name a type 1013 // unless the applicable name lookup finds a type name or the name is 1014 // qualified by the keyword typename. 1015 // 1016 // FIXME: If the next token is '<', we might want to ask the parser to 1017 // perform some heroics to see if we actually have a 1018 // template-argument-list, which would indicate a missing 'template' 1019 // keyword here. 1020 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1021 NameInfo, IsAddressOfOperand, 1022 /*TemplateArgs=*/nullptr); 1023 } 1024 1025 case LookupResult::Found: 1026 case LookupResult::FoundOverloaded: 1027 case LookupResult::FoundUnresolvedValue: 1028 break; 1029 1030 case LookupResult::Ambiguous: 1031 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1032 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1033 /*AllowDependent=*/false)) { 1034 // C++ [temp.local]p3: 1035 // A lookup that finds an injected-class-name (10.2) can result in an 1036 // ambiguity in certain cases (for example, if it is found in more than 1037 // one base class). If all of the injected-class-names that are found 1038 // refer to specializations of the same class template, and if the name 1039 // is followed by a template-argument-list, the reference refers to the 1040 // class template itself and not a specialization thereof, and is not 1041 // ambiguous. 1042 // 1043 // This filtering can make an ambiguous result into an unambiguous one, 1044 // so try again after filtering out template names. 1045 FilterAcceptableTemplateNames(Result); 1046 if (!Result.isAmbiguous()) { 1047 IsFilteredTemplateName = true; 1048 break; 1049 } 1050 } 1051 1052 // Diagnose the ambiguity and return an error. 1053 return NameClassification::Error(); 1054 } 1055 1056 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1057 (IsFilteredTemplateName || 1058 hasAnyAcceptableTemplateNames( 1059 Result, /*AllowFunctionTemplates=*/true, 1060 /*AllowDependent=*/false, 1061 /*AllowNonTemplateFunctions*/ !SS.isSet() && 1062 getLangOpts().CPlusPlus2a))) { 1063 // C++ [temp.names]p3: 1064 // After name lookup (3.4) finds that a name is a template-name or that 1065 // an operator-function-id or a literal- operator-id refers to a set of 1066 // overloaded functions any member of which is a function template if 1067 // this is followed by a <, the < is always taken as the delimiter of a 1068 // template-argument-list and never as the less-than operator. 1069 // C++2a [temp.names]p2: 1070 // A name is also considered to refer to a template if it is an 1071 // unqualified-id followed by a < and name lookup finds either one 1072 // or more functions or finds nothing. 1073 if (!IsFilteredTemplateName) 1074 FilterAcceptableTemplateNames(Result); 1075 1076 bool IsFunctionTemplate; 1077 bool IsVarTemplate; 1078 TemplateName Template; 1079 if (Result.end() - Result.begin() > 1) { 1080 IsFunctionTemplate = true; 1081 Template = Context.getOverloadedTemplateName(Result.begin(), 1082 Result.end()); 1083 } else if (!Result.empty()) { 1084 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1085 *Result.begin(), /*AllowFunctionTemplates=*/true, 1086 /*AllowDependent=*/false)); 1087 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1088 IsVarTemplate = isa<VarTemplateDecl>(TD); 1089 1090 if (SS.isSet() && !SS.isInvalid()) 1091 Template = 1092 Context.getQualifiedTemplateName(SS.getScopeRep(), 1093 /*TemplateKeyword=*/false, TD); 1094 else 1095 Template = TemplateName(TD); 1096 } else { 1097 // All results were non-template functions. This is a function template 1098 // name. 1099 IsFunctionTemplate = true; 1100 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1101 } 1102 1103 if (IsFunctionTemplate) { 1104 // Function templates always go through overload resolution, at which 1105 // point we'll perform the various checks (e.g., accessibility) we need 1106 // to based on which function we selected. 1107 Result.suppressDiagnostics(); 1108 1109 return NameClassification::FunctionTemplate(Template); 1110 } 1111 1112 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1113 : NameClassification::TypeTemplate(Template); 1114 } 1115 1116 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1117 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1118 DiagnoseUseOfDecl(Type, NameLoc); 1119 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1120 QualType T = Context.getTypeDeclType(Type); 1121 if (SS.isNotEmpty()) 1122 return buildNestedType(*this, SS, T, NameLoc); 1123 return ParsedType::make(T); 1124 } 1125 1126 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1127 if (!Class) { 1128 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1129 if (ObjCCompatibleAliasDecl *Alias = 1130 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1131 Class = Alias->getClassInterface(); 1132 } 1133 1134 if (Class) { 1135 DiagnoseUseOfDecl(Class, NameLoc); 1136 1137 if (NextToken.is(tok::period)) { 1138 // Interface. <something> is parsed as a property reference expression. 1139 // Just return "unknown" as a fall-through for now. 1140 Result.suppressDiagnostics(); 1141 return NameClassification::Unknown(); 1142 } 1143 1144 QualType T = Context.getObjCInterfaceType(Class); 1145 return ParsedType::make(T); 1146 } 1147 1148 // We can have a type template here if we're classifying a template argument. 1149 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1150 !isa<VarTemplateDecl>(FirstDecl)) 1151 return NameClassification::TypeTemplate( 1152 TemplateName(cast<TemplateDecl>(FirstDecl))); 1153 1154 // Check for a tag type hidden by a non-type decl in a few cases where it 1155 // seems likely a type is wanted instead of the non-type that was found. 1156 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1157 if ((NextToken.is(tok::identifier) || 1158 (NextIsOp && 1159 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1160 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1161 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1162 DiagnoseUseOfDecl(Type, NameLoc); 1163 QualType T = Context.getTypeDeclType(Type); 1164 if (SS.isNotEmpty()) 1165 return buildNestedType(*this, SS, T, NameLoc); 1166 return ParsedType::make(T); 1167 } 1168 1169 if (FirstDecl->isCXXClassMember()) 1170 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1171 nullptr, S); 1172 1173 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1174 return BuildDeclarationNameExpr(SS, Result, ADL); 1175 } 1176 1177 Sema::TemplateNameKindForDiagnostics 1178 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1179 auto *TD = Name.getAsTemplateDecl(); 1180 if (!TD) 1181 return TemplateNameKindForDiagnostics::DependentTemplate; 1182 if (isa<ClassTemplateDecl>(TD)) 1183 return TemplateNameKindForDiagnostics::ClassTemplate; 1184 if (isa<FunctionTemplateDecl>(TD)) 1185 return TemplateNameKindForDiagnostics::FunctionTemplate; 1186 if (isa<VarTemplateDecl>(TD)) 1187 return TemplateNameKindForDiagnostics::VarTemplate; 1188 if (isa<TypeAliasTemplateDecl>(TD)) 1189 return TemplateNameKindForDiagnostics::AliasTemplate; 1190 if (isa<TemplateTemplateParmDecl>(TD)) 1191 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1192 return TemplateNameKindForDiagnostics::DependentTemplate; 1193 } 1194 1195 // Determines the context to return to after temporarily entering a 1196 // context. This depends in an unnecessarily complicated way on the 1197 // exact ordering of callbacks from the parser. 1198 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1199 1200 // Functions defined inline within classes aren't parsed until we've 1201 // finished parsing the top-level class, so the top-level class is 1202 // the context we'll need to return to. 1203 // A Lambda call operator whose parent is a class must not be treated 1204 // as an inline member function. A Lambda can be used legally 1205 // either as an in-class member initializer or a default argument. These 1206 // are parsed once the class has been marked complete and so the containing 1207 // context would be the nested class (when the lambda is defined in one); 1208 // If the class is not complete, then the lambda is being used in an 1209 // ill-formed fashion (such as to specify the width of a bit-field, or 1210 // in an array-bound) - in which case we still want to return the 1211 // lexically containing DC (which could be a nested class). 1212 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1213 DC = DC->getLexicalParent(); 1214 1215 // A function not defined within a class will always return to its 1216 // lexical context. 1217 if (!isa<CXXRecordDecl>(DC)) 1218 return DC; 1219 1220 // A C++ inline method/friend is parsed *after* the topmost class 1221 // it was declared in is fully parsed ("complete"); the topmost 1222 // class is the context we need to return to. 1223 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1224 DC = RD; 1225 1226 // Return the declaration context of the topmost class the inline method is 1227 // declared in. 1228 return DC; 1229 } 1230 1231 return DC->getLexicalParent(); 1232 } 1233 1234 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1235 assert(getContainingDC(DC) == CurContext && 1236 "The next DeclContext should be lexically contained in the current one."); 1237 CurContext = DC; 1238 S->setEntity(DC); 1239 } 1240 1241 void Sema::PopDeclContext() { 1242 assert(CurContext && "DeclContext imbalance!"); 1243 1244 CurContext = getContainingDC(CurContext); 1245 assert(CurContext && "Popped translation unit!"); 1246 } 1247 1248 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1249 Decl *D) { 1250 // Unlike PushDeclContext, the context to which we return is not necessarily 1251 // the containing DC of TD, because the new context will be some pre-existing 1252 // TagDecl definition instead of a fresh one. 1253 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1254 CurContext = cast<TagDecl>(D)->getDefinition(); 1255 assert(CurContext && "skipping definition of undefined tag"); 1256 // Start lookups from the parent of the current context; we don't want to look 1257 // into the pre-existing complete definition. 1258 S->setEntity(CurContext->getLookupParent()); 1259 return Result; 1260 } 1261 1262 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1263 CurContext = static_cast<decltype(CurContext)>(Context); 1264 } 1265 1266 /// EnterDeclaratorContext - Used when we must lookup names in the context 1267 /// of a declarator's nested name specifier. 1268 /// 1269 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1270 // C++0x [basic.lookup.unqual]p13: 1271 // A name used in the definition of a static data member of class 1272 // X (after the qualified-id of the static member) is looked up as 1273 // if the name was used in a member function of X. 1274 // C++0x [basic.lookup.unqual]p14: 1275 // If a variable member of a namespace is defined outside of the 1276 // scope of its namespace then any name used in the definition of 1277 // the variable member (after the declarator-id) is looked up as 1278 // if the definition of the variable member occurred in its 1279 // namespace. 1280 // Both of these imply that we should push a scope whose context 1281 // is the semantic context of the declaration. We can't use 1282 // PushDeclContext here because that context is not necessarily 1283 // lexically contained in the current context. Fortunately, 1284 // the containing scope should have the appropriate information. 1285 1286 assert(!S->getEntity() && "scope already has entity"); 1287 1288 #ifndef NDEBUG 1289 Scope *Ancestor = S->getParent(); 1290 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1291 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1292 #endif 1293 1294 CurContext = DC; 1295 S->setEntity(DC); 1296 } 1297 1298 void Sema::ExitDeclaratorContext(Scope *S) { 1299 assert(S->getEntity() == CurContext && "Context imbalance!"); 1300 1301 // Switch back to the lexical context. The safety of this is 1302 // enforced by an assert in EnterDeclaratorContext. 1303 Scope *Ancestor = S->getParent(); 1304 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1305 CurContext = Ancestor->getEntity(); 1306 1307 // We don't need to do anything with the scope, which is going to 1308 // disappear. 1309 } 1310 1311 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1312 // We assume that the caller has already called 1313 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1314 FunctionDecl *FD = D->getAsFunction(); 1315 if (!FD) 1316 return; 1317 1318 // Same implementation as PushDeclContext, but enters the context 1319 // from the lexical parent, rather than the top-level class. 1320 assert(CurContext == FD->getLexicalParent() && 1321 "The next DeclContext should be lexically contained in the current one."); 1322 CurContext = FD; 1323 S->setEntity(CurContext); 1324 1325 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1326 ParmVarDecl *Param = FD->getParamDecl(P); 1327 // If the parameter has an identifier, then add it to the scope 1328 if (Param->getIdentifier()) { 1329 S->AddDecl(Param); 1330 IdResolver.AddDecl(Param); 1331 } 1332 } 1333 } 1334 1335 void Sema::ActOnExitFunctionContext() { 1336 // Same implementation as PopDeclContext, but returns to the lexical parent, 1337 // rather than the top-level class. 1338 assert(CurContext && "DeclContext imbalance!"); 1339 CurContext = CurContext->getLexicalParent(); 1340 assert(CurContext && "Popped translation unit!"); 1341 } 1342 1343 /// Determine whether we allow overloading of the function 1344 /// PrevDecl with another declaration. 1345 /// 1346 /// This routine determines whether overloading is possible, not 1347 /// whether some new function is actually an overload. It will return 1348 /// true in C++ (where we can always provide overloads) or, as an 1349 /// extension, in C when the previous function is already an 1350 /// overloaded function declaration or has the "overloadable" 1351 /// attribute. 1352 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1353 ASTContext &Context, 1354 const FunctionDecl *New) { 1355 if (Context.getLangOpts().CPlusPlus) 1356 return true; 1357 1358 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1359 return true; 1360 1361 return Previous.getResultKind() == LookupResult::Found && 1362 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1363 New->hasAttr<OverloadableAttr>()); 1364 } 1365 1366 /// Add this decl to the scope shadowed decl chains. 1367 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1368 // Move up the scope chain until we find the nearest enclosing 1369 // non-transparent context. The declaration will be introduced into this 1370 // scope. 1371 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1372 S = S->getParent(); 1373 1374 // Add scoped declarations into their context, so that they can be 1375 // found later. Declarations without a context won't be inserted 1376 // into any context. 1377 if (AddToContext) 1378 CurContext->addDecl(D); 1379 1380 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1381 // are function-local declarations. 1382 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1383 !D->getDeclContext()->getRedeclContext()->Equals( 1384 D->getLexicalDeclContext()->getRedeclContext()) && 1385 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1386 return; 1387 1388 // Template instantiations should also not be pushed into scope. 1389 if (isa<FunctionDecl>(D) && 1390 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1391 return; 1392 1393 // If this replaces anything in the current scope, 1394 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1395 IEnd = IdResolver.end(); 1396 for (; I != IEnd; ++I) { 1397 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1398 S->RemoveDecl(*I); 1399 IdResolver.RemoveDecl(*I); 1400 1401 // Should only need to replace one decl. 1402 break; 1403 } 1404 } 1405 1406 S->AddDecl(D); 1407 1408 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1409 // Implicitly-generated labels may end up getting generated in an order that 1410 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1411 // the label at the appropriate place in the identifier chain. 1412 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1413 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1414 if (IDC == CurContext) { 1415 if (!S->isDeclScope(*I)) 1416 continue; 1417 } else if (IDC->Encloses(CurContext)) 1418 break; 1419 } 1420 1421 IdResolver.InsertDeclAfter(I, D); 1422 } else { 1423 IdResolver.AddDecl(D); 1424 } 1425 } 1426 1427 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1428 bool AllowInlineNamespace) { 1429 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1430 } 1431 1432 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1433 DeclContext *TargetDC = DC->getPrimaryContext(); 1434 do { 1435 if (DeclContext *ScopeDC = S->getEntity()) 1436 if (ScopeDC->getPrimaryContext() == TargetDC) 1437 return S; 1438 } while ((S = S->getParent())); 1439 1440 return nullptr; 1441 } 1442 1443 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1444 DeclContext*, 1445 ASTContext&); 1446 1447 /// Filters out lookup results that don't fall within the given scope 1448 /// as determined by isDeclInScope. 1449 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1450 bool ConsiderLinkage, 1451 bool AllowInlineNamespace) { 1452 LookupResult::Filter F = R.makeFilter(); 1453 while (F.hasNext()) { 1454 NamedDecl *D = F.next(); 1455 1456 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1457 continue; 1458 1459 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1460 continue; 1461 1462 F.erase(); 1463 } 1464 1465 F.done(); 1466 } 1467 1468 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1469 /// have compatible owning modules. 1470 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1471 // FIXME: The Modules TS is not clear about how friend declarations are 1472 // to be treated. It's not meaningful to have different owning modules for 1473 // linkage in redeclarations of the same entity, so for now allow the 1474 // redeclaration and change the owning modules to match. 1475 if (New->getFriendObjectKind() && 1476 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1477 New->setLocalOwningModule(Old->getOwningModule()); 1478 makeMergedDefinitionVisible(New); 1479 return false; 1480 } 1481 1482 Module *NewM = New->getOwningModule(); 1483 Module *OldM = Old->getOwningModule(); 1484 1485 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1486 NewM = NewM->Parent; 1487 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1488 OldM = OldM->Parent; 1489 1490 if (NewM == OldM) 1491 return false; 1492 1493 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1494 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1495 if (NewIsModuleInterface || OldIsModuleInterface) { 1496 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1497 // if a declaration of D [...] appears in the purview of a module, all 1498 // other such declarations shall appear in the purview of the same module 1499 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1500 << New 1501 << NewIsModuleInterface 1502 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1503 << OldIsModuleInterface 1504 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1505 Diag(Old->getLocation(), diag::note_previous_declaration); 1506 New->setInvalidDecl(); 1507 return true; 1508 } 1509 1510 return false; 1511 } 1512 1513 static bool isUsingDecl(NamedDecl *D) { 1514 return isa<UsingShadowDecl>(D) || 1515 isa<UnresolvedUsingTypenameDecl>(D) || 1516 isa<UnresolvedUsingValueDecl>(D); 1517 } 1518 1519 /// Removes using shadow declarations from the lookup results. 1520 static void RemoveUsingDecls(LookupResult &R) { 1521 LookupResult::Filter F = R.makeFilter(); 1522 while (F.hasNext()) 1523 if (isUsingDecl(F.next())) 1524 F.erase(); 1525 1526 F.done(); 1527 } 1528 1529 /// Check for this common pattern: 1530 /// @code 1531 /// class S { 1532 /// S(const S&); // DO NOT IMPLEMENT 1533 /// void operator=(const S&); // DO NOT IMPLEMENT 1534 /// }; 1535 /// @endcode 1536 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1537 // FIXME: Should check for private access too but access is set after we get 1538 // the decl here. 1539 if (D->doesThisDeclarationHaveABody()) 1540 return false; 1541 1542 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1543 return CD->isCopyConstructor(); 1544 return D->isCopyAssignmentOperator(); 1545 } 1546 1547 // We need this to handle 1548 // 1549 // typedef struct { 1550 // void *foo() { return 0; } 1551 // } A; 1552 // 1553 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1554 // for example. If 'A', foo will have external linkage. If we have '*A', 1555 // foo will have no linkage. Since we can't know until we get to the end 1556 // of the typedef, this function finds out if D might have non-external linkage. 1557 // Callers should verify at the end of the TU if it D has external linkage or 1558 // not. 1559 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1560 const DeclContext *DC = D->getDeclContext(); 1561 while (!DC->isTranslationUnit()) { 1562 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1563 if (!RD->hasNameForLinkage()) 1564 return true; 1565 } 1566 DC = DC->getParent(); 1567 } 1568 1569 return !D->isExternallyVisible(); 1570 } 1571 1572 // FIXME: This needs to be refactored; some other isInMainFile users want 1573 // these semantics. 1574 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1575 if (S.TUKind != TU_Complete) 1576 return false; 1577 return S.SourceMgr.isInMainFile(Loc); 1578 } 1579 1580 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1581 assert(D); 1582 1583 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1584 return false; 1585 1586 // Ignore all entities declared within templates, and out-of-line definitions 1587 // of members of class templates. 1588 if (D->getDeclContext()->isDependentContext() || 1589 D->getLexicalDeclContext()->isDependentContext()) 1590 return false; 1591 1592 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1593 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1594 return false; 1595 // A non-out-of-line declaration of a member specialization was implicitly 1596 // instantiated; it's the out-of-line declaration that we're interested in. 1597 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1598 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1599 return false; 1600 1601 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1602 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1603 return false; 1604 } else { 1605 // 'static inline' functions are defined in headers; don't warn. 1606 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1607 return false; 1608 } 1609 1610 if (FD->doesThisDeclarationHaveABody() && 1611 Context.DeclMustBeEmitted(FD)) 1612 return false; 1613 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1614 // Constants and utility variables are defined in headers with internal 1615 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1616 // like "inline".) 1617 if (!isMainFileLoc(*this, VD->getLocation())) 1618 return false; 1619 1620 if (Context.DeclMustBeEmitted(VD)) 1621 return false; 1622 1623 if (VD->isStaticDataMember() && 1624 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1625 return false; 1626 if (VD->isStaticDataMember() && 1627 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1628 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1629 return false; 1630 1631 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1632 return false; 1633 } else { 1634 return false; 1635 } 1636 1637 // Only warn for unused decls internal to the translation unit. 1638 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1639 // for inline functions defined in the main source file, for instance. 1640 return mightHaveNonExternalLinkage(D); 1641 } 1642 1643 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1644 if (!D) 1645 return; 1646 1647 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1648 const FunctionDecl *First = FD->getFirstDecl(); 1649 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1650 return; // First should already be in the vector. 1651 } 1652 1653 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1654 const VarDecl *First = VD->getFirstDecl(); 1655 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1656 return; // First should already be in the vector. 1657 } 1658 1659 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1660 UnusedFileScopedDecls.push_back(D); 1661 } 1662 1663 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1664 if (D->isInvalidDecl()) 1665 return false; 1666 1667 bool Referenced = false; 1668 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1669 // For a decomposition declaration, warn if none of the bindings are 1670 // referenced, instead of if the variable itself is referenced (which 1671 // it is, by the bindings' expressions). 1672 for (auto *BD : DD->bindings()) { 1673 if (BD->isReferenced()) { 1674 Referenced = true; 1675 break; 1676 } 1677 } 1678 } else if (!D->getDeclName()) { 1679 return false; 1680 } else if (D->isReferenced() || D->isUsed()) { 1681 Referenced = true; 1682 } 1683 1684 if (Referenced || D->hasAttr<UnusedAttr>() || 1685 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1686 return false; 1687 1688 if (isa<LabelDecl>(D)) 1689 return true; 1690 1691 // Except for labels, we only care about unused decls that are local to 1692 // functions. 1693 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1694 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1695 // For dependent types, the diagnostic is deferred. 1696 WithinFunction = 1697 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1698 if (!WithinFunction) 1699 return false; 1700 1701 if (isa<TypedefNameDecl>(D)) 1702 return true; 1703 1704 // White-list anything that isn't a local variable. 1705 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1706 return false; 1707 1708 // Types of valid local variables should be complete, so this should succeed. 1709 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1710 1711 // White-list anything with an __attribute__((unused)) type. 1712 const auto *Ty = VD->getType().getTypePtr(); 1713 1714 // Only look at the outermost level of typedef. 1715 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1716 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1717 return false; 1718 } 1719 1720 // If we failed to complete the type for some reason, or if the type is 1721 // dependent, don't diagnose the variable. 1722 if (Ty->isIncompleteType() || Ty->isDependentType()) 1723 return false; 1724 1725 // Look at the element type to ensure that the warning behaviour is 1726 // consistent for both scalars and arrays. 1727 Ty = Ty->getBaseElementTypeUnsafe(); 1728 1729 if (const TagType *TT = Ty->getAs<TagType>()) { 1730 const TagDecl *Tag = TT->getDecl(); 1731 if (Tag->hasAttr<UnusedAttr>()) 1732 return false; 1733 1734 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1735 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1736 return false; 1737 1738 if (const Expr *Init = VD->getInit()) { 1739 if (const ExprWithCleanups *Cleanups = 1740 dyn_cast<ExprWithCleanups>(Init)) 1741 Init = Cleanups->getSubExpr(); 1742 const CXXConstructExpr *Construct = 1743 dyn_cast<CXXConstructExpr>(Init); 1744 if (Construct && !Construct->isElidable()) { 1745 CXXConstructorDecl *CD = Construct->getConstructor(); 1746 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1747 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1748 return false; 1749 } 1750 } 1751 } 1752 } 1753 1754 // TODO: __attribute__((unused)) templates? 1755 } 1756 1757 return true; 1758 } 1759 1760 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1761 FixItHint &Hint) { 1762 if (isa<LabelDecl>(D)) { 1763 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1764 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1765 true); 1766 if (AfterColon.isInvalid()) 1767 return; 1768 Hint = FixItHint::CreateRemoval( 1769 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1770 } 1771 } 1772 1773 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1774 if (D->getTypeForDecl()->isDependentType()) 1775 return; 1776 1777 for (auto *TmpD : D->decls()) { 1778 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1779 DiagnoseUnusedDecl(T); 1780 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1781 DiagnoseUnusedNestedTypedefs(R); 1782 } 1783 } 1784 1785 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1786 /// unless they are marked attr(unused). 1787 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1788 if (!ShouldDiagnoseUnusedDecl(D)) 1789 return; 1790 1791 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1792 // typedefs can be referenced later on, so the diagnostics are emitted 1793 // at end-of-translation-unit. 1794 UnusedLocalTypedefNameCandidates.insert(TD); 1795 return; 1796 } 1797 1798 FixItHint Hint; 1799 GenerateFixForUnusedDecl(D, Context, Hint); 1800 1801 unsigned DiagID; 1802 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1803 DiagID = diag::warn_unused_exception_param; 1804 else if (isa<LabelDecl>(D)) 1805 DiagID = diag::warn_unused_label; 1806 else 1807 DiagID = diag::warn_unused_variable; 1808 1809 Diag(D->getLocation(), DiagID) << D << Hint; 1810 } 1811 1812 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1813 // Verify that we have no forward references left. If so, there was a goto 1814 // or address of a label taken, but no definition of it. Label fwd 1815 // definitions are indicated with a null substmt which is also not a resolved 1816 // MS inline assembly label name. 1817 bool Diagnose = false; 1818 if (L->isMSAsmLabel()) 1819 Diagnose = !L->isResolvedMSAsmLabel(); 1820 else 1821 Diagnose = L->getStmt() == nullptr; 1822 if (Diagnose) 1823 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1824 } 1825 1826 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1827 S->mergeNRVOIntoParent(); 1828 1829 if (S->decl_empty()) return; 1830 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1831 "Scope shouldn't contain decls!"); 1832 1833 for (auto *TmpD : S->decls()) { 1834 assert(TmpD && "This decl didn't get pushed??"); 1835 1836 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1837 NamedDecl *D = cast<NamedDecl>(TmpD); 1838 1839 // Diagnose unused variables in this scope. 1840 if (!S->hasUnrecoverableErrorOccurred()) { 1841 DiagnoseUnusedDecl(D); 1842 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1843 DiagnoseUnusedNestedTypedefs(RD); 1844 } 1845 1846 if (!D->getDeclName()) continue; 1847 1848 // If this was a forward reference to a label, verify it was defined. 1849 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1850 CheckPoppedLabel(LD, *this); 1851 1852 // Remove this name from our lexical scope, and warn on it if we haven't 1853 // already. 1854 IdResolver.RemoveDecl(D); 1855 auto ShadowI = ShadowingDecls.find(D); 1856 if (ShadowI != ShadowingDecls.end()) { 1857 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1858 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1859 << D << FD << FD->getParent(); 1860 Diag(FD->getLocation(), diag::note_previous_declaration); 1861 } 1862 ShadowingDecls.erase(ShadowI); 1863 } 1864 } 1865 } 1866 1867 /// Look for an Objective-C class in the translation unit. 1868 /// 1869 /// \param Id The name of the Objective-C class we're looking for. If 1870 /// typo-correction fixes this name, the Id will be updated 1871 /// to the fixed name. 1872 /// 1873 /// \param IdLoc The location of the name in the translation unit. 1874 /// 1875 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1876 /// if there is no class with the given name. 1877 /// 1878 /// \returns The declaration of the named Objective-C class, or NULL if the 1879 /// class could not be found. 1880 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1881 SourceLocation IdLoc, 1882 bool DoTypoCorrection) { 1883 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1884 // creation from this context. 1885 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1886 1887 if (!IDecl && DoTypoCorrection) { 1888 // Perform typo correction at the given location, but only if we 1889 // find an Objective-C class name. 1890 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1891 if (TypoCorrection C = 1892 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1893 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1894 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1895 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1896 Id = IDecl->getIdentifier(); 1897 } 1898 } 1899 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1900 // This routine must always return a class definition, if any. 1901 if (Def && Def->getDefinition()) 1902 Def = Def->getDefinition(); 1903 return Def; 1904 } 1905 1906 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1907 /// from S, where a non-field would be declared. This routine copes 1908 /// with the difference between C and C++ scoping rules in structs and 1909 /// unions. For example, the following code is well-formed in C but 1910 /// ill-formed in C++: 1911 /// @code 1912 /// struct S6 { 1913 /// enum { BAR } e; 1914 /// }; 1915 /// 1916 /// void test_S6() { 1917 /// struct S6 a; 1918 /// a.e = BAR; 1919 /// } 1920 /// @endcode 1921 /// For the declaration of BAR, this routine will return a different 1922 /// scope. The scope S will be the scope of the unnamed enumeration 1923 /// within S6. In C++, this routine will return the scope associated 1924 /// with S6, because the enumeration's scope is a transparent 1925 /// context but structures can contain non-field names. In C, this 1926 /// routine will return the translation unit scope, since the 1927 /// enumeration's scope is a transparent context and structures cannot 1928 /// contain non-field names. 1929 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1930 while (((S->getFlags() & Scope::DeclScope) == 0) || 1931 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1932 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1933 S = S->getParent(); 1934 return S; 1935 } 1936 1937 /// Looks up the declaration of "struct objc_super" and 1938 /// saves it for later use in building builtin declaration of 1939 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1940 /// pre-existing declaration exists no action takes place. 1941 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1942 IdentifierInfo *II) { 1943 if (!II->isStr("objc_msgSendSuper")) 1944 return; 1945 ASTContext &Context = ThisSema.Context; 1946 1947 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1948 SourceLocation(), Sema::LookupTagName); 1949 ThisSema.LookupName(Result, S); 1950 if (Result.getResultKind() == LookupResult::Found) 1951 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1952 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1953 } 1954 1955 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 1956 ASTContext::GetBuiltinTypeError Error) { 1957 switch (Error) { 1958 case ASTContext::GE_None: 1959 return ""; 1960 case ASTContext::GE_Missing_type: 1961 return BuiltinInfo.getHeaderName(ID); 1962 case ASTContext::GE_Missing_stdio: 1963 return "stdio.h"; 1964 case ASTContext::GE_Missing_setjmp: 1965 return "setjmp.h"; 1966 case ASTContext::GE_Missing_ucontext: 1967 return "ucontext.h"; 1968 } 1969 llvm_unreachable("unhandled error kind"); 1970 } 1971 1972 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1973 /// file scope. lazily create a decl for it. ForRedeclaration is true 1974 /// if we're creating this built-in in anticipation of redeclaring the 1975 /// built-in. 1976 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1977 Scope *S, bool ForRedeclaration, 1978 SourceLocation Loc) { 1979 LookupPredefedObjCSuperType(*this, S, II); 1980 1981 ASTContext::GetBuiltinTypeError Error; 1982 QualType R = Context.GetBuiltinType(ID, Error); 1983 if (Error) { 1984 if (ForRedeclaration) 1985 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1986 << getHeaderName(Context.BuiltinInfo, ID, Error) 1987 << Context.BuiltinInfo.getName(ID); 1988 return nullptr; 1989 } 1990 1991 if (!ForRedeclaration && 1992 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1993 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1994 Diag(Loc, diag::ext_implicit_lib_function_decl) 1995 << Context.BuiltinInfo.getName(ID) << R; 1996 if (Context.BuiltinInfo.getHeaderName(ID) && 1997 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1998 Diag(Loc, diag::note_include_header_or_declare) 1999 << Context.BuiltinInfo.getHeaderName(ID) 2000 << Context.BuiltinInfo.getName(ID); 2001 } 2002 2003 if (R.isNull()) 2004 return nullptr; 2005 2006 DeclContext *Parent = Context.getTranslationUnitDecl(); 2007 if (getLangOpts().CPlusPlus) { 2008 LinkageSpecDecl *CLinkageDecl = 2009 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2010 LinkageSpecDecl::lang_c, false); 2011 CLinkageDecl->setImplicit(); 2012 Parent->addDecl(CLinkageDecl); 2013 Parent = CLinkageDecl; 2014 } 2015 2016 FunctionDecl *New = FunctionDecl::Create(Context, 2017 Parent, 2018 Loc, Loc, II, R, /*TInfo=*/nullptr, 2019 SC_Extern, 2020 false, 2021 R->isFunctionProtoType()); 2022 New->setImplicit(); 2023 2024 // Create Decl objects for each parameter, adding them to the 2025 // FunctionDecl. 2026 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2027 SmallVector<ParmVarDecl*, 16> Params; 2028 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2029 ParmVarDecl *parm = 2030 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2031 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2032 SC_None, nullptr); 2033 parm->setScopeInfo(0, i); 2034 Params.push_back(parm); 2035 } 2036 New->setParams(Params); 2037 } 2038 2039 AddKnownFunctionAttributes(New); 2040 RegisterLocallyScopedExternCDecl(New, S); 2041 2042 // TUScope is the translation-unit scope to insert this function into. 2043 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2044 // relate Scopes to DeclContexts, and probably eliminate CurContext 2045 // entirely, but we're not there yet. 2046 DeclContext *SavedContext = CurContext; 2047 CurContext = Parent; 2048 PushOnScopeChains(New, TUScope); 2049 CurContext = SavedContext; 2050 return New; 2051 } 2052 2053 /// Typedef declarations don't have linkage, but they still denote the same 2054 /// entity if their types are the same. 2055 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2056 /// isSameEntity. 2057 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2058 TypedefNameDecl *Decl, 2059 LookupResult &Previous) { 2060 // This is only interesting when modules are enabled. 2061 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2062 return; 2063 2064 // Empty sets are uninteresting. 2065 if (Previous.empty()) 2066 return; 2067 2068 LookupResult::Filter Filter = Previous.makeFilter(); 2069 while (Filter.hasNext()) { 2070 NamedDecl *Old = Filter.next(); 2071 2072 // Non-hidden declarations are never ignored. 2073 if (S.isVisible(Old)) 2074 continue; 2075 2076 // Declarations of the same entity are not ignored, even if they have 2077 // different linkages. 2078 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2079 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2080 Decl->getUnderlyingType())) 2081 continue; 2082 2083 // If both declarations give a tag declaration a typedef name for linkage 2084 // purposes, then they declare the same entity. 2085 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2086 Decl->getAnonDeclWithTypedefName()) 2087 continue; 2088 } 2089 2090 Filter.erase(); 2091 } 2092 2093 Filter.done(); 2094 } 2095 2096 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2097 QualType OldType; 2098 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2099 OldType = OldTypedef->getUnderlyingType(); 2100 else 2101 OldType = Context.getTypeDeclType(Old); 2102 QualType NewType = New->getUnderlyingType(); 2103 2104 if (NewType->isVariablyModifiedType()) { 2105 // Must not redefine a typedef with a variably-modified type. 2106 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2107 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2108 << Kind << NewType; 2109 if (Old->getLocation().isValid()) 2110 notePreviousDefinition(Old, New->getLocation()); 2111 New->setInvalidDecl(); 2112 return true; 2113 } 2114 2115 if (OldType != NewType && 2116 !OldType->isDependentType() && 2117 !NewType->isDependentType() && 2118 !Context.hasSameType(OldType, NewType)) { 2119 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2120 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2121 << Kind << NewType << OldType; 2122 if (Old->getLocation().isValid()) 2123 notePreviousDefinition(Old, New->getLocation()); 2124 New->setInvalidDecl(); 2125 return true; 2126 } 2127 return false; 2128 } 2129 2130 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2131 /// same name and scope as a previous declaration 'Old'. Figure out 2132 /// how to resolve this situation, merging decls or emitting 2133 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2134 /// 2135 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2136 LookupResult &OldDecls) { 2137 // If the new decl is known invalid already, don't bother doing any 2138 // merging checks. 2139 if (New->isInvalidDecl()) return; 2140 2141 // Allow multiple definitions for ObjC built-in typedefs. 2142 // FIXME: Verify the underlying types are equivalent! 2143 if (getLangOpts().ObjC) { 2144 const IdentifierInfo *TypeID = New->getIdentifier(); 2145 switch (TypeID->getLength()) { 2146 default: break; 2147 case 2: 2148 { 2149 if (!TypeID->isStr("id")) 2150 break; 2151 QualType T = New->getUnderlyingType(); 2152 if (!T->isPointerType()) 2153 break; 2154 if (!T->isVoidPointerType()) { 2155 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2156 if (!PT->isStructureType()) 2157 break; 2158 } 2159 Context.setObjCIdRedefinitionType(T); 2160 // Install the built-in type for 'id', ignoring the current definition. 2161 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2162 return; 2163 } 2164 case 5: 2165 if (!TypeID->isStr("Class")) 2166 break; 2167 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2168 // Install the built-in type for 'Class', ignoring the current definition. 2169 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2170 return; 2171 case 3: 2172 if (!TypeID->isStr("SEL")) 2173 break; 2174 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2175 // Install the built-in type for 'SEL', ignoring the current definition. 2176 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2177 return; 2178 } 2179 // Fall through - the typedef name was not a builtin type. 2180 } 2181 2182 // Verify the old decl was also a type. 2183 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2184 if (!Old) { 2185 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2186 << New->getDeclName(); 2187 2188 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2189 if (OldD->getLocation().isValid()) 2190 notePreviousDefinition(OldD, New->getLocation()); 2191 2192 return New->setInvalidDecl(); 2193 } 2194 2195 // If the old declaration is invalid, just give up here. 2196 if (Old->isInvalidDecl()) 2197 return New->setInvalidDecl(); 2198 2199 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2200 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2201 auto *NewTag = New->getAnonDeclWithTypedefName(); 2202 NamedDecl *Hidden = nullptr; 2203 if (OldTag && NewTag && 2204 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2205 !hasVisibleDefinition(OldTag, &Hidden)) { 2206 // There is a definition of this tag, but it is not visible. Use it 2207 // instead of our tag. 2208 New->setTypeForDecl(OldTD->getTypeForDecl()); 2209 if (OldTD->isModed()) 2210 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2211 OldTD->getUnderlyingType()); 2212 else 2213 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2214 2215 // Make the old tag definition visible. 2216 makeMergedDefinitionVisible(Hidden); 2217 2218 // If this was an unscoped enumeration, yank all of its enumerators 2219 // out of the scope. 2220 if (isa<EnumDecl>(NewTag)) { 2221 Scope *EnumScope = getNonFieldDeclScope(S); 2222 for (auto *D : NewTag->decls()) { 2223 auto *ED = cast<EnumConstantDecl>(D); 2224 assert(EnumScope->isDeclScope(ED)); 2225 EnumScope->RemoveDecl(ED); 2226 IdResolver.RemoveDecl(ED); 2227 ED->getLexicalDeclContext()->removeDecl(ED); 2228 } 2229 } 2230 } 2231 } 2232 2233 // If the typedef types are not identical, reject them in all languages and 2234 // with any extensions enabled. 2235 if (isIncompatibleTypedef(Old, New)) 2236 return; 2237 2238 // The types match. Link up the redeclaration chain and merge attributes if 2239 // the old declaration was a typedef. 2240 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2241 New->setPreviousDecl(Typedef); 2242 mergeDeclAttributes(New, Old); 2243 } 2244 2245 if (getLangOpts().MicrosoftExt) 2246 return; 2247 2248 if (getLangOpts().CPlusPlus) { 2249 // C++ [dcl.typedef]p2: 2250 // In a given non-class scope, a typedef specifier can be used to 2251 // redefine the name of any type declared in that scope to refer 2252 // to the type to which it already refers. 2253 if (!isa<CXXRecordDecl>(CurContext)) 2254 return; 2255 2256 // C++0x [dcl.typedef]p4: 2257 // In a given class scope, a typedef specifier can be used to redefine 2258 // any class-name declared in that scope that is not also a typedef-name 2259 // to refer to the type to which it already refers. 2260 // 2261 // This wording came in via DR424, which was a correction to the 2262 // wording in DR56, which accidentally banned code like: 2263 // 2264 // struct S { 2265 // typedef struct A { } A; 2266 // }; 2267 // 2268 // in the C++03 standard. We implement the C++0x semantics, which 2269 // allow the above but disallow 2270 // 2271 // struct S { 2272 // typedef int I; 2273 // typedef int I; 2274 // }; 2275 // 2276 // since that was the intent of DR56. 2277 if (!isa<TypedefNameDecl>(Old)) 2278 return; 2279 2280 Diag(New->getLocation(), diag::err_redefinition) 2281 << New->getDeclName(); 2282 notePreviousDefinition(Old, New->getLocation()); 2283 return New->setInvalidDecl(); 2284 } 2285 2286 // Modules always permit redefinition of typedefs, as does C11. 2287 if (getLangOpts().Modules || getLangOpts().C11) 2288 return; 2289 2290 // If we have a redefinition of a typedef in C, emit a warning. This warning 2291 // is normally mapped to an error, but can be controlled with 2292 // -Wtypedef-redefinition. If either the original or the redefinition is 2293 // in a system header, don't emit this for compatibility with GCC. 2294 if (getDiagnostics().getSuppressSystemWarnings() && 2295 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2296 (Old->isImplicit() || 2297 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2298 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2299 return; 2300 2301 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2302 << New->getDeclName(); 2303 notePreviousDefinition(Old, New->getLocation()); 2304 } 2305 2306 /// DeclhasAttr - returns true if decl Declaration already has the target 2307 /// attribute. 2308 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2309 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2310 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2311 for (const auto *i : D->attrs()) 2312 if (i->getKind() == A->getKind()) { 2313 if (Ann) { 2314 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2315 return true; 2316 continue; 2317 } 2318 // FIXME: Don't hardcode this check 2319 if (OA && isa<OwnershipAttr>(i)) 2320 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2321 return true; 2322 } 2323 2324 return false; 2325 } 2326 2327 static bool isAttributeTargetADefinition(Decl *D) { 2328 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2329 return VD->isThisDeclarationADefinition(); 2330 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2331 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2332 return true; 2333 } 2334 2335 /// Merge alignment attributes from \p Old to \p New, taking into account the 2336 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2337 /// 2338 /// \return \c true if any attributes were added to \p New. 2339 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2340 // Look for alignas attributes on Old, and pick out whichever attribute 2341 // specifies the strictest alignment requirement. 2342 AlignedAttr *OldAlignasAttr = nullptr; 2343 AlignedAttr *OldStrictestAlignAttr = nullptr; 2344 unsigned OldAlign = 0; 2345 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2346 // FIXME: We have no way of representing inherited dependent alignments 2347 // in a case like: 2348 // template<int A, int B> struct alignas(A) X; 2349 // template<int A, int B> struct alignas(B) X {}; 2350 // For now, we just ignore any alignas attributes which are not on the 2351 // definition in such a case. 2352 if (I->isAlignmentDependent()) 2353 return false; 2354 2355 if (I->isAlignas()) 2356 OldAlignasAttr = I; 2357 2358 unsigned Align = I->getAlignment(S.Context); 2359 if (Align > OldAlign) { 2360 OldAlign = Align; 2361 OldStrictestAlignAttr = I; 2362 } 2363 } 2364 2365 // Look for alignas attributes on New. 2366 AlignedAttr *NewAlignasAttr = nullptr; 2367 unsigned NewAlign = 0; 2368 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2369 if (I->isAlignmentDependent()) 2370 return false; 2371 2372 if (I->isAlignas()) 2373 NewAlignasAttr = I; 2374 2375 unsigned Align = I->getAlignment(S.Context); 2376 if (Align > NewAlign) 2377 NewAlign = Align; 2378 } 2379 2380 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2381 // Both declarations have 'alignas' attributes. We require them to match. 2382 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2383 // fall short. (If two declarations both have alignas, they must both match 2384 // every definition, and so must match each other if there is a definition.) 2385 2386 // If either declaration only contains 'alignas(0)' specifiers, then it 2387 // specifies the natural alignment for the type. 2388 if (OldAlign == 0 || NewAlign == 0) { 2389 QualType Ty; 2390 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2391 Ty = VD->getType(); 2392 else 2393 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2394 2395 if (OldAlign == 0) 2396 OldAlign = S.Context.getTypeAlign(Ty); 2397 if (NewAlign == 0) 2398 NewAlign = S.Context.getTypeAlign(Ty); 2399 } 2400 2401 if (OldAlign != NewAlign) { 2402 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2403 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2404 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2405 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2406 } 2407 } 2408 2409 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2410 // C++11 [dcl.align]p6: 2411 // if any declaration of an entity has an alignment-specifier, 2412 // every defining declaration of that entity shall specify an 2413 // equivalent alignment. 2414 // C11 6.7.5/7: 2415 // If the definition of an object does not have an alignment 2416 // specifier, any other declaration of that object shall also 2417 // have no alignment specifier. 2418 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2419 << OldAlignasAttr; 2420 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2421 << OldAlignasAttr; 2422 } 2423 2424 bool AnyAdded = false; 2425 2426 // Ensure we have an attribute representing the strictest alignment. 2427 if (OldAlign > NewAlign) { 2428 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2429 Clone->setInherited(true); 2430 New->addAttr(Clone); 2431 AnyAdded = true; 2432 } 2433 2434 // Ensure we have an alignas attribute if the old declaration had one. 2435 if (OldAlignasAttr && !NewAlignasAttr && 2436 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2437 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2438 Clone->setInherited(true); 2439 New->addAttr(Clone); 2440 AnyAdded = true; 2441 } 2442 2443 return AnyAdded; 2444 } 2445 2446 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2447 const InheritableAttr *Attr, 2448 Sema::AvailabilityMergeKind AMK) { 2449 // This function copies an attribute Attr from a previous declaration to the 2450 // new declaration D if the new declaration doesn't itself have that attribute 2451 // yet or if that attribute allows duplicates. 2452 // If you're adding a new attribute that requires logic different from 2453 // "use explicit attribute on decl if present, else use attribute from 2454 // previous decl", for example if the attribute needs to be consistent 2455 // between redeclarations, you need to call a custom merge function here. 2456 InheritableAttr *NewAttr = nullptr; 2457 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2458 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2459 NewAttr = S.mergeAvailabilityAttr( 2460 D, AA->getRange(), AA->getPlatform(), AA->isImplicit(), 2461 AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(), 2462 AA->getUnavailable(), AA->getMessage(), AA->getStrict(), 2463 AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex); 2464 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2465 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2466 AttrSpellingListIndex); 2467 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2468 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2469 AttrSpellingListIndex); 2470 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2471 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2472 AttrSpellingListIndex); 2473 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2474 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2475 AttrSpellingListIndex); 2476 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2477 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2478 FA->getFormatIdx(), FA->getFirstArg(), 2479 AttrSpellingListIndex); 2480 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2481 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2482 AttrSpellingListIndex); 2483 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2484 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(), 2485 AttrSpellingListIndex); 2486 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2487 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2488 AttrSpellingListIndex, 2489 IA->getSemanticSpelling()); 2490 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2491 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2492 &S.Context.Idents.get(AA->getSpelling()), 2493 AttrSpellingListIndex); 2494 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2495 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2496 isa<CUDAGlobalAttr>(Attr))) { 2497 // CUDA target attributes are part of function signature for 2498 // overloading purposes and must not be merged. 2499 return false; 2500 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2501 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2502 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2503 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2504 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2505 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2506 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2507 NewAttr = S.mergeCommonAttr(D, *CommonA); 2508 else if (isa<AlignedAttr>(Attr)) 2509 // AlignedAttrs are handled separately, because we need to handle all 2510 // such attributes on a declaration at the same time. 2511 NewAttr = nullptr; 2512 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2513 (AMK == Sema::AMK_Override || 2514 AMK == Sema::AMK_ProtocolImplementation)) 2515 NewAttr = nullptr; 2516 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2517 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2518 UA->getGuid()); 2519 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2520 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2521 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2522 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2523 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2524 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2525 2526 if (NewAttr) { 2527 NewAttr->setInherited(true); 2528 D->addAttr(NewAttr); 2529 if (isa<MSInheritanceAttr>(NewAttr)) 2530 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2531 return true; 2532 } 2533 2534 return false; 2535 } 2536 2537 static const NamedDecl *getDefinition(const Decl *D) { 2538 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2539 return TD->getDefinition(); 2540 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2541 const VarDecl *Def = VD->getDefinition(); 2542 if (Def) 2543 return Def; 2544 return VD->getActingDefinition(); 2545 } 2546 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2547 return FD->getDefinition(); 2548 return nullptr; 2549 } 2550 2551 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2552 for (const auto *Attribute : D->attrs()) 2553 if (Attribute->getKind() == Kind) 2554 return true; 2555 return false; 2556 } 2557 2558 /// checkNewAttributesAfterDef - If we already have a definition, check that 2559 /// there are no new attributes in this declaration. 2560 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2561 if (!New->hasAttrs()) 2562 return; 2563 2564 const NamedDecl *Def = getDefinition(Old); 2565 if (!Def || Def == New) 2566 return; 2567 2568 AttrVec &NewAttributes = New->getAttrs(); 2569 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2570 const Attr *NewAttribute = NewAttributes[I]; 2571 2572 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2573 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2574 Sema::SkipBodyInfo SkipBody; 2575 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2576 2577 // If we're skipping this definition, drop the "alias" attribute. 2578 if (SkipBody.ShouldSkip) { 2579 NewAttributes.erase(NewAttributes.begin() + I); 2580 --E; 2581 continue; 2582 } 2583 } else { 2584 VarDecl *VD = cast<VarDecl>(New); 2585 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2586 VarDecl::TentativeDefinition 2587 ? diag::err_alias_after_tentative 2588 : diag::err_redefinition; 2589 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2590 if (Diag == diag::err_redefinition) 2591 S.notePreviousDefinition(Def, VD->getLocation()); 2592 else 2593 S.Diag(Def->getLocation(), diag::note_previous_definition); 2594 VD->setInvalidDecl(); 2595 } 2596 ++I; 2597 continue; 2598 } 2599 2600 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2601 // Tentative definitions are only interesting for the alias check above. 2602 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2603 ++I; 2604 continue; 2605 } 2606 } 2607 2608 if (hasAttribute(Def, NewAttribute->getKind())) { 2609 ++I; 2610 continue; // regular attr merging will take care of validating this. 2611 } 2612 2613 if (isa<C11NoReturnAttr>(NewAttribute)) { 2614 // C's _Noreturn is allowed to be added to a function after it is defined. 2615 ++I; 2616 continue; 2617 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2618 if (AA->isAlignas()) { 2619 // C++11 [dcl.align]p6: 2620 // if any declaration of an entity has an alignment-specifier, 2621 // every defining declaration of that entity shall specify an 2622 // equivalent alignment. 2623 // C11 6.7.5/7: 2624 // If the definition of an object does not have an alignment 2625 // specifier, any other declaration of that object shall also 2626 // have no alignment specifier. 2627 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2628 << AA; 2629 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2630 << AA; 2631 NewAttributes.erase(NewAttributes.begin() + I); 2632 --E; 2633 continue; 2634 } 2635 } 2636 2637 S.Diag(NewAttribute->getLocation(), 2638 diag::warn_attribute_precede_definition); 2639 S.Diag(Def->getLocation(), diag::note_previous_definition); 2640 NewAttributes.erase(NewAttributes.begin() + I); 2641 --E; 2642 } 2643 } 2644 2645 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2646 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2647 AvailabilityMergeKind AMK) { 2648 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2649 UsedAttr *NewAttr = OldAttr->clone(Context); 2650 NewAttr->setInherited(true); 2651 New->addAttr(NewAttr); 2652 } 2653 2654 if (!Old->hasAttrs() && !New->hasAttrs()) 2655 return; 2656 2657 // Attributes declared post-definition are currently ignored. 2658 checkNewAttributesAfterDef(*this, New, Old); 2659 2660 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2661 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2662 if (OldA->getLabel() != NewA->getLabel()) { 2663 // This redeclaration changes __asm__ label. 2664 Diag(New->getLocation(), diag::err_different_asm_label); 2665 Diag(OldA->getLocation(), diag::note_previous_declaration); 2666 } 2667 } else if (Old->isUsed()) { 2668 // This redeclaration adds an __asm__ label to a declaration that has 2669 // already been ODR-used. 2670 Diag(New->getLocation(), diag::err_late_asm_label_name) 2671 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2672 } 2673 } 2674 2675 // Re-declaration cannot add abi_tag's. 2676 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2677 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2678 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2679 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2680 NewTag) == OldAbiTagAttr->tags_end()) { 2681 Diag(NewAbiTagAttr->getLocation(), 2682 diag::err_new_abi_tag_on_redeclaration) 2683 << NewTag; 2684 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2685 } 2686 } 2687 } else { 2688 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2689 Diag(Old->getLocation(), diag::note_previous_declaration); 2690 } 2691 } 2692 2693 // This redeclaration adds a section attribute. 2694 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2695 if (auto *VD = dyn_cast<VarDecl>(New)) { 2696 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2697 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2698 Diag(Old->getLocation(), diag::note_previous_declaration); 2699 } 2700 } 2701 } 2702 2703 // Redeclaration adds code-seg attribute. 2704 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2705 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2706 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2707 Diag(New->getLocation(), diag::warn_mismatched_section) 2708 << 0 /*codeseg*/; 2709 Diag(Old->getLocation(), diag::note_previous_declaration); 2710 } 2711 2712 if (!Old->hasAttrs()) 2713 return; 2714 2715 bool foundAny = New->hasAttrs(); 2716 2717 // Ensure that any moving of objects within the allocated map is done before 2718 // we process them. 2719 if (!foundAny) New->setAttrs(AttrVec()); 2720 2721 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2722 // Ignore deprecated/unavailable/availability attributes if requested. 2723 AvailabilityMergeKind LocalAMK = AMK_None; 2724 if (isa<DeprecatedAttr>(I) || 2725 isa<UnavailableAttr>(I) || 2726 isa<AvailabilityAttr>(I)) { 2727 switch (AMK) { 2728 case AMK_None: 2729 continue; 2730 2731 case AMK_Redeclaration: 2732 case AMK_Override: 2733 case AMK_ProtocolImplementation: 2734 LocalAMK = AMK; 2735 break; 2736 } 2737 } 2738 2739 // Already handled. 2740 if (isa<UsedAttr>(I)) 2741 continue; 2742 2743 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2744 foundAny = true; 2745 } 2746 2747 if (mergeAlignedAttrs(*this, New, Old)) 2748 foundAny = true; 2749 2750 if (!foundAny) New->dropAttrs(); 2751 } 2752 2753 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2754 /// to the new one. 2755 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2756 const ParmVarDecl *oldDecl, 2757 Sema &S) { 2758 // C++11 [dcl.attr.depend]p2: 2759 // The first declaration of a function shall specify the 2760 // carries_dependency attribute for its declarator-id if any declaration 2761 // of the function specifies the carries_dependency attribute. 2762 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2763 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2764 S.Diag(CDA->getLocation(), 2765 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2766 // Find the first declaration of the parameter. 2767 // FIXME: Should we build redeclaration chains for function parameters? 2768 const FunctionDecl *FirstFD = 2769 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2770 const ParmVarDecl *FirstVD = 2771 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2772 S.Diag(FirstVD->getLocation(), 2773 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2774 } 2775 2776 if (!oldDecl->hasAttrs()) 2777 return; 2778 2779 bool foundAny = newDecl->hasAttrs(); 2780 2781 // Ensure that any moving of objects within the allocated map is 2782 // done before we process them. 2783 if (!foundAny) newDecl->setAttrs(AttrVec()); 2784 2785 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2786 if (!DeclHasAttr(newDecl, I)) { 2787 InheritableAttr *newAttr = 2788 cast<InheritableParamAttr>(I->clone(S.Context)); 2789 newAttr->setInherited(true); 2790 newDecl->addAttr(newAttr); 2791 foundAny = true; 2792 } 2793 } 2794 2795 if (!foundAny) newDecl->dropAttrs(); 2796 } 2797 2798 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2799 const ParmVarDecl *OldParam, 2800 Sema &S) { 2801 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2802 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2803 if (*Oldnullability != *Newnullability) { 2804 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2805 << DiagNullabilityKind( 2806 *Newnullability, 2807 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2808 != 0)) 2809 << DiagNullabilityKind( 2810 *Oldnullability, 2811 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2812 != 0)); 2813 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2814 } 2815 } else { 2816 QualType NewT = NewParam->getType(); 2817 NewT = S.Context.getAttributedType( 2818 AttributedType::getNullabilityAttrKind(*Oldnullability), 2819 NewT, NewT); 2820 NewParam->setType(NewT); 2821 } 2822 } 2823 } 2824 2825 namespace { 2826 2827 /// Used in MergeFunctionDecl to keep track of function parameters in 2828 /// C. 2829 struct GNUCompatibleParamWarning { 2830 ParmVarDecl *OldParm; 2831 ParmVarDecl *NewParm; 2832 QualType PromotedType; 2833 }; 2834 2835 } // end anonymous namespace 2836 2837 /// getSpecialMember - get the special member enum for a method. 2838 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2839 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2840 if (Ctor->isDefaultConstructor()) 2841 return Sema::CXXDefaultConstructor; 2842 2843 if (Ctor->isCopyConstructor()) 2844 return Sema::CXXCopyConstructor; 2845 2846 if (Ctor->isMoveConstructor()) 2847 return Sema::CXXMoveConstructor; 2848 } else if (isa<CXXDestructorDecl>(MD)) { 2849 return Sema::CXXDestructor; 2850 } else if (MD->isCopyAssignmentOperator()) { 2851 return Sema::CXXCopyAssignment; 2852 } else if (MD->isMoveAssignmentOperator()) { 2853 return Sema::CXXMoveAssignment; 2854 } 2855 2856 return Sema::CXXInvalid; 2857 } 2858 2859 // Determine whether the previous declaration was a definition, implicit 2860 // declaration, or a declaration. 2861 template <typename T> 2862 static std::pair<diag::kind, SourceLocation> 2863 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2864 diag::kind PrevDiag; 2865 SourceLocation OldLocation = Old->getLocation(); 2866 if (Old->isThisDeclarationADefinition()) 2867 PrevDiag = diag::note_previous_definition; 2868 else if (Old->isImplicit()) { 2869 PrevDiag = diag::note_previous_implicit_declaration; 2870 if (OldLocation.isInvalid()) 2871 OldLocation = New->getLocation(); 2872 } else 2873 PrevDiag = diag::note_previous_declaration; 2874 return std::make_pair(PrevDiag, OldLocation); 2875 } 2876 2877 /// canRedefineFunction - checks if a function can be redefined. Currently, 2878 /// only extern inline functions can be redefined, and even then only in 2879 /// GNU89 mode. 2880 static bool canRedefineFunction(const FunctionDecl *FD, 2881 const LangOptions& LangOpts) { 2882 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2883 !LangOpts.CPlusPlus && 2884 FD->isInlineSpecified() && 2885 FD->getStorageClass() == SC_Extern); 2886 } 2887 2888 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2889 const AttributedType *AT = T->getAs<AttributedType>(); 2890 while (AT && !AT->isCallingConv()) 2891 AT = AT->getModifiedType()->getAs<AttributedType>(); 2892 return AT; 2893 } 2894 2895 template <typename T> 2896 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2897 const DeclContext *DC = Old->getDeclContext(); 2898 if (DC->isRecord()) 2899 return false; 2900 2901 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2902 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2903 return true; 2904 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2905 return true; 2906 return false; 2907 } 2908 2909 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2910 static bool isExternC(VarTemplateDecl *) { return false; } 2911 2912 /// Check whether a redeclaration of an entity introduced by a 2913 /// using-declaration is valid, given that we know it's not an overload 2914 /// (nor a hidden tag declaration). 2915 template<typename ExpectedDecl> 2916 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2917 ExpectedDecl *New) { 2918 // C++11 [basic.scope.declarative]p4: 2919 // Given a set of declarations in a single declarative region, each of 2920 // which specifies the same unqualified name, 2921 // -- they shall all refer to the same entity, or all refer to functions 2922 // and function templates; or 2923 // -- exactly one declaration shall declare a class name or enumeration 2924 // name that is not a typedef name and the other declarations shall all 2925 // refer to the same variable or enumerator, or all refer to functions 2926 // and function templates; in this case the class name or enumeration 2927 // name is hidden (3.3.10). 2928 2929 // C++11 [namespace.udecl]p14: 2930 // If a function declaration in namespace scope or block scope has the 2931 // same name and the same parameter-type-list as a function introduced 2932 // by a using-declaration, and the declarations do not declare the same 2933 // function, the program is ill-formed. 2934 2935 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2936 if (Old && 2937 !Old->getDeclContext()->getRedeclContext()->Equals( 2938 New->getDeclContext()->getRedeclContext()) && 2939 !(isExternC(Old) && isExternC(New))) 2940 Old = nullptr; 2941 2942 if (!Old) { 2943 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2944 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2945 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2946 return true; 2947 } 2948 return false; 2949 } 2950 2951 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2952 const FunctionDecl *B) { 2953 assert(A->getNumParams() == B->getNumParams()); 2954 2955 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2956 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2957 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2958 if (AttrA == AttrB) 2959 return true; 2960 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 2961 AttrA->isDynamic() == AttrB->isDynamic(); 2962 }; 2963 2964 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2965 } 2966 2967 /// If necessary, adjust the semantic declaration context for a qualified 2968 /// declaration to name the correct inline namespace within the qualifier. 2969 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2970 DeclaratorDecl *OldD) { 2971 // The only case where we need to update the DeclContext is when 2972 // redeclaration lookup for a qualified name finds a declaration 2973 // in an inline namespace within the context named by the qualifier: 2974 // 2975 // inline namespace N { int f(); } 2976 // int ::f(); // Sema DC needs adjusting from :: to N::. 2977 // 2978 // For unqualified declarations, the semantic context *can* change 2979 // along the redeclaration chain (for local extern declarations, 2980 // extern "C" declarations, and friend declarations in particular). 2981 if (!NewD->getQualifier()) 2982 return; 2983 2984 // NewD is probably already in the right context. 2985 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2986 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2987 if (NamedDC->Equals(SemaDC)) 2988 return; 2989 2990 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2991 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2992 "unexpected context for redeclaration"); 2993 2994 auto *LexDC = NewD->getLexicalDeclContext(); 2995 auto FixSemaDC = [=](NamedDecl *D) { 2996 if (!D) 2997 return; 2998 D->setDeclContext(SemaDC); 2999 D->setLexicalDeclContext(LexDC); 3000 }; 3001 3002 FixSemaDC(NewD); 3003 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3004 FixSemaDC(FD->getDescribedFunctionTemplate()); 3005 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3006 FixSemaDC(VD->getDescribedVarTemplate()); 3007 } 3008 3009 /// MergeFunctionDecl - We just parsed a function 'New' from 3010 /// declarator D which has the same name and scope as a previous 3011 /// declaration 'Old'. Figure out how to resolve this situation, 3012 /// merging decls or emitting diagnostics as appropriate. 3013 /// 3014 /// In C++, New and Old must be declarations that are not 3015 /// overloaded. Use IsOverload to determine whether New and Old are 3016 /// overloaded, and to select the Old declaration that New should be 3017 /// merged with. 3018 /// 3019 /// Returns true if there was an error, false otherwise. 3020 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3021 Scope *S, bool MergeTypeWithOld) { 3022 // Verify the old decl was also a function. 3023 FunctionDecl *Old = OldD->getAsFunction(); 3024 if (!Old) { 3025 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3026 if (New->getFriendObjectKind()) { 3027 Diag(New->getLocation(), diag::err_using_decl_friend); 3028 Diag(Shadow->getTargetDecl()->getLocation(), 3029 diag::note_using_decl_target); 3030 Diag(Shadow->getUsingDecl()->getLocation(), 3031 diag::note_using_decl) << 0; 3032 return true; 3033 } 3034 3035 // Check whether the two declarations might declare the same function. 3036 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3037 return true; 3038 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3039 } else { 3040 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3041 << New->getDeclName(); 3042 notePreviousDefinition(OldD, New->getLocation()); 3043 return true; 3044 } 3045 } 3046 3047 // If the old declaration is invalid, just give up here. 3048 if (Old->isInvalidDecl()) 3049 return true; 3050 3051 // Disallow redeclaration of some builtins. 3052 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3053 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3054 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3055 << Old << Old->getType(); 3056 return true; 3057 } 3058 3059 diag::kind PrevDiag; 3060 SourceLocation OldLocation; 3061 std::tie(PrevDiag, OldLocation) = 3062 getNoteDiagForInvalidRedeclaration(Old, New); 3063 3064 // Don't complain about this if we're in GNU89 mode and the old function 3065 // is an extern inline function. 3066 // Don't complain about specializations. They are not supposed to have 3067 // storage classes. 3068 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3069 New->getStorageClass() == SC_Static && 3070 Old->hasExternalFormalLinkage() && 3071 !New->getTemplateSpecializationInfo() && 3072 !canRedefineFunction(Old, getLangOpts())) { 3073 if (getLangOpts().MicrosoftExt) { 3074 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3075 Diag(OldLocation, PrevDiag); 3076 } else { 3077 Diag(New->getLocation(), diag::err_static_non_static) << New; 3078 Diag(OldLocation, PrevDiag); 3079 return true; 3080 } 3081 } 3082 3083 if (New->hasAttr<InternalLinkageAttr>() && 3084 !Old->hasAttr<InternalLinkageAttr>()) { 3085 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3086 << New->getDeclName(); 3087 notePreviousDefinition(Old, New->getLocation()); 3088 New->dropAttr<InternalLinkageAttr>(); 3089 } 3090 3091 if (CheckRedeclarationModuleOwnership(New, Old)) 3092 return true; 3093 3094 if (!getLangOpts().CPlusPlus) { 3095 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3096 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3097 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3098 << New << OldOvl; 3099 3100 // Try our best to find a decl that actually has the overloadable 3101 // attribute for the note. In most cases (e.g. programs with only one 3102 // broken declaration/definition), this won't matter. 3103 // 3104 // FIXME: We could do this if we juggled some extra state in 3105 // OverloadableAttr, rather than just removing it. 3106 const Decl *DiagOld = Old; 3107 if (OldOvl) { 3108 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3109 const auto *A = D->getAttr<OverloadableAttr>(); 3110 return A && !A->isImplicit(); 3111 }); 3112 // If we've implicitly added *all* of the overloadable attrs to this 3113 // chain, emitting a "previous redecl" note is pointless. 3114 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3115 } 3116 3117 if (DiagOld) 3118 Diag(DiagOld->getLocation(), 3119 diag::note_attribute_overloadable_prev_overload) 3120 << OldOvl; 3121 3122 if (OldOvl) 3123 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3124 else 3125 New->dropAttr<OverloadableAttr>(); 3126 } 3127 } 3128 3129 // If a function is first declared with a calling convention, but is later 3130 // declared or defined without one, all following decls assume the calling 3131 // convention of the first. 3132 // 3133 // It's OK if a function is first declared without a calling convention, 3134 // but is later declared or defined with the default calling convention. 3135 // 3136 // To test if either decl has an explicit calling convention, we look for 3137 // AttributedType sugar nodes on the type as written. If they are missing or 3138 // were canonicalized away, we assume the calling convention was implicit. 3139 // 3140 // Note also that we DO NOT return at this point, because we still have 3141 // other tests to run. 3142 QualType OldQType = Context.getCanonicalType(Old->getType()); 3143 QualType NewQType = Context.getCanonicalType(New->getType()); 3144 const FunctionType *OldType = cast<FunctionType>(OldQType); 3145 const FunctionType *NewType = cast<FunctionType>(NewQType); 3146 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3147 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3148 bool RequiresAdjustment = false; 3149 3150 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3151 FunctionDecl *First = Old->getFirstDecl(); 3152 const FunctionType *FT = 3153 First->getType().getCanonicalType()->castAs<FunctionType>(); 3154 FunctionType::ExtInfo FI = FT->getExtInfo(); 3155 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3156 if (!NewCCExplicit) { 3157 // Inherit the CC from the previous declaration if it was specified 3158 // there but not here. 3159 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3160 RequiresAdjustment = true; 3161 } else if (New->getBuiltinID()) { 3162 // Calling Conventions on a Builtin aren't really useful and setting a 3163 // default calling convention and cdecl'ing some builtin redeclarations is 3164 // common, so warn and ignore the calling convention on the redeclaration. 3165 Diag(New->getLocation(), diag::warn_cconv_ignored) 3166 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3167 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3168 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3169 RequiresAdjustment = true; 3170 } else { 3171 // Calling conventions aren't compatible, so complain. 3172 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3173 Diag(New->getLocation(), diag::err_cconv_change) 3174 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3175 << !FirstCCExplicit 3176 << (!FirstCCExplicit ? "" : 3177 FunctionType::getNameForCallConv(FI.getCC())); 3178 3179 // Put the note on the first decl, since it is the one that matters. 3180 Diag(First->getLocation(), diag::note_previous_declaration); 3181 return true; 3182 } 3183 } 3184 3185 // FIXME: diagnose the other way around? 3186 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3187 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3188 RequiresAdjustment = true; 3189 } 3190 3191 // Merge regparm attribute. 3192 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3193 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3194 if (NewTypeInfo.getHasRegParm()) { 3195 Diag(New->getLocation(), diag::err_regparm_mismatch) 3196 << NewType->getRegParmType() 3197 << OldType->getRegParmType(); 3198 Diag(OldLocation, diag::note_previous_declaration); 3199 return true; 3200 } 3201 3202 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3203 RequiresAdjustment = true; 3204 } 3205 3206 // Merge ns_returns_retained attribute. 3207 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3208 if (NewTypeInfo.getProducesResult()) { 3209 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3210 << "'ns_returns_retained'"; 3211 Diag(OldLocation, diag::note_previous_declaration); 3212 return true; 3213 } 3214 3215 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3216 RequiresAdjustment = true; 3217 } 3218 3219 if (OldTypeInfo.getNoCallerSavedRegs() != 3220 NewTypeInfo.getNoCallerSavedRegs()) { 3221 if (NewTypeInfo.getNoCallerSavedRegs()) { 3222 AnyX86NoCallerSavedRegistersAttr *Attr = 3223 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3224 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3225 Diag(OldLocation, diag::note_previous_declaration); 3226 return true; 3227 } 3228 3229 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3230 RequiresAdjustment = true; 3231 } 3232 3233 if (RequiresAdjustment) { 3234 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3235 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3236 New->setType(QualType(AdjustedType, 0)); 3237 NewQType = Context.getCanonicalType(New->getType()); 3238 NewType = cast<FunctionType>(NewQType); 3239 } 3240 3241 // If this redeclaration makes the function inline, we may need to add it to 3242 // UndefinedButUsed. 3243 if (!Old->isInlined() && New->isInlined() && 3244 !New->hasAttr<GNUInlineAttr>() && 3245 !getLangOpts().GNUInline && 3246 Old->isUsed(false) && 3247 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3248 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3249 SourceLocation())); 3250 3251 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3252 // about it. 3253 if (New->hasAttr<GNUInlineAttr>() && 3254 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3255 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3256 } 3257 3258 // If pass_object_size params don't match up perfectly, this isn't a valid 3259 // redeclaration. 3260 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3261 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3262 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3263 << New->getDeclName(); 3264 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3265 return true; 3266 } 3267 3268 if (getLangOpts().CPlusPlus) { 3269 // C++1z [over.load]p2 3270 // Certain function declarations cannot be overloaded: 3271 // -- Function declarations that differ only in the return type, 3272 // the exception specification, or both cannot be overloaded. 3273 3274 // Check the exception specifications match. This may recompute the type of 3275 // both Old and New if it resolved exception specifications, so grab the 3276 // types again after this. Because this updates the type, we do this before 3277 // any of the other checks below, which may update the "de facto" NewQType 3278 // but do not necessarily update the type of New. 3279 if (CheckEquivalentExceptionSpec(Old, New)) 3280 return true; 3281 OldQType = Context.getCanonicalType(Old->getType()); 3282 NewQType = Context.getCanonicalType(New->getType()); 3283 3284 // Go back to the type source info to compare the declared return types, 3285 // per C++1y [dcl.type.auto]p13: 3286 // Redeclarations or specializations of a function or function template 3287 // with a declared return type that uses a placeholder type shall also 3288 // use that placeholder, not a deduced type. 3289 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3290 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3291 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3292 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3293 OldDeclaredReturnType)) { 3294 QualType ResQT; 3295 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3296 OldDeclaredReturnType->isObjCObjectPointerType()) 3297 // FIXME: This does the wrong thing for a deduced return type. 3298 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3299 if (ResQT.isNull()) { 3300 if (New->isCXXClassMember() && New->isOutOfLine()) 3301 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3302 << New << New->getReturnTypeSourceRange(); 3303 else 3304 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3305 << New->getReturnTypeSourceRange(); 3306 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3307 << Old->getReturnTypeSourceRange(); 3308 return true; 3309 } 3310 else 3311 NewQType = ResQT; 3312 } 3313 3314 QualType OldReturnType = OldType->getReturnType(); 3315 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3316 if (OldReturnType != NewReturnType) { 3317 // If this function has a deduced return type and has already been 3318 // defined, copy the deduced value from the old declaration. 3319 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3320 if (OldAT && OldAT->isDeduced()) { 3321 New->setType( 3322 SubstAutoType(New->getType(), 3323 OldAT->isDependentType() ? Context.DependentTy 3324 : OldAT->getDeducedType())); 3325 NewQType = Context.getCanonicalType( 3326 SubstAutoType(NewQType, 3327 OldAT->isDependentType() ? Context.DependentTy 3328 : OldAT->getDeducedType())); 3329 } 3330 } 3331 3332 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3333 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3334 if (OldMethod && NewMethod) { 3335 // Preserve triviality. 3336 NewMethod->setTrivial(OldMethod->isTrivial()); 3337 3338 // MSVC allows explicit template specialization at class scope: 3339 // 2 CXXMethodDecls referring to the same function will be injected. 3340 // We don't want a redeclaration error. 3341 bool IsClassScopeExplicitSpecialization = 3342 OldMethod->isFunctionTemplateSpecialization() && 3343 NewMethod->isFunctionTemplateSpecialization(); 3344 bool isFriend = NewMethod->getFriendObjectKind(); 3345 3346 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3347 !IsClassScopeExplicitSpecialization) { 3348 // -- Member function declarations with the same name and the 3349 // same parameter types cannot be overloaded if any of them 3350 // is a static member function declaration. 3351 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3352 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3353 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3354 return true; 3355 } 3356 3357 // C++ [class.mem]p1: 3358 // [...] A member shall not be declared twice in the 3359 // member-specification, except that a nested class or member 3360 // class template can be declared and then later defined. 3361 if (!inTemplateInstantiation()) { 3362 unsigned NewDiag; 3363 if (isa<CXXConstructorDecl>(OldMethod)) 3364 NewDiag = diag::err_constructor_redeclared; 3365 else if (isa<CXXDestructorDecl>(NewMethod)) 3366 NewDiag = diag::err_destructor_redeclared; 3367 else if (isa<CXXConversionDecl>(NewMethod)) 3368 NewDiag = diag::err_conv_function_redeclared; 3369 else 3370 NewDiag = diag::err_member_redeclared; 3371 3372 Diag(New->getLocation(), NewDiag); 3373 } else { 3374 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3375 << New << New->getType(); 3376 } 3377 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3378 return true; 3379 3380 // Complain if this is an explicit declaration of a special 3381 // member that was initially declared implicitly. 3382 // 3383 // As an exception, it's okay to befriend such methods in order 3384 // to permit the implicit constructor/destructor/operator calls. 3385 } else if (OldMethod->isImplicit()) { 3386 if (isFriend) { 3387 NewMethod->setImplicit(); 3388 } else { 3389 Diag(NewMethod->getLocation(), 3390 diag::err_definition_of_implicitly_declared_member) 3391 << New << getSpecialMember(OldMethod); 3392 return true; 3393 } 3394 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3395 Diag(NewMethod->getLocation(), 3396 diag::err_definition_of_explicitly_defaulted_member) 3397 << getSpecialMember(OldMethod); 3398 return true; 3399 } 3400 } 3401 3402 // C++11 [dcl.attr.noreturn]p1: 3403 // The first declaration of a function shall specify the noreturn 3404 // attribute if any declaration of that function specifies the noreturn 3405 // attribute. 3406 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3407 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3408 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3409 Diag(Old->getFirstDecl()->getLocation(), 3410 diag::note_noreturn_missing_first_decl); 3411 } 3412 3413 // C++11 [dcl.attr.depend]p2: 3414 // The first declaration of a function shall specify the 3415 // carries_dependency attribute for its declarator-id if any declaration 3416 // of the function specifies the carries_dependency attribute. 3417 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3418 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3419 Diag(CDA->getLocation(), 3420 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3421 Diag(Old->getFirstDecl()->getLocation(), 3422 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3423 } 3424 3425 // (C++98 8.3.5p3): 3426 // All declarations for a function shall agree exactly in both the 3427 // return type and the parameter-type-list. 3428 // We also want to respect all the extended bits except noreturn. 3429 3430 // noreturn should now match unless the old type info didn't have it. 3431 QualType OldQTypeForComparison = OldQType; 3432 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3433 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3434 const FunctionType *OldTypeForComparison 3435 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3436 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3437 assert(OldQTypeForComparison.isCanonical()); 3438 } 3439 3440 if (haveIncompatibleLanguageLinkages(Old, New)) { 3441 // As a special case, retain the language linkage from previous 3442 // declarations of a friend function as an extension. 3443 // 3444 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3445 // and is useful because there's otherwise no way to specify language 3446 // linkage within class scope. 3447 // 3448 // Check cautiously as the friend object kind isn't yet complete. 3449 if (New->getFriendObjectKind() != Decl::FOK_None) { 3450 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3451 Diag(OldLocation, PrevDiag); 3452 } else { 3453 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3454 Diag(OldLocation, PrevDiag); 3455 return true; 3456 } 3457 } 3458 3459 if (OldQTypeForComparison == NewQType) 3460 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3461 3462 // If the types are imprecise (due to dependent constructs in friends or 3463 // local extern declarations), it's OK if they differ. We'll check again 3464 // during instantiation. 3465 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3466 return false; 3467 3468 // Fall through for conflicting redeclarations and redefinitions. 3469 } 3470 3471 // C: Function types need to be compatible, not identical. This handles 3472 // duplicate function decls like "void f(int); void f(enum X);" properly. 3473 if (!getLangOpts().CPlusPlus && 3474 Context.typesAreCompatible(OldQType, NewQType)) { 3475 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3476 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3477 const FunctionProtoType *OldProto = nullptr; 3478 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3479 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3480 // The old declaration provided a function prototype, but the 3481 // new declaration does not. Merge in the prototype. 3482 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3483 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3484 NewQType = 3485 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3486 OldProto->getExtProtoInfo()); 3487 New->setType(NewQType); 3488 New->setHasInheritedPrototype(); 3489 3490 // Synthesize parameters with the same types. 3491 SmallVector<ParmVarDecl*, 16> Params; 3492 for (const auto &ParamType : OldProto->param_types()) { 3493 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3494 SourceLocation(), nullptr, 3495 ParamType, /*TInfo=*/nullptr, 3496 SC_None, nullptr); 3497 Param->setScopeInfo(0, Params.size()); 3498 Param->setImplicit(); 3499 Params.push_back(Param); 3500 } 3501 3502 New->setParams(Params); 3503 } 3504 3505 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3506 } 3507 3508 // GNU C permits a K&R definition to follow a prototype declaration 3509 // if the declared types of the parameters in the K&R definition 3510 // match the types in the prototype declaration, even when the 3511 // promoted types of the parameters from the K&R definition differ 3512 // from the types in the prototype. GCC then keeps the types from 3513 // the prototype. 3514 // 3515 // If a variadic prototype is followed by a non-variadic K&R definition, 3516 // the K&R definition becomes variadic. This is sort of an edge case, but 3517 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3518 // C99 6.9.1p8. 3519 if (!getLangOpts().CPlusPlus && 3520 Old->hasPrototype() && !New->hasPrototype() && 3521 New->getType()->getAs<FunctionProtoType>() && 3522 Old->getNumParams() == New->getNumParams()) { 3523 SmallVector<QualType, 16> ArgTypes; 3524 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3525 const FunctionProtoType *OldProto 3526 = Old->getType()->getAs<FunctionProtoType>(); 3527 const FunctionProtoType *NewProto 3528 = New->getType()->getAs<FunctionProtoType>(); 3529 3530 // Determine whether this is the GNU C extension. 3531 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3532 NewProto->getReturnType()); 3533 bool LooseCompatible = !MergedReturn.isNull(); 3534 for (unsigned Idx = 0, End = Old->getNumParams(); 3535 LooseCompatible && Idx != End; ++Idx) { 3536 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3537 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3538 if (Context.typesAreCompatible(OldParm->getType(), 3539 NewProto->getParamType(Idx))) { 3540 ArgTypes.push_back(NewParm->getType()); 3541 } else if (Context.typesAreCompatible(OldParm->getType(), 3542 NewParm->getType(), 3543 /*CompareUnqualified=*/true)) { 3544 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3545 NewProto->getParamType(Idx) }; 3546 Warnings.push_back(Warn); 3547 ArgTypes.push_back(NewParm->getType()); 3548 } else 3549 LooseCompatible = false; 3550 } 3551 3552 if (LooseCompatible) { 3553 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3554 Diag(Warnings[Warn].NewParm->getLocation(), 3555 diag::ext_param_promoted_not_compatible_with_prototype) 3556 << Warnings[Warn].PromotedType 3557 << Warnings[Warn].OldParm->getType(); 3558 if (Warnings[Warn].OldParm->getLocation().isValid()) 3559 Diag(Warnings[Warn].OldParm->getLocation(), 3560 diag::note_previous_declaration); 3561 } 3562 3563 if (MergeTypeWithOld) 3564 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3565 OldProto->getExtProtoInfo())); 3566 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3567 } 3568 3569 // Fall through to diagnose conflicting types. 3570 } 3571 3572 // A function that has already been declared has been redeclared or 3573 // defined with a different type; show an appropriate diagnostic. 3574 3575 // If the previous declaration was an implicitly-generated builtin 3576 // declaration, then at the very least we should use a specialized note. 3577 unsigned BuiltinID; 3578 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3579 // If it's actually a library-defined builtin function like 'malloc' 3580 // or 'printf', just warn about the incompatible redeclaration. 3581 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3582 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3583 Diag(OldLocation, diag::note_previous_builtin_declaration) 3584 << Old << Old->getType(); 3585 3586 // If this is a global redeclaration, just forget hereafter 3587 // about the "builtin-ness" of the function. 3588 // 3589 // Doing this for local extern declarations is problematic. If 3590 // the builtin declaration remains visible, a second invalid 3591 // local declaration will produce a hard error; if it doesn't 3592 // remain visible, a single bogus local redeclaration (which is 3593 // actually only a warning) could break all the downstream code. 3594 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3595 New->getIdentifier()->revertBuiltin(); 3596 3597 return false; 3598 } 3599 3600 PrevDiag = diag::note_previous_builtin_declaration; 3601 } 3602 3603 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3604 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3605 return true; 3606 } 3607 3608 /// Completes the merge of two function declarations that are 3609 /// known to be compatible. 3610 /// 3611 /// This routine handles the merging of attributes and other 3612 /// properties of function declarations from the old declaration to 3613 /// the new declaration, once we know that New is in fact a 3614 /// redeclaration of Old. 3615 /// 3616 /// \returns false 3617 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3618 Scope *S, bool MergeTypeWithOld) { 3619 // Merge the attributes 3620 mergeDeclAttributes(New, Old); 3621 3622 // Merge "pure" flag. 3623 if (Old->isPure()) 3624 New->setPure(); 3625 3626 // Merge "used" flag. 3627 if (Old->getMostRecentDecl()->isUsed(false)) 3628 New->setIsUsed(); 3629 3630 // Merge attributes from the parameters. These can mismatch with K&R 3631 // declarations. 3632 if (New->getNumParams() == Old->getNumParams()) 3633 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3634 ParmVarDecl *NewParam = New->getParamDecl(i); 3635 ParmVarDecl *OldParam = Old->getParamDecl(i); 3636 mergeParamDeclAttributes(NewParam, OldParam, *this); 3637 mergeParamDeclTypes(NewParam, OldParam, *this); 3638 } 3639 3640 if (getLangOpts().CPlusPlus) 3641 return MergeCXXFunctionDecl(New, Old, S); 3642 3643 // Merge the function types so the we get the composite types for the return 3644 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3645 // was visible. 3646 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3647 if (!Merged.isNull() && MergeTypeWithOld) 3648 New->setType(Merged); 3649 3650 return false; 3651 } 3652 3653 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3654 ObjCMethodDecl *oldMethod) { 3655 // Merge the attributes, including deprecated/unavailable 3656 AvailabilityMergeKind MergeKind = 3657 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3658 ? AMK_ProtocolImplementation 3659 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3660 : AMK_Override; 3661 3662 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3663 3664 // Merge attributes from the parameters. 3665 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3666 oe = oldMethod->param_end(); 3667 for (ObjCMethodDecl::param_iterator 3668 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3669 ni != ne && oi != oe; ++ni, ++oi) 3670 mergeParamDeclAttributes(*ni, *oi, *this); 3671 3672 CheckObjCMethodOverride(newMethod, oldMethod); 3673 } 3674 3675 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3676 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3677 3678 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3679 ? diag::err_redefinition_different_type 3680 : diag::err_redeclaration_different_type) 3681 << New->getDeclName() << New->getType() << Old->getType(); 3682 3683 diag::kind PrevDiag; 3684 SourceLocation OldLocation; 3685 std::tie(PrevDiag, OldLocation) 3686 = getNoteDiagForInvalidRedeclaration(Old, New); 3687 S.Diag(OldLocation, PrevDiag); 3688 New->setInvalidDecl(); 3689 } 3690 3691 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3692 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3693 /// emitting diagnostics as appropriate. 3694 /// 3695 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3696 /// to here in AddInitializerToDecl. We can't check them before the initializer 3697 /// is attached. 3698 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3699 bool MergeTypeWithOld) { 3700 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3701 return; 3702 3703 QualType MergedT; 3704 if (getLangOpts().CPlusPlus) { 3705 if (New->getType()->isUndeducedType()) { 3706 // We don't know what the new type is until the initializer is attached. 3707 return; 3708 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3709 // These could still be something that needs exception specs checked. 3710 return MergeVarDeclExceptionSpecs(New, Old); 3711 } 3712 // C++ [basic.link]p10: 3713 // [...] the types specified by all declarations referring to a given 3714 // object or function shall be identical, except that declarations for an 3715 // array object can specify array types that differ by the presence or 3716 // absence of a major array bound (8.3.4). 3717 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3718 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3719 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3720 3721 // We are merging a variable declaration New into Old. If it has an array 3722 // bound, and that bound differs from Old's bound, we should diagnose the 3723 // mismatch. 3724 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3725 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3726 PrevVD = PrevVD->getPreviousDecl()) { 3727 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3728 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3729 continue; 3730 3731 if (!Context.hasSameType(NewArray, PrevVDTy)) 3732 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3733 } 3734 } 3735 3736 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3737 if (Context.hasSameType(OldArray->getElementType(), 3738 NewArray->getElementType())) 3739 MergedT = New->getType(); 3740 } 3741 // FIXME: Check visibility. New is hidden but has a complete type. If New 3742 // has no array bound, it should not inherit one from Old, if Old is not 3743 // visible. 3744 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3745 if (Context.hasSameType(OldArray->getElementType(), 3746 NewArray->getElementType())) 3747 MergedT = Old->getType(); 3748 } 3749 } 3750 else if (New->getType()->isObjCObjectPointerType() && 3751 Old->getType()->isObjCObjectPointerType()) { 3752 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3753 Old->getType()); 3754 } 3755 } else { 3756 // C 6.2.7p2: 3757 // All declarations that refer to the same object or function shall have 3758 // compatible type. 3759 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3760 } 3761 if (MergedT.isNull()) { 3762 // It's OK if we couldn't merge types if either type is dependent, for a 3763 // block-scope variable. In other cases (static data members of class 3764 // templates, variable templates, ...), we require the types to be 3765 // equivalent. 3766 // FIXME: The C++ standard doesn't say anything about this. 3767 if ((New->getType()->isDependentType() || 3768 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3769 // If the old type was dependent, we can't merge with it, so the new type 3770 // becomes dependent for now. We'll reproduce the original type when we 3771 // instantiate the TypeSourceInfo for the variable. 3772 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3773 New->setType(Context.DependentTy); 3774 return; 3775 } 3776 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3777 } 3778 3779 // Don't actually update the type on the new declaration if the old 3780 // declaration was an extern declaration in a different scope. 3781 if (MergeTypeWithOld) 3782 New->setType(MergedT); 3783 } 3784 3785 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3786 LookupResult &Previous) { 3787 // C11 6.2.7p4: 3788 // For an identifier with internal or external linkage declared 3789 // in a scope in which a prior declaration of that identifier is 3790 // visible, if the prior declaration specifies internal or 3791 // external linkage, the type of the identifier at the later 3792 // declaration becomes the composite type. 3793 // 3794 // If the variable isn't visible, we do not merge with its type. 3795 if (Previous.isShadowed()) 3796 return false; 3797 3798 if (S.getLangOpts().CPlusPlus) { 3799 // C++11 [dcl.array]p3: 3800 // If there is a preceding declaration of the entity in the same 3801 // scope in which the bound was specified, an omitted array bound 3802 // is taken to be the same as in that earlier declaration. 3803 return NewVD->isPreviousDeclInSameBlockScope() || 3804 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3805 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3806 } else { 3807 // If the old declaration was function-local, don't merge with its 3808 // type unless we're in the same function. 3809 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3810 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3811 } 3812 } 3813 3814 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3815 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3816 /// situation, merging decls or emitting diagnostics as appropriate. 3817 /// 3818 /// Tentative definition rules (C99 6.9.2p2) are checked by 3819 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3820 /// definitions here, since the initializer hasn't been attached. 3821 /// 3822 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3823 // If the new decl is already invalid, don't do any other checking. 3824 if (New->isInvalidDecl()) 3825 return; 3826 3827 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3828 return; 3829 3830 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3831 3832 // Verify the old decl was also a variable or variable template. 3833 VarDecl *Old = nullptr; 3834 VarTemplateDecl *OldTemplate = nullptr; 3835 if (Previous.isSingleResult()) { 3836 if (NewTemplate) { 3837 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3838 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3839 3840 if (auto *Shadow = 3841 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3842 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3843 return New->setInvalidDecl(); 3844 } else { 3845 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3846 3847 if (auto *Shadow = 3848 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3849 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3850 return New->setInvalidDecl(); 3851 } 3852 } 3853 if (!Old) { 3854 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3855 << New->getDeclName(); 3856 notePreviousDefinition(Previous.getRepresentativeDecl(), 3857 New->getLocation()); 3858 return New->setInvalidDecl(); 3859 } 3860 3861 // Ensure the template parameters are compatible. 3862 if (NewTemplate && 3863 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3864 OldTemplate->getTemplateParameters(), 3865 /*Complain=*/true, TPL_TemplateMatch)) 3866 return New->setInvalidDecl(); 3867 3868 // C++ [class.mem]p1: 3869 // A member shall not be declared twice in the member-specification [...] 3870 // 3871 // Here, we need only consider static data members. 3872 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3873 Diag(New->getLocation(), diag::err_duplicate_member) 3874 << New->getIdentifier(); 3875 Diag(Old->getLocation(), diag::note_previous_declaration); 3876 New->setInvalidDecl(); 3877 } 3878 3879 mergeDeclAttributes(New, Old); 3880 // Warn if an already-declared variable is made a weak_import in a subsequent 3881 // declaration 3882 if (New->hasAttr<WeakImportAttr>() && 3883 Old->getStorageClass() == SC_None && 3884 !Old->hasAttr<WeakImportAttr>()) { 3885 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3886 notePreviousDefinition(Old, New->getLocation()); 3887 // Remove weak_import attribute on new declaration. 3888 New->dropAttr<WeakImportAttr>(); 3889 } 3890 3891 if (New->hasAttr<InternalLinkageAttr>() && 3892 !Old->hasAttr<InternalLinkageAttr>()) { 3893 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3894 << New->getDeclName(); 3895 notePreviousDefinition(Old, New->getLocation()); 3896 New->dropAttr<InternalLinkageAttr>(); 3897 } 3898 3899 // Merge the types. 3900 VarDecl *MostRecent = Old->getMostRecentDecl(); 3901 if (MostRecent != Old) { 3902 MergeVarDeclTypes(New, MostRecent, 3903 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3904 if (New->isInvalidDecl()) 3905 return; 3906 } 3907 3908 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3909 if (New->isInvalidDecl()) 3910 return; 3911 3912 diag::kind PrevDiag; 3913 SourceLocation OldLocation; 3914 std::tie(PrevDiag, OldLocation) = 3915 getNoteDiagForInvalidRedeclaration(Old, New); 3916 3917 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3918 if (New->getStorageClass() == SC_Static && 3919 !New->isStaticDataMember() && 3920 Old->hasExternalFormalLinkage()) { 3921 if (getLangOpts().MicrosoftExt) { 3922 Diag(New->getLocation(), diag::ext_static_non_static) 3923 << New->getDeclName(); 3924 Diag(OldLocation, PrevDiag); 3925 } else { 3926 Diag(New->getLocation(), diag::err_static_non_static) 3927 << New->getDeclName(); 3928 Diag(OldLocation, PrevDiag); 3929 return New->setInvalidDecl(); 3930 } 3931 } 3932 // C99 6.2.2p4: 3933 // For an identifier declared with the storage-class specifier 3934 // extern in a scope in which a prior declaration of that 3935 // identifier is visible,23) if the prior declaration specifies 3936 // internal or external linkage, the linkage of the identifier at 3937 // the later declaration is the same as the linkage specified at 3938 // the prior declaration. If no prior declaration is visible, or 3939 // if the prior declaration specifies no linkage, then the 3940 // identifier has external linkage. 3941 if (New->hasExternalStorage() && Old->hasLinkage()) 3942 /* Okay */; 3943 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3944 !New->isStaticDataMember() && 3945 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3946 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3947 Diag(OldLocation, PrevDiag); 3948 return New->setInvalidDecl(); 3949 } 3950 3951 // Check if extern is followed by non-extern and vice-versa. 3952 if (New->hasExternalStorage() && 3953 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3954 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3955 Diag(OldLocation, PrevDiag); 3956 return New->setInvalidDecl(); 3957 } 3958 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3959 !New->hasExternalStorage()) { 3960 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3961 Diag(OldLocation, PrevDiag); 3962 return New->setInvalidDecl(); 3963 } 3964 3965 if (CheckRedeclarationModuleOwnership(New, Old)) 3966 return; 3967 3968 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3969 3970 // FIXME: The test for external storage here seems wrong? We still 3971 // need to check for mismatches. 3972 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3973 // Don't complain about out-of-line definitions of static members. 3974 !(Old->getLexicalDeclContext()->isRecord() && 3975 !New->getLexicalDeclContext()->isRecord())) { 3976 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3977 Diag(OldLocation, PrevDiag); 3978 return New->setInvalidDecl(); 3979 } 3980 3981 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3982 if (VarDecl *Def = Old->getDefinition()) { 3983 // C++1z [dcl.fcn.spec]p4: 3984 // If the definition of a variable appears in a translation unit before 3985 // its first declaration as inline, the program is ill-formed. 3986 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3987 Diag(Def->getLocation(), diag::note_previous_definition); 3988 } 3989 } 3990 3991 // If this redeclaration makes the variable inline, we may need to add it to 3992 // UndefinedButUsed. 3993 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3994 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3995 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3996 SourceLocation())); 3997 3998 if (New->getTLSKind() != Old->getTLSKind()) { 3999 if (!Old->getTLSKind()) { 4000 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4001 Diag(OldLocation, PrevDiag); 4002 } else if (!New->getTLSKind()) { 4003 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4004 Diag(OldLocation, PrevDiag); 4005 } else { 4006 // Do not allow redeclaration to change the variable between requiring 4007 // static and dynamic initialization. 4008 // FIXME: GCC allows this, but uses the TLS keyword on the first 4009 // declaration to determine the kind. Do we need to be compatible here? 4010 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4011 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4012 Diag(OldLocation, PrevDiag); 4013 } 4014 } 4015 4016 // C++ doesn't have tentative definitions, so go right ahead and check here. 4017 if (getLangOpts().CPlusPlus && 4018 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4019 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4020 Old->getCanonicalDecl()->isConstexpr()) { 4021 // This definition won't be a definition any more once it's been merged. 4022 Diag(New->getLocation(), 4023 diag::warn_deprecated_redundant_constexpr_static_def); 4024 } else if (VarDecl *Def = Old->getDefinition()) { 4025 if (checkVarDeclRedefinition(Def, New)) 4026 return; 4027 } 4028 } 4029 4030 if (haveIncompatibleLanguageLinkages(Old, New)) { 4031 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4032 Diag(OldLocation, PrevDiag); 4033 New->setInvalidDecl(); 4034 return; 4035 } 4036 4037 // Merge "used" flag. 4038 if (Old->getMostRecentDecl()->isUsed(false)) 4039 New->setIsUsed(); 4040 4041 // Keep a chain of previous declarations. 4042 New->setPreviousDecl(Old); 4043 if (NewTemplate) 4044 NewTemplate->setPreviousDecl(OldTemplate); 4045 adjustDeclContextForDeclaratorDecl(New, Old); 4046 4047 // Inherit access appropriately. 4048 New->setAccess(Old->getAccess()); 4049 if (NewTemplate) 4050 NewTemplate->setAccess(New->getAccess()); 4051 4052 if (Old->isInline()) 4053 New->setImplicitlyInline(); 4054 } 4055 4056 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4057 SourceManager &SrcMgr = getSourceManager(); 4058 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4059 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4060 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4061 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4062 auto &HSI = PP.getHeaderSearchInfo(); 4063 StringRef HdrFilename = 4064 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4065 4066 auto noteFromModuleOrInclude = [&](Module *Mod, 4067 SourceLocation IncLoc) -> bool { 4068 // Redefinition errors with modules are common with non modular mapped 4069 // headers, example: a non-modular header H in module A that also gets 4070 // included directly in a TU. Pointing twice to the same header/definition 4071 // is confusing, try to get better diagnostics when modules is on. 4072 if (IncLoc.isValid()) { 4073 if (Mod) { 4074 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4075 << HdrFilename.str() << Mod->getFullModuleName(); 4076 if (!Mod->DefinitionLoc.isInvalid()) 4077 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4078 << Mod->getFullModuleName(); 4079 } else { 4080 Diag(IncLoc, diag::note_redefinition_include_same_file) 4081 << HdrFilename.str(); 4082 } 4083 return true; 4084 } 4085 4086 return false; 4087 }; 4088 4089 // Is it the same file and same offset? Provide more information on why 4090 // this leads to a redefinition error. 4091 bool EmittedDiag = false; 4092 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4093 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4094 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4095 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4096 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4097 4098 // If the header has no guards, emit a note suggesting one. 4099 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4100 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4101 4102 if (EmittedDiag) 4103 return; 4104 } 4105 4106 // Redefinition coming from different files or couldn't do better above. 4107 if (Old->getLocation().isValid()) 4108 Diag(Old->getLocation(), diag::note_previous_definition); 4109 } 4110 4111 /// We've just determined that \p Old and \p New both appear to be definitions 4112 /// of the same variable. Either diagnose or fix the problem. 4113 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4114 if (!hasVisibleDefinition(Old) && 4115 (New->getFormalLinkage() == InternalLinkage || 4116 New->isInline() || 4117 New->getDescribedVarTemplate() || 4118 New->getNumTemplateParameterLists() || 4119 New->getDeclContext()->isDependentContext())) { 4120 // The previous definition is hidden, and multiple definitions are 4121 // permitted (in separate TUs). Demote this to a declaration. 4122 New->demoteThisDefinitionToDeclaration(); 4123 4124 // Make the canonical definition visible. 4125 if (auto *OldTD = Old->getDescribedVarTemplate()) 4126 makeMergedDefinitionVisible(OldTD); 4127 makeMergedDefinitionVisible(Old); 4128 return false; 4129 } else { 4130 Diag(New->getLocation(), diag::err_redefinition) << New; 4131 notePreviousDefinition(Old, New->getLocation()); 4132 New->setInvalidDecl(); 4133 return true; 4134 } 4135 } 4136 4137 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4138 /// no declarator (e.g. "struct foo;") is parsed. 4139 Decl * 4140 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4141 RecordDecl *&AnonRecord) { 4142 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4143 AnonRecord); 4144 } 4145 4146 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4147 // disambiguate entities defined in different scopes. 4148 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4149 // compatibility. 4150 // We will pick our mangling number depending on which version of MSVC is being 4151 // targeted. 4152 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4153 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4154 ? S->getMSCurManglingNumber() 4155 : S->getMSLastManglingNumber(); 4156 } 4157 4158 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4159 if (!Context.getLangOpts().CPlusPlus) 4160 return; 4161 4162 if (isa<CXXRecordDecl>(Tag->getParent())) { 4163 // If this tag is the direct child of a class, number it if 4164 // it is anonymous. 4165 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4166 return; 4167 MangleNumberingContext &MCtx = 4168 Context.getManglingNumberContext(Tag->getParent()); 4169 Context.setManglingNumber( 4170 Tag, MCtx.getManglingNumber( 4171 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4172 return; 4173 } 4174 4175 // If this tag isn't a direct child of a class, number it if it is local. 4176 Decl *ManglingContextDecl; 4177 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4178 Tag->getDeclContext(), ManglingContextDecl)) { 4179 Context.setManglingNumber( 4180 Tag, MCtx->getManglingNumber( 4181 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4182 } 4183 } 4184 4185 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4186 TypedefNameDecl *NewTD) { 4187 if (TagFromDeclSpec->isInvalidDecl()) 4188 return; 4189 4190 // Do nothing if the tag already has a name for linkage purposes. 4191 if (TagFromDeclSpec->hasNameForLinkage()) 4192 return; 4193 4194 // A well-formed anonymous tag must always be a TUK_Definition. 4195 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4196 4197 // The type must match the tag exactly; no qualifiers allowed. 4198 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4199 Context.getTagDeclType(TagFromDeclSpec))) { 4200 if (getLangOpts().CPlusPlus) 4201 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4202 return; 4203 } 4204 4205 // If we've already computed linkage for the anonymous tag, then 4206 // adding a typedef name for the anonymous decl can change that 4207 // linkage, which might be a serious problem. Diagnose this as 4208 // unsupported and ignore the typedef name. TODO: we should 4209 // pursue this as a language defect and establish a formal rule 4210 // for how to handle it. 4211 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4212 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4213 4214 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4215 tagLoc = getLocForEndOfToken(tagLoc); 4216 4217 llvm::SmallString<40> textToInsert; 4218 textToInsert += ' '; 4219 textToInsert += NewTD->getIdentifier()->getName(); 4220 Diag(tagLoc, diag::note_typedef_changes_linkage) 4221 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4222 return; 4223 } 4224 4225 // Otherwise, set this is the anon-decl typedef for the tag. 4226 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4227 } 4228 4229 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4230 switch (T) { 4231 case DeclSpec::TST_class: 4232 return 0; 4233 case DeclSpec::TST_struct: 4234 return 1; 4235 case DeclSpec::TST_interface: 4236 return 2; 4237 case DeclSpec::TST_union: 4238 return 3; 4239 case DeclSpec::TST_enum: 4240 return 4; 4241 default: 4242 llvm_unreachable("unexpected type specifier"); 4243 } 4244 } 4245 4246 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4247 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4248 /// parameters to cope with template friend declarations. 4249 Decl * 4250 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4251 MultiTemplateParamsArg TemplateParams, 4252 bool IsExplicitInstantiation, 4253 RecordDecl *&AnonRecord) { 4254 Decl *TagD = nullptr; 4255 TagDecl *Tag = nullptr; 4256 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4257 DS.getTypeSpecType() == DeclSpec::TST_struct || 4258 DS.getTypeSpecType() == DeclSpec::TST_interface || 4259 DS.getTypeSpecType() == DeclSpec::TST_union || 4260 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4261 TagD = DS.getRepAsDecl(); 4262 4263 if (!TagD) // We probably had an error 4264 return nullptr; 4265 4266 // Note that the above type specs guarantee that the 4267 // type rep is a Decl, whereas in many of the others 4268 // it's a Type. 4269 if (isa<TagDecl>(TagD)) 4270 Tag = cast<TagDecl>(TagD); 4271 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4272 Tag = CTD->getTemplatedDecl(); 4273 } 4274 4275 if (Tag) { 4276 handleTagNumbering(Tag, S); 4277 Tag->setFreeStanding(); 4278 if (Tag->isInvalidDecl()) 4279 return Tag; 4280 } 4281 4282 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4283 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4284 // or incomplete types shall not be restrict-qualified." 4285 if (TypeQuals & DeclSpec::TQ_restrict) 4286 Diag(DS.getRestrictSpecLoc(), 4287 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4288 << DS.getSourceRange(); 4289 } 4290 4291 if (DS.isInlineSpecified()) 4292 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4293 << getLangOpts().CPlusPlus17; 4294 4295 if (DS.hasConstexprSpecifier()) { 4296 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4297 // and definitions of functions and variables. 4298 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4299 // the declaration of a function or function template 4300 bool IsConsteval = DS.getConstexprSpecifier() == CSK_consteval; 4301 if (Tag) 4302 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4303 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << IsConsteval; 4304 else 4305 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4306 << IsConsteval; 4307 // Don't emit warnings after this error. 4308 return TagD; 4309 } 4310 4311 DiagnoseFunctionSpecifiers(DS); 4312 4313 if (DS.isFriendSpecified()) { 4314 // If we're dealing with a decl but not a TagDecl, assume that 4315 // whatever routines created it handled the friendship aspect. 4316 if (TagD && !Tag) 4317 return nullptr; 4318 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4319 } 4320 4321 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4322 bool IsExplicitSpecialization = 4323 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4324 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4325 !IsExplicitInstantiation && !IsExplicitSpecialization && 4326 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4327 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4328 // nested-name-specifier unless it is an explicit instantiation 4329 // or an explicit specialization. 4330 // 4331 // FIXME: We allow class template partial specializations here too, per the 4332 // obvious intent of DR1819. 4333 // 4334 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4335 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4336 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4337 return nullptr; 4338 } 4339 4340 // Track whether this decl-specifier declares anything. 4341 bool DeclaresAnything = true; 4342 4343 // Handle anonymous struct definitions. 4344 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4345 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4346 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4347 if (getLangOpts().CPlusPlus || 4348 Record->getDeclContext()->isRecord()) { 4349 // If CurContext is a DeclContext that can contain statements, 4350 // RecursiveASTVisitor won't visit the decls that 4351 // BuildAnonymousStructOrUnion() will put into CurContext. 4352 // Also store them here so that they can be part of the 4353 // DeclStmt that gets created in this case. 4354 // FIXME: Also return the IndirectFieldDecls created by 4355 // BuildAnonymousStructOr union, for the same reason? 4356 if (CurContext->isFunctionOrMethod()) 4357 AnonRecord = Record; 4358 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4359 Context.getPrintingPolicy()); 4360 } 4361 4362 DeclaresAnything = false; 4363 } 4364 } 4365 4366 // C11 6.7.2.1p2: 4367 // A struct-declaration that does not declare an anonymous structure or 4368 // anonymous union shall contain a struct-declarator-list. 4369 // 4370 // This rule also existed in C89 and C99; the grammar for struct-declaration 4371 // did not permit a struct-declaration without a struct-declarator-list. 4372 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4373 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4374 // Check for Microsoft C extension: anonymous struct/union member. 4375 // Handle 2 kinds of anonymous struct/union: 4376 // struct STRUCT; 4377 // union UNION; 4378 // and 4379 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4380 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4381 if ((Tag && Tag->getDeclName()) || 4382 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4383 RecordDecl *Record = nullptr; 4384 if (Tag) 4385 Record = dyn_cast<RecordDecl>(Tag); 4386 else if (const RecordType *RT = 4387 DS.getRepAsType().get()->getAsStructureType()) 4388 Record = RT->getDecl(); 4389 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4390 Record = UT->getDecl(); 4391 4392 if (Record && getLangOpts().MicrosoftExt) { 4393 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4394 << Record->isUnion() << DS.getSourceRange(); 4395 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4396 } 4397 4398 DeclaresAnything = false; 4399 } 4400 } 4401 4402 // Skip all the checks below if we have a type error. 4403 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4404 (TagD && TagD->isInvalidDecl())) 4405 return TagD; 4406 4407 if (getLangOpts().CPlusPlus && 4408 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4409 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4410 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4411 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4412 DeclaresAnything = false; 4413 4414 if (!DS.isMissingDeclaratorOk()) { 4415 // Customize diagnostic for a typedef missing a name. 4416 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4417 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4418 << DS.getSourceRange(); 4419 else 4420 DeclaresAnything = false; 4421 } 4422 4423 if (DS.isModulePrivateSpecified() && 4424 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4425 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4426 << Tag->getTagKind() 4427 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4428 4429 ActOnDocumentableDecl(TagD); 4430 4431 // C 6.7/2: 4432 // A declaration [...] shall declare at least a declarator [...], a tag, 4433 // or the members of an enumeration. 4434 // C++ [dcl.dcl]p3: 4435 // [If there are no declarators], and except for the declaration of an 4436 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4437 // names into the program, or shall redeclare a name introduced by a 4438 // previous declaration. 4439 if (!DeclaresAnything) { 4440 // In C, we allow this as a (popular) extension / bug. Don't bother 4441 // producing further diagnostics for redundant qualifiers after this. 4442 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4443 return TagD; 4444 } 4445 4446 // C++ [dcl.stc]p1: 4447 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4448 // init-declarator-list of the declaration shall not be empty. 4449 // C++ [dcl.fct.spec]p1: 4450 // If a cv-qualifier appears in a decl-specifier-seq, the 4451 // init-declarator-list of the declaration shall not be empty. 4452 // 4453 // Spurious qualifiers here appear to be valid in C. 4454 unsigned DiagID = diag::warn_standalone_specifier; 4455 if (getLangOpts().CPlusPlus) 4456 DiagID = diag::ext_standalone_specifier; 4457 4458 // Note that a linkage-specification sets a storage class, but 4459 // 'extern "C" struct foo;' is actually valid and not theoretically 4460 // useless. 4461 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4462 if (SCS == DeclSpec::SCS_mutable) 4463 // Since mutable is not a viable storage class specifier in C, there is 4464 // no reason to treat it as an extension. Instead, diagnose as an error. 4465 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4466 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4467 Diag(DS.getStorageClassSpecLoc(), DiagID) 4468 << DeclSpec::getSpecifierName(SCS); 4469 } 4470 4471 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4472 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4473 << DeclSpec::getSpecifierName(TSCS); 4474 if (DS.getTypeQualifiers()) { 4475 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4476 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4477 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4478 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4479 // Restrict is covered above. 4480 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4481 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4482 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4483 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4484 } 4485 4486 // Warn about ignored type attributes, for example: 4487 // __attribute__((aligned)) struct A; 4488 // Attributes should be placed after tag to apply to type declaration. 4489 if (!DS.getAttributes().empty()) { 4490 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4491 if (TypeSpecType == DeclSpec::TST_class || 4492 TypeSpecType == DeclSpec::TST_struct || 4493 TypeSpecType == DeclSpec::TST_interface || 4494 TypeSpecType == DeclSpec::TST_union || 4495 TypeSpecType == DeclSpec::TST_enum) { 4496 for (const ParsedAttr &AL : DS.getAttributes()) 4497 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4498 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4499 } 4500 } 4501 4502 return TagD; 4503 } 4504 4505 /// We are trying to inject an anonymous member into the given scope; 4506 /// check if there's an existing declaration that can't be overloaded. 4507 /// 4508 /// \return true if this is a forbidden redeclaration 4509 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4510 Scope *S, 4511 DeclContext *Owner, 4512 DeclarationName Name, 4513 SourceLocation NameLoc, 4514 bool IsUnion) { 4515 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4516 Sema::ForVisibleRedeclaration); 4517 if (!SemaRef.LookupName(R, S)) return false; 4518 4519 // Pick a representative declaration. 4520 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4521 assert(PrevDecl && "Expected a non-null Decl"); 4522 4523 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4524 return false; 4525 4526 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4527 << IsUnion << Name; 4528 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4529 4530 return true; 4531 } 4532 4533 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4534 /// anonymous struct or union AnonRecord into the owning context Owner 4535 /// and scope S. This routine will be invoked just after we realize 4536 /// that an unnamed union or struct is actually an anonymous union or 4537 /// struct, e.g., 4538 /// 4539 /// @code 4540 /// union { 4541 /// int i; 4542 /// float f; 4543 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4544 /// // f into the surrounding scope.x 4545 /// @endcode 4546 /// 4547 /// This routine is recursive, injecting the names of nested anonymous 4548 /// structs/unions into the owning context and scope as well. 4549 static bool 4550 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4551 RecordDecl *AnonRecord, AccessSpecifier AS, 4552 SmallVectorImpl<NamedDecl *> &Chaining) { 4553 bool Invalid = false; 4554 4555 // Look every FieldDecl and IndirectFieldDecl with a name. 4556 for (auto *D : AnonRecord->decls()) { 4557 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4558 cast<NamedDecl>(D)->getDeclName()) { 4559 ValueDecl *VD = cast<ValueDecl>(D); 4560 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4561 VD->getLocation(), 4562 AnonRecord->isUnion())) { 4563 // C++ [class.union]p2: 4564 // The names of the members of an anonymous union shall be 4565 // distinct from the names of any other entity in the 4566 // scope in which the anonymous union is declared. 4567 Invalid = true; 4568 } else { 4569 // C++ [class.union]p2: 4570 // For the purpose of name lookup, after the anonymous union 4571 // definition, the members of the anonymous union are 4572 // considered to have been defined in the scope in which the 4573 // anonymous union is declared. 4574 unsigned OldChainingSize = Chaining.size(); 4575 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4576 Chaining.append(IF->chain_begin(), IF->chain_end()); 4577 else 4578 Chaining.push_back(VD); 4579 4580 assert(Chaining.size() >= 2); 4581 NamedDecl **NamedChain = 4582 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4583 for (unsigned i = 0; i < Chaining.size(); i++) 4584 NamedChain[i] = Chaining[i]; 4585 4586 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4587 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4588 VD->getType(), {NamedChain, Chaining.size()}); 4589 4590 for (const auto *Attr : VD->attrs()) 4591 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4592 4593 IndirectField->setAccess(AS); 4594 IndirectField->setImplicit(); 4595 SemaRef.PushOnScopeChains(IndirectField, S); 4596 4597 // That includes picking up the appropriate access specifier. 4598 if (AS != AS_none) IndirectField->setAccess(AS); 4599 4600 Chaining.resize(OldChainingSize); 4601 } 4602 } 4603 } 4604 4605 return Invalid; 4606 } 4607 4608 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4609 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4610 /// illegal input values are mapped to SC_None. 4611 static StorageClass 4612 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4613 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4614 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4615 "Parser allowed 'typedef' as storage class VarDecl."); 4616 switch (StorageClassSpec) { 4617 case DeclSpec::SCS_unspecified: return SC_None; 4618 case DeclSpec::SCS_extern: 4619 if (DS.isExternInLinkageSpec()) 4620 return SC_None; 4621 return SC_Extern; 4622 case DeclSpec::SCS_static: return SC_Static; 4623 case DeclSpec::SCS_auto: return SC_Auto; 4624 case DeclSpec::SCS_register: return SC_Register; 4625 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4626 // Illegal SCSs map to None: error reporting is up to the caller. 4627 case DeclSpec::SCS_mutable: // Fall through. 4628 case DeclSpec::SCS_typedef: return SC_None; 4629 } 4630 llvm_unreachable("unknown storage class specifier"); 4631 } 4632 4633 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4634 assert(Record->hasInClassInitializer()); 4635 4636 for (const auto *I : Record->decls()) { 4637 const auto *FD = dyn_cast<FieldDecl>(I); 4638 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4639 FD = IFD->getAnonField(); 4640 if (FD && FD->hasInClassInitializer()) 4641 return FD->getLocation(); 4642 } 4643 4644 llvm_unreachable("couldn't find in-class initializer"); 4645 } 4646 4647 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4648 SourceLocation DefaultInitLoc) { 4649 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4650 return; 4651 4652 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4653 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4654 } 4655 4656 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4657 CXXRecordDecl *AnonUnion) { 4658 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4659 return; 4660 4661 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4662 } 4663 4664 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4665 /// anonymous structure or union. Anonymous unions are a C++ feature 4666 /// (C++ [class.union]) and a C11 feature; anonymous structures 4667 /// are a C11 feature and GNU C++ extension. 4668 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4669 AccessSpecifier AS, 4670 RecordDecl *Record, 4671 const PrintingPolicy &Policy) { 4672 DeclContext *Owner = Record->getDeclContext(); 4673 4674 // Diagnose whether this anonymous struct/union is an extension. 4675 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4676 Diag(Record->getLocation(), diag::ext_anonymous_union); 4677 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4678 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4679 else if (!Record->isUnion() && !getLangOpts().C11) 4680 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4681 4682 // C and C++ require different kinds of checks for anonymous 4683 // structs/unions. 4684 bool Invalid = false; 4685 if (getLangOpts().CPlusPlus) { 4686 const char *PrevSpec = nullptr; 4687 unsigned DiagID; 4688 if (Record->isUnion()) { 4689 // C++ [class.union]p6: 4690 // C++17 [class.union.anon]p2: 4691 // Anonymous unions declared in a named namespace or in the 4692 // global namespace shall be declared static. 4693 DeclContext *OwnerScope = Owner->getRedeclContext(); 4694 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4695 (OwnerScope->isTranslationUnit() || 4696 (OwnerScope->isNamespace() && 4697 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4698 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4699 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4700 4701 // Recover by adding 'static'. 4702 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4703 PrevSpec, DiagID, Policy); 4704 } 4705 // C++ [class.union]p6: 4706 // A storage class is not allowed in a declaration of an 4707 // anonymous union in a class scope. 4708 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4709 isa<RecordDecl>(Owner)) { 4710 Diag(DS.getStorageClassSpecLoc(), 4711 diag::err_anonymous_union_with_storage_spec) 4712 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4713 4714 // Recover by removing the storage specifier. 4715 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4716 SourceLocation(), 4717 PrevSpec, DiagID, Context.getPrintingPolicy()); 4718 } 4719 } 4720 4721 // Ignore const/volatile/restrict qualifiers. 4722 if (DS.getTypeQualifiers()) { 4723 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4724 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4725 << Record->isUnion() << "const" 4726 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4727 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4728 Diag(DS.getVolatileSpecLoc(), 4729 diag::ext_anonymous_struct_union_qualified) 4730 << Record->isUnion() << "volatile" 4731 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4732 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4733 Diag(DS.getRestrictSpecLoc(), 4734 diag::ext_anonymous_struct_union_qualified) 4735 << Record->isUnion() << "restrict" 4736 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4737 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4738 Diag(DS.getAtomicSpecLoc(), 4739 diag::ext_anonymous_struct_union_qualified) 4740 << Record->isUnion() << "_Atomic" 4741 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4742 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4743 Diag(DS.getUnalignedSpecLoc(), 4744 diag::ext_anonymous_struct_union_qualified) 4745 << Record->isUnion() << "__unaligned" 4746 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4747 4748 DS.ClearTypeQualifiers(); 4749 } 4750 4751 // C++ [class.union]p2: 4752 // The member-specification of an anonymous union shall only 4753 // define non-static data members. [Note: nested types and 4754 // functions cannot be declared within an anonymous union. ] 4755 for (auto *Mem : Record->decls()) { 4756 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4757 // C++ [class.union]p3: 4758 // An anonymous union shall not have private or protected 4759 // members (clause 11). 4760 assert(FD->getAccess() != AS_none); 4761 if (FD->getAccess() != AS_public) { 4762 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4763 << Record->isUnion() << (FD->getAccess() == AS_protected); 4764 Invalid = true; 4765 } 4766 4767 // C++ [class.union]p1 4768 // An object of a class with a non-trivial constructor, a non-trivial 4769 // copy constructor, a non-trivial destructor, or a non-trivial copy 4770 // assignment operator cannot be a member of a union, nor can an 4771 // array of such objects. 4772 if (CheckNontrivialField(FD)) 4773 Invalid = true; 4774 } else if (Mem->isImplicit()) { 4775 // Any implicit members are fine. 4776 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4777 // This is a type that showed up in an 4778 // elaborated-type-specifier inside the anonymous struct or 4779 // union, but which actually declares a type outside of the 4780 // anonymous struct or union. It's okay. 4781 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4782 if (!MemRecord->isAnonymousStructOrUnion() && 4783 MemRecord->getDeclName()) { 4784 // Visual C++ allows type definition in anonymous struct or union. 4785 if (getLangOpts().MicrosoftExt) 4786 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4787 << Record->isUnion(); 4788 else { 4789 // This is a nested type declaration. 4790 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4791 << Record->isUnion(); 4792 Invalid = true; 4793 } 4794 } else { 4795 // This is an anonymous type definition within another anonymous type. 4796 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4797 // not part of standard C++. 4798 Diag(MemRecord->getLocation(), 4799 diag::ext_anonymous_record_with_anonymous_type) 4800 << Record->isUnion(); 4801 } 4802 } else if (isa<AccessSpecDecl>(Mem)) { 4803 // Any access specifier is fine. 4804 } else if (isa<StaticAssertDecl>(Mem)) { 4805 // In C++1z, static_assert declarations are also fine. 4806 } else { 4807 // We have something that isn't a non-static data 4808 // member. Complain about it. 4809 unsigned DK = diag::err_anonymous_record_bad_member; 4810 if (isa<TypeDecl>(Mem)) 4811 DK = diag::err_anonymous_record_with_type; 4812 else if (isa<FunctionDecl>(Mem)) 4813 DK = diag::err_anonymous_record_with_function; 4814 else if (isa<VarDecl>(Mem)) 4815 DK = diag::err_anonymous_record_with_static; 4816 4817 // Visual C++ allows type definition in anonymous struct or union. 4818 if (getLangOpts().MicrosoftExt && 4819 DK == diag::err_anonymous_record_with_type) 4820 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4821 << Record->isUnion(); 4822 else { 4823 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4824 Invalid = true; 4825 } 4826 } 4827 } 4828 4829 // C++11 [class.union]p8 (DR1460): 4830 // At most one variant member of a union may have a 4831 // brace-or-equal-initializer. 4832 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4833 Owner->isRecord()) 4834 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4835 cast<CXXRecordDecl>(Record)); 4836 } 4837 4838 if (!Record->isUnion() && !Owner->isRecord()) { 4839 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4840 << getLangOpts().CPlusPlus; 4841 Invalid = true; 4842 } 4843 4844 // C++ [dcl.dcl]p3: 4845 // [If there are no declarators], and except for the declaration of an 4846 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4847 // names into the program 4848 // C++ [class.mem]p2: 4849 // each such member-declaration shall either declare at least one member 4850 // name of the class or declare at least one unnamed bit-field 4851 // 4852 // For C this is an error even for a named struct, and is diagnosed elsewhere. 4853 if (getLangOpts().CPlusPlus && Record->field_empty()) 4854 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4855 4856 // Mock up a declarator. 4857 Declarator Dc(DS, DeclaratorContext::MemberContext); 4858 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4859 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4860 4861 // Create a declaration for this anonymous struct/union. 4862 NamedDecl *Anon = nullptr; 4863 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4864 Anon = FieldDecl::Create( 4865 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 4866 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 4867 /*BitWidth=*/nullptr, /*Mutable=*/false, 4868 /*InitStyle=*/ICIS_NoInit); 4869 Anon->setAccess(AS); 4870 if (getLangOpts().CPlusPlus) 4871 FieldCollector->Add(cast<FieldDecl>(Anon)); 4872 } else { 4873 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4874 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4875 if (SCSpec == DeclSpec::SCS_mutable) { 4876 // mutable can only appear on non-static class members, so it's always 4877 // an error here 4878 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4879 Invalid = true; 4880 SC = SC_None; 4881 } 4882 4883 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 4884 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4885 Context.getTypeDeclType(Record), TInfo, SC); 4886 4887 // Default-initialize the implicit variable. This initialization will be 4888 // trivial in almost all cases, except if a union member has an in-class 4889 // initializer: 4890 // union { int n = 0; }; 4891 ActOnUninitializedDecl(Anon); 4892 } 4893 Anon->setImplicit(); 4894 4895 // Mark this as an anonymous struct/union type. 4896 Record->setAnonymousStructOrUnion(true); 4897 4898 // Add the anonymous struct/union object to the current 4899 // context. We'll be referencing this object when we refer to one of 4900 // its members. 4901 Owner->addDecl(Anon); 4902 4903 // Inject the members of the anonymous struct/union into the owning 4904 // context and into the identifier resolver chain for name lookup 4905 // purposes. 4906 SmallVector<NamedDecl*, 2> Chain; 4907 Chain.push_back(Anon); 4908 4909 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4910 Invalid = true; 4911 4912 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4913 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4914 Decl *ManglingContextDecl; 4915 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4916 NewVD->getDeclContext(), ManglingContextDecl)) { 4917 Context.setManglingNumber( 4918 NewVD, MCtx->getManglingNumber( 4919 NewVD, getMSManglingNumber(getLangOpts(), S))); 4920 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4921 } 4922 } 4923 } 4924 4925 if (Invalid) 4926 Anon->setInvalidDecl(); 4927 4928 return Anon; 4929 } 4930 4931 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4932 /// Microsoft C anonymous structure. 4933 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4934 /// Example: 4935 /// 4936 /// struct A { int a; }; 4937 /// struct B { struct A; int b; }; 4938 /// 4939 /// void foo() { 4940 /// B var; 4941 /// var.a = 3; 4942 /// } 4943 /// 4944 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4945 RecordDecl *Record) { 4946 assert(Record && "expected a record!"); 4947 4948 // Mock up a declarator. 4949 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4950 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4951 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4952 4953 auto *ParentDecl = cast<RecordDecl>(CurContext); 4954 QualType RecTy = Context.getTypeDeclType(Record); 4955 4956 // Create a declaration for this anonymous struct. 4957 NamedDecl *Anon = 4958 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 4959 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 4960 /*BitWidth=*/nullptr, /*Mutable=*/false, 4961 /*InitStyle=*/ICIS_NoInit); 4962 Anon->setImplicit(); 4963 4964 // Add the anonymous struct object to the current context. 4965 CurContext->addDecl(Anon); 4966 4967 // Inject the members of the anonymous struct into the current 4968 // context and into the identifier resolver chain for name lookup 4969 // purposes. 4970 SmallVector<NamedDecl*, 2> Chain; 4971 Chain.push_back(Anon); 4972 4973 RecordDecl *RecordDef = Record->getDefinition(); 4974 if (RequireCompleteType(Anon->getLocation(), RecTy, 4975 diag::err_field_incomplete) || 4976 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4977 AS_none, Chain)) { 4978 Anon->setInvalidDecl(); 4979 ParentDecl->setInvalidDecl(); 4980 } 4981 4982 return Anon; 4983 } 4984 4985 /// GetNameForDeclarator - Determine the full declaration name for the 4986 /// given Declarator. 4987 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4988 return GetNameFromUnqualifiedId(D.getName()); 4989 } 4990 4991 /// Retrieves the declaration name from a parsed unqualified-id. 4992 DeclarationNameInfo 4993 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4994 DeclarationNameInfo NameInfo; 4995 NameInfo.setLoc(Name.StartLocation); 4996 4997 switch (Name.getKind()) { 4998 4999 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5000 case UnqualifiedIdKind::IK_Identifier: 5001 NameInfo.setName(Name.Identifier); 5002 return NameInfo; 5003 5004 case UnqualifiedIdKind::IK_DeductionGuideName: { 5005 // C++ [temp.deduct.guide]p3: 5006 // The simple-template-id shall name a class template specialization. 5007 // The template-name shall be the same identifier as the template-name 5008 // of the simple-template-id. 5009 // These together intend to imply that the template-name shall name a 5010 // class template. 5011 // FIXME: template<typename T> struct X {}; 5012 // template<typename T> using Y = X<T>; 5013 // Y(int) -> Y<int>; 5014 // satisfies these rules but does not name a class template. 5015 TemplateName TN = Name.TemplateName.get().get(); 5016 auto *Template = TN.getAsTemplateDecl(); 5017 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5018 Diag(Name.StartLocation, 5019 diag::err_deduction_guide_name_not_class_template) 5020 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5021 if (Template) 5022 Diag(Template->getLocation(), diag::note_template_decl_here); 5023 return DeclarationNameInfo(); 5024 } 5025 5026 NameInfo.setName( 5027 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5028 return NameInfo; 5029 } 5030 5031 case UnqualifiedIdKind::IK_OperatorFunctionId: 5032 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5033 Name.OperatorFunctionId.Operator)); 5034 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5035 = Name.OperatorFunctionId.SymbolLocations[0]; 5036 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5037 = Name.EndLocation.getRawEncoding(); 5038 return NameInfo; 5039 5040 case UnqualifiedIdKind::IK_LiteralOperatorId: 5041 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5042 Name.Identifier)); 5043 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5044 return NameInfo; 5045 5046 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5047 TypeSourceInfo *TInfo; 5048 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5049 if (Ty.isNull()) 5050 return DeclarationNameInfo(); 5051 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5052 Context.getCanonicalType(Ty))); 5053 NameInfo.setNamedTypeInfo(TInfo); 5054 return NameInfo; 5055 } 5056 5057 case UnqualifiedIdKind::IK_ConstructorName: { 5058 TypeSourceInfo *TInfo; 5059 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5060 if (Ty.isNull()) 5061 return DeclarationNameInfo(); 5062 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5063 Context.getCanonicalType(Ty))); 5064 NameInfo.setNamedTypeInfo(TInfo); 5065 return NameInfo; 5066 } 5067 5068 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5069 // In well-formed code, we can only have a constructor 5070 // template-id that refers to the current context, so go there 5071 // to find the actual type being constructed. 5072 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5073 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5074 return DeclarationNameInfo(); 5075 5076 // Determine the type of the class being constructed. 5077 QualType CurClassType = Context.getTypeDeclType(CurClass); 5078 5079 // FIXME: Check two things: that the template-id names the same type as 5080 // CurClassType, and that the template-id does not occur when the name 5081 // was qualified. 5082 5083 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5084 Context.getCanonicalType(CurClassType))); 5085 // FIXME: should we retrieve TypeSourceInfo? 5086 NameInfo.setNamedTypeInfo(nullptr); 5087 return NameInfo; 5088 } 5089 5090 case UnqualifiedIdKind::IK_DestructorName: { 5091 TypeSourceInfo *TInfo; 5092 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5093 if (Ty.isNull()) 5094 return DeclarationNameInfo(); 5095 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5096 Context.getCanonicalType(Ty))); 5097 NameInfo.setNamedTypeInfo(TInfo); 5098 return NameInfo; 5099 } 5100 5101 case UnqualifiedIdKind::IK_TemplateId: { 5102 TemplateName TName = Name.TemplateId->Template.get(); 5103 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5104 return Context.getNameForTemplate(TName, TNameLoc); 5105 } 5106 5107 } // switch (Name.getKind()) 5108 5109 llvm_unreachable("Unknown name kind"); 5110 } 5111 5112 static QualType getCoreType(QualType Ty) { 5113 do { 5114 if (Ty->isPointerType() || Ty->isReferenceType()) 5115 Ty = Ty->getPointeeType(); 5116 else if (Ty->isArrayType()) 5117 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5118 else 5119 return Ty.withoutLocalFastQualifiers(); 5120 } while (true); 5121 } 5122 5123 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5124 /// and Definition have "nearly" matching parameters. This heuristic is 5125 /// used to improve diagnostics in the case where an out-of-line function 5126 /// definition doesn't match any declaration within the class or namespace. 5127 /// Also sets Params to the list of indices to the parameters that differ 5128 /// between the declaration and the definition. If hasSimilarParameters 5129 /// returns true and Params is empty, then all of the parameters match. 5130 static bool hasSimilarParameters(ASTContext &Context, 5131 FunctionDecl *Declaration, 5132 FunctionDecl *Definition, 5133 SmallVectorImpl<unsigned> &Params) { 5134 Params.clear(); 5135 if (Declaration->param_size() != Definition->param_size()) 5136 return false; 5137 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5138 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5139 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5140 5141 // The parameter types are identical 5142 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5143 continue; 5144 5145 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5146 QualType DefParamBaseTy = getCoreType(DefParamTy); 5147 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5148 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5149 5150 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5151 (DeclTyName && DeclTyName == DefTyName)) 5152 Params.push_back(Idx); 5153 else // The two parameters aren't even close 5154 return false; 5155 } 5156 5157 return true; 5158 } 5159 5160 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5161 /// declarator needs to be rebuilt in the current instantiation. 5162 /// Any bits of declarator which appear before the name are valid for 5163 /// consideration here. That's specifically the type in the decl spec 5164 /// and the base type in any member-pointer chunks. 5165 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5166 DeclarationName Name) { 5167 // The types we specifically need to rebuild are: 5168 // - typenames, typeofs, and decltypes 5169 // - types which will become injected class names 5170 // Of course, we also need to rebuild any type referencing such a 5171 // type. It's safest to just say "dependent", but we call out a 5172 // few cases here. 5173 5174 DeclSpec &DS = D.getMutableDeclSpec(); 5175 switch (DS.getTypeSpecType()) { 5176 case DeclSpec::TST_typename: 5177 case DeclSpec::TST_typeofType: 5178 case DeclSpec::TST_underlyingType: 5179 case DeclSpec::TST_atomic: { 5180 // Grab the type from the parser. 5181 TypeSourceInfo *TSI = nullptr; 5182 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5183 if (T.isNull() || !T->isDependentType()) break; 5184 5185 // Make sure there's a type source info. This isn't really much 5186 // of a waste; most dependent types should have type source info 5187 // attached already. 5188 if (!TSI) 5189 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5190 5191 // Rebuild the type in the current instantiation. 5192 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5193 if (!TSI) return true; 5194 5195 // Store the new type back in the decl spec. 5196 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5197 DS.UpdateTypeRep(LocType); 5198 break; 5199 } 5200 5201 case DeclSpec::TST_decltype: 5202 case DeclSpec::TST_typeofExpr: { 5203 Expr *E = DS.getRepAsExpr(); 5204 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5205 if (Result.isInvalid()) return true; 5206 DS.UpdateExprRep(Result.get()); 5207 break; 5208 } 5209 5210 default: 5211 // Nothing to do for these decl specs. 5212 break; 5213 } 5214 5215 // It doesn't matter what order we do this in. 5216 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5217 DeclaratorChunk &Chunk = D.getTypeObject(I); 5218 5219 // The only type information in the declarator which can come 5220 // before the declaration name is the base type of a member 5221 // pointer. 5222 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5223 continue; 5224 5225 // Rebuild the scope specifier in-place. 5226 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5227 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5228 return true; 5229 } 5230 5231 return false; 5232 } 5233 5234 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5235 D.setFunctionDefinitionKind(FDK_Declaration); 5236 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5237 5238 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5239 Dcl && Dcl->getDeclContext()->isFileContext()) 5240 Dcl->setTopLevelDeclInObjCContainer(); 5241 5242 if (getLangOpts().OpenCL) 5243 setCurrentOpenCLExtensionForDecl(Dcl); 5244 5245 return Dcl; 5246 } 5247 5248 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5249 /// If T is the name of a class, then each of the following shall have a 5250 /// name different from T: 5251 /// - every static data member of class T; 5252 /// - every member function of class T 5253 /// - every member of class T that is itself a type; 5254 /// \returns true if the declaration name violates these rules. 5255 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5256 DeclarationNameInfo NameInfo) { 5257 DeclarationName Name = NameInfo.getName(); 5258 5259 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5260 while (Record && Record->isAnonymousStructOrUnion()) 5261 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5262 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5263 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5264 return true; 5265 } 5266 5267 return false; 5268 } 5269 5270 /// Diagnose a declaration whose declarator-id has the given 5271 /// nested-name-specifier. 5272 /// 5273 /// \param SS The nested-name-specifier of the declarator-id. 5274 /// 5275 /// \param DC The declaration context to which the nested-name-specifier 5276 /// resolves. 5277 /// 5278 /// \param Name The name of the entity being declared. 5279 /// 5280 /// \param Loc The location of the name of the entity being declared. 5281 /// 5282 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5283 /// we're declaring an explicit / partial specialization / instantiation. 5284 /// 5285 /// \returns true if we cannot safely recover from this error, false otherwise. 5286 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5287 DeclarationName Name, 5288 SourceLocation Loc, bool IsTemplateId) { 5289 DeclContext *Cur = CurContext; 5290 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5291 Cur = Cur->getParent(); 5292 5293 // If the user provided a superfluous scope specifier that refers back to the 5294 // class in which the entity is already declared, diagnose and ignore it. 5295 // 5296 // class X { 5297 // void X::f(); 5298 // }; 5299 // 5300 // Note, it was once ill-formed to give redundant qualification in all 5301 // contexts, but that rule was removed by DR482. 5302 if (Cur->Equals(DC)) { 5303 if (Cur->isRecord()) { 5304 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5305 : diag::err_member_extra_qualification) 5306 << Name << FixItHint::CreateRemoval(SS.getRange()); 5307 SS.clear(); 5308 } else { 5309 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5310 } 5311 return false; 5312 } 5313 5314 // Check whether the qualifying scope encloses the scope of the original 5315 // declaration. For a template-id, we perform the checks in 5316 // CheckTemplateSpecializationScope. 5317 if (!Cur->Encloses(DC) && !IsTemplateId) { 5318 if (Cur->isRecord()) 5319 Diag(Loc, diag::err_member_qualification) 5320 << Name << SS.getRange(); 5321 else if (isa<TranslationUnitDecl>(DC)) 5322 Diag(Loc, diag::err_invalid_declarator_global_scope) 5323 << Name << SS.getRange(); 5324 else if (isa<FunctionDecl>(Cur)) 5325 Diag(Loc, diag::err_invalid_declarator_in_function) 5326 << Name << SS.getRange(); 5327 else if (isa<BlockDecl>(Cur)) 5328 Diag(Loc, diag::err_invalid_declarator_in_block) 5329 << Name << SS.getRange(); 5330 else 5331 Diag(Loc, diag::err_invalid_declarator_scope) 5332 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5333 5334 return true; 5335 } 5336 5337 if (Cur->isRecord()) { 5338 // Cannot qualify members within a class. 5339 Diag(Loc, diag::err_member_qualification) 5340 << Name << SS.getRange(); 5341 SS.clear(); 5342 5343 // C++ constructors and destructors with incorrect scopes can break 5344 // our AST invariants by having the wrong underlying types. If 5345 // that's the case, then drop this declaration entirely. 5346 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5347 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5348 !Context.hasSameType(Name.getCXXNameType(), 5349 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5350 return true; 5351 5352 return false; 5353 } 5354 5355 // C++11 [dcl.meaning]p1: 5356 // [...] "The nested-name-specifier of the qualified declarator-id shall 5357 // not begin with a decltype-specifer" 5358 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5359 while (SpecLoc.getPrefix()) 5360 SpecLoc = SpecLoc.getPrefix(); 5361 if (dyn_cast_or_null<DecltypeType>( 5362 SpecLoc.getNestedNameSpecifier()->getAsType())) 5363 Diag(Loc, diag::err_decltype_in_declarator) 5364 << SpecLoc.getTypeLoc().getSourceRange(); 5365 5366 return false; 5367 } 5368 5369 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5370 MultiTemplateParamsArg TemplateParamLists) { 5371 // TODO: consider using NameInfo for diagnostic. 5372 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5373 DeclarationName Name = NameInfo.getName(); 5374 5375 // All of these full declarators require an identifier. If it doesn't have 5376 // one, the ParsedFreeStandingDeclSpec action should be used. 5377 if (D.isDecompositionDeclarator()) { 5378 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5379 } else if (!Name) { 5380 if (!D.isInvalidType()) // Reject this if we think it is valid. 5381 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5382 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5383 return nullptr; 5384 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5385 return nullptr; 5386 5387 // The scope passed in may not be a decl scope. Zip up the scope tree until 5388 // we find one that is. 5389 while ((S->getFlags() & Scope::DeclScope) == 0 || 5390 (S->getFlags() & Scope::TemplateParamScope) != 0) 5391 S = S->getParent(); 5392 5393 DeclContext *DC = CurContext; 5394 if (D.getCXXScopeSpec().isInvalid()) 5395 D.setInvalidType(); 5396 else if (D.getCXXScopeSpec().isSet()) { 5397 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5398 UPPC_DeclarationQualifier)) 5399 return nullptr; 5400 5401 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5402 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5403 if (!DC || isa<EnumDecl>(DC)) { 5404 // If we could not compute the declaration context, it's because the 5405 // declaration context is dependent but does not refer to a class, 5406 // class template, or class template partial specialization. Complain 5407 // and return early, to avoid the coming semantic disaster. 5408 Diag(D.getIdentifierLoc(), 5409 diag::err_template_qualified_declarator_no_match) 5410 << D.getCXXScopeSpec().getScopeRep() 5411 << D.getCXXScopeSpec().getRange(); 5412 return nullptr; 5413 } 5414 bool IsDependentContext = DC->isDependentContext(); 5415 5416 if (!IsDependentContext && 5417 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5418 return nullptr; 5419 5420 // If a class is incomplete, do not parse entities inside it. 5421 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5422 Diag(D.getIdentifierLoc(), 5423 diag::err_member_def_undefined_record) 5424 << Name << DC << D.getCXXScopeSpec().getRange(); 5425 return nullptr; 5426 } 5427 if (!D.getDeclSpec().isFriendSpecified()) { 5428 if (diagnoseQualifiedDeclaration( 5429 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5430 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5431 if (DC->isRecord()) 5432 return nullptr; 5433 5434 D.setInvalidType(); 5435 } 5436 } 5437 5438 // Check whether we need to rebuild the type of the given 5439 // declaration in the current instantiation. 5440 if (EnteringContext && IsDependentContext && 5441 TemplateParamLists.size() != 0) { 5442 ContextRAII SavedContext(*this, DC); 5443 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5444 D.setInvalidType(); 5445 } 5446 } 5447 5448 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5449 QualType R = TInfo->getType(); 5450 5451 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5452 UPPC_DeclarationType)) 5453 D.setInvalidType(); 5454 5455 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5456 forRedeclarationInCurContext()); 5457 5458 // See if this is a redefinition of a variable in the same scope. 5459 if (!D.getCXXScopeSpec().isSet()) { 5460 bool IsLinkageLookup = false; 5461 bool CreateBuiltins = false; 5462 5463 // If the declaration we're planning to build will be a function 5464 // or object with linkage, then look for another declaration with 5465 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5466 // 5467 // If the declaration we're planning to build will be declared with 5468 // external linkage in the translation unit, create any builtin with 5469 // the same name. 5470 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5471 /* Do nothing*/; 5472 else if (CurContext->isFunctionOrMethod() && 5473 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5474 R->isFunctionType())) { 5475 IsLinkageLookup = true; 5476 CreateBuiltins = 5477 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5478 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5479 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5480 CreateBuiltins = true; 5481 5482 if (IsLinkageLookup) { 5483 Previous.clear(LookupRedeclarationWithLinkage); 5484 Previous.setRedeclarationKind(ForExternalRedeclaration); 5485 } 5486 5487 LookupName(Previous, S, CreateBuiltins); 5488 } else { // Something like "int foo::x;" 5489 LookupQualifiedName(Previous, DC); 5490 5491 // C++ [dcl.meaning]p1: 5492 // When the declarator-id is qualified, the declaration shall refer to a 5493 // previously declared member of the class or namespace to which the 5494 // qualifier refers (or, in the case of a namespace, of an element of the 5495 // inline namespace set of that namespace (7.3.1)) or to a specialization 5496 // thereof; [...] 5497 // 5498 // Note that we already checked the context above, and that we do not have 5499 // enough information to make sure that Previous contains the declaration 5500 // we want to match. For example, given: 5501 // 5502 // class X { 5503 // void f(); 5504 // void f(float); 5505 // }; 5506 // 5507 // void X::f(int) { } // ill-formed 5508 // 5509 // In this case, Previous will point to the overload set 5510 // containing the two f's declared in X, but neither of them 5511 // matches. 5512 5513 // C++ [dcl.meaning]p1: 5514 // [...] the member shall not merely have been introduced by a 5515 // using-declaration in the scope of the class or namespace nominated by 5516 // the nested-name-specifier of the declarator-id. 5517 RemoveUsingDecls(Previous); 5518 } 5519 5520 if (Previous.isSingleResult() && 5521 Previous.getFoundDecl()->isTemplateParameter()) { 5522 // Maybe we will complain about the shadowed template parameter. 5523 if (!D.isInvalidType()) 5524 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5525 Previous.getFoundDecl()); 5526 5527 // Just pretend that we didn't see the previous declaration. 5528 Previous.clear(); 5529 } 5530 5531 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5532 // Forget that the previous declaration is the injected-class-name. 5533 Previous.clear(); 5534 5535 // In C++, the previous declaration we find might be a tag type 5536 // (class or enum). In this case, the new declaration will hide the 5537 // tag type. Note that this applies to functions, function templates, and 5538 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5539 if (Previous.isSingleTagDecl() && 5540 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5541 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5542 Previous.clear(); 5543 5544 // Check that there are no default arguments other than in the parameters 5545 // of a function declaration (C++ only). 5546 if (getLangOpts().CPlusPlus) 5547 CheckExtraCXXDefaultArguments(D); 5548 5549 NamedDecl *New; 5550 5551 bool AddToScope = true; 5552 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5553 if (TemplateParamLists.size()) { 5554 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5555 return nullptr; 5556 } 5557 5558 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5559 } else if (R->isFunctionType()) { 5560 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5561 TemplateParamLists, 5562 AddToScope); 5563 } else { 5564 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5565 AddToScope); 5566 } 5567 5568 if (!New) 5569 return nullptr; 5570 5571 // If this has an identifier and is not a function template specialization, 5572 // add it to the scope stack. 5573 if (New->getDeclName() && AddToScope) 5574 PushOnScopeChains(New, S); 5575 5576 if (isInOpenMPDeclareTargetContext()) 5577 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5578 5579 return New; 5580 } 5581 5582 /// Helper method to turn variable array types into constant array 5583 /// types in certain situations which would otherwise be errors (for 5584 /// GCC compatibility). 5585 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5586 ASTContext &Context, 5587 bool &SizeIsNegative, 5588 llvm::APSInt &Oversized) { 5589 // This method tries to turn a variable array into a constant 5590 // array even when the size isn't an ICE. This is necessary 5591 // for compatibility with code that depends on gcc's buggy 5592 // constant expression folding, like struct {char x[(int)(char*)2];} 5593 SizeIsNegative = false; 5594 Oversized = 0; 5595 5596 if (T->isDependentType()) 5597 return QualType(); 5598 5599 QualifierCollector Qs; 5600 const Type *Ty = Qs.strip(T); 5601 5602 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5603 QualType Pointee = PTy->getPointeeType(); 5604 QualType FixedType = 5605 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5606 Oversized); 5607 if (FixedType.isNull()) return FixedType; 5608 FixedType = Context.getPointerType(FixedType); 5609 return Qs.apply(Context, FixedType); 5610 } 5611 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5612 QualType Inner = PTy->getInnerType(); 5613 QualType FixedType = 5614 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5615 Oversized); 5616 if (FixedType.isNull()) return FixedType; 5617 FixedType = Context.getParenType(FixedType); 5618 return Qs.apply(Context, FixedType); 5619 } 5620 5621 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5622 if (!VLATy) 5623 return QualType(); 5624 // FIXME: We should probably handle this case 5625 if (VLATy->getElementType()->isVariablyModifiedType()) 5626 return QualType(); 5627 5628 Expr::EvalResult Result; 5629 if (!VLATy->getSizeExpr() || 5630 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5631 return QualType(); 5632 5633 llvm::APSInt Res = Result.Val.getInt(); 5634 5635 // Check whether the array size is negative. 5636 if (Res.isSigned() && Res.isNegative()) { 5637 SizeIsNegative = true; 5638 return QualType(); 5639 } 5640 5641 // Check whether the array is too large to be addressed. 5642 unsigned ActiveSizeBits 5643 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5644 Res); 5645 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5646 Oversized = Res; 5647 return QualType(); 5648 } 5649 5650 return Context.getConstantArrayType(VLATy->getElementType(), 5651 Res, ArrayType::Normal, 0); 5652 } 5653 5654 static void 5655 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5656 SrcTL = SrcTL.getUnqualifiedLoc(); 5657 DstTL = DstTL.getUnqualifiedLoc(); 5658 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5659 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5660 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5661 DstPTL.getPointeeLoc()); 5662 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5663 return; 5664 } 5665 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5666 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5667 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5668 DstPTL.getInnerLoc()); 5669 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5670 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5671 return; 5672 } 5673 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5674 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5675 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5676 TypeLoc DstElemTL = DstATL.getElementLoc(); 5677 DstElemTL.initializeFullCopy(SrcElemTL); 5678 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5679 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5680 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5681 } 5682 5683 /// Helper method to turn variable array types into constant array 5684 /// types in certain situations which would otherwise be errors (for 5685 /// GCC compatibility). 5686 static TypeSourceInfo* 5687 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5688 ASTContext &Context, 5689 bool &SizeIsNegative, 5690 llvm::APSInt &Oversized) { 5691 QualType FixedTy 5692 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5693 SizeIsNegative, Oversized); 5694 if (FixedTy.isNull()) 5695 return nullptr; 5696 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5697 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5698 FixedTInfo->getTypeLoc()); 5699 return FixedTInfo; 5700 } 5701 5702 /// Register the given locally-scoped extern "C" declaration so 5703 /// that it can be found later for redeclarations. We include any extern "C" 5704 /// declaration that is not visible in the translation unit here, not just 5705 /// function-scope declarations. 5706 void 5707 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5708 if (!getLangOpts().CPlusPlus && 5709 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5710 // Don't need to track declarations in the TU in C. 5711 return; 5712 5713 // Note that we have a locally-scoped external with this name. 5714 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5715 } 5716 5717 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5718 // FIXME: We can have multiple results via __attribute__((overloadable)). 5719 auto Result = Context.getExternCContextDecl()->lookup(Name); 5720 return Result.empty() ? nullptr : *Result.begin(); 5721 } 5722 5723 /// Diagnose function specifiers on a declaration of an identifier that 5724 /// does not identify a function. 5725 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5726 // FIXME: We should probably indicate the identifier in question to avoid 5727 // confusion for constructs like "virtual int a(), b;" 5728 if (DS.isVirtualSpecified()) 5729 Diag(DS.getVirtualSpecLoc(), 5730 diag::err_virtual_non_function); 5731 5732 if (DS.hasExplicitSpecifier()) 5733 Diag(DS.getExplicitSpecLoc(), 5734 diag::err_explicit_non_function); 5735 5736 if (DS.isNoreturnSpecified()) 5737 Diag(DS.getNoreturnSpecLoc(), 5738 diag::err_noreturn_non_function); 5739 } 5740 5741 NamedDecl* 5742 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5743 TypeSourceInfo *TInfo, LookupResult &Previous) { 5744 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5745 if (D.getCXXScopeSpec().isSet()) { 5746 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5747 << D.getCXXScopeSpec().getRange(); 5748 D.setInvalidType(); 5749 // Pretend we didn't see the scope specifier. 5750 DC = CurContext; 5751 Previous.clear(); 5752 } 5753 5754 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5755 5756 if (D.getDeclSpec().isInlineSpecified()) 5757 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5758 << getLangOpts().CPlusPlus17; 5759 if (D.getDeclSpec().hasConstexprSpecifier()) 5760 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5761 << 1 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval); 5762 5763 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5764 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5765 Diag(D.getName().StartLocation, 5766 diag::err_deduction_guide_invalid_specifier) 5767 << "typedef"; 5768 else 5769 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5770 << D.getName().getSourceRange(); 5771 return nullptr; 5772 } 5773 5774 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5775 if (!NewTD) return nullptr; 5776 5777 // Handle attributes prior to checking for duplicates in MergeVarDecl 5778 ProcessDeclAttributes(S, NewTD, D); 5779 5780 CheckTypedefForVariablyModifiedType(S, NewTD); 5781 5782 bool Redeclaration = D.isRedeclaration(); 5783 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5784 D.setRedeclaration(Redeclaration); 5785 return ND; 5786 } 5787 5788 void 5789 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5790 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5791 // then it shall have block scope. 5792 // Note that variably modified types must be fixed before merging the decl so 5793 // that redeclarations will match. 5794 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5795 QualType T = TInfo->getType(); 5796 if (T->isVariablyModifiedType()) { 5797 setFunctionHasBranchProtectedScope(); 5798 5799 if (S->getFnParent() == nullptr) { 5800 bool SizeIsNegative; 5801 llvm::APSInt Oversized; 5802 TypeSourceInfo *FixedTInfo = 5803 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5804 SizeIsNegative, 5805 Oversized); 5806 if (FixedTInfo) { 5807 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5808 NewTD->setTypeSourceInfo(FixedTInfo); 5809 } else { 5810 if (SizeIsNegative) 5811 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5812 else if (T->isVariableArrayType()) 5813 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5814 else if (Oversized.getBoolValue()) 5815 Diag(NewTD->getLocation(), diag::err_array_too_large) 5816 << Oversized.toString(10); 5817 else 5818 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5819 NewTD->setInvalidDecl(); 5820 } 5821 } 5822 } 5823 } 5824 5825 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5826 /// declares a typedef-name, either using the 'typedef' type specifier or via 5827 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5828 NamedDecl* 5829 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5830 LookupResult &Previous, bool &Redeclaration) { 5831 5832 // Find the shadowed declaration before filtering for scope. 5833 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5834 5835 // Merge the decl with the existing one if appropriate. If the decl is 5836 // in an outer scope, it isn't the same thing. 5837 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5838 /*AllowInlineNamespace*/false); 5839 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5840 if (!Previous.empty()) { 5841 Redeclaration = true; 5842 MergeTypedefNameDecl(S, NewTD, Previous); 5843 } 5844 5845 if (ShadowedDecl && !Redeclaration) 5846 CheckShadow(NewTD, ShadowedDecl, Previous); 5847 5848 // If this is the C FILE type, notify the AST context. 5849 if (IdentifierInfo *II = NewTD->getIdentifier()) 5850 if (!NewTD->isInvalidDecl() && 5851 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5852 if (II->isStr("FILE")) 5853 Context.setFILEDecl(NewTD); 5854 else if (II->isStr("jmp_buf")) 5855 Context.setjmp_bufDecl(NewTD); 5856 else if (II->isStr("sigjmp_buf")) 5857 Context.setsigjmp_bufDecl(NewTD); 5858 else if (II->isStr("ucontext_t")) 5859 Context.setucontext_tDecl(NewTD); 5860 } 5861 5862 return NewTD; 5863 } 5864 5865 /// Determines whether the given declaration is an out-of-scope 5866 /// previous declaration. 5867 /// 5868 /// This routine should be invoked when name lookup has found a 5869 /// previous declaration (PrevDecl) that is not in the scope where a 5870 /// new declaration by the same name is being introduced. If the new 5871 /// declaration occurs in a local scope, previous declarations with 5872 /// linkage may still be considered previous declarations (C99 5873 /// 6.2.2p4-5, C++ [basic.link]p6). 5874 /// 5875 /// \param PrevDecl the previous declaration found by name 5876 /// lookup 5877 /// 5878 /// \param DC the context in which the new declaration is being 5879 /// declared. 5880 /// 5881 /// \returns true if PrevDecl is an out-of-scope previous declaration 5882 /// for a new delcaration with the same name. 5883 static bool 5884 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5885 ASTContext &Context) { 5886 if (!PrevDecl) 5887 return false; 5888 5889 if (!PrevDecl->hasLinkage()) 5890 return false; 5891 5892 if (Context.getLangOpts().CPlusPlus) { 5893 // C++ [basic.link]p6: 5894 // If there is a visible declaration of an entity with linkage 5895 // having the same name and type, ignoring entities declared 5896 // outside the innermost enclosing namespace scope, the block 5897 // scope declaration declares that same entity and receives the 5898 // linkage of the previous declaration. 5899 DeclContext *OuterContext = DC->getRedeclContext(); 5900 if (!OuterContext->isFunctionOrMethod()) 5901 // This rule only applies to block-scope declarations. 5902 return false; 5903 5904 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5905 if (PrevOuterContext->isRecord()) 5906 // We found a member function: ignore it. 5907 return false; 5908 5909 // Find the innermost enclosing namespace for the new and 5910 // previous declarations. 5911 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5912 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5913 5914 // The previous declaration is in a different namespace, so it 5915 // isn't the same function. 5916 if (!OuterContext->Equals(PrevOuterContext)) 5917 return false; 5918 } 5919 5920 return true; 5921 } 5922 5923 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 5924 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5925 if (!SS.isSet()) return; 5926 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 5927 } 5928 5929 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5930 QualType type = decl->getType(); 5931 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5932 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5933 // Various kinds of declaration aren't allowed to be __autoreleasing. 5934 unsigned kind = -1U; 5935 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5936 if (var->hasAttr<BlocksAttr>()) 5937 kind = 0; // __block 5938 else if (!var->hasLocalStorage()) 5939 kind = 1; // global 5940 } else if (isa<ObjCIvarDecl>(decl)) { 5941 kind = 3; // ivar 5942 } else if (isa<FieldDecl>(decl)) { 5943 kind = 2; // field 5944 } 5945 5946 if (kind != -1U) { 5947 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5948 << kind; 5949 } 5950 } else if (lifetime == Qualifiers::OCL_None) { 5951 // Try to infer lifetime. 5952 if (!type->isObjCLifetimeType()) 5953 return false; 5954 5955 lifetime = type->getObjCARCImplicitLifetime(); 5956 type = Context.getLifetimeQualifiedType(type, lifetime); 5957 decl->setType(type); 5958 } 5959 5960 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5961 // Thread-local variables cannot have lifetime. 5962 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5963 var->getTLSKind()) { 5964 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5965 << var->getType(); 5966 return true; 5967 } 5968 } 5969 5970 return false; 5971 } 5972 5973 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5974 // Ensure that an auto decl is deduced otherwise the checks below might cache 5975 // the wrong linkage. 5976 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5977 5978 // 'weak' only applies to declarations with external linkage. 5979 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5980 if (!ND.isExternallyVisible()) { 5981 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5982 ND.dropAttr<WeakAttr>(); 5983 } 5984 } 5985 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5986 if (ND.isExternallyVisible()) { 5987 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5988 ND.dropAttr<WeakRefAttr>(); 5989 ND.dropAttr<AliasAttr>(); 5990 } 5991 } 5992 5993 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5994 if (VD->hasInit()) { 5995 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5996 assert(VD->isThisDeclarationADefinition() && 5997 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5998 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5999 VD->dropAttr<AliasAttr>(); 6000 } 6001 } 6002 } 6003 6004 // 'selectany' only applies to externally visible variable declarations. 6005 // It does not apply to functions. 6006 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6007 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6008 S.Diag(Attr->getLocation(), 6009 diag::err_attribute_selectany_non_extern_data); 6010 ND.dropAttr<SelectAnyAttr>(); 6011 } 6012 } 6013 6014 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6015 auto *VD = dyn_cast<VarDecl>(&ND); 6016 bool IsAnonymousNS = false; 6017 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6018 if (VD) { 6019 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6020 while (NS && !IsAnonymousNS) { 6021 IsAnonymousNS = NS->isAnonymousNamespace(); 6022 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6023 } 6024 } 6025 // dll attributes require external linkage. Static locals may have external 6026 // linkage but still cannot be explicitly imported or exported. 6027 // In Microsoft mode, a variable defined in anonymous namespace must have 6028 // external linkage in order to be exported. 6029 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6030 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6031 (!AnonNSInMicrosoftMode && 6032 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6033 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6034 << &ND << Attr; 6035 ND.setInvalidDecl(); 6036 } 6037 } 6038 6039 // Virtual functions cannot be marked as 'notail'. 6040 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6041 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6042 if (MD->isVirtual()) { 6043 S.Diag(ND.getLocation(), 6044 diag::err_invalid_attribute_on_virtual_function) 6045 << Attr; 6046 ND.dropAttr<NotTailCalledAttr>(); 6047 } 6048 6049 // Check the attributes on the function type, if any. 6050 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6051 // Don't declare this variable in the second operand of the for-statement; 6052 // GCC miscompiles that by ending its lifetime before evaluating the 6053 // third operand. See gcc.gnu.org/PR86769. 6054 AttributedTypeLoc ATL; 6055 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6056 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6057 TL = ATL.getModifiedLoc()) { 6058 // The [[lifetimebound]] attribute can be applied to the implicit object 6059 // parameter of a non-static member function (other than a ctor or dtor) 6060 // by applying it to the function type. 6061 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6062 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6063 if (!MD || MD->isStatic()) { 6064 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6065 << !MD << A->getRange(); 6066 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6067 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6068 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6069 } 6070 } 6071 } 6072 } 6073 } 6074 6075 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6076 NamedDecl *NewDecl, 6077 bool IsSpecialization, 6078 bool IsDefinition) { 6079 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6080 return; 6081 6082 bool IsTemplate = false; 6083 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6084 OldDecl = OldTD->getTemplatedDecl(); 6085 IsTemplate = true; 6086 if (!IsSpecialization) 6087 IsDefinition = false; 6088 } 6089 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6090 NewDecl = NewTD->getTemplatedDecl(); 6091 IsTemplate = true; 6092 } 6093 6094 if (!OldDecl || !NewDecl) 6095 return; 6096 6097 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6098 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6099 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6100 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6101 6102 // dllimport and dllexport are inheritable attributes so we have to exclude 6103 // inherited attribute instances. 6104 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6105 (NewExportAttr && !NewExportAttr->isInherited()); 6106 6107 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6108 // the only exception being explicit specializations. 6109 // Implicitly generated declarations are also excluded for now because there 6110 // is no other way to switch these to use dllimport or dllexport. 6111 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6112 6113 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6114 // Allow with a warning for free functions and global variables. 6115 bool JustWarn = false; 6116 if (!OldDecl->isCXXClassMember()) { 6117 auto *VD = dyn_cast<VarDecl>(OldDecl); 6118 if (VD && !VD->getDescribedVarTemplate()) 6119 JustWarn = true; 6120 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6121 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6122 JustWarn = true; 6123 } 6124 6125 // We cannot change a declaration that's been used because IR has already 6126 // been emitted. Dllimported functions will still work though (modulo 6127 // address equality) as they can use the thunk. 6128 if (OldDecl->isUsed()) 6129 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6130 JustWarn = false; 6131 6132 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6133 : diag::err_attribute_dll_redeclaration; 6134 S.Diag(NewDecl->getLocation(), DiagID) 6135 << NewDecl 6136 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6137 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6138 if (!JustWarn) { 6139 NewDecl->setInvalidDecl(); 6140 return; 6141 } 6142 } 6143 6144 // A redeclaration is not allowed to drop a dllimport attribute, the only 6145 // exceptions being inline function definitions (except for function 6146 // templates), local extern declarations, qualified friend declarations or 6147 // special MSVC extension: in the last case, the declaration is treated as if 6148 // it were marked dllexport. 6149 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6150 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6151 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6152 // Ignore static data because out-of-line definitions are diagnosed 6153 // separately. 6154 IsStaticDataMember = VD->isStaticDataMember(); 6155 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6156 VarDecl::DeclarationOnly; 6157 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6158 IsInline = FD->isInlined(); 6159 IsQualifiedFriend = FD->getQualifier() && 6160 FD->getFriendObjectKind() == Decl::FOK_Declared; 6161 } 6162 6163 if (OldImportAttr && !HasNewAttr && 6164 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6165 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6166 if (IsMicrosoft && IsDefinition) { 6167 S.Diag(NewDecl->getLocation(), 6168 diag::warn_redeclaration_without_import_attribute) 6169 << NewDecl; 6170 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6171 NewDecl->dropAttr<DLLImportAttr>(); 6172 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6173 NewImportAttr->getRange(), S.Context, 6174 NewImportAttr->getSpellingListIndex())); 6175 } else { 6176 S.Diag(NewDecl->getLocation(), 6177 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6178 << NewDecl << OldImportAttr; 6179 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6180 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6181 OldDecl->dropAttr<DLLImportAttr>(); 6182 NewDecl->dropAttr<DLLImportAttr>(); 6183 } 6184 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6185 // In MinGW, seeing a function declared inline drops the dllimport 6186 // attribute. 6187 OldDecl->dropAttr<DLLImportAttr>(); 6188 NewDecl->dropAttr<DLLImportAttr>(); 6189 S.Diag(NewDecl->getLocation(), 6190 diag::warn_dllimport_dropped_from_inline_function) 6191 << NewDecl << OldImportAttr; 6192 } 6193 6194 // A specialization of a class template member function is processed here 6195 // since it's a redeclaration. If the parent class is dllexport, the 6196 // specialization inherits that attribute. This doesn't happen automatically 6197 // since the parent class isn't instantiated until later. 6198 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6199 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6200 !NewImportAttr && !NewExportAttr) { 6201 if (const DLLExportAttr *ParentExportAttr = 6202 MD->getParent()->getAttr<DLLExportAttr>()) { 6203 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6204 NewAttr->setInherited(true); 6205 NewDecl->addAttr(NewAttr); 6206 } 6207 } 6208 } 6209 } 6210 6211 /// Given that we are within the definition of the given function, 6212 /// will that definition behave like C99's 'inline', where the 6213 /// definition is discarded except for optimization purposes? 6214 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6215 // Try to avoid calling GetGVALinkageForFunction. 6216 6217 // All cases of this require the 'inline' keyword. 6218 if (!FD->isInlined()) return false; 6219 6220 // This is only possible in C++ with the gnu_inline attribute. 6221 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6222 return false; 6223 6224 // Okay, go ahead and call the relatively-more-expensive function. 6225 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6226 } 6227 6228 /// Determine whether a variable is extern "C" prior to attaching 6229 /// an initializer. We can't just call isExternC() here, because that 6230 /// will also compute and cache whether the declaration is externally 6231 /// visible, which might change when we attach the initializer. 6232 /// 6233 /// This can only be used if the declaration is known to not be a 6234 /// redeclaration of an internal linkage declaration. 6235 /// 6236 /// For instance: 6237 /// 6238 /// auto x = []{}; 6239 /// 6240 /// Attaching the initializer here makes this declaration not externally 6241 /// visible, because its type has internal linkage. 6242 /// 6243 /// FIXME: This is a hack. 6244 template<typename T> 6245 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6246 if (S.getLangOpts().CPlusPlus) { 6247 // In C++, the overloadable attribute negates the effects of extern "C". 6248 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6249 return false; 6250 6251 // So do CUDA's host/device attributes. 6252 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6253 D->template hasAttr<CUDAHostAttr>())) 6254 return false; 6255 } 6256 return D->isExternC(); 6257 } 6258 6259 static bool shouldConsiderLinkage(const VarDecl *VD) { 6260 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6261 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6262 isa<OMPDeclareMapperDecl>(DC)) 6263 return VD->hasExternalStorage(); 6264 if (DC->isFileContext()) 6265 return true; 6266 if (DC->isRecord()) 6267 return false; 6268 llvm_unreachable("Unexpected context"); 6269 } 6270 6271 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6272 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6273 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6274 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6275 return true; 6276 if (DC->isRecord()) 6277 return false; 6278 llvm_unreachable("Unexpected context"); 6279 } 6280 6281 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6282 ParsedAttr::Kind Kind) { 6283 // Check decl attributes on the DeclSpec. 6284 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6285 return true; 6286 6287 // Walk the declarator structure, checking decl attributes that were in a type 6288 // position to the decl itself. 6289 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6290 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6291 return true; 6292 } 6293 6294 // Finally, check attributes on the decl itself. 6295 return PD.getAttributes().hasAttribute(Kind); 6296 } 6297 6298 /// Adjust the \c DeclContext for a function or variable that might be a 6299 /// function-local external declaration. 6300 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6301 if (!DC->isFunctionOrMethod()) 6302 return false; 6303 6304 // If this is a local extern function or variable declared within a function 6305 // template, don't add it into the enclosing namespace scope until it is 6306 // instantiated; it might have a dependent type right now. 6307 if (DC->isDependentContext()) 6308 return true; 6309 6310 // C++11 [basic.link]p7: 6311 // When a block scope declaration of an entity with linkage is not found to 6312 // refer to some other declaration, then that entity is a member of the 6313 // innermost enclosing namespace. 6314 // 6315 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6316 // semantically-enclosing namespace, not a lexically-enclosing one. 6317 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6318 DC = DC->getParent(); 6319 return true; 6320 } 6321 6322 /// Returns true if given declaration has external C language linkage. 6323 static bool isDeclExternC(const Decl *D) { 6324 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6325 return FD->isExternC(); 6326 if (const auto *VD = dyn_cast<VarDecl>(D)) 6327 return VD->isExternC(); 6328 6329 llvm_unreachable("Unknown type of decl!"); 6330 } 6331 6332 NamedDecl *Sema::ActOnVariableDeclarator( 6333 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6334 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6335 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6336 QualType R = TInfo->getType(); 6337 DeclarationName Name = GetNameForDeclarator(D).getName(); 6338 6339 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6340 6341 if (D.isDecompositionDeclarator()) { 6342 // Take the name of the first declarator as our name for diagnostic 6343 // purposes. 6344 auto &Decomp = D.getDecompositionDeclarator(); 6345 if (!Decomp.bindings().empty()) { 6346 II = Decomp.bindings()[0].Name; 6347 Name = II; 6348 } 6349 } else if (!II) { 6350 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6351 return nullptr; 6352 } 6353 6354 if (getLangOpts().OpenCL) { 6355 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6356 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6357 // argument. 6358 if (R->isImageType() || R->isPipeType()) { 6359 Diag(D.getIdentifierLoc(), 6360 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6361 << R; 6362 D.setInvalidType(); 6363 return nullptr; 6364 } 6365 6366 // OpenCL v1.2 s6.9.r: 6367 // The event type cannot be used to declare a program scope variable. 6368 // OpenCL v2.0 s6.9.q: 6369 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6370 if (NULL == S->getParent()) { 6371 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6372 Diag(D.getIdentifierLoc(), 6373 diag::err_invalid_type_for_program_scope_var) << R; 6374 D.setInvalidType(); 6375 return nullptr; 6376 } 6377 } 6378 6379 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6380 QualType NR = R; 6381 while (NR->isPointerType()) { 6382 if (NR->isFunctionPointerType()) { 6383 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6384 D.setInvalidType(); 6385 break; 6386 } 6387 NR = NR->getPointeeType(); 6388 } 6389 6390 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6391 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6392 // half array type (unless the cl_khr_fp16 extension is enabled). 6393 if (Context.getBaseElementType(R)->isHalfType()) { 6394 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6395 D.setInvalidType(); 6396 } 6397 } 6398 6399 if (R->isSamplerT()) { 6400 // OpenCL v1.2 s6.9.b p4: 6401 // The sampler type cannot be used with the __local and __global address 6402 // space qualifiers. 6403 if (R.getAddressSpace() == LangAS::opencl_local || 6404 R.getAddressSpace() == LangAS::opencl_global) { 6405 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6406 } 6407 6408 // OpenCL v1.2 s6.12.14.1: 6409 // A global sampler must be declared with either the constant address 6410 // space qualifier or with the const qualifier. 6411 if (DC->isTranslationUnit() && 6412 !(R.getAddressSpace() == LangAS::opencl_constant || 6413 R.isConstQualified())) { 6414 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6415 D.setInvalidType(); 6416 } 6417 } 6418 6419 // OpenCL v1.2 s6.9.r: 6420 // The event type cannot be used with the __local, __constant and __global 6421 // address space qualifiers. 6422 if (R->isEventT()) { 6423 if (R.getAddressSpace() != LangAS::opencl_private) { 6424 Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6425 D.setInvalidType(); 6426 } 6427 } 6428 6429 // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not 6430 // supported. OpenCL C does not support thread_local either, and 6431 // also reject all other thread storage class specifiers. 6432 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6433 if (TSC != TSCS_unspecified) { 6434 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6435 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6436 diag::err_opencl_unknown_type_specifier) 6437 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6438 << DeclSpec::getSpecifierName(TSC) << 1; 6439 D.setInvalidType(); 6440 return nullptr; 6441 } 6442 } 6443 6444 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6445 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6446 6447 // dllimport globals without explicit storage class are treated as extern. We 6448 // have to change the storage class this early to get the right DeclContext. 6449 if (SC == SC_None && !DC->isRecord() && 6450 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6451 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6452 SC = SC_Extern; 6453 6454 DeclContext *OriginalDC = DC; 6455 bool IsLocalExternDecl = SC == SC_Extern && 6456 adjustContextForLocalExternDecl(DC); 6457 6458 if (SCSpec == DeclSpec::SCS_mutable) { 6459 // mutable can only appear on non-static class members, so it's always 6460 // an error here 6461 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6462 D.setInvalidType(); 6463 SC = SC_None; 6464 } 6465 6466 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6467 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6468 D.getDeclSpec().getStorageClassSpecLoc())) { 6469 // In C++11, the 'register' storage class specifier is deprecated. 6470 // Suppress the warning in system macros, it's used in macros in some 6471 // popular C system headers, such as in glibc's htonl() macro. 6472 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6473 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6474 : diag::warn_deprecated_register) 6475 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6476 } 6477 6478 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6479 6480 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6481 // C99 6.9p2: The storage-class specifiers auto and register shall not 6482 // appear in the declaration specifiers in an external declaration. 6483 // Global Register+Asm is a GNU extension we support. 6484 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6485 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6486 D.setInvalidType(); 6487 } 6488 } 6489 6490 bool IsMemberSpecialization = false; 6491 bool IsVariableTemplateSpecialization = false; 6492 bool IsPartialSpecialization = false; 6493 bool IsVariableTemplate = false; 6494 VarDecl *NewVD = nullptr; 6495 VarTemplateDecl *NewTemplate = nullptr; 6496 TemplateParameterList *TemplateParams = nullptr; 6497 if (!getLangOpts().CPlusPlus) { 6498 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6499 II, R, TInfo, SC); 6500 6501 if (R->getContainedDeducedType()) 6502 ParsingInitForAutoVars.insert(NewVD); 6503 6504 if (D.isInvalidType()) 6505 NewVD->setInvalidDecl(); 6506 } else { 6507 bool Invalid = false; 6508 6509 if (DC->isRecord() && !CurContext->isRecord()) { 6510 // This is an out-of-line definition of a static data member. 6511 switch (SC) { 6512 case SC_None: 6513 break; 6514 case SC_Static: 6515 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6516 diag::err_static_out_of_line) 6517 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6518 break; 6519 case SC_Auto: 6520 case SC_Register: 6521 case SC_Extern: 6522 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6523 // to names of variables declared in a block or to function parameters. 6524 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6525 // of class members 6526 6527 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6528 diag::err_storage_class_for_static_member) 6529 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6530 break; 6531 case SC_PrivateExtern: 6532 llvm_unreachable("C storage class in c++!"); 6533 } 6534 } 6535 6536 if (SC == SC_Static && CurContext->isRecord()) { 6537 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6538 if (RD->isLocalClass()) 6539 Diag(D.getIdentifierLoc(), 6540 diag::err_static_data_member_not_allowed_in_local_class) 6541 << Name << RD->getDeclName(); 6542 6543 // C++98 [class.union]p1: If a union contains a static data member, 6544 // the program is ill-formed. C++11 drops this restriction. 6545 if (RD->isUnion()) 6546 Diag(D.getIdentifierLoc(), 6547 getLangOpts().CPlusPlus11 6548 ? diag::warn_cxx98_compat_static_data_member_in_union 6549 : diag::ext_static_data_member_in_union) << Name; 6550 // We conservatively disallow static data members in anonymous structs. 6551 else if (!RD->getDeclName()) 6552 Diag(D.getIdentifierLoc(), 6553 diag::err_static_data_member_not_allowed_in_anon_struct) 6554 << Name << RD->isUnion(); 6555 } 6556 } 6557 6558 // Match up the template parameter lists with the scope specifier, then 6559 // determine whether we have a template or a template specialization. 6560 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6561 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6562 D.getCXXScopeSpec(), 6563 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6564 ? D.getName().TemplateId 6565 : nullptr, 6566 TemplateParamLists, 6567 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6568 6569 if (TemplateParams) { 6570 if (!TemplateParams->size() && 6571 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6572 // There is an extraneous 'template<>' for this variable. Complain 6573 // about it, but allow the declaration of the variable. 6574 Diag(TemplateParams->getTemplateLoc(), 6575 diag::err_template_variable_noparams) 6576 << II 6577 << SourceRange(TemplateParams->getTemplateLoc(), 6578 TemplateParams->getRAngleLoc()); 6579 TemplateParams = nullptr; 6580 } else { 6581 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6582 // This is an explicit specialization or a partial specialization. 6583 // FIXME: Check that we can declare a specialization here. 6584 IsVariableTemplateSpecialization = true; 6585 IsPartialSpecialization = TemplateParams->size() > 0; 6586 } else { // if (TemplateParams->size() > 0) 6587 // This is a template declaration. 6588 IsVariableTemplate = true; 6589 6590 // Check that we can declare a template here. 6591 if (CheckTemplateDeclScope(S, TemplateParams)) 6592 return nullptr; 6593 6594 // Only C++1y supports variable templates (N3651). 6595 Diag(D.getIdentifierLoc(), 6596 getLangOpts().CPlusPlus14 6597 ? diag::warn_cxx11_compat_variable_template 6598 : diag::ext_variable_template); 6599 } 6600 } 6601 } else { 6602 assert((Invalid || 6603 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6604 "should have a 'template<>' for this decl"); 6605 } 6606 6607 if (IsVariableTemplateSpecialization) { 6608 SourceLocation TemplateKWLoc = 6609 TemplateParamLists.size() > 0 6610 ? TemplateParamLists[0]->getTemplateLoc() 6611 : SourceLocation(); 6612 DeclResult Res = ActOnVarTemplateSpecialization( 6613 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6614 IsPartialSpecialization); 6615 if (Res.isInvalid()) 6616 return nullptr; 6617 NewVD = cast<VarDecl>(Res.get()); 6618 AddToScope = false; 6619 } else if (D.isDecompositionDeclarator()) { 6620 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6621 D.getIdentifierLoc(), R, TInfo, SC, 6622 Bindings); 6623 } else 6624 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6625 D.getIdentifierLoc(), II, R, TInfo, SC); 6626 6627 // If this is supposed to be a variable template, create it as such. 6628 if (IsVariableTemplate) { 6629 NewTemplate = 6630 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6631 TemplateParams, NewVD); 6632 NewVD->setDescribedVarTemplate(NewTemplate); 6633 } 6634 6635 // If this decl has an auto type in need of deduction, make a note of the 6636 // Decl so we can diagnose uses of it in its own initializer. 6637 if (R->getContainedDeducedType()) 6638 ParsingInitForAutoVars.insert(NewVD); 6639 6640 if (D.isInvalidType() || Invalid) { 6641 NewVD->setInvalidDecl(); 6642 if (NewTemplate) 6643 NewTemplate->setInvalidDecl(); 6644 } 6645 6646 SetNestedNameSpecifier(*this, NewVD, D); 6647 6648 // If we have any template parameter lists that don't directly belong to 6649 // the variable (matching the scope specifier), store them. 6650 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6651 if (TemplateParamLists.size() > VDTemplateParamLists) 6652 NewVD->setTemplateParameterListsInfo( 6653 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6654 6655 if (D.getDeclSpec().hasConstexprSpecifier()) { 6656 NewVD->setConstexpr(true); 6657 // C++1z [dcl.spec.constexpr]p1: 6658 // A static data member declared with the constexpr specifier is 6659 // implicitly an inline variable. 6660 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6661 NewVD->setImplicitlyInline(); 6662 if (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval) 6663 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6664 diag::err_constexpr_wrong_decl_kind) 6665 << /*consteval*/ 1; 6666 } 6667 } 6668 6669 if (D.getDeclSpec().isInlineSpecified()) { 6670 if (!getLangOpts().CPlusPlus) { 6671 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6672 << 0; 6673 } else if (CurContext->isFunctionOrMethod()) { 6674 // 'inline' is not allowed on block scope variable declaration. 6675 Diag(D.getDeclSpec().getInlineSpecLoc(), 6676 diag::err_inline_declaration_block_scope) << Name 6677 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6678 } else { 6679 Diag(D.getDeclSpec().getInlineSpecLoc(), 6680 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6681 : diag::ext_inline_variable); 6682 NewVD->setInlineSpecified(); 6683 } 6684 } 6685 6686 // Set the lexical context. If the declarator has a C++ scope specifier, the 6687 // lexical context will be different from the semantic context. 6688 NewVD->setLexicalDeclContext(CurContext); 6689 if (NewTemplate) 6690 NewTemplate->setLexicalDeclContext(CurContext); 6691 6692 if (IsLocalExternDecl) { 6693 if (D.isDecompositionDeclarator()) 6694 for (auto *B : Bindings) 6695 B->setLocalExternDecl(); 6696 else 6697 NewVD->setLocalExternDecl(); 6698 } 6699 6700 bool EmitTLSUnsupportedError = false; 6701 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6702 // C++11 [dcl.stc]p4: 6703 // When thread_local is applied to a variable of block scope the 6704 // storage-class-specifier static is implied if it does not appear 6705 // explicitly. 6706 // Core issue: 'static' is not implied if the variable is declared 6707 // 'extern'. 6708 if (NewVD->hasLocalStorage() && 6709 (SCSpec != DeclSpec::SCS_unspecified || 6710 TSCS != DeclSpec::TSCS_thread_local || 6711 !DC->isFunctionOrMethod())) 6712 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6713 diag::err_thread_non_global) 6714 << DeclSpec::getSpecifierName(TSCS); 6715 else if (!Context.getTargetInfo().isTLSSupported()) { 6716 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6717 // Postpone error emission until we've collected attributes required to 6718 // figure out whether it's a host or device variable and whether the 6719 // error should be ignored. 6720 EmitTLSUnsupportedError = true; 6721 // We still need to mark the variable as TLS so it shows up in AST with 6722 // proper storage class for other tools to use even if we're not going 6723 // to emit any code for it. 6724 NewVD->setTSCSpec(TSCS); 6725 } else 6726 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6727 diag::err_thread_unsupported); 6728 } else 6729 NewVD->setTSCSpec(TSCS); 6730 } 6731 6732 // C99 6.7.4p3 6733 // An inline definition of a function with external linkage shall 6734 // not contain a definition of a modifiable object with static or 6735 // thread storage duration... 6736 // We only apply this when the function is required to be defined 6737 // elsewhere, i.e. when the function is not 'extern inline'. Note 6738 // that a local variable with thread storage duration still has to 6739 // be marked 'static'. Also note that it's possible to get these 6740 // semantics in C++ using __attribute__((gnu_inline)). 6741 if (SC == SC_Static && S->getFnParent() != nullptr && 6742 !NewVD->getType().isConstQualified()) { 6743 FunctionDecl *CurFD = getCurFunctionDecl(); 6744 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6745 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6746 diag::warn_static_local_in_extern_inline); 6747 MaybeSuggestAddingStaticToDecl(CurFD); 6748 } 6749 } 6750 6751 if (D.getDeclSpec().isModulePrivateSpecified()) { 6752 if (IsVariableTemplateSpecialization) 6753 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6754 << (IsPartialSpecialization ? 1 : 0) 6755 << FixItHint::CreateRemoval( 6756 D.getDeclSpec().getModulePrivateSpecLoc()); 6757 else if (IsMemberSpecialization) 6758 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6759 << 2 6760 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6761 else if (NewVD->hasLocalStorage()) 6762 Diag(NewVD->getLocation(), diag::err_module_private_local) 6763 << 0 << NewVD->getDeclName() 6764 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6765 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6766 else { 6767 NewVD->setModulePrivate(); 6768 if (NewTemplate) 6769 NewTemplate->setModulePrivate(); 6770 for (auto *B : Bindings) 6771 B->setModulePrivate(); 6772 } 6773 } 6774 6775 // Handle attributes prior to checking for duplicates in MergeVarDecl 6776 ProcessDeclAttributes(S, NewVD, D); 6777 6778 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6779 if (EmitTLSUnsupportedError && 6780 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6781 (getLangOpts().OpenMPIsDevice && 6782 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6783 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6784 diag::err_thread_unsupported); 6785 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6786 // storage [duration]." 6787 if (SC == SC_None && S->getFnParent() != nullptr && 6788 (NewVD->hasAttr<CUDASharedAttr>() || 6789 NewVD->hasAttr<CUDAConstantAttr>())) { 6790 NewVD->setStorageClass(SC_Static); 6791 } 6792 } 6793 6794 // Ensure that dllimport globals without explicit storage class are treated as 6795 // extern. The storage class is set above using parsed attributes. Now we can 6796 // check the VarDecl itself. 6797 assert(!NewVD->hasAttr<DLLImportAttr>() || 6798 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6799 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6800 6801 // In auto-retain/release, infer strong retension for variables of 6802 // retainable type. 6803 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6804 NewVD->setInvalidDecl(); 6805 6806 // Handle GNU asm-label extension (encoded as an attribute). 6807 if (Expr *E = (Expr*)D.getAsmLabel()) { 6808 // The parser guarantees this is a string. 6809 StringLiteral *SE = cast<StringLiteral>(E); 6810 StringRef Label = SE->getString(); 6811 if (S->getFnParent() != nullptr) { 6812 switch (SC) { 6813 case SC_None: 6814 case SC_Auto: 6815 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6816 break; 6817 case SC_Register: 6818 // Local Named register 6819 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6820 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6821 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6822 break; 6823 case SC_Static: 6824 case SC_Extern: 6825 case SC_PrivateExtern: 6826 break; 6827 } 6828 } else if (SC == SC_Register) { 6829 // Global Named register 6830 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6831 const auto &TI = Context.getTargetInfo(); 6832 bool HasSizeMismatch; 6833 6834 if (!TI.isValidGCCRegisterName(Label)) 6835 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6836 else if (!TI.validateGlobalRegisterVariable(Label, 6837 Context.getTypeSize(R), 6838 HasSizeMismatch)) 6839 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6840 else if (HasSizeMismatch) 6841 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6842 } 6843 6844 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6845 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 6846 NewVD->setInvalidDecl(true); 6847 } 6848 } 6849 6850 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6851 Context, Label, 0)); 6852 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6853 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6854 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6855 if (I != ExtnameUndeclaredIdentifiers.end()) { 6856 if (isDeclExternC(NewVD)) { 6857 NewVD->addAttr(I->second); 6858 ExtnameUndeclaredIdentifiers.erase(I); 6859 } else 6860 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6861 << /*Variable*/1 << NewVD; 6862 } 6863 } 6864 6865 // Find the shadowed declaration before filtering for scope. 6866 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6867 ? getShadowedDeclaration(NewVD, Previous) 6868 : nullptr; 6869 6870 // Don't consider existing declarations that are in a different 6871 // scope and are out-of-semantic-context declarations (if the new 6872 // declaration has linkage). 6873 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6874 D.getCXXScopeSpec().isNotEmpty() || 6875 IsMemberSpecialization || 6876 IsVariableTemplateSpecialization); 6877 6878 // Check whether the previous declaration is in the same block scope. This 6879 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6880 if (getLangOpts().CPlusPlus && 6881 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6882 NewVD->setPreviousDeclInSameBlockScope( 6883 Previous.isSingleResult() && !Previous.isShadowed() && 6884 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6885 6886 if (!getLangOpts().CPlusPlus) { 6887 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6888 } else { 6889 // If this is an explicit specialization of a static data member, check it. 6890 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6891 CheckMemberSpecialization(NewVD, Previous)) 6892 NewVD->setInvalidDecl(); 6893 6894 // Merge the decl with the existing one if appropriate. 6895 if (!Previous.empty()) { 6896 if (Previous.isSingleResult() && 6897 isa<FieldDecl>(Previous.getFoundDecl()) && 6898 D.getCXXScopeSpec().isSet()) { 6899 // The user tried to define a non-static data member 6900 // out-of-line (C++ [dcl.meaning]p1). 6901 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6902 << D.getCXXScopeSpec().getRange(); 6903 Previous.clear(); 6904 NewVD->setInvalidDecl(); 6905 } 6906 } else if (D.getCXXScopeSpec().isSet()) { 6907 // No previous declaration in the qualifying scope. 6908 Diag(D.getIdentifierLoc(), diag::err_no_member) 6909 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6910 << D.getCXXScopeSpec().getRange(); 6911 NewVD->setInvalidDecl(); 6912 } 6913 6914 if (!IsVariableTemplateSpecialization) 6915 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6916 6917 if (NewTemplate) { 6918 VarTemplateDecl *PrevVarTemplate = 6919 NewVD->getPreviousDecl() 6920 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6921 : nullptr; 6922 6923 // Check the template parameter list of this declaration, possibly 6924 // merging in the template parameter list from the previous variable 6925 // template declaration. 6926 if (CheckTemplateParameterList( 6927 TemplateParams, 6928 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6929 : nullptr, 6930 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6931 DC->isDependentContext()) 6932 ? TPC_ClassTemplateMember 6933 : TPC_VarTemplate)) 6934 NewVD->setInvalidDecl(); 6935 6936 // If we are providing an explicit specialization of a static variable 6937 // template, make a note of that. 6938 if (PrevVarTemplate && 6939 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6940 PrevVarTemplate->setMemberSpecialization(); 6941 } 6942 } 6943 6944 // Diagnose shadowed variables iff this isn't a redeclaration. 6945 if (ShadowedDecl && !D.isRedeclaration()) 6946 CheckShadow(NewVD, ShadowedDecl, Previous); 6947 6948 ProcessPragmaWeak(S, NewVD); 6949 6950 // If this is the first declaration of an extern C variable, update 6951 // the map of such variables. 6952 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6953 isIncompleteDeclExternC(*this, NewVD)) 6954 RegisterLocallyScopedExternCDecl(NewVD, S); 6955 6956 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6957 Decl *ManglingContextDecl; 6958 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6959 NewVD->getDeclContext(), ManglingContextDecl)) { 6960 Context.setManglingNumber( 6961 NewVD, MCtx->getManglingNumber( 6962 NewVD, getMSManglingNumber(getLangOpts(), S))); 6963 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6964 } 6965 } 6966 6967 // Special handling of variable named 'main'. 6968 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6969 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6970 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6971 6972 // C++ [basic.start.main]p3 6973 // A program that declares a variable main at global scope is ill-formed. 6974 if (getLangOpts().CPlusPlus) 6975 Diag(D.getBeginLoc(), diag::err_main_global_variable); 6976 6977 // In C, and external-linkage variable named main results in undefined 6978 // behavior. 6979 else if (NewVD->hasExternalFormalLinkage()) 6980 Diag(D.getBeginLoc(), diag::warn_main_redefined); 6981 } 6982 6983 if (D.isRedeclaration() && !Previous.empty()) { 6984 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6985 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6986 D.isFunctionDefinition()); 6987 } 6988 6989 if (NewTemplate) { 6990 if (NewVD->isInvalidDecl()) 6991 NewTemplate->setInvalidDecl(); 6992 ActOnDocumentableDecl(NewTemplate); 6993 return NewTemplate; 6994 } 6995 6996 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6997 CompleteMemberSpecialization(NewVD, Previous); 6998 6999 return NewVD; 7000 } 7001 7002 /// Enum describing the %select options in diag::warn_decl_shadow. 7003 enum ShadowedDeclKind { 7004 SDK_Local, 7005 SDK_Global, 7006 SDK_StaticMember, 7007 SDK_Field, 7008 SDK_Typedef, 7009 SDK_Using 7010 }; 7011 7012 /// Determine what kind of declaration we're shadowing. 7013 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7014 const DeclContext *OldDC) { 7015 if (isa<TypeAliasDecl>(ShadowedDecl)) 7016 return SDK_Using; 7017 else if (isa<TypedefDecl>(ShadowedDecl)) 7018 return SDK_Typedef; 7019 else if (isa<RecordDecl>(OldDC)) 7020 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7021 7022 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7023 } 7024 7025 /// Return the location of the capture if the given lambda captures the given 7026 /// variable \p VD, or an invalid source location otherwise. 7027 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7028 const VarDecl *VD) { 7029 for (const Capture &Capture : LSI->Captures) { 7030 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7031 return Capture.getLocation(); 7032 } 7033 return SourceLocation(); 7034 } 7035 7036 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7037 const LookupResult &R) { 7038 // Only diagnose if we're shadowing an unambiguous field or variable. 7039 if (R.getResultKind() != LookupResult::Found) 7040 return false; 7041 7042 // Return false if warning is ignored. 7043 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7044 } 7045 7046 /// Return the declaration shadowed by the given variable \p D, or null 7047 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7048 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7049 const LookupResult &R) { 7050 if (!shouldWarnIfShadowedDecl(Diags, R)) 7051 return nullptr; 7052 7053 // Don't diagnose declarations at file scope. 7054 if (D->hasGlobalStorage()) 7055 return nullptr; 7056 7057 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7058 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7059 ? ShadowedDecl 7060 : nullptr; 7061 } 7062 7063 /// Return the declaration shadowed by the given typedef \p D, or null 7064 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7065 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7066 const LookupResult &R) { 7067 // Don't warn if typedef declaration is part of a class 7068 if (D->getDeclContext()->isRecord()) 7069 return nullptr; 7070 7071 if (!shouldWarnIfShadowedDecl(Diags, R)) 7072 return nullptr; 7073 7074 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7075 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7076 } 7077 7078 /// Diagnose variable or built-in function shadowing. Implements 7079 /// -Wshadow. 7080 /// 7081 /// This method is called whenever a VarDecl is added to a "useful" 7082 /// scope. 7083 /// 7084 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7085 /// \param R the lookup of the name 7086 /// 7087 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7088 const LookupResult &R) { 7089 DeclContext *NewDC = D->getDeclContext(); 7090 7091 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7092 // Fields are not shadowed by variables in C++ static methods. 7093 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7094 if (MD->isStatic()) 7095 return; 7096 7097 // Fields shadowed by constructor parameters are a special case. Usually 7098 // the constructor initializes the field with the parameter. 7099 if (isa<CXXConstructorDecl>(NewDC)) 7100 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7101 // Remember that this was shadowed so we can either warn about its 7102 // modification or its existence depending on warning settings. 7103 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7104 return; 7105 } 7106 } 7107 7108 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7109 if (shadowedVar->isExternC()) { 7110 // For shadowing external vars, make sure that we point to the global 7111 // declaration, not a locally scoped extern declaration. 7112 for (auto I : shadowedVar->redecls()) 7113 if (I->isFileVarDecl()) { 7114 ShadowedDecl = I; 7115 break; 7116 } 7117 } 7118 7119 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7120 7121 unsigned WarningDiag = diag::warn_decl_shadow; 7122 SourceLocation CaptureLoc; 7123 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7124 isa<CXXMethodDecl>(NewDC)) { 7125 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7126 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7127 if (RD->getLambdaCaptureDefault() == LCD_None) { 7128 // Try to avoid warnings for lambdas with an explicit capture list. 7129 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7130 // Warn only when the lambda captures the shadowed decl explicitly. 7131 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7132 if (CaptureLoc.isInvalid()) 7133 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7134 } else { 7135 // Remember that this was shadowed so we can avoid the warning if the 7136 // shadowed decl isn't captured and the warning settings allow it. 7137 cast<LambdaScopeInfo>(getCurFunction()) 7138 ->ShadowingDecls.push_back( 7139 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7140 return; 7141 } 7142 } 7143 7144 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7145 // A variable can't shadow a local variable in an enclosing scope, if 7146 // they are separated by a non-capturing declaration context. 7147 for (DeclContext *ParentDC = NewDC; 7148 ParentDC && !ParentDC->Equals(OldDC); 7149 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7150 // Only block literals, captured statements, and lambda expressions 7151 // can capture; other scopes don't. 7152 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7153 !isLambdaCallOperator(ParentDC)) { 7154 return; 7155 } 7156 } 7157 } 7158 } 7159 } 7160 7161 // Only warn about certain kinds of shadowing for class members. 7162 if (NewDC && NewDC->isRecord()) { 7163 // In particular, don't warn about shadowing non-class members. 7164 if (!OldDC->isRecord()) 7165 return; 7166 7167 // TODO: should we warn about static data members shadowing 7168 // static data members from base classes? 7169 7170 // TODO: don't diagnose for inaccessible shadowed members. 7171 // This is hard to do perfectly because we might friend the 7172 // shadowing context, but that's just a false negative. 7173 } 7174 7175 7176 DeclarationName Name = R.getLookupName(); 7177 7178 // Emit warning and note. 7179 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7180 return; 7181 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7182 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7183 if (!CaptureLoc.isInvalid()) 7184 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7185 << Name << /*explicitly*/ 1; 7186 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7187 } 7188 7189 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7190 /// when these variables are captured by the lambda. 7191 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7192 for (const auto &Shadow : LSI->ShadowingDecls) { 7193 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7194 // Try to avoid the warning when the shadowed decl isn't captured. 7195 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7196 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7197 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7198 ? diag::warn_decl_shadow_uncaptured_local 7199 : diag::warn_decl_shadow) 7200 << Shadow.VD->getDeclName() 7201 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7202 if (!CaptureLoc.isInvalid()) 7203 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7204 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7205 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7206 } 7207 } 7208 7209 /// Check -Wshadow without the advantage of a previous lookup. 7210 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7211 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7212 return; 7213 7214 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7215 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7216 LookupName(R, S); 7217 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7218 CheckShadow(D, ShadowedDecl, R); 7219 } 7220 7221 /// Check if 'E', which is an expression that is about to be modified, refers 7222 /// to a constructor parameter that shadows a field. 7223 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7224 // Quickly ignore expressions that can't be shadowing ctor parameters. 7225 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7226 return; 7227 E = E->IgnoreParenImpCasts(); 7228 auto *DRE = dyn_cast<DeclRefExpr>(E); 7229 if (!DRE) 7230 return; 7231 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7232 auto I = ShadowingDecls.find(D); 7233 if (I == ShadowingDecls.end()) 7234 return; 7235 const NamedDecl *ShadowedDecl = I->second; 7236 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7237 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7238 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7239 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7240 7241 // Avoid issuing multiple warnings about the same decl. 7242 ShadowingDecls.erase(I); 7243 } 7244 7245 /// Check for conflict between this global or extern "C" declaration and 7246 /// previous global or extern "C" declarations. This is only used in C++. 7247 template<typename T> 7248 static bool checkGlobalOrExternCConflict( 7249 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7250 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7251 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7252 7253 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7254 // The common case: this global doesn't conflict with any extern "C" 7255 // declaration. 7256 return false; 7257 } 7258 7259 if (Prev) { 7260 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7261 // Both the old and new declarations have C language linkage. This is a 7262 // redeclaration. 7263 Previous.clear(); 7264 Previous.addDecl(Prev); 7265 return true; 7266 } 7267 7268 // This is a global, non-extern "C" declaration, and there is a previous 7269 // non-global extern "C" declaration. Diagnose if this is a variable 7270 // declaration. 7271 if (!isa<VarDecl>(ND)) 7272 return false; 7273 } else { 7274 // The declaration is extern "C". Check for any declaration in the 7275 // translation unit which might conflict. 7276 if (IsGlobal) { 7277 // We have already performed the lookup into the translation unit. 7278 IsGlobal = false; 7279 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7280 I != E; ++I) { 7281 if (isa<VarDecl>(*I)) { 7282 Prev = *I; 7283 break; 7284 } 7285 } 7286 } else { 7287 DeclContext::lookup_result R = 7288 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7289 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7290 I != E; ++I) { 7291 if (isa<VarDecl>(*I)) { 7292 Prev = *I; 7293 break; 7294 } 7295 // FIXME: If we have any other entity with this name in global scope, 7296 // the declaration is ill-formed, but that is a defect: it breaks the 7297 // 'stat' hack, for instance. Only variables can have mangled name 7298 // clashes with extern "C" declarations, so only they deserve a 7299 // diagnostic. 7300 } 7301 } 7302 7303 if (!Prev) 7304 return false; 7305 } 7306 7307 // Use the first declaration's location to ensure we point at something which 7308 // is lexically inside an extern "C" linkage-spec. 7309 assert(Prev && "should have found a previous declaration to diagnose"); 7310 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7311 Prev = FD->getFirstDecl(); 7312 else 7313 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7314 7315 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7316 << IsGlobal << ND; 7317 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7318 << IsGlobal; 7319 return false; 7320 } 7321 7322 /// Apply special rules for handling extern "C" declarations. Returns \c true 7323 /// if we have found that this is a redeclaration of some prior entity. 7324 /// 7325 /// Per C++ [dcl.link]p6: 7326 /// Two declarations [for a function or variable] with C language linkage 7327 /// with the same name that appear in different scopes refer to the same 7328 /// [entity]. An entity with C language linkage shall not be declared with 7329 /// the same name as an entity in global scope. 7330 template<typename T> 7331 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7332 LookupResult &Previous) { 7333 if (!S.getLangOpts().CPlusPlus) { 7334 // In C, when declaring a global variable, look for a corresponding 'extern' 7335 // variable declared in function scope. We don't need this in C++, because 7336 // we find local extern decls in the surrounding file-scope DeclContext. 7337 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7338 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7339 Previous.clear(); 7340 Previous.addDecl(Prev); 7341 return true; 7342 } 7343 } 7344 return false; 7345 } 7346 7347 // A declaration in the translation unit can conflict with an extern "C" 7348 // declaration. 7349 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7350 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7351 7352 // An extern "C" declaration can conflict with a declaration in the 7353 // translation unit or can be a redeclaration of an extern "C" declaration 7354 // in another scope. 7355 if (isIncompleteDeclExternC(S,ND)) 7356 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7357 7358 // Neither global nor extern "C": nothing to do. 7359 return false; 7360 } 7361 7362 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7363 // If the decl is already known invalid, don't check it. 7364 if (NewVD->isInvalidDecl()) 7365 return; 7366 7367 QualType T = NewVD->getType(); 7368 7369 // Defer checking an 'auto' type until its initializer is attached. 7370 if (T->isUndeducedType()) 7371 return; 7372 7373 if (NewVD->hasAttrs()) 7374 CheckAlignasUnderalignment(NewVD); 7375 7376 if (T->isObjCObjectType()) { 7377 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7378 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7379 T = Context.getObjCObjectPointerType(T); 7380 NewVD->setType(T); 7381 } 7382 7383 // Emit an error if an address space was applied to decl with local storage. 7384 // This includes arrays of objects with address space qualifiers, but not 7385 // automatic variables that point to other address spaces. 7386 // ISO/IEC TR 18037 S5.1.2 7387 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7388 T.getAddressSpace() != LangAS::Default) { 7389 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7390 NewVD->setInvalidDecl(); 7391 return; 7392 } 7393 7394 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7395 // scope. 7396 if (getLangOpts().OpenCLVersion == 120 && 7397 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7398 NewVD->isStaticLocal()) { 7399 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7400 NewVD->setInvalidDecl(); 7401 return; 7402 } 7403 7404 if (getLangOpts().OpenCL) { 7405 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7406 if (NewVD->hasAttr<BlocksAttr>()) { 7407 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7408 return; 7409 } 7410 7411 if (T->isBlockPointerType()) { 7412 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7413 // can't use 'extern' storage class. 7414 if (!T.isConstQualified()) { 7415 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7416 << 0 /*const*/; 7417 NewVD->setInvalidDecl(); 7418 return; 7419 } 7420 if (NewVD->hasExternalStorage()) { 7421 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7422 NewVD->setInvalidDecl(); 7423 return; 7424 } 7425 } 7426 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7427 // __constant address space. 7428 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7429 // variables inside a function can also be declared in the global 7430 // address space. 7431 // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local 7432 // address space additionally. 7433 // FIXME: Add local AS for OpenCL C++. 7434 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7435 NewVD->hasExternalStorage()) { 7436 if (!T->isSamplerT() && 7437 !(T.getAddressSpace() == LangAS::opencl_constant || 7438 (T.getAddressSpace() == LangAS::opencl_global && 7439 (getLangOpts().OpenCLVersion == 200 || 7440 getLangOpts().OpenCLCPlusPlus)))) { 7441 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7442 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7443 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7444 << Scope << "global or constant"; 7445 else 7446 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7447 << Scope << "constant"; 7448 NewVD->setInvalidDecl(); 7449 return; 7450 } 7451 } else { 7452 if (T.getAddressSpace() == LangAS::opencl_global) { 7453 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7454 << 1 /*is any function*/ << "global"; 7455 NewVD->setInvalidDecl(); 7456 return; 7457 } 7458 if (T.getAddressSpace() == LangAS::opencl_constant || 7459 T.getAddressSpace() == LangAS::opencl_local) { 7460 FunctionDecl *FD = getCurFunctionDecl(); 7461 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7462 // in functions. 7463 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7464 if (T.getAddressSpace() == LangAS::opencl_constant) 7465 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7466 << 0 /*non-kernel only*/ << "constant"; 7467 else 7468 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7469 << 0 /*non-kernel only*/ << "local"; 7470 NewVD->setInvalidDecl(); 7471 return; 7472 } 7473 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7474 // in the outermost scope of a kernel function. 7475 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7476 if (!getCurScope()->isFunctionScope()) { 7477 if (T.getAddressSpace() == LangAS::opencl_constant) 7478 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7479 << "constant"; 7480 else 7481 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7482 << "local"; 7483 NewVD->setInvalidDecl(); 7484 return; 7485 } 7486 } 7487 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7488 // Do not allow other address spaces on automatic variable. 7489 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7490 NewVD->setInvalidDecl(); 7491 return; 7492 } 7493 } 7494 } 7495 7496 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7497 && !NewVD->hasAttr<BlocksAttr>()) { 7498 if (getLangOpts().getGC() != LangOptions::NonGC) 7499 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7500 else { 7501 assert(!getLangOpts().ObjCAutoRefCount); 7502 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7503 } 7504 } 7505 7506 bool isVM = T->isVariablyModifiedType(); 7507 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7508 NewVD->hasAttr<BlocksAttr>()) 7509 setFunctionHasBranchProtectedScope(); 7510 7511 if ((isVM && NewVD->hasLinkage()) || 7512 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7513 bool SizeIsNegative; 7514 llvm::APSInt Oversized; 7515 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7516 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7517 QualType FixedT; 7518 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7519 FixedT = FixedTInfo->getType(); 7520 else if (FixedTInfo) { 7521 // Type and type-as-written are canonically different. We need to fix up 7522 // both types separately. 7523 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7524 Oversized); 7525 } 7526 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7527 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7528 // FIXME: This won't give the correct result for 7529 // int a[10][n]; 7530 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7531 7532 if (NewVD->isFileVarDecl()) 7533 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7534 << SizeRange; 7535 else if (NewVD->isStaticLocal()) 7536 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7537 << SizeRange; 7538 else 7539 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7540 << SizeRange; 7541 NewVD->setInvalidDecl(); 7542 return; 7543 } 7544 7545 if (!FixedTInfo) { 7546 if (NewVD->isFileVarDecl()) 7547 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7548 else 7549 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7550 NewVD->setInvalidDecl(); 7551 return; 7552 } 7553 7554 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7555 NewVD->setType(FixedT); 7556 NewVD->setTypeSourceInfo(FixedTInfo); 7557 } 7558 7559 if (T->isVoidType()) { 7560 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7561 // of objects and functions. 7562 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7563 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7564 << T; 7565 NewVD->setInvalidDecl(); 7566 return; 7567 } 7568 } 7569 7570 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7571 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7572 NewVD->setInvalidDecl(); 7573 return; 7574 } 7575 7576 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7577 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7578 NewVD->setInvalidDecl(); 7579 return; 7580 } 7581 7582 if (NewVD->isConstexpr() && !T->isDependentType() && 7583 RequireLiteralType(NewVD->getLocation(), T, 7584 diag::err_constexpr_var_non_literal)) { 7585 NewVD->setInvalidDecl(); 7586 return; 7587 } 7588 } 7589 7590 /// Perform semantic checking on a newly-created variable 7591 /// declaration. 7592 /// 7593 /// This routine performs all of the type-checking required for a 7594 /// variable declaration once it has been built. It is used both to 7595 /// check variables after they have been parsed and their declarators 7596 /// have been translated into a declaration, and to check variables 7597 /// that have been instantiated from a template. 7598 /// 7599 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7600 /// 7601 /// Returns true if the variable declaration is a redeclaration. 7602 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7603 CheckVariableDeclarationType(NewVD); 7604 7605 // If the decl is already known invalid, don't check it. 7606 if (NewVD->isInvalidDecl()) 7607 return false; 7608 7609 // If we did not find anything by this name, look for a non-visible 7610 // extern "C" declaration with the same name. 7611 if (Previous.empty() && 7612 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7613 Previous.setShadowed(); 7614 7615 if (!Previous.empty()) { 7616 MergeVarDecl(NewVD, Previous); 7617 return true; 7618 } 7619 return false; 7620 } 7621 7622 namespace { 7623 struct FindOverriddenMethod { 7624 Sema *S; 7625 CXXMethodDecl *Method; 7626 7627 /// Member lookup function that determines whether a given C++ 7628 /// method overrides a method in a base class, to be used with 7629 /// CXXRecordDecl::lookupInBases(). 7630 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7631 RecordDecl *BaseRecord = 7632 Specifier->getType()->getAs<RecordType>()->getDecl(); 7633 7634 DeclarationName Name = Method->getDeclName(); 7635 7636 // FIXME: Do we care about other names here too? 7637 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7638 // We really want to find the base class destructor here. 7639 QualType T = S->Context.getTypeDeclType(BaseRecord); 7640 CanQualType CT = S->Context.getCanonicalType(T); 7641 7642 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7643 } 7644 7645 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7646 Path.Decls = Path.Decls.slice(1)) { 7647 NamedDecl *D = Path.Decls.front(); 7648 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7649 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7650 return true; 7651 } 7652 } 7653 7654 return false; 7655 } 7656 }; 7657 7658 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7659 } // end anonymous namespace 7660 7661 /// Report an error regarding overriding, along with any relevant 7662 /// overridden methods. 7663 /// 7664 /// \param DiagID the primary error to report. 7665 /// \param MD the overriding method. 7666 /// \param OEK which overrides to include as notes. 7667 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7668 OverrideErrorKind OEK = OEK_All) { 7669 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7670 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7671 // This check (& the OEK parameter) could be replaced by a predicate, but 7672 // without lambdas that would be overkill. This is still nicer than writing 7673 // out the diag loop 3 times. 7674 if ((OEK == OEK_All) || 7675 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7676 (OEK == OEK_Deleted && O->isDeleted())) 7677 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7678 } 7679 } 7680 7681 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7682 /// and if so, check that it's a valid override and remember it. 7683 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7684 // Look for methods in base classes that this method might override. 7685 CXXBasePaths Paths; 7686 FindOverriddenMethod FOM; 7687 FOM.Method = MD; 7688 FOM.S = this; 7689 bool hasDeletedOverridenMethods = false; 7690 bool hasNonDeletedOverridenMethods = false; 7691 bool AddedAny = false; 7692 if (DC->lookupInBases(FOM, Paths)) { 7693 for (auto *I : Paths.found_decls()) { 7694 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7695 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7696 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7697 !CheckOverridingFunctionAttributes(MD, OldMD) && 7698 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7699 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7700 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7701 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7702 AddedAny = true; 7703 } 7704 } 7705 } 7706 } 7707 7708 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7709 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7710 } 7711 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7712 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7713 } 7714 7715 return AddedAny; 7716 } 7717 7718 namespace { 7719 // Struct for holding all of the extra arguments needed by 7720 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7721 struct ActOnFDArgs { 7722 Scope *S; 7723 Declarator &D; 7724 MultiTemplateParamsArg TemplateParamLists; 7725 bool AddToScope; 7726 }; 7727 } // end anonymous namespace 7728 7729 namespace { 7730 7731 // Callback to only accept typo corrections that have a non-zero edit distance. 7732 // Also only accept corrections that have the same parent decl. 7733 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 7734 public: 7735 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7736 CXXRecordDecl *Parent) 7737 : Context(Context), OriginalFD(TypoFD), 7738 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7739 7740 bool ValidateCandidate(const TypoCorrection &candidate) override { 7741 if (candidate.getEditDistance() == 0) 7742 return false; 7743 7744 SmallVector<unsigned, 1> MismatchedParams; 7745 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7746 CDeclEnd = candidate.end(); 7747 CDecl != CDeclEnd; ++CDecl) { 7748 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7749 7750 if (FD && !FD->hasBody() && 7751 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7752 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7753 CXXRecordDecl *Parent = MD->getParent(); 7754 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7755 return true; 7756 } else if (!ExpectedParent) { 7757 return true; 7758 } 7759 } 7760 } 7761 7762 return false; 7763 } 7764 7765 std::unique_ptr<CorrectionCandidateCallback> clone() override { 7766 return llvm::make_unique<DifferentNameValidatorCCC>(*this); 7767 } 7768 7769 private: 7770 ASTContext &Context; 7771 FunctionDecl *OriginalFD; 7772 CXXRecordDecl *ExpectedParent; 7773 }; 7774 7775 } // end anonymous namespace 7776 7777 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7778 TypoCorrectedFunctionDefinitions.insert(F); 7779 } 7780 7781 /// Generate diagnostics for an invalid function redeclaration. 7782 /// 7783 /// This routine handles generating the diagnostic messages for an invalid 7784 /// function redeclaration, including finding possible similar declarations 7785 /// or performing typo correction if there are no previous declarations with 7786 /// the same name. 7787 /// 7788 /// Returns a NamedDecl iff typo correction was performed and substituting in 7789 /// the new declaration name does not cause new errors. 7790 static NamedDecl *DiagnoseInvalidRedeclaration( 7791 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7792 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7793 DeclarationName Name = NewFD->getDeclName(); 7794 DeclContext *NewDC = NewFD->getDeclContext(); 7795 SmallVector<unsigned, 1> MismatchedParams; 7796 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7797 TypoCorrection Correction; 7798 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7799 unsigned DiagMsg = 7800 IsLocalFriend ? diag::err_no_matching_local_friend : 7801 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 7802 diag::err_member_decl_does_not_match; 7803 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7804 IsLocalFriend ? Sema::LookupLocalFriendName 7805 : Sema::LookupOrdinaryName, 7806 Sema::ForVisibleRedeclaration); 7807 7808 NewFD->setInvalidDecl(); 7809 if (IsLocalFriend) 7810 SemaRef.LookupName(Prev, S); 7811 else 7812 SemaRef.LookupQualifiedName(Prev, NewDC); 7813 assert(!Prev.isAmbiguous() && 7814 "Cannot have an ambiguity in previous-declaration lookup"); 7815 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7816 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 7817 MD ? MD->getParent() : nullptr); 7818 if (!Prev.empty()) { 7819 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7820 Func != FuncEnd; ++Func) { 7821 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7822 if (FD && 7823 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7824 // Add 1 to the index so that 0 can mean the mismatch didn't 7825 // involve a parameter 7826 unsigned ParamNum = 7827 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7828 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7829 } 7830 } 7831 // If the qualified name lookup yielded nothing, try typo correction 7832 } else if ((Correction = SemaRef.CorrectTypo( 7833 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7834 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 7835 IsLocalFriend ? nullptr : NewDC))) { 7836 // Set up everything for the call to ActOnFunctionDeclarator 7837 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7838 ExtraArgs.D.getIdentifierLoc()); 7839 Previous.clear(); 7840 Previous.setLookupName(Correction.getCorrection()); 7841 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7842 CDeclEnd = Correction.end(); 7843 CDecl != CDeclEnd; ++CDecl) { 7844 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7845 if (FD && !FD->hasBody() && 7846 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7847 Previous.addDecl(FD); 7848 } 7849 } 7850 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7851 7852 NamedDecl *Result; 7853 // Retry building the function declaration with the new previous 7854 // declarations, and with errors suppressed. 7855 { 7856 // Trap errors. 7857 Sema::SFINAETrap Trap(SemaRef); 7858 7859 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7860 // pieces need to verify the typo-corrected C++ declaration and hopefully 7861 // eliminate the need for the parameter pack ExtraArgs. 7862 Result = SemaRef.ActOnFunctionDeclarator( 7863 ExtraArgs.S, ExtraArgs.D, 7864 Correction.getCorrectionDecl()->getDeclContext(), 7865 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7866 ExtraArgs.AddToScope); 7867 7868 if (Trap.hasErrorOccurred()) 7869 Result = nullptr; 7870 } 7871 7872 if (Result) { 7873 // Determine which correction we picked. 7874 Decl *Canonical = Result->getCanonicalDecl(); 7875 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7876 I != E; ++I) 7877 if ((*I)->getCanonicalDecl() == Canonical) 7878 Correction.setCorrectionDecl(*I); 7879 7880 // Let Sema know about the correction. 7881 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7882 SemaRef.diagnoseTypo( 7883 Correction, 7884 SemaRef.PDiag(IsLocalFriend 7885 ? diag::err_no_matching_local_friend_suggest 7886 : diag::err_member_decl_does_not_match_suggest) 7887 << Name << NewDC << IsDefinition); 7888 return Result; 7889 } 7890 7891 // Pretend the typo correction never occurred 7892 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7893 ExtraArgs.D.getIdentifierLoc()); 7894 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7895 Previous.clear(); 7896 Previous.setLookupName(Name); 7897 } 7898 7899 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7900 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7901 7902 bool NewFDisConst = false; 7903 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7904 NewFDisConst = NewMD->isConst(); 7905 7906 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7907 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7908 NearMatch != NearMatchEnd; ++NearMatch) { 7909 FunctionDecl *FD = NearMatch->first; 7910 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7911 bool FDisConst = MD && MD->isConst(); 7912 bool IsMember = MD || !IsLocalFriend; 7913 7914 // FIXME: These notes are poorly worded for the local friend case. 7915 if (unsigned Idx = NearMatch->second) { 7916 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7917 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7918 if (Loc.isInvalid()) Loc = FD->getLocation(); 7919 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7920 : diag::note_local_decl_close_param_match) 7921 << Idx << FDParam->getType() 7922 << NewFD->getParamDecl(Idx - 1)->getType(); 7923 } else if (FDisConst != NewFDisConst) { 7924 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7925 << NewFDisConst << FD->getSourceRange().getEnd(); 7926 } else 7927 SemaRef.Diag(FD->getLocation(), 7928 IsMember ? diag::note_member_def_close_match 7929 : diag::note_local_decl_close_match); 7930 } 7931 return nullptr; 7932 } 7933 7934 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7935 switch (D.getDeclSpec().getStorageClassSpec()) { 7936 default: llvm_unreachable("Unknown storage class!"); 7937 case DeclSpec::SCS_auto: 7938 case DeclSpec::SCS_register: 7939 case DeclSpec::SCS_mutable: 7940 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7941 diag::err_typecheck_sclass_func); 7942 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7943 D.setInvalidType(); 7944 break; 7945 case DeclSpec::SCS_unspecified: break; 7946 case DeclSpec::SCS_extern: 7947 if (D.getDeclSpec().isExternInLinkageSpec()) 7948 return SC_None; 7949 return SC_Extern; 7950 case DeclSpec::SCS_static: { 7951 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7952 // C99 6.7.1p5: 7953 // The declaration of an identifier for a function that has 7954 // block scope shall have no explicit storage-class specifier 7955 // other than extern 7956 // See also (C++ [dcl.stc]p4). 7957 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7958 diag::err_static_block_func); 7959 break; 7960 } else 7961 return SC_Static; 7962 } 7963 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7964 } 7965 7966 // No explicit storage class has already been returned 7967 return SC_None; 7968 } 7969 7970 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7971 DeclContext *DC, QualType &R, 7972 TypeSourceInfo *TInfo, 7973 StorageClass SC, 7974 bool &IsVirtualOkay) { 7975 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7976 DeclarationName Name = NameInfo.getName(); 7977 7978 FunctionDecl *NewFD = nullptr; 7979 bool isInline = D.getDeclSpec().isInlineSpecified(); 7980 7981 if (!SemaRef.getLangOpts().CPlusPlus) { 7982 // Determine whether the function was written with a 7983 // prototype. This true when: 7984 // - there is a prototype in the declarator, or 7985 // - the type R of the function is some kind of typedef or other non- 7986 // attributed reference to a type name (which eventually refers to a 7987 // function type). 7988 bool HasPrototype = 7989 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7990 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7991 7992 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 7993 R, TInfo, SC, isInline, HasPrototype, 7994 CSK_unspecified); 7995 if (D.isInvalidType()) 7996 NewFD->setInvalidDecl(); 7997 7998 return NewFD; 7999 } 8000 8001 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8002 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8003 // Check that the return type is not an abstract class type. 8004 // For record types, this is done by the AbstractClassUsageDiagnoser once 8005 // the class has been completely parsed. 8006 if (!DC->isRecord() && 8007 SemaRef.RequireNonAbstractType( 8008 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 8009 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8010 D.setInvalidType(); 8011 8012 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8013 // This is a C++ constructor declaration. 8014 assert(DC->isRecord() && 8015 "Constructors can only be declared in a member context"); 8016 8017 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8018 return CXXConstructorDecl::Create( 8019 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8020 TInfo, ExplicitSpecifier, isInline, 8021 /*isImplicitlyDeclared=*/false, ConstexprKind); 8022 8023 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8024 // This is a C++ destructor declaration. 8025 if (DC->isRecord()) { 8026 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8027 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8028 CXXDestructorDecl *NewDD = 8029 CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(), 8030 NameInfo, R, TInfo, isInline, 8031 /*isImplicitlyDeclared=*/false); 8032 8033 // If the destructor needs an implicit exception specification, set it 8034 // now. FIXME: It'd be nice to be able to create the right type to start 8035 // with, but the type needs to reference the destructor declaration. 8036 if (SemaRef.getLangOpts().CPlusPlus11) 8037 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8038 8039 IsVirtualOkay = true; 8040 return NewDD; 8041 8042 } else { 8043 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8044 D.setInvalidType(); 8045 8046 // Create a FunctionDecl to satisfy the function definition parsing 8047 // code path. 8048 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8049 D.getIdentifierLoc(), Name, R, TInfo, SC, 8050 isInline, 8051 /*hasPrototype=*/true, ConstexprKind); 8052 } 8053 8054 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8055 if (!DC->isRecord()) { 8056 SemaRef.Diag(D.getIdentifierLoc(), 8057 diag::err_conv_function_not_member); 8058 return nullptr; 8059 } 8060 8061 SemaRef.CheckConversionDeclarator(D, R, SC); 8062 IsVirtualOkay = true; 8063 return CXXConversionDecl::Create( 8064 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8065 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation()); 8066 8067 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8068 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8069 8070 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8071 ExplicitSpecifier, NameInfo, R, TInfo, 8072 D.getEndLoc()); 8073 } else if (DC->isRecord()) { 8074 // If the name of the function is the same as the name of the record, 8075 // then this must be an invalid constructor that has a return type. 8076 // (The parser checks for a return type and makes the declarator a 8077 // constructor if it has no return type). 8078 if (Name.getAsIdentifierInfo() && 8079 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8080 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8081 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8082 << SourceRange(D.getIdentifierLoc()); 8083 return nullptr; 8084 } 8085 8086 // This is a C++ method declaration. 8087 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8088 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8089 TInfo, SC, isInline, ConstexprKind, SourceLocation()); 8090 IsVirtualOkay = !Ret->isStatic(); 8091 return Ret; 8092 } else { 8093 bool isFriend = 8094 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8095 if (!isFriend && SemaRef.CurContext->isRecord()) 8096 return nullptr; 8097 8098 // Determine whether the function was written with a 8099 // prototype. This true when: 8100 // - we're in C++ (where every function has a prototype), 8101 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8102 R, TInfo, SC, isInline, true /*HasPrototype*/, 8103 ConstexprKind); 8104 } 8105 } 8106 8107 enum OpenCLParamType { 8108 ValidKernelParam, 8109 PtrPtrKernelParam, 8110 PtrKernelParam, 8111 InvalidAddrSpacePtrKernelParam, 8112 InvalidKernelParam, 8113 RecordKernelParam 8114 }; 8115 8116 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8117 // Size dependent types are just typedefs to normal integer types 8118 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8119 // integers other than by their names. 8120 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8121 8122 // Remove typedefs one by one until we reach a typedef 8123 // for a size dependent type. 8124 QualType DesugaredTy = Ty; 8125 do { 8126 ArrayRef<StringRef> Names(SizeTypeNames); 8127 auto Match = llvm::find(Names, DesugaredTy.getAsString()); 8128 if (Names.end() != Match) 8129 return true; 8130 8131 Ty = DesugaredTy; 8132 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8133 } while (DesugaredTy != Ty); 8134 8135 return false; 8136 } 8137 8138 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8139 if (PT->isPointerType()) { 8140 QualType PointeeType = PT->getPointeeType(); 8141 if (PointeeType->isPointerType()) 8142 return PtrPtrKernelParam; 8143 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8144 PointeeType.getAddressSpace() == LangAS::opencl_private || 8145 PointeeType.getAddressSpace() == LangAS::Default) 8146 return InvalidAddrSpacePtrKernelParam; 8147 return PtrKernelParam; 8148 } 8149 8150 // OpenCL v1.2 s6.9.k: 8151 // Arguments to kernel functions in a program cannot be declared with the 8152 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8153 // uintptr_t or a struct and/or union that contain fields declared to be one 8154 // of these built-in scalar types. 8155 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8156 return InvalidKernelParam; 8157 8158 if (PT->isImageType()) 8159 return PtrKernelParam; 8160 8161 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8162 return InvalidKernelParam; 8163 8164 // OpenCL extension spec v1.2 s9.5: 8165 // This extension adds support for half scalar and vector types as built-in 8166 // types that can be used for arithmetic operations, conversions etc. 8167 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8168 return InvalidKernelParam; 8169 8170 if (PT->isRecordType()) 8171 return RecordKernelParam; 8172 8173 // Look into an array argument to check if it has a forbidden type. 8174 if (PT->isArrayType()) { 8175 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8176 // Call ourself to check an underlying type of an array. Since the 8177 // getPointeeOrArrayElementType returns an innermost type which is not an 8178 // array, this recursive call only happens once. 8179 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8180 } 8181 8182 return ValidKernelParam; 8183 } 8184 8185 static void checkIsValidOpenCLKernelParameter( 8186 Sema &S, 8187 Declarator &D, 8188 ParmVarDecl *Param, 8189 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8190 QualType PT = Param->getType(); 8191 8192 // Cache the valid types we encounter to avoid rechecking structs that are 8193 // used again 8194 if (ValidTypes.count(PT.getTypePtr())) 8195 return; 8196 8197 switch (getOpenCLKernelParameterType(S, PT)) { 8198 case PtrPtrKernelParam: 8199 // OpenCL v1.2 s6.9.a: 8200 // A kernel function argument cannot be declared as a 8201 // pointer to a pointer type. 8202 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8203 D.setInvalidType(); 8204 return; 8205 8206 case InvalidAddrSpacePtrKernelParam: 8207 // OpenCL v1.0 s6.5: 8208 // __kernel function arguments declared to be a pointer of a type can point 8209 // to one of the following address spaces only : __global, __local or 8210 // __constant. 8211 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8212 D.setInvalidType(); 8213 return; 8214 8215 // OpenCL v1.2 s6.9.k: 8216 // Arguments to kernel functions in a program cannot be declared with the 8217 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8218 // uintptr_t or a struct and/or union that contain fields declared to be 8219 // one of these built-in scalar types. 8220 8221 case InvalidKernelParam: 8222 // OpenCL v1.2 s6.8 n: 8223 // A kernel function argument cannot be declared 8224 // of event_t type. 8225 // Do not diagnose half type since it is diagnosed as invalid argument 8226 // type for any function elsewhere. 8227 if (!PT->isHalfType()) { 8228 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8229 8230 // Explain what typedefs are involved. 8231 const TypedefType *Typedef = nullptr; 8232 while ((Typedef = PT->getAs<TypedefType>())) { 8233 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8234 // SourceLocation may be invalid for a built-in type. 8235 if (Loc.isValid()) 8236 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8237 PT = Typedef->desugar(); 8238 } 8239 } 8240 8241 D.setInvalidType(); 8242 return; 8243 8244 case PtrKernelParam: 8245 case ValidKernelParam: 8246 ValidTypes.insert(PT.getTypePtr()); 8247 return; 8248 8249 case RecordKernelParam: 8250 break; 8251 } 8252 8253 // Track nested structs we will inspect 8254 SmallVector<const Decl *, 4> VisitStack; 8255 8256 // Track where we are in the nested structs. Items will migrate from 8257 // VisitStack to HistoryStack as we do the DFS for bad field. 8258 SmallVector<const FieldDecl *, 4> HistoryStack; 8259 HistoryStack.push_back(nullptr); 8260 8261 // At this point we already handled everything except of a RecordType or 8262 // an ArrayType of a RecordType. 8263 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8264 const RecordType *RecTy = 8265 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8266 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8267 8268 VisitStack.push_back(RecTy->getDecl()); 8269 assert(VisitStack.back() && "First decl null?"); 8270 8271 do { 8272 const Decl *Next = VisitStack.pop_back_val(); 8273 if (!Next) { 8274 assert(!HistoryStack.empty()); 8275 // Found a marker, we have gone up a level 8276 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8277 ValidTypes.insert(Hist->getType().getTypePtr()); 8278 8279 continue; 8280 } 8281 8282 // Adds everything except the original parameter declaration (which is not a 8283 // field itself) to the history stack. 8284 const RecordDecl *RD; 8285 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8286 HistoryStack.push_back(Field); 8287 8288 QualType FieldTy = Field->getType(); 8289 // Other field types (known to be valid or invalid) are handled while we 8290 // walk around RecordDecl::fields(). 8291 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8292 "Unexpected type."); 8293 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8294 8295 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8296 } else { 8297 RD = cast<RecordDecl>(Next); 8298 } 8299 8300 // Add a null marker so we know when we've gone back up a level 8301 VisitStack.push_back(nullptr); 8302 8303 for (const auto *FD : RD->fields()) { 8304 QualType QT = FD->getType(); 8305 8306 if (ValidTypes.count(QT.getTypePtr())) 8307 continue; 8308 8309 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8310 if (ParamType == ValidKernelParam) 8311 continue; 8312 8313 if (ParamType == RecordKernelParam) { 8314 VisitStack.push_back(FD); 8315 continue; 8316 } 8317 8318 // OpenCL v1.2 s6.9.p: 8319 // Arguments to kernel functions that are declared to be a struct or union 8320 // do not allow OpenCL objects to be passed as elements of the struct or 8321 // union. 8322 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8323 ParamType == InvalidAddrSpacePtrKernelParam) { 8324 S.Diag(Param->getLocation(), 8325 diag::err_record_with_pointers_kernel_param) 8326 << PT->isUnionType() 8327 << PT; 8328 } else { 8329 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8330 } 8331 8332 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8333 << OrigRecDecl->getDeclName(); 8334 8335 // We have an error, now let's go back up through history and show where 8336 // the offending field came from 8337 for (ArrayRef<const FieldDecl *>::const_iterator 8338 I = HistoryStack.begin() + 1, 8339 E = HistoryStack.end(); 8340 I != E; ++I) { 8341 const FieldDecl *OuterField = *I; 8342 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8343 << OuterField->getType(); 8344 } 8345 8346 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8347 << QT->isPointerType() 8348 << QT; 8349 D.setInvalidType(); 8350 return; 8351 } 8352 } while (!VisitStack.empty()); 8353 } 8354 8355 /// Find the DeclContext in which a tag is implicitly declared if we see an 8356 /// elaborated type specifier in the specified context, and lookup finds 8357 /// nothing. 8358 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8359 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8360 DC = DC->getParent(); 8361 return DC; 8362 } 8363 8364 /// Find the Scope in which a tag is implicitly declared if we see an 8365 /// elaborated type specifier in the specified context, and lookup finds 8366 /// nothing. 8367 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8368 while (S->isClassScope() || 8369 (LangOpts.CPlusPlus && 8370 S->isFunctionPrototypeScope()) || 8371 ((S->getFlags() & Scope::DeclScope) == 0) || 8372 (S->getEntity() && S->getEntity()->isTransparentContext())) 8373 S = S->getParent(); 8374 return S; 8375 } 8376 8377 NamedDecl* 8378 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8379 TypeSourceInfo *TInfo, LookupResult &Previous, 8380 MultiTemplateParamsArg TemplateParamLists, 8381 bool &AddToScope) { 8382 QualType R = TInfo->getType(); 8383 8384 assert(R->isFunctionType()); 8385 8386 // TODO: consider using NameInfo for diagnostic. 8387 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8388 DeclarationName Name = NameInfo.getName(); 8389 StorageClass SC = getFunctionStorageClass(*this, D); 8390 8391 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8392 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8393 diag::err_invalid_thread) 8394 << DeclSpec::getSpecifierName(TSCS); 8395 8396 if (D.isFirstDeclarationOfMember()) 8397 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8398 D.getIdentifierLoc()); 8399 8400 bool isFriend = false; 8401 FunctionTemplateDecl *FunctionTemplate = nullptr; 8402 bool isMemberSpecialization = false; 8403 bool isFunctionTemplateSpecialization = false; 8404 8405 bool isDependentClassScopeExplicitSpecialization = false; 8406 bool HasExplicitTemplateArgs = false; 8407 TemplateArgumentListInfo TemplateArgs; 8408 8409 bool isVirtualOkay = false; 8410 8411 DeclContext *OriginalDC = DC; 8412 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8413 8414 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8415 isVirtualOkay); 8416 if (!NewFD) return nullptr; 8417 8418 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8419 NewFD->setTopLevelDeclInObjCContainer(); 8420 8421 // Set the lexical context. If this is a function-scope declaration, or has a 8422 // C++ scope specifier, or is the object of a friend declaration, the lexical 8423 // context will be different from the semantic context. 8424 NewFD->setLexicalDeclContext(CurContext); 8425 8426 if (IsLocalExternDecl) 8427 NewFD->setLocalExternDecl(); 8428 8429 if (getLangOpts().CPlusPlus) { 8430 bool isInline = D.getDeclSpec().isInlineSpecified(); 8431 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8432 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8433 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8434 isFriend = D.getDeclSpec().isFriendSpecified(); 8435 if (isFriend && !isInline && D.isFunctionDefinition()) { 8436 // C++ [class.friend]p5 8437 // A function can be defined in a friend declaration of a 8438 // class . . . . Such a function is implicitly inline. 8439 NewFD->setImplicitlyInline(); 8440 } 8441 8442 // If this is a method defined in an __interface, and is not a constructor 8443 // or an overloaded operator, then set the pure flag (isVirtual will already 8444 // return true). 8445 if (const CXXRecordDecl *Parent = 8446 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8447 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8448 NewFD->setPure(true); 8449 8450 // C++ [class.union]p2 8451 // A union can have member functions, but not virtual functions. 8452 if (isVirtual && Parent->isUnion()) 8453 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8454 } 8455 8456 SetNestedNameSpecifier(*this, NewFD, D); 8457 isMemberSpecialization = false; 8458 isFunctionTemplateSpecialization = false; 8459 if (D.isInvalidType()) 8460 NewFD->setInvalidDecl(); 8461 8462 // Match up the template parameter lists with the scope specifier, then 8463 // determine whether we have a template or a template specialization. 8464 bool Invalid = false; 8465 if (TemplateParameterList *TemplateParams = 8466 MatchTemplateParametersToScopeSpecifier( 8467 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8468 D.getCXXScopeSpec(), 8469 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8470 ? D.getName().TemplateId 8471 : nullptr, 8472 TemplateParamLists, isFriend, isMemberSpecialization, 8473 Invalid)) { 8474 if (TemplateParams->size() > 0) { 8475 // This is a function template 8476 8477 // Check that we can declare a template here. 8478 if (CheckTemplateDeclScope(S, TemplateParams)) 8479 NewFD->setInvalidDecl(); 8480 8481 // A destructor cannot be a template. 8482 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8483 Diag(NewFD->getLocation(), diag::err_destructor_template); 8484 NewFD->setInvalidDecl(); 8485 } 8486 8487 // If we're adding a template to a dependent context, we may need to 8488 // rebuilding some of the types used within the template parameter list, 8489 // now that we know what the current instantiation is. 8490 if (DC->isDependentContext()) { 8491 ContextRAII SavedContext(*this, DC); 8492 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8493 Invalid = true; 8494 } 8495 8496 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8497 NewFD->getLocation(), 8498 Name, TemplateParams, 8499 NewFD); 8500 FunctionTemplate->setLexicalDeclContext(CurContext); 8501 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8502 8503 // For source fidelity, store the other template param lists. 8504 if (TemplateParamLists.size() > 1) { 8505 NewFD->setTemplateParameterListsInfo(Context, 8506 TemplateParamLists.drop_back(1)); 8507 } 8508 } else { 8509 // This is a function template specialization. 8510 isFunctionTemplateSpecialization = true; 8511 // For source fidelity, store all the template param lists. 8512 if (TemplateParamLists.size() > 0) 8513 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8514 8515 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8516 if (isFriend) { 8517 // We want to remove the "template<>", found here. 8518 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8519 8520 // If we remove the template<> and the name is not a 8521 // template-id, we're actually silently creating a problem: 8522 // the friend declaration will refer to an untemplated decl, 8523 // and clearly the user wants a template specialization. So 8524 // we need to insert '<>' after the name. 8525 SourceLocation InsertLoc; 8526 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8527 InsertLoc = D.getName().getSourceRange().getEnd(); 8528 InsertLoc = getLocForEndOfToken(InsertLoc); 8529 } 8530 8531 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8532 << Name << RemoveRange 8533 << FixItHint::CreateRemoval(RemoveRange) 8534 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8535 } 8536 } 8537 } else { 8538 // All template param lists were matched against the scope specifier: 8539 // this is NOT (an explicit specialization of) a template. 8540 if (TemplateParamLists.size() > 0) 8541 // For source fidelity, store all the template param lists. 8542 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8543 } 8544 8545 if (Invalid) { 8546 NewFD->setInvalidDecl(); 8547 if (FunctionTemplate) 8548 FunctionTemplate->setInvalidDecl(); 8549 } 8550 8551 // C++ [dcl.fct.spec]p5: 8552 // The virtual specifier shall only be used in declarations of 8553 // nonstatic class member functions that appear within a 8554 // member-specification of a class declaration; see 10.3. 8555 // 8556 if (isVirtual && !NewFD->isInvalidDecl()) { 8557 if (!isVirtualOkay) { 8558 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8559 diag::err_virtual_non_function); 8560 } else if (!CurContext->isRecord()) { 8561 // 'virtual' was specified outside of the class. 8562 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8563 diag::err_virtual_out_of_class) 8564 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8565 } else if (NewFD->getDescribedFunctionTemplate()) { 8566 // C++ [temp.mem]p3: 8567 // A member function template shall not be virtual. 8568 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8569 diag::err_virtual_member_function_template) 8570 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8571 } else { 8572 // Okay: Add virtual to the method. 8573 NewFD->setVirtualAsWritten(true); 8574 } 8575 8576 if (getLangOpts().CPlusPlus14 && 8577 NewFD->getReturnType()->isUndeducedType()) 8578 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8579 } 8580 8581 if (getLangOpts().CPlusPlus14 && 8582 (NewFD->isDependentContext() || 8583 (isFriend && CurContext->isDependentContext())) && 8584 NewFD->getReturnType()->isUndeducedType()) { 8585 // If the function template is referenced directly (for instance, as a 8586 // member of the current instantiation), pretend it has a dependent type. 8587 // This is not really justified by the standard, but is the only sane 8588 // thing to do. 8589 // FIXME: For a friend function, we have not marked the function as being 8590 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8591 const FunctionProtoType *FPT = 8592 NewFD->getType()->castAs<FunctionProtoType>(); 8593 QualType Result = 8594 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8595 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8596 FPT->getExtProtoInfo())); 8597 } 8598 8599 // C++ [dcl.fct.spec]p3: 8600 // The inline specifier shall not appear on a block scope function 8601 // declaration. 8602 if (isInline && !NewFD->isInvalidDecl()) { 8603 if (CurContext->isFunctionOrMethod()) { 8604 // 'inline' is not allowed on block scope function declaration. 8605 Diag(D.getDeclSpec().getInlineSpecLoc(), 8606 diag::err_inline_declaration_block_scope) << Name 8607 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8608 } 8609 } 8610 8611 // C++ [dcl.fct.spec]p6: 8612 // The explicit specifier shall be used only in the declaration of a 8613 // constructor or conversion function within its class definition; 8614 // see 12.3.1 and 12.3.2. 8615 if (hasExplicit && !NewFD->isInvalidDecl() && 8616 !isa<CXXDeductionGuideDecl>(NewFD)) { 8617 if (!CurContext->isRecord()) { 8618 // 'explicit' was specified outside of the class. 8619 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8620 diag::err_explicit_out_of_class) 8621 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 8622 } else if (!isa<CXXConstructorDecl>(NewFD) && 8623 !isa<CXXConversionDecl>(NewFD)) { 8624 // 'explicit' was specified on a function that wasn't a constructor 8625 // or conversion function. 8626 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8627 diag::err_explicit_non_ctor_or_conv_function) 8628 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 8629 } 8630 } 8631 8632 if (ConstexprKind != CSK_unspecified) { 8633 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8634 // are implicitly inline. 8635 NewFD->setImplicitlyInline(); 8636 8637 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8638 // be either constructors or to return a literal type. Therefore, 8639 // destructors cannot be declared constexpr. 8640 if (isa<CXXDestructorDecl>(NewFD)) 8641 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 8642 << (ConstexprKind == CSK_consteval); 8643 } 8644 8645 // If __module_private__ was specified, mark the function accordingly. 8646 if (D.getDeclSpec().isModulePrivateSpecified()) { 8647 if (isFunctionTemplateSpecialization) { 8648 SourceLocation ModulePrivateLoc 8649 = D.getDeclSpec().getModulePrivateSpecLoc(); 8650 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8651 << 0 8652 << FixItHint::CreateRemoval(ModulePrivateLoc); 8653 } else { 8654 NewFD->setModulePrivate(); 8655 if (FunctionTemplate) 8656 FunctionTemplate->setModulePrivate(); 8657 } 8658 } 8659 8660 if (isFriend) { 8661 if (FunctionTemplate) { 8662 FunctionTemplate->setObjectOfFriendDecl(); 8663 FunctionTemplate->setAccess(AS_public); 8664 } 8665 NewFD->setObjectOfFriendDecl(); 8666 NewFD->setAccess(AS_public); 8667 } 8668 8669 // If a function is defined as defaulted or deleted, mark it as such now. 8670 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8671 // definition kind to FDK_Definition. 8672 switch (D.getFunctionDefinitionKind()) { 8673 case FDK_Declaration: 8674 case FDK_Definition: 8675 break; 8676 8677 case FDK_Defaulted: 8678 NewFD->setDefaulted(); 8679 break; 8680 8681 case FDK_Deleted: 8682 NewFD->setDeletedAsWritten(); 8683 break; 8684 } 8685 8686 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8687 D.isFunctionDefinition()) { 8688 // C++ [class.mfct]p2: 8689 // A member function may be defined (8.4) in its class definition, in 8690 // which case it is an inline member function (7.1.2) 8691 NewFD->setImplicitlyInline(); 8692 } 8693 8694 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8695 !CurContext->isRecord()) { 8696 // C++ [class.static]p1: 8697 // A data or function member of a class may be declared static 8698 // in a class definition, in which case it is a static member of 8699 // the class. 8700 8701 // Complain about the 'static' specifier if it's on an out-of-line 8702 // member function definition. 8703 8704 // MSVC permits the use of a 'static' storage specifier on an out-of-line 8705 // member function template declaration and class member template 8706 // declaration (MSVC versions before 2015), warn about this. 8707 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8708 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 8709 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 8710 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 8711 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 8712 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8713 } 8714 8715 // C++11 [except.spec]p15: 8716 // A deallocation function with no exception-specification is treated 8717 // as if it were specified with noexcept(true). 8718 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8719 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8720 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8721 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8722 NewFD->setType(Context.getFunctionType( 8723 FPT->getReturnType(), FPT->getParamTypes(), 8724 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8725 } 8726 8727 // Filter out previous declarations that don't match the scope. 8728 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8729 D.getCXXScopeSpec().isNotEmpty() || 8730 isMemberSpecialization || 8731 isFunctionTemplateSpecialization); 8732 8733 // Handle GNU asm-label extension (encoded as an attribute). 8734 if (Expr *E = (Expr*) D.getAsmLabel()) { 8735 // The parser guarantees this is a string. 8736 StringLiteral *SE = cast<StringLiteral>(E); 8737 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8738 SE->getString(), 0)); 8739 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8740 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8741 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8742 if (I != ExtnameUndeclaredIdentifiers.end()) { 8743 if (isDeclExternC(NewFD)) { 8744 NewFD->addAttr(I->second); 8745 ExtnameUndeclaredIdentifiers.erase(I); 8746 } else 8747 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8748 << /*Variable*/0 << NewFD; 8749 } 8750 } 8751 8752 // Copy the parameter declarations from the declarator D to the function 8753 // declaration NewFD, if they are available. First scavenge them into Params. 8754 SmallVector<ParmVarDecl*, 16> Params; 8755 unsigned FTIIdx; 8756 if (D.isFunctionDeclarator(FTIIdx)) { 8757 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8758 8759 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8760 // function that takes no arguments, not a function that takes a 8761 // single void argument. 8762 // We let through "const void" here because Sema::GetTypeForDeclarator 8763 // already checks for that case. 8764 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8765 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8766 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8767 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8768 Param->setDeclContext(NewFD); 8769 Params.push_back(Param); 8770 8771 if (Param->isInvalidDecl()) 8772 NewFD->setInvalidDecl(); 8773 } 8774 } 8775 8776 if (!getLangOpts().CPlusPlus) { 8777 // In C, find all the tag declarations from the prototype and move them 8778 // into the function DeclContext. Remove them from the surrounding tag 8779 // injection context of the function, which is typically but not always 8780 // the TU. 8781 DeclContext *PrototypeTagContext = 8782 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8783 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8784 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8785 8786 // We don't want to reparent enumerators. Look at their parent enum 8787 // instead. 8788 if (!TD) { 8789 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8790 TD = cast<EnumDecl>(ECD->getDeclContext()); 8791 } 8792 if (!TD) 8793 continue; 8794 DeclContext *TagDC = TD->getLexicalDeclContext(); 8795 if (!TagDC->containsDecl(TD)) 8796 continue; 8797 TagDC->removeDecl(TD); 8798 TD->setDeclContext(NewFD); 8799 NewFD->addDecl(TD); 8800 8801 // Preserve the lexical DeclContext if it is not the surrounding tag 8802 // injection context of the FD. In this example, the semantic context of 8803 // E will be f and the lexical context will be S, while both the 8804 // semantic and lexical contexts of S will be f: 8805 // void f(struct S { enum E { a } f; } s); 8806 if (TagDC != PrototypeTagContext) 8807 TD->setLexicalDeclContext(TagDC); 8808 } 8809 } 8810 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8811 // When we're declaring a function with a typedef, typeof, etc as in the 8812 // following example, we'll need to synthesize (unnamed) 8813 // parameters for use in the declaration. 8814 // 8815 // @code 8816 // typedef void fn(int); 8817 // fn f; 8818 // @endcode 8819 8820 // Synthesize a parameter for each argument type. 8821 for (const auto &AI : FT->param_types()) { 8822 ParmVarDecl *Param = 8823 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8824 Param->setScopeInfo(0, Params.size()); 8825 Params.push_back(Param); 8826 } 8827 } else { 8828 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8829 "Should not need args for typedef of non-prototype fn"); 8830 } 8831 8832 // Finally, we know we have the right number of parameters, install them. 8833 NewFD->setParams(Params); 8834 8835 if (D.getDeclSpec().isNoreturnSpecified()) 8836 NewFD->addAttr( 8837 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8838 Context, 0)); 8839 8840 // Functions returning a variably modified type violate C99 6.7.5.2p2 8841 // because all functions have linkage. 8842 if (!NewFD->isInvalidDecl() && 8843 NewFD->getReturnType()->isVariablyModifiedType()) { 8844 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8845 NewFD->setInvalidDecl(); 8846 } 8847 8848 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8849 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8850 !NewFD->hasAttr<SectionAttr>()) { 8851 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8852 PragmaClangTextSection.SectionName, 8853 PragmaClangTextSection.PragmaLocation)); 8854 } 8855 8856 // Apply an implicit SectionAttr if #pragma code_seg is active. 8857 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8858 !NewFD->hasAttr<SectionAttr>()) { 8859 NewFD->addAttr( 8860 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8861 CodeSegStack.CurrentValue->getString(), 8862 CodeSegStack.CurrentPragmaLocation)); 8863 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8864 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8865 ASTContext::PSF_Read, 8866 NewFD)) 8867 NewFD->dropAttr<SectionAttr>(); 8868 } 8869 8870 // Apply an implicit CodeSegAttr from class declspec or 8871 // apply an implicit SectionAttr from #pragma code_seg if active. 8872 if (!NewFD->hasAttr<CodeSegAttr>()) { 8873 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 8874 D.isFunctionDefinition())) { 8875 NewFD->addAttr(SAttr); 8876 } 8877 } 8878 8879 // Handle attributes. 8880 ProcessDeclAttributes(S, NewFD, D); 8881 8882 if (getLangOpts().OpenCL) { 8883 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8884 // type declaration will generate a compilation error. 8885 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8886 if (AddressSpace != LangAS::Default) { 8887 Diag(NewFD->getLocation(), 8888 diag::err_opencl_return_value_with_address_space); 8889 NewFD->setInvalidDecl(); 8890 } 8891 } 8892 8893 if (!getLangOpts().CPlusPlus) { 8894 // Perform semantic checking on the function declaration. 8895 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8896 CheckMain(NewFD, D.getDeclSpec()); 8897 8898 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8899 CheckMSVCRTEntryPoint(NewFD); 8900 8901 if (!NewFD->isInvalidDecl()) 8902 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8903 isMemberSpecialization)); 8904 else if (!Previous.empty()) 8905 // Recover gracefully from an invalid redeclaration. 8906 D.setRedeclaration(true); 8907 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8908 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8909 "previous declaration set still overloaded"); 8910 8911 // Diagnose no-prototype function declarations with calling conventions that 8912 // don't support variadic calls. Only do this in C and do it after merging 8913 // possibly prototyped redeclarations. 8914 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8915 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8916 CallingConv CC = FT->getExtInfo().getCC(); 8917 if (!supportsVariadicCall(CC)) { 8918 // Windows system headers sometimes accidentally use stdcall without 8919 // (void) parameters, so we relax this to a warning. 8920 int DiagID = 8921 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8922 Diag(NewFD->getLocation(), DiagID) 8923 << FunctionType::getNameForCallConv(CC); 8924 } 8925 } 8926 } else { 8927 // C++11 [replacement.functions]p3: 8928 // The program's definitions shall not be specified as inline. 8929 // 8930 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8931 // 8932 // Suppress the diagnostic if the function is __attribute__((used)), since 8933 // that forces an external definition to be emitted. 8934 if (D.getDeclSpec().isInlineSpecified() && 8935 NewFD->isReplaceableGlobalAllocationFunction() && 8936 !NewFD->hasAttr<UsedAttr>()) 8937 Diag(D.getDeclSpec().getInlineSpecLoc(), 8938 diag::ext_operator_new_delete_declared_inline) 8939 << NewFD->getDeclName(); 8940 8941 // If the declarator is a template-id, translate the parser's template 8942 // argument list into our AST format. 8943 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8944 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8945 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8946 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8947 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8948 TemplateId->NumArgs); 8949 translateTemplateArguments(TemplateArgsPtr, 8950 TemplateArgs); 8951 8952 HasExplicitTemplateArgs = true; 8953 8954 if (NewFD->isInvalidDecl()) { 8955 HasExplicitTemplateArgs = false; 8956 } else if (FunctionTemplate) { 8957 // Function template with explicit template arguments. 8958 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8959 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8960 8961 HasExplicitTemplateArgs = false; 8962 } else { 8963 assert((isFunctionTemplateSpecialization || 8964 D.getDeclSpec().isFriendSpecified()) && 8965 "should have a 'template<>' for this decl"); 8966 // "friend void foo<>(int);" is an implicit specialization decl. 8967 isFunctionTemplateSpecialization = true; 8968 } 8969 } else if (isFriend && isFunctionTemplateSpecialization) { 8970 // This combination is only possible in a recovery case; the user 8971 // wrote something like: 8972 // template <> friend void foo(int); 8973 // which we're recovering from as if the user had written: 8974 // friend void foo<>(int); 8975 // Go ahead and fake up a template id. 8976 HasExplicitTemplateArgs = true; 8977 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8978 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8979 } 8980 8981 // We do not add HD attributes to specializations here because 8982 // they may have different constexpr-ness compared to their 8983 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8984 // may end up with different effective targets. Instead, a 8985 // specialization inherits its target attributes from its template 8986 // in the CheckFunctionTemplateSpecialization() call below. 8987 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8988 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8989 8990 // If it's a friend (and only if it's a friend), it's possible 8991 // that either the specialized function type or the specialized 8992 // template is dependent, and therefore matching will fail. In 8993 // this case, don't check the specialization yet. 8994 bool InstantiationDependent = false; 8995 if (isFunctionTemplateSpecialization && isFriend && 8996 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8997 TemplateSpecializationType::anyDependentTemplateArguments( 8998 TemplateArgs, 8999 InstantiationDependent))) { 9000 assert(HasExplicitTemplateArgs && 9001 "friend function specialization without template args"); 9002 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9003 Previous)) 9004 NewFD->setInvalidDecl(); 9005 } else if (isFunctionTemplateSpecialization) { 9006 if (CurContext->isDependentContext() && CurContext->isRecord() 9007 && !isFriend) { 9008 isDependentClassScopeExplicitSpecialization = true; 9009 } else if (!NewFD->isInvalidDecl() && 9010 CheckFunctionTemplateSpecialization( 9011 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9012 Previous)) 9013 NewFD->setInvalidDecl(); 9014 9015 // C++ [dcl.stc]p1: 9016 // A storage-class-specifier shall not be specified in an explicit 9017 // specialization (14.7.3) 9018 FunctionTemplateSpecializationInfo *Info = 9019 NewFD->getTemplateSpecializationInfo(); 9020 if (Info && SC != SC_None) { 9021 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9022 Diag(NewFD->getLocation(), 9023 diag::err_explicit_specialization_inconsistent_storage_class) 9024 << SC 9025 << FixItHint::CreateRemoval( 9026 D.getDeclSpec().getStorageClassSpecLoc()); 9027 9028 else 9029 Diag(NewFD->getLocation(), 9030 diag::ext_explicit_specialization_storage_class) 9031 << FixItHint::CreateRemoval( 9032 D.getDeclSpec().getStorageClassSpecLoc()); 9033 } 9034 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9035 if (CheckMemberSpecialization(NewFD, Previous)) 9036 NewFD->setInvalidDecl(); 9037 } 9038 9039 // Perform semantic checking on the function declaration. 9040 if (!isDependentClassScopeExplicitSpecialization) { 9041 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9042 CheckMain(NewFD, D.getDeclSpec()); 9043 9044 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9045 CheckMSVCRTEntryPoint(NewFD); 9046 9047 if (!NewFD->isInvalidDecl()) 9048 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9049 isMemberSpecialization)); 9050 else if (!Previous.empty()) 9051 // Recover gracefully from an invalid redeclaration. 9052 D.setRedeclaration(true); 9053 } 9054 9055 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9056 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9057 "previous declaration set still overloaded"); 9058 9059 NamedDecl *PrincipalDecl = (FunctionTemplate 9060 ? cast<NamedDecl>(FunctionTemplate) 9061 : NewFD); 9062 9063 if (isFriend && NewFD->getPreviousDecl()) { 9064 AccessSpecifier Access = AS_public; 9065 if (!NewFD->isInvalidDecl()) 9066 Access = NewFD->getPreviousDecl()->getAccess(); 9067 9068 NewFD->setAccess(Access); 9069 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9070 } 9071 9072 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9073 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9074 PrincipalDecl->setNonMemberOperator(); 9075 9076 // If we have a function template, check the template parameter 9077 // list. This will check and merge default template arguments. 9078 if (FunctionTemplate) { 9079 FunctionTemplateDecl *PrevTemplate = 9080 FunctionTemplate->getPreviousDecl(); 9081 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9082 PrevTemplate ? PrevTemplate->getTemplateParameters() 9083 : nullptr, 9084 D.getDeclSpec().isFriendSpecified() 9085 ? (D.isFunctionDefinition() 9086 ? TPC_FriendFunctionTemplateDefinition 9087 : TPC_FriendFunctionTemplate) 9088 : (D.getCXXScopeSpec().isSet() && 9089 DC && DC->isRecord() && 9090 DC->isDependentContext()) 9091 ? TPC_ClassTemplateMember 9092 : TPC_FunctionTemplate); 9093 } 9094 9095 if (NewFD->isInvalidDecl()) { 9096 // Ignore all the rest of this. 9097 } else if (!D.isRedeclaration()) { 9098 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9099 AddToScope }; 9100 // Fake up an access specifier if it's supposed to be a class member. 9101 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9102 NewFD->setAccess(AS_public); 9103 9104 // Qualified decls generally require a previous declaration. 9105 if (D.getCXXScopeSpec().isSet()) { 9106 // ...with the major exception of templated-scope or 9107 // dependent-scope friend declarations. 9108 9109 // TODO: we currently also suppress this check in dependent 9110 // contexts because (1) the parameter depth will be off when 9111 // matching friend templates and (2) we might actually be 9112 // selecting a friend based on a dependent factor. But there 9113 // are situations where these conditions don't apply and we 9114 // can actually do this check immediately. 9115 // 9116 // Unless the scope is dependent, it's always an error if qualified 9117 // redeclaration lookup found nothing at all. Diagnose that now; 9118 // nothing will diagnose that error later. 9119 if (isFriend && 9120 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9121 (!Previous.empty() && CurContext->isDependentContext()))) { 9122 // ignore these 9123 } else { 9124 // The user tried to provide an out-of-line definition for a 9125 // function that is a member of a class or namespace, but there 9126 // was no such member function declared (C++ [class.mfct]p2, 9127 // C++ [namespace.memdef]p2). For example: 9128 // 9129 // class X { 9130 // void f() const; 9131 // }; 9132 // 9133 // void X::f() { } // ill-formed 9134 // 9135 // Complain about this problem, and attempt to suggest close 9136 // matches (e.g., those that differ only in cv-qualifiers and 9137 // whether the parameter types are references). 9138 9139 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9140 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9141 AddToScope = ExtraArgs.AddToScope; 9142 return Result; 9143 } 9144 } 9145 9146 // Unqualified local friend declarations are required to resolve 9147 // to something. 9148 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9149 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9150 *this, Previous, NewFD, ExtraArgs, true, S)) { 9151 AddToScope = ExtraArgs.AddToScope; 9152 return Result; 9153 } 9154 } 9155 } else if (!D.isFunctionDefinition() && 9156 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9157 !isFriend && !isFunctionTemplateSpecialization && 9158 !isMemberSpecialization) { 9159 // An out-of-line member function declaration must also be a 9160 // definition (C++ [class.mfct]p2). 9161 // Note that this is not the case for explicit specializations of 9162 // function templates or member functions of class templates, per 9163 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9164 // extension for compatibility with old SWIG code which likes to 9165 // generate them. 9166 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9167 << D.getCXXScopeSpec().getRange(); 9168 } 9169 } 9170 9171 ProcessPragmaWeak(S, NewFD); 9172 checkAttributesAfterMerging(*this, *NewFD); 9173 9174 AddKnownFunctionAttributes(NewFD); 9175 9176 if (NewFD->hasAttr<OverloadableAttr>() && 9177 !NewFD->getType()->getAs<FunctionProtoType>()) { 9178 Diag(NewFD->getLocation(), 9179 diag::err_attribute_overloadable_no_prototype) 9180 << NewFD; 9181 9182 // Turn this into a variadic function with no parameters. 9183 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9184 FunctionProtoType::ExtProtoInfo EPI( 9185 Context.getDefaultCallingConvention(true, false)); 9186 EPI.Variadic = true; 9187 EPI.ExtInfo = FT->getExtInfo(); 9188 9189 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9190 NewFD->setType(R); 9191 } 9192 9193 // If there's a #pragma GCC visibility in scope, and this isn't a class 9194 // member, set the visibility of this function. 9195 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9196 AddPushedVisibilityAttribute(NewFD); 9197 9198 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9199 // marking the function. 9200 AddCFAuditedAttribute(NewFD); 9201 9202 // If this is a function definition, check if we have to apply optnone due to 9203 // a pragma. 9204 if(D.isFunctionDefinition()) 9205 AddRangeBasedOptnone(NewFD); 9206 9207 // If this is the first declaration of an extern C variable, update 9208 // the map of such variables. 9209 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9210 isIncompleteDeclExternC(*this, NewFD)) 9211 RegisterLocallyScopedExternCDecl(NewFD, S); 9212 9213 // Set this FunctionDecl's range up to the right paren. 9214 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9215 9216 if (D.isRedeclaration() && !Previous.empty()) { 9217 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9218 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9219 isMemberSpecialization || 9220 isFunctionTemplateSpecialization, 9221 D.isFunctionDefinition()); 9222 } 9223 9224 if (getLangOpts().CUDA) { 9225 IdentifierInfo *II = NewFD->getIdentifier(); 9226 if (II && II->isStr(getCudaConfigureFuncName()) && 9227 !NewFD->isInvalidDecl() && 9228 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9229 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9230 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9231 << getCudaConfigureFuncName(); 9232 Context.setcudaConfigureCallDecl(NewFD); 9233 } 9234 9235 // Variadic functions, other than a *declaration* of printf, are not allowed 9236 // in device-side CUDA code, unless someone passed 9237 // -fcuda-allow-variadic-functions. 9238 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9239 (NewFD->hasAttr<CUDADeviceAttr>() || 9240 NewFD->hasAttr<CUDAGlobalAttr>()) && 9241 !(II && II->isStr("printf") && NewFD->isExternC() && 9242 !D.isFunctionDefinition())) { 9243 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9244 } 9245 } 9246 9247 MarkUnusedFileScopedDecl(NewFD); 9248 9249 9250 9251 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9252 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9253 if ((getLangOpts().OpenCLVersion >= 120) 9254 && (SC == SC_Static)) { 9255 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9256 D.setInvalidType(); 9257 } 9258 9259 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9260 if (!NewFD->getReturnType()->isVoidType()) { 9261 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9262 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9263 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9264 : FixItHint()); 9265 D.setInvalidType(); 9266 } 9267 9268 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9269 for (auto Param : NewFD->parameters()) 9270 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9271 9272 if (getLangOpts().OpenCLCPlusPlus) { 9273 if (DC->isRecord()) { 9274 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9275 D.setInvalidType(); 9276 } 9277 if (FunctionTemplate) { 9278 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9279 D.setInvalidType(); 9280 } 9281 } 9282 } 9283 9284 if (getLangOpts().CPlusPlus) { 9285 if (FunctionTemplate) { 9286 if (NewFD->isInvalidDecl()) 9287 FunctionTemplate->setInvalidDecl(); 9288 return FunctionTemplate; 9289 } 9290 9291 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9292 CompleteMemberSpecialization(NewFD, Previous); 9293 } 9294 9295 for (const ParmVarDecl *Param : NewFD->parameters()) { 9296 QualType PT = Param->getType(); 9297 9298 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9299 // types. 9300 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9301 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9302 QualType ElemTy = PipeTy->getElementType(); 9303 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9304 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9305 D.setInvalidType(); 9306 } 9307 } 9308 } 9309 } 9310 9311 // Here we have an function template explicit specialization at class scope. 9312 // The actual specialization will be postponed to template instatiation 9313 // time via the ClassScopeFunctionSpecializationDecl node. 9314 if (isDependentClassScopeExplicitSpecialization) { 9315 ClassScopeFunctionSpecializationDecl *NewSpec = 9316 ClassScopeFunctionSpecializationDecl::Create( 9317 Context, CurContext, NewFD->getLocation(), 9318 cast<CXXMethodDecl>(NewFD), 9319 HasExplicitTemplateArgs, TemplateArgs); 9320 CurContext->addDecl(NewSpec); 9321 AddToScope = false; 9322 } 9323 9324 // Diagnose availability attributes. Availability cannot be used on functions 9325 // that are run during load/unload. 9326 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9327 if (NewFD->hasAttr<ConstructorAttr>()) { 9328 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9329 << 1; 9330 NewFD->dropAttr<AvailabilityAttr>(); 9331 } 9332 if (NewFD->hasAttr<DestructorAttr>()) { 9333 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9334 << 2; 9335 NewFD->dropAttr<AvailabilityAttr>(); 9336 } 9337 } 9338 9339 return NewFD; 9340 } 9341 9342 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9343 /// when __declspec(code_seg) "is applied to a class, all member functions of 9344 /// the class and nested classes -- this includes compiler-generated special 9345 /// member functions -- are put in the specified segment." 9346 /// The actual behavior is a little more complicated. The Microsoft compiler 9347 /// won't check outer classes if there is an active value from #pragma code_seg. 9348 /// The CodeSeg is always applied from the direct parent but only from outer 9349 /// classes when the #pragma code_seg stack is empty. See: 9350 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9351 /// available since MS has removed the page. 9352 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9353 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9354 if (!Method) 9355 return nullptr; 9356 const CXXRecordDecl *Parent = Method->getParent(); 9357 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9358 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9359 NewAttr->setImplicit(true); 9360 return NewAttr; 9361 } 9362 9363 // The Microsoft compiler won't check outer classes for the CodeSeg 9364 // when the #pragma code_seg stack is active. 9365 if (S.CodeSegStack.CurrentValue) 9366 return nullptr; 9367 9368 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9369 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9370 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9371 NewAttr->setImplicit(true); 9372 return NewAttr; 9373 } 9374 } 9375 return nullptr; 9376 } 9377 9378 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9379 /// containing class. Otherwise it will return implicit SectionAttr if the 9380 /// function is a definition and there is an active value on CodeSegStack 9381 /// (from the current #pragma code-seg value). 9382 /// 9383 /// \param FD Function being declared. 9384 /// \param IsDefinition Whether it is a definition or just a declarartion. 9385 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9386 /// nullptr if no attribute should be added. 9387 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9388 bool IsDefinition) { 9389 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9390 return A; 9391 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9392 CodeSegStack.CurrentValue) { 9393 return SectionAttr::CreateImplicit(getASTContext(), 9394 SectionAttr::Declspec_allocate, 9395 CodeSegStack.CurrentValue->getString(), 9396 CodeSegStack.CurrentPragmaLocation); 9397 } 9398 return nullptr; 9399 } 9400 9401 /// Determines if we can perform a correct type check for \p D as a 9402 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9403 /// best-effort check. 9404 /// 9405 /// \param NewD The new declaration. 9406 /// \param OldD The old declaration. 9407 /// \param NewT The portion of the type of the new declaration to check. 9408 /// \param OldT The portion of the type of the old declaration to check. 9409 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9410 QualType NewT, QualType OldT) { 9411 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9412 return true; 9413 9414 // For dependently-typed local extern declarations and friends, we can't 9415 // perform a correct type check in general until instantiation: 9416 // 9417 // int f(); 9418 // template<typename T> void g() { T f(); } 9419 // 9420 // (valid if g() is only instantiated with T = int). 9421 if (NewT->isDependentType() && 9422 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9423 return false; 9424 9425 // Similarly, if the previous declaration was a dependent local extern 9426 // declaration, we don't really know its type yet. 9427 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9428 return false; 9429 9430 return true; 9431 } 9432 9433 /// Checks if the new declaration declared in dependent context must be 9434 /// put in the same redeclaration chain as the specified declaration. 9435 /// 9436 /// \param D Declaration that is checked. 9437 /// \param PrevDecl Previous declaration found with proper lookup method for the 9438 /// same declaration name. 9439 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9440 /// belongs to. 9441 /// 9442 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9443 if (!D->getLexicalDeclContext()->isDependentContext()) 9444 return true; 9445 9446 // Don't chain dependent friend function definitions until instantiation, to 9447 // permit cases like 9448 // 9449 // void func(); 9450 // template<typename T> class C1 { friend void func() {} }; 9451 // template<typename T> class C2 { friend void func() {} }; 9452 // 9453 // ... which is valid if only one of C1 and C2 is ever instantiated. 9454 // 9455 // FIXME: This need only apply to function definitions. For now, we proxy 9456 // this by checking for a file-scope function. We do not want this to apply 9457 // to friend declarations nominating member functions, because that gets in 9458 // the way of access checks. 9459 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9460 return false; 9461 9462 auto *VD = dyn_cast<ValueDecl>(D); 9463 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9464 return !VD || !PrevVD || 9465 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9466 PrevVD->getType()); 9467 } 9468 9469 /// Check the target attribute of the function for MultiVersion 9470 /// validity. 9471 /// 9472 /// Returns true if there was an error, false otherwise. 9473 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9474 const auto *TA = FD->getAttr<TargetAttr>(); 9475 assert(TA && "MultiVersion Candidate requires a target attribute"); 9476 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9477 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9478 enum ErrType { Feature = 0, Architecture = 1 }; 9479 9480 if (!ParseInfo.Architecture.empty() && 9481 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9482 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9483 << Architecture << ParseInfo.Architecture; 9484 return true; 9485 } 9486 9487 for (const auto &Feat : ParseInfo.Features) { 9488 auto BareFeat = StringRef{Feat}.substr(1); 9489 if (Feat[0] == '-') { 9490 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9491 << Feature << ("no-" + BareFeat).str(); 9492 return true; 9493 } 9494 9495 if (!TargetInfo.validateCpuSupports(BareFeat) || 9496 !TargetInfo.isValidFeatureName(BareFeat)) { 9497 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9498 << Feature << BareFeat; 9499 return true; 9500 } 9501 } 9502 return false; 9503 } 9504 9505 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9506 MultiVersionKind MVType) { 9507 for (const Attr *A : FD->attrs()) { 9508 switch (A->getKind()) { 9509 case attr::CPUDispatch: 9510 case attr::CPUSpecific: 9511 if (MVType != MultiVersionKind::CPUDispatch && 9512 MVType != MultiVersionKind::CPUSpecific) 9513 return true; 9514 break; 9515 case attr::Target: 9516 if (MVType != MultiVersionKind::Target) 9517 return true; 9518 break; 9519 default: 9520 return true; 9521 } 9522 } 9523 return false; 9524 } 9525 9526 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9527 const FunctionDecl *NewFD, 9528 bool CausesMV, 9529 MultiVersionKind MVType) { 9530 enum DoesntSupport { 9531 FuncTemplates = 0, 9532 VirtFuncs = 1, 9533 DeducedReturn = 2, 9534 Constructors = 3, 9535 Destructors = 4, 9536 DeletedFuncs = 5, 9537 DefaultedFuncs = 6, 9538 ConstexprFuncs = 7, 9539 ConstevalFuncs = 8, 9540 }; 9541 enum Different { 9542 CallingConv = 0, 9543 ReturnType = 1, 9544 ConstexprSpec = 2, 9545 InlineSpec = 3, 9546 StorageClass = 4, 9547 Linkage = 5 9548 }; 9549 9550 bool IsCPUSpecificCPUDispatchMVType = 9551 MVType == MultiVersionKind::CPUDispatch || 9552 MVType == MultiVersionKind::CPUSpecific; 9553 9554 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { 9555 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9556 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9557 return true; 9558 } 9559 9560 if (!NewFD->getType()->getAs<FunctionProtoType>()) 9561 return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9562 9563 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9564 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9565 if (OldFD) 9566 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9567 return true; 9568 } 9569 9570 // For now, disallow all other attributes. These should be opt-in, but 9571 // an analysis of all of them is a future FIXME. 9572 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 9573 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 9574 << IsCPUSpecificCPUDispatchMVType; 9575 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9576 return true; 9577 } 9578 9579 if (HasNonMultiVersionAttributes(NewFD, MVType)) 9580 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 9581 << IsCPUSpecificCPUDispatchMVType; 9582 9583 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9584 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9585 << IsCPUSpecificCPUDispatchMVType << FuncTemplates; 9586 9587 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9588 if (NewCXXFD->isVirtual()) 9589 return S.Diag(NewCXXFD->getLocation(), 9590 diag::err_multiversion_doesnt_support) 9591 << IsCPUSpecificCPUDispatchMVType << VirtFuncs; 9592 9593 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9594 return S.Diag(NewCXXCtor->getLocation(), 9595 diag::err_multiversion_doesnt_support) 9596 << IsCPUSpecificCPUDispatchMVType << Constructors; 9597 9598 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9599 return S.Diag(NewCXXDtor->getLocation(), 9600 diag::err_multiversion_doesnt_support) 9601 << IsCPUSpecificCPUDispatchMVType << Destructors; 9602 } 9603 9604 if (NewFD->isDeleted()) 9605 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9606 << IsCPUSpecificCPUDispatchMVType << DeletedFuncs; 9607 9608 if (NewFD->isDefaulted()) 9609 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9610 << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs; 9611 9612 if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch || 9613 MVType == MultiVersionKind::CPUSpecific)) 9614 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9615 << IsCPUSpecificCPUDispatchMVType 9616 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 9617 9618 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9619 const auto *NewType = cast<FunctionType>(NewQType); 9620 QualType NewReturnType = NewType->getReturnType(); 9621 9622 if (NewReturnType->isUndeducedType()) 9623 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9624 << IsCPUSpecificCPUDispatchMVType << DeducedReturn; 9625 9626 // Only allow transition to MultiVersion if it hasn't been used. 9627 if (OldFD && CausesMV && OldFD->isUsed(false)) 9628 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9629 9630 // Ensure the return type is identical. 9631 if (OldFD) { 9632 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9633 const auto *OldType = cast<FunctionType>(OldQType); 9634 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9635 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9636 9637 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9638 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9639 << CallingConv; 9640 9641 QualType OldReturnType = OldType->getReturnType(); 9642 9643 if (OldReturnType != NewReturnType) 9644 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9645 << ReturnType; 9646 9647 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 9648 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9649 << ConstexprSpec; 9650 9651 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9652 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9653 << InlineSpec; 9654 9655 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9656 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9657 << StorageClass; 9658 9659 if (OldFD->isExternC() != NewFD->isExternC()) 9660 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9661 << Linkage; 9662 9663 if (S.CheckEquivalentExceptionSpec( 9664 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9665 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9666 return true; 9667 } 9668 return false; 9669 } 9670 9671 /// Check the validity of a multiversion function declaration that is the 9672 /// first of its kind. Also sets the multiversion'ness' of the function itself. 9673 /// 9674 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9675 /// 9676 /// Returns true if there was an error, false otherwise. 9677 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 9678 MultiVersionKind MVType, 9679 const TargetAttr *TA) { 9680 assert(MVType != MultiVersionKind::None && 9681 "Function lacks multiversion attribute"); 9682 9683 // Target only causes MV if it is default, otherwise this is a normal 9684 // function. 9685 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 9686 return false; 9687 9688 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 9689 FD->setInvalidDecl(); 9690 return true; 9691 } 9692 9693 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 9694 FD->setInvalidDecl(); 9695 return true; 9696 } 9697 9698 FD->setIsMultiVersion(); 9699 return false; 9700 } 9701 9702 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 9703 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 9704 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 9705 return true; 9706 } 9707 9708 return false; 9709 } 9710 9711 static bool CheckTargetCausesMultiVersioning( 9712 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 9713 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9714 LookupResult &Previous) { 9715 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9716 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9717 // Sort order doesn't matter, it just needs to be consistent. 9718 llvm::sort(NewParsed.Features); 9719 9720 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9721 // to change, this is a simple redeclaration. 9722 if (!NewTA->isDefaultVersion() && 9723 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 9724 return false; 9725 9726 // Otherwise, this decl causes MultiVersioning. 9727 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9728 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9729 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9730 NewFD->setInvalidDecl(); 9731 return true; 9732 } 9733 9734 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 9735 MultiVersionKind::Target)) { 9736 NewFD->setInvalidDecl(); 9737 return true; 9738 } 9739 9740 if (CheckMultiVersionValue(S, NewFD)) { 9741 NewFD->setInvalidDecl(); 9742 return true; 9743 } 9744 9745 // If this is 'default', permit the forward declaration. 9746 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 9747 Redeclaration = true; 9748 OldDecl = OldFD; 9749 OldFD->setIsMultiVersion(); 9750 NewFD->setIsMultiVersion(); 9751 return false; 9752 } 9753 9754 if (CheckMultiVersionValue(S, OldFD)) { 9755 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9756 NewFD->setInvalidDecl(); 9757 return true; 9758 } 9759 9760 TargetAttr::ParsedTargetAttr OldParsed = 9761 OldTA->parse(std::less<std::string>()); 9762 9763 if (OldParsed == NewParsed) { 9764 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9765 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9766 NewFD->setInvalidDecl(); 9767 return true; 9768 } 9769 9770 for (const auto *FD : OldFD->redecls()) { 9771 const auto *CurTA = FD->getAttr<TargetAttr>(); 9772 // We allow forward declarations before ANY multiversioning attributes, but 9773 // nothing after the fact. 9774 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 9775 (!CurTA || CurTA->isInherited())) { 9776 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 9777 << 0; 9778 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9779 NewFD->setInvalidDecl(); 9780 return true; 9781 } 9782 } 9783 9784 OldFD->setIsMultiVersion(); 9785 NewFD->setIsMultiVersion(); 9786 Redeclaration = false; 9787 MergeTypeWithPrevious = false; 9788 OldDecl = nullptr; 9789 Previous.clear(); 9790 return false; 9791 } 9792 9793 /// Check the validity of a new function declaration being added to an existing 9794 /// multiversioned declaration collection. 9795 static bool CheckMultiVersionAdditionalDecl( 9796 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 9797 MultiVersionKind NewMVType, const TargetAttr *NewTA, 9798 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 9799 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9800 LookupResult &Previous) { 9801 9802 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 9803 // Disallow mixing of multiversioning types. 9804 if ((OldMVType == MultiVersionKind::Target && 9805 NewMVType != MultiVersionKind::Target) || 9806 (NewMVType == MultiVersionKind::Target && 9807 OldMVType != MultiVersionKind::Target)) { 9808 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9809 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9810 NewFD->setInvalidDecl(); 9811 return true; 9812 } 9813 9814 TargetAttr::ParsedTargetAttr NewParsed; 9815 if (NewTA) { 9816 NewParsed = NewTA->parse(); 9817 llvm::sort(NewParsed.Features); 9818 } 9819 9820 bool UseMemberUsingDeclRules = 9821 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9822 9823 // Next, check ALL non-overloads to see if this is a redeclaration of a 9824 // previous member of the MultiVersion set. 9825 for (NamedDecl *ND : Previous) { 9826 FunctionDecl *CurFD = ND->getAsFunction(); 9827 if (!CurFD) 9828 continue; 9829 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9830 continue; 9831 9832 if (NewMVType == MultiVersionKind::Target) { 9833 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9834 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9835 NewFD->setIsMultiVersion(); 9836 Redeclaration = true; 9837 OldDecl = ND; 9838 return false; 9839 } 9840 9841 TargetAttr::ParsedTargetAttr CurParsed = 9842 CurTA->parse(std::less<std::string>()); 9843 if (CurParsed == NewParsed) { 9844 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9845 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9846 NewFD->setInvalidDecl(); 9847 return true; 9848 } 9849 } else { 9850 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 9851 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 9852 // Handle CPUDispatch/CPUSpecific versions. 9853 // Only 1 CPUDispatch function is allowed, this will make it go through 9854 // the redeclaration errors. 9855 if (NewMVType == MultiVersionKind::CPUDispatch && 9856 CurFD->hasAttr<CPUDispatchAttr>()) { 9857 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 9858 std::equal( 9859 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 9860 NewCPUDisp->cpus_begin(), 9861 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9862 return Cur->getName() == New->getName(); 9863 })) { 9864 NewFD->setIsMultiVersion(); 9865 Redeclaration = true; 9866 OldDecl = ND; 9867 return false; 9868 } 9869 9870 // If the declarations don't match, this is an error condition. 9871 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 9872 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9873 NewFD->setInvalidDecl(); 9874 return true; 9875 } 9876 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 9877 9878 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 9879 std::equal( 9880 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 9881 NewCPUSpec->cpus_begin(), 9882 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9883 return Cur->getName() == New->getName(); 9884 })) { 9885 NewFD->setIsMultiVersion(); 9886 Redeclaration = true; 9887 OldDecl = ND; 9888 return false; 9889 } 9890 9891 // Only 1 version of CPUSpecific is allowed for each CPU. 9892 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 9893 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 9894 if (CurII == NewII) { 9895 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 9896 << NewII; 9897 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9898 NewFD->setInvalidDecl(); 9899 return true; 9900 } 9901 } 9902 } 9903 } 9904 // If the two decls aren't the same MVType, there is no possible error 9905 // condition. 9906 } 9907 } 9908 9909 // Else, this is simply a non-redecl case. Checking the 'value' is only 9910 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 9911 // handled in the attribute adding step. 9912 if (NewMVType == MultiVersionKind::Target && 9913 CheckMultiVersionValue(S, NewFD)) { 9914 NewFD->setInvalidDecl(); 9915 return true; 9916 } 9917 9918 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 9919 !OldFD->isMultiVersion(), NewMVType)) { 9920 NewFD->setInvalidDecl(); 9921 return true; 9922 } 9923 9924 // Permit forward declarations in the case where these two are compatible. 9925 if (!OldFD->isMultiVersion()) { 9926 OldFD->setIsMultiVersion(); 9927 NewFD->setIsMultiVersion(); 9928 Redeclaration = true; 9929 OldDecl = OldFD; 9930 return false; 9931 } 9932 9933 NewFD->setIsMultiVersion(); 9934 Redeclaration = false; 9935 MergeTypeWithPrevious = false; 9936 OldDecl = nullptr; 9937 Previous.clear(); 9938 return false; 9939 } 9940 9941 9942 /// Check the validity of a mulitversion function declaration. 9943 /// Also sets the multiversion'ness' of the function itself. 9944 /// 9945 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9946 /// 9947 /// Returns true if there was an error, false otherwise. 9948 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9949 bool &Redeclaration, NamedDecl *&OldDecl, 9950 bool &MergeTypeWithPrevious, 9951 LookupResult &Previous) { 9952 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9953 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 9954 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 9955 9956 // Mixing Multiversioning types is prohibited. 9957 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 9958 (NewCPUDisp && NewCPUSpec)) { 9959 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9960 NewFD->setInvalidDecl(); 9961 return true; 9962 } 9963 9964 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 9965 9966 // Main isn't allowed to become a multiversion function, however it IS 9967 // permitted to have 'main' be marked with the 'target' optimization hint. 9968 if (NewFD->isMain()) { 9969 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 9970 MVType == MultiVersionKind::CPUDispatch || 9971 MVType == MultiVersionKind::CPUSpecific) { 9972 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9973 NewFD->setInvalidDecl(); 9974 return true; 9975 } 9976 return false; 9977 } 9978 9979 if (!OldDecl || !OldDecl->getAsFunction() || 9980 OldDecl->getDeclContext()->getRedeclContext() != 9981 NewFD->getDeclContext()->getRedeclContext()) { 9982 // If there's no previous declaration, AND this isn't attempting to cause 9983 // multiversioning, this isn't an error condition. 9984 if (MVType == MultiVersionKind::None) 9985 return false; 9986 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 9987 } 9988 9989 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9990 9991 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 9992 return false; 9993 9994 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 9995 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 9996 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 9997 NewFD->setInvalidDecl(); 9998 return true; 9999 } 10000 10001 // Handle the target potentially causes multiversioning case. 10002 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10003 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10004 Redeclaration, OldDecl, 10005 MergeTypeWithPrevious, Previous); 10006 10007 // At this point, we have a multiversion function decl (in OldFD) AND an 10008 // appropriate attribute in the current function decl. Resolve that these are 10009 // still compatible with previous declarations. 10010 return CheckMultiVersionAdditionalDecl( 10011 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10012 OldDecl, MergeTypeWithPrevious, Previous); 10013 } 10014 10015 /// Perform semantic checking of a new function declaration. 10016 /// 10017 /// Performs semantic analysis of the new function declaration 10018 /// NewFD. This routine performs all semantic checking that does not 10019 /// require the actual declarator involved in the declaration, and is 10020 /// used both for the declaration of functions as they are parsed 10021 /// (called via ActOnDeclarator) and for the declaration of functions 10022 /// that have been instantiated via C++ template instantiation (called 10023 /// via InstantiateDecl). 10024 /// 10025 /// \param IsMemberSpecialization whether this new function declaration is 10026 /// a member specialization (that replaces any definition provided by the 10027 /// previous declaration). 10028 /// 10029 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10030 /// 10031 /// \returns true if the function declaration is a redeclaration. 10032 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10033 LookupResult &Previous, 10034 bool IsMemberSpecialization) { 10035 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10036 "Variably modified return types are not handled here"); 10037 10038 // Determine whether the type of this function should be merged with 10039 // a previous visible declaration. This never happens for functions in C++, 10040 // and always happens in C if the previous declaration was visible. 10041 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10042 !Previous.isShadowed(); 10043 10044 bool Redeclaration = false; 10045 NamedDecl *OldDecl = nullptr; 10046 bool MayNeedOverloadableChecks = false; 10047 10048 // Merge or overload the declaration with an existing declaration of 10049 // the same name, if appropriate. 10050 if (!Previous.empty()) { 10051 // Determine whether NewFD is an overload of PrevDecl or 10052 // a declaration that requires merging. If it's an overload, 10053 // there's no more work to do here; we'll just add the new 10054 // function to the scope. 10055 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10056 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10057 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10058 Redeclaration = true; 10059 OldDecl = Candidate; 10060 } 10061 } else { 10062 MayNeedOverloadableChecks = true; 10063 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10064 /*NewIsUsingDecl*/ false)) { 10065 case Ovl_Match: 10066 Redeclaration = true; 10067 break; 10068 10069 case Ovl_NonFunction: 10070 Redeclaration = true; 10071 break; 10072 10073 case Ovl_Overload: 10074 Redeclaration = false; 10075 break; 10076 } 10077 } 10078 } 10079 10080 // Check for a previous extern "C" declaration with this name. 10081 if (!Redeclaration && 10082 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10083 if (!Previous.empty()) { 10084 // This is an extern "C" declaration with the same name as a previous 10085 // declaration, and thus redeclares that entity... 10086 Redeclaration = true; 10087 OldDecl = Previous.getFoundDecl(); 10088 MergeTypeWithPrevious = false; 10089 10090 // ... except in the presence of __attribute__((overloadable)). 10091 if (OldDecl->hasAttr<OverloadableAttr>() || 10092 NewFD->hasAttr<OverloadableAttr>()) { 10093 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10094 MayNeedOverloadableChecks = true; 10095 Redeclaration = false; 10096 OldDecl = nullptr; 10097 } 10098 } 10099 } 10100 } 10101 10102 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10103 MergeTypeWithPrevious, Previous)) 10104 return Redeclaration; 10105 10106 // C++11 [dcl.constexpr]p8: 10107 // A constexpr specifier for a non-static member function that is not 10108 // a constructor declares that member function to be const. 10109 // 10110 // This needs to be delayed until we know whether this is an out-of-line 10111 // definition of a static member function. 10112 // 10113 // This rule is not present in C++1y, so we produce a backwards 10114 // compatibility warning whenever it happens in C++11. 10115 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10116 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10117 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10118 !MD->getMethodQualifiers().hasConst()) { 10119 CXXMethodDecl *OldMD = nullptr; 10120 if (OldDecl) 10121 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10122 if (!OldMD || !OldMD->isStatic()) { 10123 const FunctionProtoType *FPT = 10124 MD->getType()->castAs<FunctionProtoType>(); 10125 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10126 EPI.TypeQuals.addConst(); 10127 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10128 FPT->getParamTypes(), EPI)); 10129 10130 // Warn that we did this, if we're not performing template instantiation. 10131 // In that case, we'll have warned already when the template was defined. 10132 if (!inTemplateInstantiation()) { 10133 SourceLocation AddConstLoc; 10134 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10135 .IgnoreParens().getAs<FunctionTypeLoc>()) 10136 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10137 10138 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10139 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10140 } 10141 } 10142 } 10143 10144 if (Redeclaration) { 10145 // NewFD and OldDecl represent declarations that need to be 10146 // merged. 10147 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10148 NewFD->setInvalidDecl(); 10149 return Redeclaration; 10150 } 10151 10152 Previous.clear(); 10153 Previous.addDecl(OldDecl); 10154 10155 if (FunctionTemplateDecl *OldTemplateDecl = 10156 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10157 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10158 FunctionTemplateDecl *NewTemplateDecl 10159 = NewFD->getDescribedFunctionTemplate(); 10160 assert(NewTemplateDecl && "Template/non-template mismatch"); 10161 10162 // The call to MergeFunctionDecl above may have created some state in 10163 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10164 // can add it as a redeclaration. 10165 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10166 10167 NewFD->setPreviousDeclaration(OldFD); 10168 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10169 if (NewFD->isCXXClassMember()) { 10170 NewFD->setAccess(OldTemplateDecl->getAccess()); 10171 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10172 } 10173 10174 // If this is an explicit specialization of a member that is a function 10175 // template, mark it as a member specialization. 10176 if (IsMemberSpecialization && 10177 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10178 NewTemplateDecl->setMemberSpecialization(); 10179 assert(OldTemplateDecl->isMemberSpecialization()); 10180 // Explicit specializations of a member template do not inherit deleted 10181 // status from the parent member template that they are specializing. 10182 if (OldFD->isDeleted()) { 10183 // FIXME: This assert will not hold in the presence of modules. 10184 assert(OldFD->getCanonicalDecl() == OldFD); 10185 // FIXME: We need an update record for this AST mutation. 10186 OldFD->setDeletedAsWritten(false); 10187 } 10188 } 10189 10190 } else { 10191 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10192 auto *OldFD = cast<FunctionDecl>(OldDecl); 10193 // This needs to happen first so that 'inline' propagates. 10194 NewFD->setPreviousDeclaration(OldFD); 10195 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10196 if (NewFD->isCXXClassMember()) 10197 NewFD->setAccess(OldFD->getAccess()); 10198 } 10199 } 10200 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10201 !NewFD->getAttr<OverloadableAttr>()) { 10202 assert((Previous.empty() || 10203 llvm::any_of(Previous, 10204 [](const NamedDecl *ND) { 10205 return ND->hasAttr<OverloadableAttr>(); 10206 })) && 10207 "Non-redecls shouldn't happen without overloadable present"); 10208 10209 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10210 const auto *FD = dyn_cast<FunctionDecl>(ND); 10211 return FD && !FD->hasAttr<OverloadableAttr>(); 10212 }); 10213 10214 if (OtherUnmarkedIter != Previous.end()) { 10215 Diag(NewFD->getLocation(), 10216 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10217 Diag((*OtherUnmarkedIter)->getLocation(), 10218 diag::note_attribute_overloadable_prev_overload) 10219 << false; 10220 10221 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10222 } 10223 } 10224 10225 // Semantic checking for this function declaration (in isolation). 10226 10227 if (getLangOpts().CPlusPlus) { 10228 // C++-specific checks. 10229 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10230 CheckConstructor(Constructor); 10231 } else if (CXXDestructorDecl *Destructor = 10232 dyn_cast<CXXDestructorDecl>(NewFD)) { 10233 CXXRecordDecl *Record = Destructor->getParent(); 10234 QualType ClassType = Context.getTypeDeclType(Record); 10235 10236 // FIXME: Shouldn't we be able to perform this check even when the class 10237 // type is dependent? Both gcc and edg can handle that. 10238 if (!ClassType->isDependentType()) { 10239 DeclarationName Name 10240 = Context.DeclarationNames.getCXXDestructorName( 10241 Context.getCanonicalType(ClassType)); 10242 if (NewFD->getDeclName() != Name) { 10243 Diag(NewFD->getLocation(), diag::err_destructor_name); 10244 NewFD->setInvalidDecl(); 10245 return Redeclaration; 10246 } 10247 } 10248 } else if (CXXConversionDecl *Conversion 10249 = dyn_cast<CXXConversionDecl>(NewFD)) { 10250 ActOnConversionDeclarator(Conversion); 10251 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10252 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10253 CheckDeductionGuideTemplate(TD); 10254 10255 // A deduction guide is not on the list of entities that can be 10256 // explicitly specialized. 10257 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10258 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10259 << /*explicit specialization*/ 1; 10260 } 10261 10262 // Find any virtual functions that this function overrides. 10263 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10264 if (!Method->isFunctionTemplateSpecialization() && 10265 !Method->getDescribedFunctionTemplate() && 10266 Method->isCanonicalDecl()) { 10267 if (AddOverriddenMethods(Method->getParent(), Method)) { 10268 // If the function was marked as "static", we have a problem. 10269 if (NewFD->getStorageClass() == SC_Static) { 10270 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10271 } 10272 } 10273 } 10274 10275 if (Method->isStatic()) 10276 checkThisInStaticMemberFunctionType(Method); 10277 } 10278 10279 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10280 if (NewFD->isOverloadedOperator() && 10281 CheckOverloadedOperatorDeclaration(NewFD)) { 10282 NewFD->setInvalidDecl(); 10283 return Redeclaration; 10284 } 10285 10286 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10287 if (NewFD->getLiteralIdentifier() && 10288 CheckLiteralOperatorDeclaration(NewFD)) { 10289 NewFD->setInvalidDecl(); 10290 return Redeclaration; 10291 } 10292 10293 // In C++, check default arguments now that we have merged decls. Unless 10294 // the lexical context is the class, because in this case this is done 10295 // during delayed parsing anyway. 10296 if (!CurContext->isRecord()) 10297 CheckCXXDefaultArguments(NewFD); 10298 10299 // If this function declares a builtin function, check the type of this 10300 // declaration against the expected type for the builtin. 10301 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10302 ASTContext::GetBuiltinTypeError Error; 10303 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10304 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10305 // If the type of the builtin differs only in its exception 10306 // specification, that's OK. 10307 // FIXME: If the types do differ in this way, it would be better to 10308 // retain the 'noexcept' form of the type. 10309 if (!T.isNull() && 10310 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10311 NewFD->getType())) 10312 // The type of this function differs from the type of the builtin, 10313 // so forget about the builtin entirely. 10314 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10315 } 10316 10317 // If this function is declared as being extern "C", then check to see if 10318 // the function returns a UDT (class, struct, or union type) that is not C 10319 // compatible, and if it does, warn the user. 10320 // But, issue any diagnostic on the first declaration only. 10321 if (Previous.empty() && NewFD->isExternC()) { 10322 QualType R = NewFD->getReturnType(); 10323 if (R->isIncompleteType() && !R->isVoidType()) 10324 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10325 << NewFD << R; 10326 else if (!R.isPODType(Context) && !R->isVoidType() && 10327 !R->isObjCObjectPointerType()) 10328 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10329 } 10330 10331 // C++1z [dcl.fct]p6: 10332 // [...] whether the function has a non-throwing exception-specification 10333 // [is] part of the function type 10334 // 10335 // This results in an ABI break between C++14 and C++17 for functions whose 10336 // declared type includes an exception-specification in a parameter or 10337 // return type. (Exception specifications on the function itself are OK in 10338 // most cases, and exception specifications are not permitted in most other 10339 // contexts where they could make it into a mangling.) 10340 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10341 auto HasNoexcept = [&](QualType T) -> bool { 10342 // Strip off declarator chunks that could be between us and a function 10343 // type. We don't need to look far, exception specifications are very 10344 // restricted prior to C++17. 10345 if (auto *RT = T->getAs<ReferenceType>()) 10346 T = RT->getPointeeType(); 10347 else if (T->isAnyPointerType()) 10348 T = T->getPointeeType(); 10349 else if (auto *MPT = T->getAs<MemberPointerType>()) 10350 T = MPT->getPointeeType(); 10351 if (auto *FPT = T->getAs<FunctionProtoType>()) 10352 if (FPT->isNothrow()) 10353 return true; 10354 return false; 10355 }; 10356 10357 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10358 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10359 for (QualType T : FPT->param_types()) 10360 AnyNoexcept |= HasNoexcept(T); 10361 if (AnyNoexcept) 10362 Diag(NewFD->getLocation(), 10363 diag::warn_cxx17_compat_exception_spec_in_signature) 10364 << NewFD; 10365 } 10366 10367 if (!Redeclaration && LangOpts.CUDA) 10368 checkCUDATargetOverload(NewFD, Previous); 10369 } 10370 return Redeclaration; 10371 } 10372 10373 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10374 // C++11 [basic.start.main]p3: 10375 // A program that [...] declares main to be inline, static or 10376 // constexpr is ill-formed. 10377 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10378 // appear in a declaration of main. 10379 // static main is not an error under C99, but we should warn about it. 10380 // We accept _Noreturn main as an extension. 10381 if (FD->getStorageClass() == SC_Static) 10382 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10383 ? diag::err_static_main : diag::warn_static_main) 10384 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10385 if (FD->isInlineSpecified()) 10386 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10387 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10388 if (DS.isNoreturnSpecified()) { 10389 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10390 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10391 Diag(NoreturnLoc, diag::ext_noreturn_main); 10392 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10393 << FixItHint::CreateRemoval(NoreturnRange); 10394 } 10395 if (FD->isConstexpr()) { 10396 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10397 << FD->isConsteval() 10398 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10399 FD->setConstexprKind(CSK_unspecified); 10400 } 10401 10402 if (getLangOpts().OpenCL) { 10403 Diag(FD->getLocation(), diag::err_opencl_no_main) 10404 << FD->hasAttr<OpenCLKernelAttr>(); 10405 FD->setInvalidDecl(); 10406 return; 10407 } 10408 10409 QualType T = FD->getType(); 10410 assert(T->isFunctionType() && "function decl is not of function type"); 10411 const FunctionType* FT = T->castAs<FunctionType>(); 10412 10413 // Set default calling convention for main() 10414 if (FT->getCallConv() != CC_C) { 10415 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10416 FD->setType(QualType(FT, 0)); 10417 T = Context.getCanonicalType(FD->getType()); 10418 } 10419 10420 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10421 // In C with GNU extensions we allow main() to have non-integer return 10422 // type, but we should warn about the extension, and we disable the 10423 // implicit-return-zero rule. 10424 10425 // GCC in C mode accepts qualified 'int'. 10426 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10427 FD->setHasImplicitReturnZero(true); 10428 else { 10429 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10430 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10431 if (RTRange.isValid()) 10432 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10433 << FixItHint::CreateReplacement(RTRange, "int"); 10434 } 10435 } else { 10436 // In C and C++, main magically returns 0 if you fall off the end; 10437 // set the flag which tells us that. 10438 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10439 10440 // All the standards say that main() should return 'int'. 10441 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10442 FD->setHasImplicitReturnZero(true); 10443 else { 10444 // Otherwise, this is just a flat-out error. 10445 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10446 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10447 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10448 : FixItHint()); 10449 FD->setInvalidDecl(true); 10450 } 10451 } 10452 10453 // Treat protoless main() as nullary. 10454 if (isa<FunctionNoProtoType>(FT)) return; 10455 10456 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10457 unsigned nparams = FTP->getNumParams(); 10458 assert(FD->getNumParams() == nparams); 10459 10460 bool HasExtraParameters = (nparams > 3); 10461 10462 if (FTP->isVariadic()) { 10463 Diag(FD->getLocation(), diag::ext_variadic_main); 10464 // FIXME: if we had information about the location of the ellipsis, we 10465 // could add a FixIt hint to remove it as a parameter. 10466 } 10467 10468 // Darwin passes an undocumented fourth argument of type char**. If 10469 // other platforms start sprouting these, the logic below will start 10470 // getting shifty. 10471 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10472 HasExtraParameters = false; 10473 10474 if (HasExtraParameters) { 10475 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10476 FD->setInvalidDecl(true); 10477 nparams = 3; 10478 } 10479 10480 // FIXME: a lot of the following diagnostics would be improved 10481 // if we had some location information about types. 10482 10483 QualType CharPP = 10484 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10485 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10486 10487 for (unsigned i = 0; i < nparams; ++i) { 10488 QualType AT = FTP->getParamType(i); 10489 10490 bool mismatch = true; 10491 10492 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10493 mismatch = false; 10494 else if (Expected[i] == CharPP) { 10495 // As an extension, the following forms are okay: 10496 // char const ** 10497 // char const * const * 10498 // char * const * 10499 10500 QualifierCollector qs; 10501 const PointerType* PT; 10502 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10503 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10504 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10505 Context.CharTy)) { 10506 qs.removeConst(); 10507 mismatch = !qs.empty(); 10508 } 10509 } 10510 10511 if (mismatch) { 10512 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10513 // TODO: suggest replacing given type with expected type 10514 FD->setInvalidDecl(true); 10515 } 10516 } 10517 10518 if (nparams == 1 && !FD->isInvalidDecl()) { 10519 Diag(FD->getLocation(), diag::warn_main_one_arg); 10520 } 10521 10522 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10523 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10524 FD->setInvalidDecl(); 10525 } 10526 } 10527 10528 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10529 QualType T = FD->getType(); 10530 assert(T->isFunctionType() && "function decl is not of function type"); 10531 const FunctionType *FT = T->castAs<FunctionType>(); 10532 10533 // Set an implicit return of 'zero' if the function can return some integral, 10534 // enumeration, pointer or nullptr type. 10535 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10536 FT->getReturnType()->isAnyPointerType() || 10537 FT->getReturnType()->isNullPtrType()) 10538 // DllMain is exempt because a return value of zero means it failed. 10539 if (FD->getName() != "DllMain") 10540 FD->setHasImplicitReturnZero(true); 10541 10542 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10543 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10544 FD->setInvalidDecl(); 10545 } 10546 } 10547 10548 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10549 // FIXME: Need strict checking. In C89, we need to check for 10550 // any assignment, increment, decrement, function-calls, or 10551 // commas outside of a sizeof. In C99, it's the same list, 10552 // except that the aforementioned are allowed in unevaluated 10553 // expressions. Everything else falls under the 10554 // "may accept other forms of constant expressions" exception. 10555 // (We never end up here for C++, so the constant expression 10556 // rules there don't matter.) 10557 const Expr *Culprit; 10558 if (Init->isConstantInitializer(Context, false, &Culprit)) 10559 return false; 10560 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10561 << Culprit->getSourceRange(); 10562 return true; 10563 } 10564 10565 namespace { 10566 // Visits an initialization expression to see if OrigDecl is evaluated in 10567 // its own initialization and throws a warning if it does. 10568 class SelfReferenceChecker 10569 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10570 Sema &S; 10571 Decl *OrigDecl; 10572 bool isRecordType; 10573 bool isPODType; 10574 bool isReferenceType; 10575 10576 bool isInitList; 10577 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10578 10579 public: 10580 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10581 10582 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10583 S(S), OrigDecl(OrigDecl) { 10584 isPODType = false; 10585 isRecordType = false; 10586 isReferenceType = false; 10587 isInitList = false; 10588 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10589 isPODType = VD->getType().isPODType(S.Context); 10590 isRecordType = VD->getType()->isRecordType(); 10591 isReferenceType = VD->getType()->isReferenceType(); 10592 } 10593 } 10594 10595 // For most expressions, just call the visitor. For initializer lists, 10596 // track the index of the field being initialized since fields are 10597 // initialized in order allowing use of previously initialized fields. 10598 void CheckExpr(Expr *E) { 10599 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10600 if (!InitList) { 10601 Visit(E); 10602 return; 10603 } 10604 10605 // Track and increment the index here. 10606 isInitList = true; 10607 InitFieldIndex.push_back(0); 10608 for (auto Child : InitList->children()) { 10609 CheckExpr(cast<Expr>(Child)); 10610 ++InitFieldIndex.back(); 10611 } 10612 InitFieldIndex.pop_back(); 10613 } 10614 10615 // Returns true if MemberExpr is checked and no further checking is needed. 10616 // Returns false if additional checking is required. 10617 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10618 llvm::SmallVector<FieldDecl*, 4> Fields; 10619 Expr *Base = E; 10620 bool ReferenceField = false; 10621 10622 // Get the field members used. 10623 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10624 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10625 if (!FD) 10626 return false; 10627 Fields.push_back(FD); 10628 if (FD->getType()->isReferenceType()) 10629 ReferenceField = true; 10630 Base = ME->getBase()->IgnoreParenImpCasts(); 10631 } 10632 10633 // Keep checking only if the base Decl is the same. 10634 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10635 if (!DRE || DRE->getDecl() != OrigDecl) 10636 return false; 10637 10638 // A reference field can be bound to an unininitialized field. 10639 if (CheckReference && !ReferenceField) 10640 return true; 10641 10642 // Convert FieldDecls to their index number. 10643 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10644 for (const FieldDecl *I : llvm::reverse(Fields)) 10645 UsedFieldIndex.push_back(I->getFieldIndex()); 10646 10647 // See if a warning is needed by checking the first difference in index 10648 // numbers. If field being used has index less than the field being 10649 // initialized, then the use is safe. 10650 for (auto UsedIter = UsedFieldIndex.begin(), 10651 UsedEnd = UsedFieldIndex.end(), 10652 OrigIter = InitFieldIndex.begin(), 10653 OrigEnd = InitFieldIndex.end(); 10654 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10655 if (*UsedIter < *OrigIter) 10656 return true; 10657 if (*UsedIter > *OrigIter) 10658 break; 10659 } 10660 10661 // TODO: Add a different warning which will print the field names. 10662 HandleDeclRefExpr(DRE); 10663 return true; 10664 } 10665 10666 // For most expressions, the cast is directly above the DeclRefExpr. 10667 // For conditional operators, the cast can be outside the conditional 10668 // operator if both expressions are DeclRefExpr's. 10669 void HandleValue(Expr *E) { 10670 E = E->IgnoreParens(); 10671 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10672 HandleDeclRefExpr(DRE); 10673 return; 10674 } 10675 10676 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10677 Visit(CO->getCond()); 10678 HandleValue(CO->getTrueExpr()); 10679 HandleValue(CO->getFalseExpr()); 10680 return; 10681 } 10682 10683 if (BinaryConditionalOperator *BCO = 10684 dyn_cast<BinaryConditionalOperator>(E)) { 10685 Visit(BCO->getCond()); 10686 HandleValue(BCO->getFalseExpr()); 10687 return; 10688 } 10689 10690 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10691 HandleValue(OVE->getSourceExpr()); 10692 return; 10693 } 10694 10695 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10696 if (BO->getOpcode() == BO_Comma) { 10697 Visit(BO->getLHS()); 10698 HandleValue(BO->getRHS()); 10699 return; 10700 } 10701 } 10702 10703 if (isa<MemberExpr>(E)) { 10704 if (isInitList) { 10705 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10706 false /*CheckReference*/)) 10707 return; 10708 } 10709 10710 Expr *Base = E->IgnoreParenImpCasts(); 10711 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10712 // Check for static member variables and don't warn on them. 10713 if (!isa<FieldDecl>(ME->getMemberDecl())) 10714 return; 10715 Base = ME->getBase()->IgnoreParenImpCasts(); 10716 } 10717 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10718 HandleDeclRefExpr(DRE); 10719 return; 10720 } 10721 10722 Visit(E); 10723 } 10724 10725 // Reference types not handled in HandleValue are handled here since all 10726 // uses of references are bad, not just r-value uses. 10727 void VisitDeclRefExpr(DeclRefExpr *E) { 10728 if (isReferenceType) 10729 HandleDeclRefExpr(E); 10730 } 10731 10732 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10733 if (E->getCastKind() == CK_LValueToRValue) { 10734 HandleValue(E->getSubExpr()); 10735 return; 10736 } 10737 10738 Inherited::VisitImplicitCastExpr(E); 10739 } 10740 10741 void VisitMemberExpr(MemberExpr *E) { 10742 if (isInitList) { 10743 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10744 return; 10745 } 10746 10747 // Don't warn on arrays since they can be treated as pointers. 10748 if (E->getType()->canDecayToPointerType()) return; 10749 10750 // Warn when a non-static method call is followed by non-static member 10751 // field accesses, which is followed by a DeclRefExpr. 10752 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10753 bool Warn = (MD && !MD->isStatic()); 10754 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10755 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10756 if (!isa<FieldDecl>(ME->getMemberDecl())) 10757 Warn = false; 10758 Base = ME->getBase()->IgnoreParenImpCasts(); 10759 } 10760 10761 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10762 if (Warn) 10763 HandleDeclRefExpr(DRE); 10764 return; 10765 } 10766 10767 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10768 // Visit that expression. 10769 Visit(Base); 10770 } 10771 10772 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10773 Expr *Callee = E->getCallee(); 10774 10775 if (isa<UnresolvedLookupExpr>(Callee)) 10776 return Inherited::VisitCXXOperatorCallExpr(E); 10777 10778 Visit(Callee); 10779 for (auto Arg: E->arguments()) 10780 HandleValue(Arg->IgnoreParenImpCasts()); 10781 } 10782 10783 void VisitUnaryOperator(UnaryOperator *E) { 10784 // For POD record types, addresses of its own members are well-defined. 10785 if (E->getOpcode() == UO_AddrOf && isRecordType && 10786 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10787 if (!isPODType) 10788 HandleValue(E->getSubExpr()); 10789 return; 10790 } 10791 10792 if (E->isIncrementDecrementOp()) { 10793 HandleValue(E->getSubExpr()); 10794 return; 10795 } 10796 10797 Inherited::VisitUnaryOperator(E); 10798 } 10799 10800 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10801 10802 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10803 if (E->getConstructor()->isCopyConstructor()) { 10804 Expr *ArgExpr = E->getArg(0); 10805 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10806 if (ILE->getNumInits() == 1) 10807 ArgExpr = ILE->getInit(0); 10808 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10809 if (ICE->getCastKind() == CK_NoOp) 10810 ArgExpr = ICE->getSubExpr(); 10811 HandleValue(ArgExpr); 10812 return; 10813 } 10814 Inherited::VisitCXXConstructExpr(E); 10815 } 10816 10817 void VisitCallExpr(CallExpr *E) { 10818 // Treat std::move as a use. 10819 if (E->isCallToStdMove()) { 10820 HandleValue(E->getArg(0)); 10821 return; 10822 } 10823 10824 Inherited::VisitCallExpr(E); 10825 } 10826 10827 void VisitBinaryOperator(BinaryOperator *E) { 10828 if (E->isCompoundAssignmentOp()) { 10829 HandleValue(E->getLHS()); 10830 Visit(E->getRHS()); 10831 return; 10832 } 10833 10834 Inherited::VisitBinaryOperator(E); 10835 } 10836 10837 // A custom visitor for BinaryConditionalOperator is needed because the 10838 // regular visitor would check the condition and true expression separately 10839 // but both point to the same place giving duplicate diagnostics. 10840 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10841 Visit(E->getCond()); 10842 Visit(E->getFalseExpr()); 10843 } 10844 10845 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10846 Decl* ReferenceDecl = DRE->getDecl(); 10847 if (OrigDecl != ReferenceDecl) return; 10848 unsigned diag; 10849 if (isReferenceType) { 10850 diag = diag::warn_uninit_self_reference_in_reference_init; 10851 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10852 diag = diag::warn_static_self_reference_in_init; 10853 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10854 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10855 DRE->getDecl()->getType()->isRecordType()) { 10856 diag = diag::warn_uninit_self_reference_in_init; 10857 } else { 10858 // Local variables will be handled by the CFG analysis. 10859 return; 10860 } 10861 10862 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 10863 S.PDiag(diag) 10864 << DRE->getDecl() << OrigDecl->getLocation() 10865 << DRE->getSourceRange()); 10866 } 10867 }; 10868 10869 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10870 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10871 bool DirectInit) { 10872 // Parameters arguments are occassionially constructed with itself, 10873 // for instance, in recursive functions. Skip them. 10874 if (isa<ParmVarDecl>(OrigDecl)) 10875 return; 10876 10877 E = E->IgnoreParens(); 10878 10879 // Skip checking T a = a where T is not a record or reference type. 10880 // Doing so is a way to silence uninitialized warnings. 10881 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10882 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10883 if (ICE->getCastKind() == CK_LValueToRValue) 10884 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10885 if (DRE->getDecl() == OrigDecl) 10886 return; 10887 10888 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10889 } 10890 } // end anonymous namespace 10891 10892 namespace { 10893 // Simple wrapper to add the name of a variable or (if no variable is 10894 // available) a DeclarationName into a diagnostic. 10895 struct VarDeclOrName { 10896 VarDecl *VDecl; 10897 DeclarationName Name; 10898 10899 friend const Sema::SemaDiagnosticBuilder & 10900 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10901 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10902 } 10903 }; 10904 } // end anonymous namespace 10905 10906 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10907 DeclarationName Name, QualType Type, 10908 TypeSourceInfo *TSI, 10909 SourceRange Range, bool DirectInit, 10910 Expr *Init) { 10911 bool IsInitCapture = !VDecl; 10912 assert((!VDecl || !VDecl->isInitCapture()) && 10913 "init captures are expected to be deduced prior to initialization"); 10914 10915 VarDeclOrName VN{VDecl, Name}; 10916 10917 DeducedType *Deduced = Type->getContainedDeducedType(); 10918 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10919 10920 // C++11 [dcl.spec.auto]p3 10921 if (!Init) { 10922 assert(VDecl && "no init for init capture deduction?"); 10923 10924 // Except for class argument deduction, and then for an initializing 10925 // declaration only, i.e. no static at class scope or extern. 10926 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10927 VDecl->hasExternalStorage() || 10928 VDecl->isStaticDataMember()) { 10929 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10930 << VDecl->getDeclName() << Type; 10931 return QualType(); 10932 } 10933 } 10934 10935 ArrayRef<Expr*> DeduceInits; 10936 if (Init) 10937 DeduceInits = Init; 10938 10939 if (DirectInit) { 10940 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10941 DeduceInits = PL->exprs(); 10942 } 10943 10944 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10945 assert(VDecl && "non-auto type for init capture deduction?"); 10946 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10947 InitializationKind Kind = InitializationKind::CreateForInit( 10948 VDecl->getLocation(), DirectInit, Init); 10949 // FIXME: Initialization should not be taking a mutable list of inits. 10950 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10951 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10952 InitsCopy); 10953 } 10954 10955 if (DirectInit) { 10956 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10957 DeduceInits = IL->inits(); 10958 } 10959 10960 // Deduction only works if we have exactly one source expression. 10961 if (DeduceInits.empty()) { 10962 // It isn't possible to write this directly, but it is possible to 10963 // end up in this situation with "auto x(some_pack...);" 10964 Diag(Init->getBeginLoc(), IsInitCapture 10965 ? diag::err_init_capture_no_expression 10966 : diag::err_auto_var_init_no_expression) 10967 << VN << Type << Range; 10968 return QualType(); 10969 } 10970 10971 if (DeduceInits.size() > 1) { 10972 Diag(DeduceInits[1]->getBeginLoc(), 10973 IsInitCapture ? diag::err_init_capture_multiple_expressions 10974 : diag::err_auto_var_init_multiple_expressions) 10975 << VN << Type << Range; 10976 return QualType(); 10977 } 10978 10979 Expr *DeduceInit = DeduceInits[0]; 10980 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10981 Diag(Init->getBeginLoc(), IsInitCapture 10982 ? diag::err_init_capture_paren_braces 10983 : diag::err_auto_var_init_paren_braces) 10984 << isa<InitListExpr>(Init) << VN << Type << Range; 10985 return QualType(); 10986 } 10987 10988 // Expressions default to 'id' when we're in a debugger. 10989 bool DefaultedAnyToId = false; 10990 if (getLangOpts().DebuggerCastResultToId && 10991 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10992 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10993 if (Result.isInvalid()) { 10994 return QualType(); 10995 } 10996 Init = Result.get(); 10997 DefaultedAnyToId = true; 10998 } 10999 11000 // C++ [dcl.decomp]p1: 11001 // If the assignment-expression [...] has array type A and no ref-qualifier 11002 // is present, e has type cv A 11003 if (VDecl && isa<DecompositionDecl>(VDecl) && 11004 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11005 DeduceInit->getType()->isConstantArrayType()) 11006 return Context.getQualifiedType(DeduceInit->getType(), 11007 Type.getQualifiers()); 11008 11009 QualType DeducedType; 11010 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11011 if (!IsInitCapture) 11012 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11013 else if (isa<InitListExpr>(Init)) 11014 Diag(Range.getBegin(), 11015 diag::err_init_capture_deduction_failure_from_init_list) 11016 << VN 11017 << (DeduceInit->getType().isNull() ? TSI->getType() 11018 : DeduceInit->getType()) 11019 << DeduceInit->getSourceRange(); 11020 else 11021 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11022 << VN << TSI->getType() 11023 << (DeduceInit->getType().isNull() ? TSI->getType() 11024 : DeduceInit->getType()) 11025 << DeduceInit->getSourceRange(); 11026 } 11027 11028 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11029 // 'id' instead of a specific object type prevents most of our usual 11030 // checks. 11031 // We only want to warn outside of template instantiations, though: 11032 // inside a template, the 'id' could have come from a parameter. 11033 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11034 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11035 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11036 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11037 } 11038 11039 return DeducedType; 11040 } 11041 11042 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11043 Expr *Init) { 11044 QualType DeducedType = deduceVarTypeFromInitializer( 11045 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11046 VDecl->getSourceRange(), DirectInit, Init); 11047 if (DeducedType.isNull()) { 11048 VDecl->setInvalidDecl(); 11049 return true; 11050 } 11051 11052 VDecl->setType(DeducedType); 11053 assert(VDecl->isLinkageValid()); 11054 11055 // In ARC, infer lifetime. 11056 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11057 VDecl->setInvalidDecl(); 11058 11059 // If this is a redeclaration, check that the type we just deduced matches 11060 // the previously declared type. 11061 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11062 // We never need to merge the type, because we cannot form an incomplete 11063 // array of auto, nor deduce such a type. 11064 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11065 } 11066 11067 // Check the deduced type is valid for a variable declaration. 11068 CheckVariableDeclarationType(VDecl); 11069 return VDecl->isInvalidDecl(); 11070 } 11071 11072 /// AddInitializerToDecl - Adds the initializer Init to the 11073 /// declaration dcl. If DirectInit is true, this is C++ direct 11074 /// initialization rather than copy initialization. 11075 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11076 // If there is no declaration, there was an error parsing it. Just ignore 11077 // the initializer. 11078 if (!RealDecl || RealDecl->isInvalidDecl()) { 11079 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11080 return; 11081 } 11082 11083 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11084 // Pure-specifiers are handled in ActOnPureSpecifier. 11085 Diag(Method->getLocation(), diag::err_member_function_initialization) 11086 << Method->getDeclName() << Init->getSourceRange(); 11087 Method->setInvalidDecl(); 11088 return; 11089 } 11090 11091 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11092 if (!VDecl) { 11093 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11094 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11095 RealDecl->setInvalidDecl(); 11096 return; 11097 } 11098 11099 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11100 if (VDecl->getType()->isUndeducedType()) { 11101 // Attempt typo correction early so that the type of the init expression can 11102 // be deduced based on the chosen correction if the original init contains a 11103 // TypoExpr. 11104 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11105 if (!Res.isUsable()) { 11106 RealDecl->setInvalidDecl(); 11107 return; 11108 } 11109 Init = Res.get(); 11110 11111 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11112 return; 11113 } 11114 11115 // dllimport cannot be used on variable definitions. 11116 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11117 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11118 VDecl->setInvalidDecl(); 11119 return; 11120 } 11121 11122 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11123 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11124 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11125 VDecl->setInvalidDecl(); 11126 return; 11127 } 11128 11129 if (!VDecl->getType()->isDependentType()) { 11130 // A definition must end up with a complete type, which means it must be 11131 // complete with the restriction that an array type might be completed by 11132 // the initializer; note that later code assumes this restriction. 11133 QualType BaseDeclType = VDecl->getType(); 11134 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11135 BaseDeclType = Array->getElementType(); 11136 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11137 diag::err_typecheck_decl_incomplete_type)) { 11138 RealDecl->setInvalidDecl(); 11139 return; 11140 } 11141 11142 // The variable can not have an abstract class type. 11143 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11144 diag::err_abstract_type_in_decl, 11145 AbstractVariableType)) 11146 VDecl->setInvalidDecl(); 11147 } 11148 11149 // If adding the initializer will turn this declaration into a definition, 11150 // and we already have a definition for this variable, diagnose or otherwise 11151 // handle the situation. 11152 VarDecl *Def; 11153 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11154 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11155 !VDecl->isThisDeclarationADemotedDefinition() && 11156 checkVarDeclRedefinition(Def, VDecl)) 11157 return; 11158 11159 if (getLangOpts().CPlusPlus) { 11160 // C++ [class.static.data]p4 11161 // If a static data member is of const integral or const 11162 // enumeration type, its declaration in the class definition can 11163 // specify a constant-initializer which shall be an integral 11164 // constant expression (5.19). In that case, the member can appear 11165 // in integral constant expressions. The member shall still be 11166 // defined in a namespace scope if it is used in the program and the 11167 // namespace scope definition shall not contain an initializer. 11168 // 11169 // We already performed a redefinition check above, but for static 11170 // data members we also need to check whether there was an in-class 11171 // declaration with an initializer. 11172 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11173 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11174 << VDecl->getDeclName(); 11175 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11176 diag::note_previous_initializer) 11177 << 0; 11178 return; 11179 } 11180 11181 if (VDecl->hasLocalStorage()) 11182 setFunctionHasBranchProtectedScope(); 11183 11184 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11185 VDecl->setInvalidDecl(); 11186 return; 11187 } 11188 } 11189 11190 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11191 // a kernel function cannot be initialized." 11192 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11193 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11194 VDecl->setInvalidDecl(); 11195 return; 11196 } 11197 11198 // Get the decls type and save a reference for later, since 11199 // CheckInitializerTypes may change it. 11200 QualType DclT = VDecl->getType(), SavT = DclT; 11201 11202 // Expressions default to 'id' when we're in a debugger 11203 // and we are assigning it to a variable of Objective-C pointer type. 11204 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11205 Init->getType() == Context.UnknownAnyTy) { 11206 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11207 if (Result.isInvalid()) { 11208 VDecl->setInvalidDecl(); 11209 return; 11210 } 11211 Init = Result.get(); 11212 } 11213 11214 // Perform the initialization. 11215 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11216 if (!VDecl->isInvalidDecl()) { 11217 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11218 InitializationKind Kind = InitializationKind::CreateForInit( 11219 VDecl->getLocation(), DirectInit, Init); 11220 11221 MultiExprArg Args = Init; 11222 if (CXXDirectInit) 11223 Args = MultiExprArg(CXXDirectInit->getExprs(), 11224 CXXDirectInit->getNumExprs()); 11225 11226 // Try to correct any TypoExprs in the initialization arguments. 11227 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11228 ExprResult Res = CorrectDelayedTyposInExpr( 11229 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11230 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11231 return Init.Failed() ? ExprError() : E; 11232 }); 11233 if (Res.isInvalid()) { 11234 VDecl->setInvalidDecl(); 11235 } else if (Res.get() != Args[Idx]) { 11236 Args[Idx] = Res.get(); 11237 } 11238 } 11239 if (VDecl->isInvalidDecl()) 11240 return; 11241 11242 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11243 /*TopLevelOfInitList=*/false, 11244 /*TreatUnavailableAsInvalid=*/false); 11245 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11246 if (Result.isInvalid()) { 11247 VDecl->setInvalidDecl(); 11248 return; 11249 } 11250 11251 Init = Result.getAs<Expr>(); 11252 } 11253 11254 // Check for self-references within variable initializers. 11255 // Variables declared within a function/method body (except for references) 11256 // are handled by a dataflow analysis. 11257 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11258 VDecl->getType()->isReferenceType()) { 11259 CheckSelfReference(*this, RealDecl, Init, DirectInit); 11260 } 11261 11262 // If the type changed, it means we had an incomplete type that was 11263 // completed by the initializer. For example: 11264 // int ary[] = { 1, 3, 5 }; 11265 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 11266 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 11267 VDecl->setType(DclT); 11268 11269 if (!VDecl->isInvalidDecl()) { 11270 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 11271 11272 if (VDecl->hasAttr<BlocksAttr>()) 11273 checkRetainCycles(VDecl, Init); 11274 11275 // It is safe to assign a weak reference into a strong variable. 11276 // Although this code can still have problems: 11277 // id x = self.weakProp; 11278 // id y = self.weakProp; 11279 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11280 // paths through the function. This should be revisited if 11281 // -Wrepeated-use-of-weak is made flow-sensitive. 11282 if (FunctionScopeInfo *FSI = getCurFunction()) 11283 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 11284 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 11285 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11286 Init->getBeginLoc())) 11287 FSI->markSafeWeakUse(Init); 11288 } 11289 11290 // The initialization is usually a full-expression. 11291 // 11292 // FIXME: If this is a braced initialization of an aggregate, it is not 11293 // an expression, and each individual field initializer is a separate 11294 // full-expression. For instance, in: 11295 // 11296 // struct Temp { ~Temp(); }; 11297 // struct S { S(Temp); }; 11298 // struct T { S a, b; } t = { Temp(), Temp() } 11299 // 11300 // we should destroy the first Temp before constructing the second. 11301 ExprResult Result = 11302 ActOnFinishFullExpr(Init, VDecl->getLocation(), 11303 /*DiscardedValue*/ false, VDecl->isConstexpr()); 11304 if (Result.isInvalid()) { 11305 VDecl->setInvalidDecl(); 11306 return; 11307 } 11308 Init = Result.get(); 11309 11310 // Attach the initializer to the decl. 11311 VDecl->setInit(Init); 11312 11313 if (VDecl->isLocalVarDecl()) { 11314 // Don't check the initializer if the declaration is malformed. 11315 if (VDecl->isInvalidDecl()) { 11316 // do nothing 11317 11318 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 11319 // This is true even in OpenCL C++. 11320 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 11321 CheckForConstantInitializer(Init, DclT); 11322 11323 // Otherwise, C++ does not restrict the initializer. 11324 } else if (getLangOpts().CPlusPlus) { 11325 // do nothing 11326 11327 // C99 6.7.8p4: All the expressions in an initializer for an object that has 11328 // static storage duration shall be constant expressions or string literals. 11329 } else if (VDecl->getStorageClass() == SC_Static) { 11330 CheckForConstantInitializer(Init, DclT); 11331 11332 // C89 is stricter than C99 for aggregate initializers. 11333 // C89 6.5.7p3: All the expressions [...] in an initializer list 11334 // for an object that has aggregate or union type shall be 11335 // constant expressions. 11336 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 11337 isa<InitListExpr>(Init)) { 11338 const Expr *Culprit; 11339 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 11340 Diag(Culprit->getExprLoc(), 11341 diag::ext_aggregate_init_not_constant) 11342 << Culprit->getSourceRange(); 11343 } 11344 } 11345 11346 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 11347 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 11348 if (VDecl->hasLocalStorage()) 11349 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 11350 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 11351 VDecl->getLexicalDeclContext()->isRecord()) { 11352 // This is an in-class initialization for a static data member, e.g., 11353 // 11354 // struct S { 11355 // static const int value = 17; 11356 // }; 11357 11358 // C++ [class.mem]p4: 11359 // A member-declarator can contain a constant-initializer only 11360 // if it declares a static member (9.4) of const integral or 11361 // const enumeration type, see 9.4.2. 11362 // 11363 // C++11 [class.static.data]p3: 11364 // If a non-volatile non-inline const static data member is of integral 11365 // or enumeration type, its declaration in the class definition can 11366 // specify a brace-or-equal-initializer in which every initializer-clause 11367 // that is an assignment-expression is a constant expression. A static 11368 // data member of literal type can be declared in the class definition 11369 // with the constexpr specifier; if so, its declaration shall specify a 11370 // brace-or-equal-initializer in which every initializer-clause that is 11371 // an assignment-expression is a constant expression. 11372 11373 // Do nothing on dependent types. 11374 if (DclT->isDependentType()) { 11375 11376 // Allow any 'static constexpr' members, whether or not they are of literal 11377 // type. We separately check that every constexpr variable is of literal 11378 // type. 11379 } else if (VDecl->isConstexpr()) { 11380 11381 // Require constness. 11382 } else if (!DclT.isConstQualified()) { 11383 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 11384 << Init->getSourceRange(); 11385 VDecl->setInvalidDecl(); 11386 11387 // We allow integer constant expressions in all cases. 11388 } else if (DclT->isIntegralOrEnumerationType()) { 11389 // Check whether the expression is a constant expression. 11390 SourceLocation Loc; 11391 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 11392 // In C++11, a non-constexpr const static data member with an 11393 // in-class initializer cannot be volatile. 11394 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 11395 else if (Init->isValueDependent()) 11396 ; // Nothing to check. 11397 else if (Init->isIntegerConstantExpr(Context, &Loc)) 11398 ; // Ok, it's an ICE! 11399 else if (Init->getType()->isScopedEnumeralType() && 11400 Init->isCXX11ConstantExpr(Context)) 11401 ; // Ok, it is a scoped-enum constant expression. 11402 else if (Init->isEvaluatable(Context)) { 11403 // If we can constant fold the initializer through heroics, accept it, 11404 // but report this as a use of an extension for -pedantic. 11405 Diag(Loc, diag::ext_in_class_initializer_non_constant) 11406 << Init->getSourceRange(); 11407 } else { 11408 // Otherwise, this is some crazy unknown case. Report the issue at the 11409 // location provided by the isIntegerConstantExpr failed check. 11410 Diag(Loc, diag::err_in_class_initializer_non_constant) 11411 << Init->getSourceRange(); 11412 VDecl->setInvalidDecl(); 11413 } 11414 11415 // We allow foldable floating-point constants as an extension. 11416 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 11417 // In C++98, this is a GNU extension. In C++11, it is not, but we support 11418 // it anyway and provide a fixit to add the 'constexpr'. 11419 if (getLangOpts().CPlusPlus11) { 11420 Diag(VDecl->getLocation(), 11421 diag::ext_in_class_initializer_float_type_cxx11) 11422 << DclT << Init->getSourceRange(); 11423 Diag(VDecl->getBeginLoc(), 11424 diag::note_in_class_initializer_float_type_cxx11) 11425 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11426 } else { 11427 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 11428 << DclT << Init->getSourceRange(); 11429 11430 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 11431 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 11432 << Init->getSourceRange(); 11433 VDecl->setInvalidDecl(); 11434 } 11435 } 11436 11437 // Suggest adding 'constexpr' in C++11 for literal types. 11438 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 11439 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 11440 << DclT << Init->getSourceRange() 11441 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11442 VDecl->setConstexpr(true); 11443 11444 } else { 11445 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 11446 << DclT << Init->getSourceRange(); 11447 VDecl->setInvalidDecl(); 11448 } 11449 } else if (VDecl->isFileVarDecl()) { 11450 // In C, extern is typically used to avoid tentative definitions when 11451 // declaring variables in headers, but adding an intializer makes it a 11452 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 11453 // In C++, extern is often used to give implictly static const variables 11454 // external linkage, so don't warn in that case. If selectany is present, 11455 // this might be header code intended for C and C++ inclusion, so apply the 11456 // C++ rules. 11457 if (VDecl->getStorageClass() == SC_Extern && 11458 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 11459 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 11460 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 11461 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 11462 Diag(VDecl->getLocation(), diag::warn_extern_init); 11463 11464 // In Microsoft C++ mode, a const variable defined in namespace scope has 11465 // external linkage by default if the variable is declared with 11466 // __declspec(dllexport). 11467 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 11468 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 11469 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 11470 VDecl->setStorageClass(SC_Extern); 11471 11472 // C99 6.7.8p4. All file scoped initializers need to be constant. 11473 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 11474 CheckForConstantInitializer(Init, DclT); 11475 } 11476 11477 // We will represent direct-initialization similarly to copy-initialization: 11478 // int x(1); -as-> int x = 1; 11479 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 11480 // 11481 // Clients that want to distinguish between the two forms, can check for 11482 // direct initializer using VarDecl::getInitStyle(). 11483 // A major benefit is that clients that don't particularly care about which 11484 // exactly form was it (like the CodeGen) can handle both cases without 11485 // special case code. 11486 11487 // C++ 8.5p11: 11488 // The form of initialization (using parentheses or '=') is generally 11489 // insignificant, but does matter when the entity being initialized has a 11490 // class type. 11491 if (CXXDirectInit) { 11492 assert(DirectInit && "Call-style initializer must be direct init."); 11493 VDecl->setInitStyle(VarDecl::CallInit); 11494 } else if (DirectInit) { 11495 // This must be list-initialization. No other way is direct-initialization. 11496 VDecl->setInitStyle(VarDecl::ListInit); 11497 } 11498 11499 CheckCompleteVariableDeclaration(VDecl); 11500 } 11501 11502 /// ActOnInitializerError - Given that there was an error parsing an 11503 /// initializer for the given declaration, try to return to some form 11504 /// of sanity. 11505 void Sema::ActOnInitializerError(Decl *D) { 11506 // Our main concern here is re-establishing invariants like "a 11507 // variable's type is either dependent or complete". 11508 if (!D || D->isInvalidDecl()) return; 11509 11510 VarDecl *VD = dyn_cast<VarDecl>(D); 11511 if (!VD) return; 11512 11513 // Bindings are not usable if we can't make sense of the initializer. 11514 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11515 for (auto *BD : DD->bindings()) 11516 BD->setInvalidDecl(); 11517 11518 // Auto types are meaningless if we can't make sense of the initializer. 11519 if (ParsingInitForAutoVars.count(D)) { 11520 D->setInvalidDecl(); 11521 return; 11522 } 11523 11524 QualType Ty = VD->getType(); 11525 if (Ty->isDependentType()) return; 11526 11527 // Require a complete type. 11528 if (RequireCompleteType(VD->getLocation(), 11529 Context.getBaseElementType(Ty), 11530 diag::err_typecheck_decl_incomplete_type)) { 11531 VD->setInvalidDecl(); 11532 return; 11533 } 11534 11535 // Require a non-abstract type. 11536 if (RequireNonAbstractType(VD->getLocation(), Ty, 11537 diag::err_abstract_type_in_decl, 11538 AbstractVariableType)) { 11539 VD->setInvalidDecl(); 11540 return; 11541 } 11542 11543 // Don't bother complaining about constructors or destructors, 11544 // though. 11545 } 11546 11547 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11548 // If there is no declaration, there was an error parsing it. Just ignore it. 11549 if (!RealDecl) 11550 return; 11551 11552 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11553 QualType Type = Var->getType(); 11554 11555 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11556 if (isa<DecompositionDecl>(RealDecl)) { 11557 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11558 Var->setInvalidDecl(); 11559 return; 11560 } 11561 11562 if (Type->isUndeducedType() && 11563 DeduceVariableDeclarationType(Var, false, nullptr)) 11564 return; 11565 11566 // C++11 [class.static.data]p3: A static data member can be declared with 11567 // the constexpr specifier; if so, its declaration shall specify 11568 // a brace-or-equal-initializer. 11569 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11570 // the definition of a variable [...] or the declaration of a static data 11571 // member. 11572 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11573 !Var->isThisDeclarationADemotedDefinition()) { 11574 if (Var->isStaticDataMember()) { 11575 // C++1z removes the relevant rule; the in-class declaration is always 11576 // a definition there. 11577 if (!getLangOpts().CPlusPlus17) { 11578 Diag(Var->getLocation(), 11579 diag::err_constexpr_static_mem_var_requires_init) 11580 << Var->getDeclName(); 11581 Var->setInvalidDecl(); 11582 return; 11583 } 11584 } else { 11585 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11586 Var->setInvalidDecl(); 11587 return; 11588 } 11589 } 11590 11591 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11592 // be initialized. 11593 if (!Var->isInvalidDecl() && 11594 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11595 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11596 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11597 Var->setInvalidDecl(); 11598 return; 11599 } 11600 11601 switch (Var->isThisDeclarationADefinition()) { 11602 case VarDecl::Definition: 11603 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11604 break; 11605 11606 // We have an out-of-line definition of a static data member 11607 // that has an in-class initializer, so we type-check this like 11608 // a declaration. 11609 // 11610 LLVM_FALLTHROUGH; 11611 11612 case VarDecl::DeclarationOnly: 11613 // It's only a declaration. 11614 11615 // Block scope. C99 6.7p7: If an identifier for an object is 11616 // declared with no linkage (C99 6.2.2p6), the type for the 11617 // object shall be complete. 11618 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11619 !Var->hasLinkage() && !Var->isInvalidDecl() && 11620 RequireCompleteType(Var->getLocation(), Type, 11621 diag::err_typecheck_decl_incomplete_type)) 11622 Var->setInvalidDecl(); 11623 11624 // Make sure that the type is not abstract. 11625 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11626 RequireNonAbstractType(Var->getLocation(), Type, 11627 diag::err_abstract_type_in_decl, 11628 AbstractVariableType)) 11629 Var->setInvalidDecl(); 11630 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11631 Var->getStorageClass() == SC_PrivateExtern) { 11632 Diag(Var->getLocation(), diag::warn_private_extern); 11633 Diag(Var->getLocation(), diag::note_private_extern); 11634 } 11635 11636 return; 11637 11638 case VarDecl::TentativeDefinition: 11639 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11640 // object that has file scope without an initializer, and without a 11641 // storage-class specifier or with the storage-class specifier "static", 11642 // constitutes a tentative definition. Note: A tentative definition with 11643 // external linkage is valid (C99 6.2.2p5). 11644 if (!Var->isInvalidDecl()) { 11645 if (const IncompleteArrayType *ArrayT 11646 = Context.getAsIncompleteArrayType(Type)) { 11647 if (RequireCompleteType(Var->getLocation(), 11648 ArrayT->getElementType(), 11649 diag::err_illegal_decl_array_incomplete_type)) 11650 Var->setInvalidDecl(); 11651 } else if (Var->getStorageClass() == SC_Static) { 11652 // C99 6.9.2p3: If the declaration of an identifier for an object is 11653 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11654 // declared type shall not be an incomplete type. 11655 // NOTE: code such as the following 11656 // static struct s; 11657 // struct s { int a; }; 11658 // is accepted by gcc. Hence here we issue a warning instead of 11659 // an error and we do not invalidate the static declaration. 11660 // NOTE: to avoid multiple warnings, only check the first declaration. 11661 if (Var->isFirstDecl()) 11662 RequireCompleteType(Var->getLocation(), Type, 11663 diag::ext_typecheck_decl_incomplete_type); 11664 } 11665 } 11666 11667 // Record the tentative definition; we're done. 11668 if (!Var->isInvalidDecl()) 11669 TentativeDefinitions.push_back(Var); 11670 return; 11671 } 11672 11673 // Provide a specific diagnostic for uninitialized variable 11674 // definitions with incomplete array type. 11675 if (Type->isIncompleteArrayType()) { 11676 Diag(Var->getLocation(), 11677 diag::err_typecheck_incomplete_array_needs_initializer); 11678 Var->setInvalidDecl(); 11679 return; 11680 } 11681 11682 // Provide a specific diagnostic for uninitialized variable 11683 // definitions with reference type. 11684 if (Type->isReferenceType()) { 11685 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11686 << Var->getDeclName() 11687 << SourceRange(Var->getLocation(), Var->getLocation()); 11688 Var->setInvalidDecl(); 11689 return; 11690 } 11691 11692 // Do not attempt to type-check the default initializer for a 11693 // variable with dependent type. 11694 if (Type->isDependentType()) 11695 return; 11696 11697 if (Var->isInvalidDecl()) 11698 return; 11699 11700 if (!Var->hasAttr<AliasAttr>()) { 11701 if (RequireCompleteType(Var->getLocation(), 11702 Context.getBaseElementType(Type), 11703 diag::err_typecheck_decl_incomplete_type)) { 11704 Var->setInvalidDecl(); 11705 return; 11706 } 11707 } else { 11708 return; 11709 } 11710 11711 // The variable can not have an abstract class type. 11712 if (RequireNonAbstractType(Var->getLocation(), Type, 11713 diag::err_abstract_type_in_decl, 11714 AbstractVariableType)) { 11715 Var->setInvalidDecl(); 11716 return; 11717 } 11718 11719 // Check for jumps past the implicit initializer. C++0x 11720 // clarifies that this applies to a "variable with automatic 11721 // storage duration", not a "local variable". 11722 // C++11 [stmt.dcl]p3 11723 // A program that jumps from a point where a variable with automatic 11724 // storage duration is not in scope to a point where it is in scope is 11725 // ill-formed unless the variable has scalar type, class type with a 11726 // trivial default constructor and a trivial destructor, a cv-qualified 11727 // version of one of these types, or an array of one of the preceding 11728 // types and is declared without an initializer. 11729 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11730 if (const RecordType *Record 11731 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11732 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11733 // Mark the function (if we're in one) for further checking even if the 11734 // looser rules of C++11 do not require such checks, so that we can 11735 // diagnose incompatibilities with C++98. 11736 if (!CXXRecord->isPOD()) 11737 setFunctionHasBranchProtectedScope(); 11738 } 11739 } 11740 // In OpenCL, we can't initialize objects in the __local address space, 11741 // even implicitly, so don't synthesize an implicit initializer. 11742 if (getLangOpts().OpenCL && 11743 Var->getType().getAddressSpace() == LangAS::opencl_local) 11744 return; 11745 // C++03 [dcl.init]p9: 11746 // If no initializer is specified for an object, and the 11747 // object is of (possibly cv-qualified) non-POD class type (or 11748 // array thereof), the object shall be default-initialized; if 11749 // the object is of const-qualified type, the underlying class 11750 // type shall have a user-declared default 11751 // constructor. Otherwise, if no initializer is specified for 11752 // a non- static object, the object and its subobjects, if 11753 // any, have an indeterminate initial value); if the object 11754 // or any of its subobjects are of const-qualified type, the 11755 // program is ill-formed. 11756 // C++0x [dcl.init]p11: 11757 // If no initializer is specified for an object, the object is 11758 // default-initialized; [...]. 11759 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11760 InitializationKind Kind 11761 = InitializationKind::CreateDefault(Var->getLocation()); 11762 11763 InitializationSequence InitSeq(*this, Entity, Kind, None); 11764 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11765 if (Init.isInvalid()) 11766 Var->setInvalidDecl(); 11767 else if (Init.get()) { 11768 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11769 // This is important for template substitution. 11770 Var->setInitStyle(VarDecl::CallInit); 11771 } 11772 11773 CheckCompleteVariableDeclaration(Var); 11774 } 11775 } 11776 11777 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11778 // If there is no declaration, there was an error parsing it. Ignore it. 11779 if (!D) 11780 return; 11781 11782 VarDecl *VD = dyn_cast<VarDecl>(D); 11783 if (!VD) { 11784 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11785 D->setInvalidDecl(); 11786 return; 11787 } 11788 11789 VD->setCXXForRangeDecl(true); 11790 11791 // for-range-declaration cannot be given a storage class specifier. 11792 int Error = -1; 11793 switch (VD->getStorageClass()) { 11794 case SC_None: 11795 break; 11796 case SC_Extern: 11797 Error = 0; 11798 break; 11799 case SC_Static: 11800 Error = 1; 11801 break; 11802 case SC_PrivateExtern: 11803 Error = 2; 11804 break; 11805 case SC_Auto: 11806 Error = 3; 11807 break; 11808 case SC_Register: 11809 Error = 4; 11810 break; 11811 } 11812 if (Error != -1) { 11813 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11814 << VD->getDeclName() << Error; 11815 D->setInvalidDecl(); 11816 } 11817 } 11818 11819 StmtResult 11820 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11821 IdentifierInfo *Ident, 11822 ParsedAttributes &Attrs, 11823 SourceLocation AttrEnd) { 11824 // C++1y [stmt.iter]p1: 11825 // A range-based for statement of the form 11826 // for ( for-range-identifier : for-range-initializer ) statement 11827 // is equivalent to 11828 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11829 DeclSpec DS(Attrs.getPool().getFactory()); 11830 11831 const char *PrevSpec; 11832 unsigned DiagID; 11833 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11834 getPrintingPolicy()); 11835 11836 Declarator D(DS, DeclaratorContext::ForContext); 11837 D.SetIdentifier(Ident, IdentLoc); 11838 D.takeAttributes(Attrs, AttrEnd); 11839 11840 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 11841 IdentLoc); 11842 Decl *Var = ActOnDeclarator(S, D); 11843 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11844 FinalizeDeclaration(Var); 11845 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11846 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11847 } 11848 11849 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11850 if (var->isInvalidDecl()) return; 11851 11852 if (getLangOpts().OpenCL) { 11853 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11854 // initialiser 11855 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11856 !var->hasInit()) { 11857 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11858 << 1 /*Init*/; 11859 var->setInvalidDecl(); 11860 return; 11861 } 11862 } 11863 11864 // In Objective-C, don't allow jumps past the implicit initialization of a 11865 // local retaining variable. 11866 if (getLangOpts().ObjC && 11867 var->hasLocalStorage()) { 11868 switch (var->getType().getObjCLifetime()) { 11869 case Qualifiers::OCL_None: 11870 case Qualifiers::OCL_ExplicitNone: 11871 case Qualifiers::OCL_Autoreleasing: 11872 break; 11873 11874 case Qualifiers::OCL_Weak: 11875 case Qualifiers::OCL_Strong: 11876 setFunctionHasBranchProtectedScope(); 11877 break; 11878 } 11879 } 11880 11881 if (var->hasLocalStorage() && 11882 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11883 setFunctionHasBranchProtectedScope(); 11884 11885 // Warn about externally-visible variables being defined without a 11886 // prior declaration. We only want to do this for global 11887 // declarations, but we also specifically need to avoid doing it for 11888 // class members because the linkage of an anonymous class can 11889 // change if it's later given a typedef name. 11890 if (var->isThisDeclarationADefinition() && 11891 var->getDeclContext()->getRedeclContext()->isFileContext() && 11892 var->isExternallyVisible() && var->hasLinkage() && 11893 !var->isInline() && !var->getDescribedVarTemplate() && 11894 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11895 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11896 var->getLocation())) { 11897 // Find a previous declaration that's not a definition. 11898 VarDecl *prev = var->getPreviousDecl(); 11899 while (prev && prev->isThisDeclarationADefinition()) 11900 prev = prev->getPreviousDecl(); 11901 11902 if (!prev) { 11903 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11904 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 11905 << /* variable */ 0; 11906 } 11907 } 11908 11909 // Cache the result of checking for constant initialization. 11910 Optional<bool> CacheHasConstInit; 11911 const Expr *CacheCulprit; 11912 auto checkConstInit = [&]() mutable { 11913 if (!CacheHasConstInit) 11914 CacheHasConstInit = var->getInit()->isConstantInitializer( 11915 Context, var->getType()->isReferenceType(), &CacheCulprit); 11916 return *CacheHasConstInit; 11917 }; 11918 11919 if (var->getTLSKind() == VarDecl::TLS_Static) { 11920 if (var->getType().isDestructedType()) { 11921 // GNU C++98 edits for __thread, [basic.start.term]p3: 11922 // The type of an object with thread storage duration shall not 11923 // have a non-trivial destructor. 11924 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11925 if (getLangOpts().CPlusPlus11) 11926 Diag(var->getLocation(), diag::note_use_thread_local); 11927 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11928 if (!checkConstInit()) { 11929 // GNU C++98 edits for __thread, [basic.start.init]p4: 11930 // An object of thread storage duration shall not require dynamic 11931 // initialization. 11932 // FIXME: Need strict checking here. 11933 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11934 << CacheCulprit->getSourceRange(); 11935 if (getLangOpts().CPlusPlus11) 11936 Diag(var->getLocation(), diag::note_use_thread_local); 11937 } 11938 } 11939 } 11940 11941 // Apply section attributes and pragmas to global variables. 11942 bool GlobalStorage = var->hasGlobalStorage(); 11943 if (GlobalStorage && var->isThisDeclarationADefinition() && 11944 !inTemplateInstantiation()) { 11945 PragmaStack<StringLiteral *> *Stack = nullptr; 11946 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11947 if (var->getType().isConstQualified()) 11948 Stack = &ConstSegStack; 11949 else if (!var->getInit()) { 11950 Stack = &BSSSegStack; 11951 SectionFlags |= ASTContext::PSF_Write; 11952 } else { 11953 Stack = &DataSegStack; 11954 SectionFlags |= ASTContext::PSF_Write; 11955 } 11956 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11957 var->addAttr(SectionAttr::CreateImplicit( 11958 Context, SectionAttr::Declspec_allocate, 11959 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11960 } 11961 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11962 if (UnifySection(SA->getName(), SectionFlags, var)) 11963 var->dropAttr<SectionAttr>(); 11964 11965 // Apply the init_seg attribute if this has an initializer. If the 11966 // initializer turns out to not be dynamic, we'll end up ignoring this 11967 // attribute. 11968 if (CurInitSeg && var->getInit()) 11969 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11970 CurInitSegLoc)); 11971 } 11972 11973 // All the following checks are C++ only. 11974 if (!getLangOpts().CPlusPlus) { 11975 // If this variable must be emitted, add it as an initializer for the 11976 // current module. 11977 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11978 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11979 return; 11980 } 11981 11982 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11983 CheckCompleteDecompositionDeclaration(DD); 11984 11985 QualType type = var->getType(); 11986 if (type->isDependentType()) return; 11987 11988 if (var->hasAttr<BlocksAttr>()) 11989 getCurFunction()->addByrefBlockVar(var); 11990 11991 Expr *Init = var->getInit(); 11992 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11993 QualType baseType = Context.getBaseElementType(type); 11994 11995 if (Init && !Init->isValueDependent()) { 11996 if (var->isConstexpr()) { 11997 SmallVector<PartialDiagnosticAt, 8> Notes; 11998 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11999 SourceLocation DiagLoc = var->getLocation(); 12000 // If the note doesn't add any useful information other than a source 12001 // location, fold it into the primary diagnostic. 12002 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12003 diag::note_invalid_subexpr_in_const_expr) { 12004 DiagLoc = Notes[0].first; 12005 Notes.clear(); 12006 } 12007 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12008 << var << Init->getSourceRange(); 12009 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12010 Diag(Notes[I].first, Notes[I].second); 12011 } 12012 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12013 // Check whether the initializer of a const variable of integral or 12014 // enumeration type is an ICE now, since we can't tell whether it was 12015 // initialized by a constant expression if we check later. 12016 var->checkInitIsICE(); 12017 } 12018 12019 // Don't emit further diagnostics about constexpr globals since they 12020 // were just diagnosed. 12021 if (!var->isConstexpr() && GlobalStorage && 12022 var->hasAttr<RequireConstantInitAttr>()) { 12023 // FIXME: Need strict checking in C++03 here. 12024 bool DiagErr = getLangOpts().CPlusPlus11 12025 ? !var->checkInitIsICE() : !checkConstInit(); 12026 if (DiagErr) { 12027 auto attr = var->getAttr<RequireConstantInitAttr>(); 12028 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12029 << Init->getSourceRange(); 12030 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 12031 << attr->getRange(); 12032 if (getLangOpts().CPlusPlus11) { 12033 APValue Value; 12034 SmallVector<PartialDiagnosticAt, 8> Notes; 12035 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12036 for (auto &it : Notes) 12037 Diag(it.first, it.second); 12038 } else { 12039 Diag(CacheCulprit->getExprLoc(), 12040 diag::note_invalid_subexpr_in_const_expr) 12041 << CacheCulprit->getSourceRange(); 12042 } 12043 } 12044 } 12045 else if (!var->isConstexpr() && IsGlobal && 12046 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12047 var->getLocation())) { 12048 // Warn about globals which don't have a constant initializer. Don't 12049 // warn about globals with a non-trivial destructor because we already 12050 // warned about them. 12051 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12052 if (!(RD && !RD->hasTrivialDestructor())) { 12053 if (!checkConstInit()) 12054 Diag(var->getLocation(), diag::warn_global_constructor) 12055 << Init->getSourceRange(); 12056 } 12057 } 12058 } 12059 12060 // Require the destructor. 12061 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12062 FinalizeVarWithDestructor(var, recordType); 12063 12064 // If this variable must be emitted, add it as an initializer for the current 12065 // module. 12066 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12067 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12068 } 12069 12070 /// Determines if a variable's alignment is dependent. 12071 static bool hasDependentAlignment(VarDecl *VD) { 12072 if (VD->getType()->isDependentType()) 12073 return true; 12074 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12075 if (I->isAlignmentDependent()) 12076 return true; 12077 return false; 12078 } 12079 12080 /// Check if VD needs to be dllexport/dllimport due to being in a 12081 /// dllexport/import function. 12082 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12083 assert(VD->isStaticLocal()); 12084 12085 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12086 12087 // Find outermost function when VD is in lambda function. 12088 while (FD && !getDLLAttr(FD) && 12089 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12090 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12091 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12092 } 12093 12094 if (!FD) 12095 return; 12096 12097 // Static locals inherit dll attributes from their function. 12098 if (Attr *A = getDLLAttr(FD)) { 12099 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12100 NewAttr->setInherited(true); 12101 VD->addAttr(NewAttr); 12102 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12103 auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(), 12104 getASTContext(), 12105 A->getSpellingListIndex()); 12106 NewAttr->setInherited(true); 12107 VD->addAttr(NewAttr); 12108 12109 // Export this function to enforce exporting this static variable even 12110 // if it is not used in this compilation unit. 12111 if (!FD->hasAttr<DLLExportAttr>()) 12112 FD->addAttr(NewAttr); 12113 12114 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12115 auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(), 12116 getASTContext(), 12117 A->getSpellingListIndex()); 12118 NewAttr->setInherited(true); 12119 VD->addAttr(NewAttr); 12120 } 12121 } 12122 12123 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12124 /// any semantic actions necessary after any initializer has been attached. 12125 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12126 // Note that we are no longer parsing the initializer for this declaration. 12127 ParsingInitForAutoVars.erase(ThisDecl); 12128 12129 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12130 if (!VD) 12131 return; 12132 12133 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12134 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12135 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12136 if (PragmaClangBSSSection.Valid) 12137 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 12138 PragmaClangBSSSection.SectionName, 12139 PragmaClangBSSSection.PragmaLocation)); 12140 if (PragmaClangDataSection.Valid) 12141 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 12142 PragmaClangDataSection.SectionName, 12143 PragmaClangDataSection.PragmaLocation)); 12144 if (PragmaClangRodataSection.Valid) 12145 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 12146 PragmaClangRodataSection.SectionName, 12147 PragmaClangRodataSection.PragmaLocation)); 12148 } 12149 12150 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12151 for (auto *BD : DD->bindings()) { 12152 FinalizeDeclaration(BD); 12153 } 12154 } 12155 12156 checkAttributesAfterMerging(*this, *VD); 12157 12158 // Perform TLS alignment check here after attributes attached to the variable 12159 // which may affect the alignment have been processed. Only perform the check 12160 // if the target has a maximum TLS alignment (zero means no constraints). 12161 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12162 // Protect the check so that it's not performed on dependent types and 12163 // dependent alignments (we can't determine the alignment in that case). 12164 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12165 !VD->isInvalidDecl()) { 12166 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12167 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12168 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12169 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12170 << (unsigned)MaxAlignChars.getQuantity(); 12171 } 12172 } 12173 } 12174 12175 if (VD->isStaticLocal()) { 12176 CheckStaticLocalForDllExport(VD); 12177 12178 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12179 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12180 // function, only __shared__ variables or variables without any device 12181 // memory qualifiers may be declared with static storage class. 12182 // Note: It is unclear how a function-scope non-const static variable 12183 // without device memory qualifier is implemented, therefore only static 12184 // const variable without device memory qualifier is allowed. 12185 [&]() { 12186 if (!getLangOpts().CUDA) 12187 return; 12188 if (VD->hasAttr<CUDASharedAttr>()) 12189 return; 12190 if (VD->getType().isConstQualified() && 12191 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12192 return; 12193 if (CUDADiagIfDeviceCode(VD->getLocation(), 12194 diag::err_device_static_local_var) 12195 << CurrentCUDATarget()) 12196 VD->setInvalidDecl(); 12197 }(); 12198 } 12199 } 12200 12201 // Perform check for initializers of device-side global variables. 12202 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12203 // 7.5). We must also apply the same checks to all __shared__ 12204 // variables whether they are local or not. CUDA also allows 12205 // constant initializers for __constant__ and __device__ variables. 12206 if (getLangOpts().CUDA) 12207 checkAllowedCUDAInitializer(VD); 12208 12209 // Grab the dllimport or dllexport attribute off of the VarDecl. 12210 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12211 12212 // Imported static data members cannot be defined out-of-line. 12213 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12214 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12215 VD->isThisDeclarationADefinition()) { 12216 // We allow definitions of dllimport class template static data members 12217 // with a warning. 12218 CXXRecordDecl *Context = 12219 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12220 bool IsClassTemplateMember = 12221 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12222 Context->getDescribedClassTemplate(); 12223 12224 Diag(VD->getLocation(), 12225 IsClassTemplateMember 12226 ? diag::warn_attribute_dllimport_static_field_definition 12227 : diag::err_attribute_dllimport_static_field_definition); 12228 Diag(IA->getLocation(), diag::note_attribute); 12229 if (!IsClassTemplateMember) 12230 VD->setInvalidDecl(); 12231 } 12232 } 12233 12234 // dllimport/dllexport variables cannot be thread local, their TLS index 12235 // isn't exported with the variable. 12236 if (DLLAttr && VD->getTLSKind()) { 12237 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12238 if (F && getDLLAttr(F)) { 12239 assert(VD->isStaticLocal()); 12240 // But if this is a static local in a dlimport/dllexport function, the 12241 // function will never be inlined, which means the var would never be 12242 // imported, so having it marked import/export is safe. 12243 } else { 12244 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 12245 << DLLAttr; 12246 VD->setInvalidDecl(); 12247 } 12248 } 12249 12250 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 12251 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 12252 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 12253 VD->dropAttr<UsedAttr>(); 12254 } 12255 } 12256 12257 const DeclContext *DC = VD->getDeclContext(); 12258 // If there's a #pragma GCC visibility in scope, and this isn't a class 12259 // member, set the visibility of this variable. 12260 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 12261 AddPushedVisibilityAttribute(VD); 12262 12263 // FIXME: Warn on unused var template partial specializations. 12264 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 12265 MarkUnusedFileScopedDecl(VD); 12266 12267 // Now we have parsed the initializer and can update the table of magic 12268 // tag values. 12269 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 12270 !VD->getType()->isIntegralOrEnumerationType()) 12271 return; 12272 12273 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 12274 const Expr *MagicValueExpr = VD->getInit(); 12275 if (!MagicValueExpr) { 12276 continue; 12277 } 12278 llvm::APSInt MagicValueInt; 12279 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 12280 Diag(I->getRange().getBegin(), 12281 diag::err_type_tag_for_datatype_not_ice) 12282 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12283 continue; 12284 } 12285 if (MagicValueInt.getActiveBits() > 64) { 12286 Diag(I->getRange().getBegin(), 12287 diag::err_type_tag_for_datatype_too_large) 12288 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12289 continue; 12290 } 12291 uint64_t MagicValue = MagicValueInt.getZExtValue(); 12292 RegisterTypeTagForDatatype(I->getArgumentKind(), 12293 MagicValue, 12294 I->getMatchingCType(), 12295 I->getLayoutCompatible(), 12296 I->getMustBeNull()); 12297 } 12298 } 12299 12300 static bool hasDeducedAuto(DeclaratorDecl *DD) { 12301 auto *VD = dyn_cast<VarDecl>(DD); 12302 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 12303 } 12304 12305 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 12306 ArrayRef<Decl *> Group) { 12307 SmallVector<Decl*, 8> Decls; 12308 12309 if (DS.isTypeSpecOwned()) 12310 Decls.push_back(DS.getRepAsDecl()); 12311 12312 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 12313 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 12314 bool DiagnosedMultipleDecomps = false; 12315 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 12316 bool DiagnosedNonDeducedAuto = false; 12317 12318 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12319 if (Decl *D = Group[i]) { 12320 // For declarators, there are some additional syntactic-ish checks we need 12321 // to perform. 12322 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 12323 if (!FirstDeclaratorInGroup) 12324 FirstDeclaratorInGroup = DD; 12325 if (!FirstDecompDeclaratorInGroup) 12326 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 12327 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 12328 !hasDeducedAuto(DD)) 12329 FirstNonDeducedAutoInGroup = DD; 12330 12331 if (FirstDeclaratorInGroup != DD) { 12332 // A decomposition declaration cannot be combined with any other 12333 // declaration in the same group. 12334 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 12335 Diag(FirstDecompDeclaratorInGroup->getLocation(), 12336 diag::err_decomp_decl_not_alone) 12337 << FirstDeclaratorInGroup->getSourceRange() 12338 << DD->getSourceRange(); 12339 DiagnosedMultipleDecomps = true; 12340 } 12341 12342 // A declarator that uses 'auto' in any way other than to declare a 12343 // variable with a deduced type cannot be combined with any other 12344 // declarator in the same group. 12345 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 12346 Diag(FirstNonDeducedAutoInGroup->getLocation(), 12347 diag::err_auto_non_deduced_not_alone) 12348 << FirstNonDeducedAutoInGroup->getType() 12349 ->hasAutoForTrailingReturnType() 12350 << FirstDeclaratorInGroup->getSourceRange() 12351 << DD->getSourceRange(); 12352 DiagnosedNonDeducedAuto = true; 12353 } 12354 } 12355 } 12356 12357 Decls.push_back(D); 12358 } 12359 } 12360 12361 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 12362 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 12363 handleTagNumbering(Tag, S); 12364 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 12365 getLangOpts().CPlusPlus) 12366 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 12367 } 12368 } 12369 12370 return BuildDeclaratorGroup(Decls); 12371 } 12372 12373 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 12374 /// group, performing any necessary semantic checking. 12375 Sema::DeclGroupPtrTy 12376 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 12377 // C++14 [dcl.spec.auto]p7: (DR1347) 12378 // If the type that replaces the placeholder type is not the same in each 12379 // deduction, the program is ill-formed. 12380 if (Group.size() > 1) { 12381 QualType Deduced; 12382 VarDecl *DeducedDecl = nullptr; 12383 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12384 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 12385 if (!D || D->isInvalidDecl()) 12386 break; 12387 DeducedType *DT = D->getType()->getContainedDeducedType(); 12388 if (!DT || DT->getDeducedType().isNull()) 12389 continue; 12390 if (Deduced.isNull()) { 12391 Deduced = DT->getDeducedType(); 12392 DeducedDecl = D; 12393 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 12394 auto *AT = dyn_cast<AutoType>(DT); 12395 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 12396 diag::err_auto_different_deductions) 12397 << (AT ? (unsigned)AT->getKeyword() : 3) 12398 << Deduced << DeducedDecl->getDeclName() 12399 << DT->getDeducedType() << D->getDeclName() 12400 << DeducedDecl->getInit()->getSourceRange() 12401 << D->getInit()->getSourceRange(); 12402 D->setInvalidDecl(); 12403 break; 12404 } 12405 } 12406 } 12407 12408 ActOnDocumentableDecls(Group); 12409 12410 return DeclGroupPtrTy::make( 12411 DeclGroupRef::Create(Context, Group.data(), Group.size())); 12412 } 12413 12414 void Sema::ActOnDocumentableDecl(Decl *D) { 12415 ActOnDocumentableDecls(D); 12416 } 12417 12418 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 12419 // Don't parse the comment if Doxygen diagnostics are ignored. 12420 if (Group.empty() || !Group[0]) 12421 return; 12422 12423 if (Diags.isIgnored(diag::warn_doc_param_not_found, 12424 Group[0]->getLocation()) && 12425 Diags.isIgnored(diag::warn_unknown_comment_command_name, 12426 Group[0]->getLocation())) 12427 return; 12428 12429 if (Group.size() >= 2) { 12430 // This is a decl group. Normally it will contain only declarations 12431 // produced from declarator list. But in case we have any definitions or 12432 // additional declaration references: 12433 // 'typedef struct S {} S;' 12434 // 'typedef struct S *S;' 12435 // 'struct S *pS;' 12436 // FinalizeDeclaratorGroup adds these as separate declarations. 12437 Decl *MaybeTagDecl = Group[0]; 12438 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 12439 Group = Group.slice(1); 12440 } 12441 } 12442 12443 // See if there are any new comments that are not attached to a decl. 12444 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 12445 if (!Comments.empty() && 12446 !Comments.back()->isAttached()) { 12447 // There is at least one comment that not attached to a decl. 12448 // Maybe it should be attached to one of these decls? 12449 // 12450 // Note that this way we pick up not only comments that precede the 12451 // declaration, but also comments that *follow* the declaration -- thanks to 12452 // the lookahead in the lexer: we've consumed the semicolon and looked 12453 // ahead through comments. 12454 for (unsigned i = 0, e = Group.size(); i != e; ++i) 12455 Context.getCommentForDecl(Group[i], &PP); 12456 } 12457 } 12458 12459 /// Common checks for a parameter-declaration that should apply to both function 12460 /// parameters and non-type template parameters. 12461 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 12462 // Check that there are no default arguments inside the type of this 12463 // parameter. 12464 if (getLangOpts().CPlusPlus) 12465 CheckExtraCXXDefaultArguments(D); 12466 12467 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12468 if (D.getCXXScopeSpec().isSet()) { 12469 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12470 << D.getCXXScopeSpec().getRange(); 12471 } 12472 12473 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 12474 // simple identifier except [...irrelevant cases...]. 12475 switch (D.getName().getKind()) { 12476 case UnqualifiedIdKind::IK_Identifier: 12477 break; 12478 12479 case UnqualifiedIdKind::IK_OperatorFunctionId: 12480 case UnqualifiedIdKind::IK_ConversionFunctionId: 12481 case UnqualifiedIdKind::IK_LiteralOperatorId: 12482 case UnqualifiedIdKind::IK_ConstructorName: 12483 case UnqualifiedIdKind::IK_DestructorName: 12484 case UnqualifiedIdKind::IK_ImplicitSelfParam: 12485 case UnqualifiedIdKind::IK_DeductionGuideName: 12486 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12487 << GetNameForDeclarator(D).getName(); 12488 break; 12489 12490 case UnqualifiedIdKind::IK_TemplateId: 12491 case UnqualifiedIdKind::IK_ConstructorTemplateId: 12492 // GetNameForDeclarator would not produce a useful name in this case. 12493 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 12494 break; 12495 } 12496 } 12497 12498 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 12499 /// to introduce parameters into function prototype scope. 12500 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 12501 const DeclSpec &DS = D.getDeclSpec(); 12502 12503 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 12504 12505 // C++03 [dcl.stc]p2 also permits 'auto'. 12506 StorageClass SC = SC_None; 12507 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 12508 SC = SC_Register; 12509 // In C++11, the 'register' storage class specifier is deprecated. 12510 // In C++17, it is not allowed, but we tolerate it as an extension. 12511 if (getLangOpts().CPlusPlus11) { 12512 Diag(DS.getStorageClassSpecLoc(), 12513 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 12514 : diag::warn_deprecated_register) 12515 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12516 } 12517 } else if (getLangOpts().CPlusPlus && 12518 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 12519 SC = SC_Auto; 12520 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 12521 Diag(DS.getStorageClassSpecLoc(), 12522 diag::err_invalid_storage_class_in_func_decl); 12523 D.getMutableDeclSpec().ClearStorageClassSpecs(); 12524 } 12525 12526 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12527 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12528 << DeclSpec::getSpecifierName(TSCS); 12529 if (DS.isInlineSpecified()) 12530 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12531 << getLangOpts().CPlusPlus17; 12532 if (DS.hasConstexprSpecifier()) 12533 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12534 << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval); 12535 12536 DiagnoseFunctionSpecifiers(DS); 12537 12538 CheckFunctionOrTemplateParamDeclarator(S, D); 12539 12540 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12541 QualType parmDeclType = TInfo->getType(); 12542 12543 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12544 IdentifierInfo *II = D.getIdentifier(); 12545 if (II) { 12546 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12547 ForVisibleRedeclaration); 12548 LookupName(R, S); 12549 if (R.isSingleResult()) { 12550 NamedDecl *PrevDecl = R.getFoundDecl(); 12551 if (PrevDecl->isTemplateParameter()) { 12552 // Maybe we will complain about the shadowed template parameter. 12553 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12554 // Just pretend that we didn't see the previous declaration. 12555 PrevDecl = nullptr; 12556 } else if (S->isDeclScope(PrevDecl)) { 12557 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12558 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12559 12560 // Recover by removing the name 12561 II = nullptr; 12562 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12563 D.setInvalidType(true); 12564 } 12565 } 12566 } 12567 12568 // Temporarily put parameter variables in the translation unit, not 12569 // the enclosing context. This prevents them from accidentally 12570 // looking like class members in C++. 12571 ParmVarDecl *New = 12572 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 12573 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 12574 12575 if (D.isInvalidType()) 12576 New->setInvalidDecl(); 12577 12578 assert(S->isFunctionPrototypeScope()); 12579 assert(S->getFunctionPrototypeDepth() >= 1); 12580 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12581 S->getNextFunctionPrototypeIndex()); 12582 12583 // Add the parameter declaration into this scope. 12584 S->AddDecl(New); 12585 if (II) 12586 IdResolver.AddDecl(New); 12587 12588 ProcessDeclAttributes(S, New, D); 12589 12590 if (D.getDeclSpec().isModulePrivateSpecified()) 12591 Diag(New->getLocation(), diag::err_module_private_local) 12592 << 1 << New->getDeclName() 12593 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12594 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12595 12596 if (New->hasAttr<BlocksAttr>()) { 12597 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12598 } 12599 return New; 12600 } 12601 12602 /// Synthesizes a variable for a parameter arising from a 12603 /// typedef. 12604 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12605 SourceLocation Loc, 12606 QualType T) { 12607 /* FIXME: setting StartLoc == Loc. 12608 Would it be worth to modify callers so as to provide proper source 12609 location for the unnamed parameters, embedding the parameter's type? */ 12610 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12611 T, Context.getTrivialTypeSourceInfo(T, Loc), 12612 SC_None, nullptr); 12613 Param->setImplicit(); 12614 return Param; 12615 } 12616 12617 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12618 // Don't diagnose unused-parameter errors in template instantiations; we 12619 // will already have done so in the template itself. 12620 if (inTemplateInstantiation()) 12621 return; 12622 12623 for (const ParmVarDecl *Parameter : Parameters) { 12624 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12625 !Parameter->hasAttr<UnusedAttr>()) { 12626 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12627 << Parameter->getDeclName(); 12628 } 12629 } 12630 } 12631 12632 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12633 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12634 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12635 return; 12636 12637 // Warn if the return value is pass-by-value and larger than the specified 12638 // threshold. 12639 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12640 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12641 if (Size > LangOpts.NumLargeByValueCopy) 12642 Diag(D->getLocation(), diag::warn_return_value_size) 12643 << D->getDeclName() << Size; 12644 } 12645 12646 // Warn if any parameter is pass-by-value and larger than the specified 12647 // threshold. 12648 for (const ParmVarDecl *Parameter : Parameters) { 12649 QualType T = Parameter->getType(); 12650 if (T->isDependentType() || !T.isPODType(Context)) 12651 continue; 12652 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12653 if (Size > LangOpts.NumLargeByValueCopy) 12654 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12655 << Parameter->getDeclName() << Size; 12656 } 12657 } 12658 12659 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12660 SourceLocation NameLoc, IdentifierInfo *Name, 12661 QualType T, TypeSourceInfo *TSInfo, 12662 StorageClass SC) { 12663 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12664 if (getLangOpts().ObjCAutoRefCount && 12665 T.getObjCLifetime() == Qualifiers::OCL_None && 12666 T->isObjCLifetimeType()) { 12667 12668 Qualifiers::ObjCLifetime lifetime; 12669 12670 // Special cases for arrays: 12671 // - if it's const, use __unsafe_unretained 12672 // - otherwise, it's an error 12673 if (T->isArrayType()) { 12674 if (!T.isConstQualified()) { 12675 if (DelayedDiagnostics.shouldDelayDiagnostics()) 12676 DelayedDiagnostics.add( 12677 sema::DelayedDiagnostic::makeForbiddenType( 12678 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12679 else 12680 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 12681 << TSInfo->getTypeLoc().getSourceRange(); 12682 } 12683 lifetime = Qualifiers::OCL_ExplicitNone; 12684 } else { 12685 lifetime = T->getObjCARCImplicitLifetime(); 12686 } 12687 T = Context.getLifetimeQualifiedType(T, lifetime); 12688 } 12689 12690 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12691 Context.getAdjustedParameterType(T), 12692 TSInfo, SC, nullptr); 12693 12694 // Parameters can not be abstract class types. 12695 // For record types, this is done by the AbstractClassUsageDiagnoser once 12696 // the class has been completely parsed. 12697 if (!CurContext->isRecord() && 12698 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12699 AbstractParamType)) 12700 New->setInvalidDecl(); 12701 12702 // Parameter declarators cannot be interface types. All ObjC objects are 12703 // passed by reference. 12704 if (T->isObjCObjectType()) { 12705 SourceLocation TypeEndLoc = 12706 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 12707 Diag(NameLoc, 12708 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12709 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12710 T = Context.getObjCObjectPointerType(T); 12711 New->setType(T); 12712 } 12713 12714 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12715 // duration shall not be qualified by an address-space qualifier." 12716 // Since all parameters have automatic store duration, they can not have 12717 // an address space. 12718 if (T.getAddressSpace() != LangAS::Default && 12719 // OpenCL allows function arguments declared to be an array of a type 12720 // to be qualified with an address space. 12721 !(getLangOpts().OpenCL && 12722 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12723 Diag(NameLoc, diag::err_arg_with_address_space); 12724 New->setInvalidDecl(); 12725 } 12726 12727 return New; 12728 } 12729 12730 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12731 SourceLocation LocAfterDecls) { 12732 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12733 12734 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12735 // for a K&R function. 12736 if (!FTI.hasPrototype) { 12737 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12738 --i; 12739 if (FTI.Params[i].Param == nullptr) { 12740 SmallString<256> Code; 12741 llvm::raw_svector_ostream(Code) 12742 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12743 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12744 << FTI.Params[i].Ident 12745 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12746 12747 // Implicitly declare the argument as type 'int' for lack of a better 12748 // type. 12749 AttributeFactory attrs; 12750 DeclSpec DS(attrs); 12751 const char* PrevSpec; // unused 12752 unsigned DiagID; // unused 12753 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12754 DiagID, Context.getPrintingPolicy()); 12755 // Use the identifier location for the type source range. 12756 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12757 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12758 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12759 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12760 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12761 } 12762 } 12763 } 12764 } 12765 12766 Decl * 12767 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12768 MultiTemplateParamsArg TemplateParameterLists, 12769 SkipBodyInfo *SkipBody) { 12770 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12771 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12772 Scope *ParentScope = FnBodyScope->getParent(); 12773 12774 D.setFunctionDefinitionKind(FDK_Definition); 12775 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12776 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12777 } 12778 12779 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12780 Consumer.HandleInlineFunctionDefinition(D); 12781 } 12782 12783 static bool 12784 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12785 const FunctionDecl *&PossiblePrototype) { 12786 // Don't warn about invalid declarations. 12787 if (FD->isInvalidDecl()) 12788 return false; 12789 12790 // Or declarations that aren't global. 12791 if (!FD->isGlobal()) 12792 return false; 12793 12794 // Don't warn about C++ member functions. 12795 if (isa<CXXMethodDecl>(FD)) 12796 return false; 12797 12798 // Don't warn about 'main'. 12799 if (FD->isMain()) 12800 return false; 12801 12802 // Don't warn about inline functions. 12803 if (FD->isInlined()) 12804 return false; 12805 12806 // Don't warn about function templates. 12807 if (FD->getDescribedFunctionTemplate()) 12808 return false; 12809 12810 // Don't warn about function template specializations. 12811 if (FD->isFunctionTemplateSpecialization()) 12812 return false; 12813 12814 // Don't warn for OpenCL kernels. 12815 if (FD->hasAttr<OpenCLKernelAttr>()) 12816 return false; 12817 12818 // Don't warn on explicitly deleted functions. 12819 if (FD->isDeleted()) 12820 return false; 12821 12822 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12823 Prev; Prev = Prev->getPreviousDecl()) { 12824 // Ignore any declarations that occur in function or method 12825 // scope, because they aren't visible from the header. 12826 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12827 continue; 12828 12829 PossiblePrototype = Prev; 12830 return Prev->getType()->isFunctionNoProtoType(); 12831 } 12832 12833 return true; 12834 } 12835 12836 void 12837 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12838 const FunctionDecl *EffectiveDefinition, 12839 SkipBodyInfo *SkipBody) { 12840 const FunctionDecl *Definition = EffectiveDefinition; 12841 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12842 // If this is a friend function defined in a class template, it does not 12843 // have a body until it is used, nevertheless it is a definition, see 12844 // [temp.inst]p2: 12845 // 12846 // ... for the purpose of determining whether an instantiated redeclaration 12847 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12848 // corresponds to a definition in the template is considered to be a 12849 // definition. 12850 // 12851 // The following code must produce redefinition error: 12852 // 12853 // template<typename T> struct C20 { friend void func_20() {} }; 12854 // C20<int> c20i; 12855 // void func_20() {} 12856 // 12857 for (auto I : FD->redecls()) { 12858 if (I != FD && !I->isInvalidDecl() && 12859 I->getFriendObjectKind() != Decl::FOK_None) { 12860 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12861 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12862 // A merged copy of the same function, instantiated as a member of 12863 // the same class, is OK. 12864 if (declaresSameEntity(OrigFD, Original) && 12865 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12866 cast<Decl>(FD->getLexicalDeclContext()))) 12867 continue; 12868 } 12869 12870 if (Original->isThisDeclarationADefinition()) { 12871 Definition = I; 12872 break; 12873 } 12874 } 12875 } 12876 } 12877 } 12878 12879 if (!Definition) 12880 // Similar to friend functions a friend function template may be a 12881 // definition and do not have a body if it is instantiated in a class 12882 // template. 12883 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 12884 for (auto I : FTD->redecls()) { 12885 auto D = cast<FunctionTemplateDecl>(I); 12886 if (D != FTD) { 12887 assert(!D->isThisDeclarationADefinition() && 12888 "More than one definition in redeclaration chain"); 12889 if (D->getFriendObjectKind() != Decl::FOK_None) 12890 if (FunctionTemplateDecl *FT = 12891 D->getInstantiatedFromMemberTemplate()) { 12892 if (FT->isThisDeclarationADefinition()) { 12893 Definition = D->getTemplatedDecl(); 12894 break; 12895 } 12896 } 12897 } 12898 } 12899 } 12900 12901 if (!Definition) 12902 return; 12903 12904 if (canRedefineFunction(Definition, getLangOpts())) 12905 return; 12906 12907 // Don't emit an error when this is redefinition of a typo-corrected 12908 // definition. 12909 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12910 return; 12911 12912 // If we don't have a visible definition of the function, and it's inline or 12913 // a template, skip the new definition. 12914 if (SkipBody && !hasVisibleDefinition(Definition) && 12915 (Definition->getFormalLinkage() == InternalLinkage || 12916 Definition->isInlined() || 12917 Definition->getDescribedFunctionTemplate() || 12918 Definition->getNumTemplateParameterLists())) { 12919 SkipBody->ShouldSkip = true; 12920 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 12921 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12922 makeMergedDefinitionVisible(TD); 12923 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12924 return; 12925 } 12926 12927 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12928 Definition->getStorageClass() == SC_Extern) 12929 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12930 << FD->getDeclName() << getLangOpts().CPlusPlus; 12931 else 12932 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12933 12934 Diag(Definition->getLocation(), diag::note_previous_definition); 12935 FD->setInvalidDecl(); 12936 } 12937 12938 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12939 Sema &S) { 12940 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12941 12942 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12943 LSI->CallOperator = CallOperator; 12944 LSI->Lambda = LambdaClass; 12945 LSI->ReturnType = CallOperator->getReturnType(); 12946 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12947 12948 if (LCD == LCD_None) 12949 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12950 else if (LCD == LCD_ByCopy) 12951 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12952 else if (LCD == LCD_ByRef) 12953 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12954 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12955 12956 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12957 LSI->Mutable = !CallOperator->isConst(); 12958 12959 // Add the captures to the LSI so they can be noted as already 12960 // captured within tryCaptureVar. 12961 auto I = LambdaClass->field_begin(); 12962 for (const auto &C : LambdaClass->captures()) { 12963 if (C.capturesVariable()) { 12964 VarDecl *VD = C.getCapturedVar(); 12965 if (VD->isInitCapture()) 12966 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12967 QualType CaptureType = VD->getType(); 12968 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12969 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12970 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12971 /*EllipsisLoc*/C.isPackExpansion() 12972 ? C.getEllipsisLoc() : SourceLocation(), 12973 CaptureType, /*Invalid*/false); 12974 12975 } else if (C.capturesThis()) { 12976 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 12977 C.getCaptureKind() == LCK_StarThis); 12978 } else { 12979 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 12980 I->getType()); 12981 } 12982 ++I; 12983 } 12984 } 12985 12986 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12987 SkipBodyInfo *SkipBody) { 12988 if (!D) { 12989 // Parsing the function declaration failed in some way. Push on a fake scope 12990 // anyway so we can try to parse the function body. 12991 PushFunctionScope(); 12992 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12993 return D; 12994 } 12995 12996 FunctionDecl *FD = nullptr; 12997 12998 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12999 FD = FunTmpl->getTemplatedDecl(); 13000 else 13001 FD = cast<FunctionDecl>(D); 13002 13003 // Do not push if it is a lambda because one is already pushed when building 13004 // the lambda in ActOnStartOfLambdaDefinition(). 13005 if (!isLambdaCallOperator(FD)) 13006 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13007 13008 // Check for defining attributes before the check for redefinition. 13009 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13010 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13011 FD->dropAttr<AliasAttr>(); 13012 FD->setInvalidDecl(); 13013 } 13014 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13015 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13016 FD->dropAttr<IFuncAttr>(); 13017 FD->setInvalidDecl(); 13018 } 13019 13020 // See if this is a redefinition. If 'will have body' is already set, then 13021 // these checks were already performed when it was set. 13022 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13023 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13024 13025 // If we're skipping the body, we're done. Don't enter the scope. 13026 if (SkipBody && SkipBody->ShouldSkip) 13027 return D; 13028 } 13029 13030 // Mark this function as "will have a body eventually". This lets users to 13031 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13032 // this function. 13033 FD->setWillHaveBody(); 13034 13035 // If we are instantiating a generic lambda call operator, push 13036 // a LambdaScopeInfo onto the function stack. But use the information 13037 // that's already been calculated (ActOnLambdaExpr) to prime the current 13038 // LambdaScopeInfo. 13039 // When the template operator is being specialized, the LambdaScopeInfo, 13040 // has to be properly restored so that tryCaptureVariable doesn't try 13041 // and capture any new variables. In addition when calculating potential 13042 // captures during transformation of nested lambdas, it is necessary to 13043 // have the LSI properly restored. 13044 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13045 assert(inTemplateInstantiation() && 13046 "There should be an active template instantiation on the stack " 13047 "when instantiating a generic lambda!"); 13048 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13049 } else { 13050 // Enter a new function scope 13051 PushFunctionScope(); 13052 } 13053 13054 // Builtin functions cannot be defined. 13055 if (unsigned BuiltinID = FD->getBuiltinID()) { 13056 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13057 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13058 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13059 FD->setInvalidDecl(); 13060 } 13061 } 13062 13063 // The return type of a function definition must be complete 13064 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13065 QualType ResultType = FD->getReturnType(); 13066 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13067 !FD->isInvalidDecl() && 13068 RequireCompleteType(FD->getLocation(), ResultType, 13069 diag::err_func_def_incomplete_result)) 13070 FD->setInvalidDecl(); 13071 13072 if (FnBodyScope) 13073 PushDeclContext(FnBodyScope, FD); 13074 13075 // Check the validity of our function parameters 13076 CheckParmsForFunctionDef(FD->parameters(), 13077 /*CheckParameterNames=*/true); 13078 13079 // Add non-parameter declarations already in the function to the current 13080 // scope. 13081 if (FnBodyScope) { 13082 for (Decl *NPD : FD->decls()) { 13083 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13084 if (!NonParmDecl) 13085 continue; 13086 assert(!isa<ParmVarDecl>(NonParmDecl) && 13087 "parameters should not be in newly created FD yet"); 13088 13089 // If the decl has a name, make it accessible in the current scope. 13090 if (NonParmDecl->getDeclName()) 13091 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13092 13093 // Similarly, dive into enums and fish their constants out, making them 13094 // accessible in this scope. 13095 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13096 for (auto *EI : ED->enumerators()) 13097 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13098 } 13099 } 13100 } 13101 13102 // Introduce our parameters into the function scope 13103 for (auto Param : FD->parameters()) { 13104 Param->setOwningFunction(FD); 13105 13106 // If this has an identifier, add it to the scope stack. 13107 if (Param->getIdentifier() && FnBodyScope) { 13108 CheckShadow(FnBodyScope, Param); 13109 13110 PushOnScopeChains(Param, FnBodyScope); 13111 } 13112 } 13113 13114 // Ensure that the function's exception specification is instantiated. 13115 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13116 ResolveExceptionSpec(D->getLocation(), FPT); 13117 13118 // dllimport cannot be applied to non-inline function definitions. 13119 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13120 !FD->isTemplateInstantiation()) { 13121 assert(!FD->hasAttr<DLLExportAttr>()); 13122 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13123 FD->setInvalidDecl(); 13124 return D; 13125 } 13126 // We want to attach documentation to original Decl (which might be 13127 // a function template). 13128 ActOnDocumentableDecl(D); 13129 if (getCurLexicalContext()->isObjCContainer() && 13130 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13131 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13132 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13133 13134 return D; 13135 } 13136 13137 /// Given the set of return statements within a function body, 13138 /// compute the variables that are subject to the named return value 13139 /// optimization. 13140 /// 13141 /// Each of the variables that is subject to the named return value 13142 /// optimization will be marked as NRVO variables in the AST, and any 13143 /// return statement that has a marked NRVO variable as its NRVO candidate can 13144 /// use the named return value optimization. 13145 /// 13146 /// This function applies a very simplistic algorithm for NRVO: if every return 13147 /// statement in the scope of a variable has the same NRVO candidate, that 13148 /// candidate is an NRVO variable. 13149 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13150 ReturnStmt **Returns = Scope->Returns.data(); 13151 13152 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13153 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13154 if (!NRVOCandidate->isNRVOVariable()) 13155 Returns[I]->setNRVOCandidate(nullptr); 13156 } 13157 } 13158 } 13159 13160 bool Sema::canDelayFunctionBody(const Declarator &D) { 13161 // We can't delay parsing the body of a constexpr function template (yet). 13162 if (D.getDeclSpec().hasConstexprSpecifier()) 13163 return false; 13164 13165 // We can't delay parsing the body of a function template with a deduced 13166 // return type (yet). 13167 if (D.getDeclSpec().hasAutoTypeSpec()) { 13168 // If the placeholder introduces a non-deduced trailing return type, 13169 // we can still delay parsing it. 13170 if (D.getNumTypeObjects()) { 13171 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13172 if (Outer.Kind == DeclaratorChunk::Function && 13173 Outer.Fun.hasTrailingReturnType()) { 13174 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13175 return Ty.isNull() || !Ty->isUndeducedType(); 13176 } 13177 } 13178 return false; 13179 } 13180 13181 return true; 13182 } 13183 13184 bool Sema::canSkipFunctionBody(Decl *D) { 13185 // We cannot skip the body of a function (or function template) which is 13186 // constexpr, since we may need to evaluate its body in order to parse the 13187 // rest of the file. 13188 // We cannot skip the body of a function with an undeduced return type, 13189 // because any callers of that function need to know the type. 13190 if (const FunctionDecl *FD = D->getAsFunction()) { 13191 if (FD->isConstexpr()) 13192 return false; 13193 // We can't simply call Type::isUndeducedType here, because inside template 13194 // auto can be deduced to a dependent type, which is not considered 13195 // "undeduced". 13196 if (FD->getReturnType()->getContainedDeducedType()) 13197 return false; 13198 } 13199 return Consumer.shouldSkipFunctionBody(D); 13200 } 13201 13202 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13203 if (!Decl) 13204 return nullptr; 13205 if (FunctionDecl *FD = Decl->getAsFunction()) 13206 FD->setHasSkippedBody(); 13207 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13208 MD->setHasSkippedBody(); 13209 return Decl; 13210 } 13211 13212 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13213 return ActOnFinishFunctionBody(D, BodyArg, false); 13214 } 13215 13216 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13217 /// body. 13218 class ExitFunctionBodyRAII { 13219 public: 13220 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13221 ~ExitFunctionBodyRAII() { 13222 if (!IsLambda) 13223 S.PopExpressionEvaluationContext(); 13224 } 13225 13226 private: 13227 Sema &S; 13228 bool IsLambda = false; 13229 }; 13230 13231 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 13232 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 13233 13234 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 13235 if (EscapeInfo.count(BD)) 13236 return EscapeInfo[BD]; 13237 13238 bool R = false; 13239 const BlockDecl *CurBD = BD; 13240 13241 do { 13242 R = !CurBD->doesNotEscape(); 13243 if (R) 13244 break; 13245 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 13246 } while (CurBD); 13247 13248 return EscapeInfo[BD] = R; 13249 }; 13250 13251 // If the location where 'self' is implicitly retained is inside a escaping 13252 // block, emit a diagnostic. 13253 for (const std::pair<SourceLocation, const BlockDecl *> &P : 13254 S.ImplicitlyRetainedSelfLocs) 13255 if (IsOrNestedInEscapingBlock(P.second)) 13256 S.Diag(P.first, diag::warn_implicitly_retains_self) 13257 << FixItHint::CreateInsertion(P.first, "self->"); 13258 } 13259 13260 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 13261 bool IsInstantiation) { 13262 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 13263 13264 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13265 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 13266 13267 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 13268 CheckCompletedCoroutineBody(FD, Body); 13269 13270 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 13271 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 13272 // meant to pop the context added in ActOnStartOfFunctionDef(). 13273 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 13274 13275 if (FD) { 13276 FD->setBody(Body); 13277 FD->setWillHaveBody(false); 13278 13279 if (getLangOpts().CPlusPlus14) { 13280 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 13281 FD->getReturnType()->isUndeducedType()) { 13282 // If the function has a deduced result type but contains no 'return' 13283 // statements, the result type as written must be exactly 'auto', and 13284 // the deduced result type is 'void'. 13285 if (!FD->getReturnType()->getAs<AutoType>()) { 13286 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 13287 << FD->getReturnType(); 13288 FD->setInvalidDecl(); 13289 } else { 13290 // Substitute 'void' for the 'auto' in the type. 13291 TypeLoc ResultType = getReturnTypeLoc(FD); 13292 Context.adjustDeducedFunctionResultType( 13293 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 13294 } 13295 } 13296 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 13297 // In C++11, we don't use 'auto' deduction rules for lambda call 13298 // operators because we don't support return type deduction. 13299 auto *LSI = getCurLambda(); 13300 if (LSI->HasImplicitReturnType) { 13301 deduceClosureReturnType(*LSI); 13302 13303 // C++11 [expr.prim.lambda]p4: 13304 // [...] if there are no return statements in the compound-statement 13305 // [the deduced type is] the type void 13306 QualType RetType = 13307 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 13308 13309 // Update the return type to the deduced type. 13310 const FunctionProtoType *Proto = 13311 FD->getType()->getAs<FunctionProtoType>(); 13312 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 13313 Proto->getExtProtoInfo())); 13314 } 13315 } 13316 13317 // If the function implicitly returns zero (like 'main') or is naked, 13318 // don't complain about missing return statements. 13319 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 13320 WP.disableCheckFallThrough(); 13321 13322 // MSVC permits the use of pure specifier (=0) on function definition, 13323 // defined at class scope, warn about this non-standard construct. 13324 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 13325 Diag(FD->getLocation(), diag::ext_pure_function_definition); 13326 13327 if (!FD->isInvalidDecl()) { 13328 // Don't diagnose unused parameters of defaulted or deleted functions. 13329 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 13330 DiagnoseUnusedParameters(FD->parameters()); 13331 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 13332 FD->getReturnType(), FD); 13333 13334 // If this is a structor, we need a vtable. 13335 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 13336 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 13337 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 13338 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 13339 13340 // Try to apply the named return value optimization. We have to check 13341 // if we can do this here because lambdas keep return statements around 13342 // to deduce an implicit return type. 13343 if (FD->getReturnType()->isRecordType() && 13344 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 13345 computeNRVO(Body, getCurFunction()); 13346 } 13347 13348 // GNU warning -Wmissing-prototypes: 13349 // Warn if a global function is defined without a previous 13350 // prototype declaration. This warning is issued even if the 13351 // definition itself provides a prototype. The aim is to detect 13352 // global functions that fail to be declared in header files. 13353 const FunctionDecl *PossiblePrototype = nullptr; 13354 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 13355 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 13356 13357 if (PossiblePrototype) { 13358 // We found a declaration that is not a prototype, 13359 // but that could be a zero-parameter prototype 13360 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 13361 TypeLoc TL = TI->getTypeLoc(); 13362 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 13363 Diag(PossiblePrototype->getLocation(), 13364 diag::note_declaration_not_a_prototype) 13365 << (FD->getNumParams() != 0) 13366 << (FD->getNumParams() == 0 13367 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 13368 : FixItHint{}); 13369 } 13370 } else { 13371 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13372 << /* function */ 1 13373 << (FD->getStorageClass() == SC_None 13374 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 13375 "static ") 13376 : FixItHint{}); 13377 } 13378 13379 // GNU warning -Wstrict-prototypes 13380 // Warn if K&R function is defined without a previous declaration. 13381 // This warning is issued only if the definition itself does not provide 13382 // a prototype. Only K&R definitions do not provide a prototype. 13383 // An empty list in a function declarator that is part of a definition 13384 // of that function specifies that the function has no parameters 13385 // (C99 6.7.5.3p14) 13386 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 13387 !LangOpts.CPlusPlus) { 13388 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 13389 TypeLoc TL = TI->getTypeLoc(); 13390 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 13391 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 13392 } 13393 } 13394 13395 // Warn on CPUDispatch with an actual body. 13396 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 13397 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 13398 if (!CmpndBody->body_empty()) 13399 Diag(CmpndBody->body_front()->getBeginLoc(), 13400 diag::warn_dispatch_body_ignored); 13401 13402 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 13403 const CXXMethodDecl *KeyFunction; 13404 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 13405 MD->isVirtual() && 13406 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 13407 MD == KeyFunction->getCanonicalDecl()) { 13408 // Update the key-function state if necessary for this ABI. 13409 if (FD->isInlined() && 13410 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 13411 Context.setNonKeyFunction(MD); 13412 13413 // If the newly-chosen key function is already defined, then we 13414 // need to mark the vtable as used retroactively. 13415 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 13416 const FunctionDecl *Definition; 13417 if (KeyFunction && KeyFunction->isDefined(Definition)) 13418 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 13419 } else { 13420 // We just defined they key function; mark the vtable as used. 13421 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 13422 } 13423 } 13424 } 13425 13426 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 13427 "Function parsing confused"); 13428 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 13429 assert(MD == getCurMethodDecl() && "Method parsing confused"); 13430 MD->setBody(Body); 13431 if (!MD->isInvalidDecl()) { 13432 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 13433 MD->getReturnType(), MD); 13434 13435 if (Body) 13436 computeNRVO(Body, getCurFunction()); 13437 } 13438 if (getCurFunction()->ObjCShouldCallSuper) { 13439 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 13440 << MD->getSelector().getAsString(); 13441 getCurFunction()->ObjCShouldCallSuper = false; 13442 } 13443 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 13444 const ObjCMethodDecl *InitMethod = nullptr; 13445 bool isDesignated = 13446 MD->isDesignatedInitializerForTheInterface(&InitMethod); 13447 assert(isDesignated && InitMethod); 13448 (void)isDesignated; 13449 13450 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 13451 auto IFace = MD->getClassInterface(); 13452 if (!IFace) 13453 return false; 13454 auto SuperD = IFace->getSuperClass(); 13455 if (!SuperD) 13456 return false; 13457 return SuperD->getIdentifier() == 13458 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 13459 }; 13460 // Don't issue this warning for unavailable inits or direct subclasses 13461 // of NSObject. 13462 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 13463 Diag(MD->getLocation(), 13464 diag::warn_objc_designated_init_missing_super_call); 13465 Diag(InitMethod->getLocation(), 13466 diag::note_objc_designated_init_marked_here); 13467 } 13468 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 13469 } 13470 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 13471 // Don't issue this warning for unavaialable inits. 13472 if (!MD->isUnavailable()) 13473 Diag(MD->getLocation(), 13474 diag::warn_objc_secondary_init_missing_init_call); 13475 getCurFunction()->ObjCWarnForNoInitDelegation = false; 13476 } 13477 13478 diagnoseImplicitlyRetainedSelf(*this); 13479 } else { 13480 // Parsing the function declaration failed in some way. Pop the fake scope 13481 // we pushed on. 13482 PopFunctionScopeInfo(ActivePolicy, dcl); 13483 return nullptr; 13484 } 13485 13486 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13487 DiagnoseUnguardedAvailabilityViolations(dcl); 13488 13489 assert(!getCurFunction()->ObjCShouldCallSuper && 13490 "This should only be set for ObjC methods, which should have been " 13491 "handled in the block above."); 13492 13493 // Verify and clean out per-function state. 13494 if (Body && (!FD || !FD->isDefaulted())) { 13495 // C++ constructors that have function-try-blocks can't have return 13496 // statements in the handlers of that block. (C++ [except.handle]p14) 13497 // Verify this. 13498 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 13499 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 13500 13501 // Verify that gotos and switch cases don't jump into scopes illegally. 13502 if (getCurFunction()->NeedsScopeChecking() && 13503 !PP.isCodeCompletionEnabled()) 13504 DiagnoseInvalidJumps(Body); 13505 13506 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 13507 if (!Destructor->getParent()->isDependentType()) 13508 CheckDestructor(Destructor); 13509 13510 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13511 Destructor->getParent()); 13512 } 13513 13514 // If any errors have occurred, clear out any temporaries that may have 13515 // been leftover. This ensures that these temporaries won't be picked up for 13516 // deletion in some later function. 13517 if (getDiagnostics().hasErrorOccurred() || 13518 getDiagnostics().getSuppressAllDiagnostics()) { 13519 DiscardCleanupsInEvaluationContext(); 13520 } 13521 if (!getDiagnostics().hasUncompilableErrorOccurred() && 13522 !isa<FunctionTemplateDecl>(dcl)) { 13523 // Since the body is valid, issue any analysis-based warnings that are 13524 // enabled. 13525 ActivePolicy = &WP; 13526 } 13527 13528 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 13529 (!CheckConstexprFunctionDecl(FD) || 13530 !CheckConstexprFunctionBody(FD, Body))) 13531 FD->setInvalidDecl(); 13532 13533 if (FD && FD->hasAttr<NakedAttr>()) { 13534 for (const Stmt *S : Body->children()) { 13535 // Allow local register variables without initializer as they don't 13536 // require prologue. 13537 bool RegisterVariables = false; 13538 if (auto *DS = dyn_cast<DeclStmt>(S)) { 13539 for (const auto *Decl : DS->decls()) { 13540 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 13541 RegisterVariables = 13542 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 13543 if (!RegisterVariables) 13544 break; 13545 } 13546 } 13547 } 13548 if (RegisterVariables) 13549 continue; 13550 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 13551 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 13552 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 13553 FD->setInvalidDecl(); 13554 break; 13555 } 13556 } 13557 } 13558 13559 assert(ExprCleanupObjects.size() == 13560 ExprEvalContexts.back().NumCleanupObjects && 13561 "Leftover temporaries in function"); 13562 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 13563 assert(MaybeODRUseExprs.empty() && 13564 "Leftover expressions for odr-use checking"); 13565 } 13566 13567 if (!IsInstantiation) 13568 PopDeclContext(); 13569 13570 PopFunctionScopeInfo(ActivePolicy, dcl); 13571 // If any errors have occurred, clear out any temporaries that may have 13572 // been leftover. This ensures that these temporaries won't be picked up for 13573 // deletion in some later function. 13574 if (getDiagnostics().hasErrorOccurred()) { 13575 DiscardCleanupsInEvaluationContext(); 13576 } 13577 13578 return dcl; 13579 } 13580 13581 /// When we finish delayed parsing of an attribute, we must attach it to the 13582 /// relevant Decl. 13583 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 13584 ParsedAttributes &Attrs) { 13585 // Always attach attributes to the underlying decl. 13586 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 13587 D = TD->getTemplatedDecl(); 13588 ProcessDeclAttributeList(S, D, Attrs); 13589 13590 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 13591 if (Method->isStatic()) 13592 checkThisInStaticMemberFunctionAttributes(Method); 13593 } 13594 13595 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 13596 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 13597 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 13598 IdentifierInfo &II, Scope *S) { 13599 // Find the scope in which the identifier is injected and the corresponding 13600 // DeclContext. 13601 // FIXME: C89 does not say what happens if there is no enclosing block scope. 13602 // In that case, we inject the declaration into the translation unit scope 13603 // instead. 13604 Scope *BlockScope = S; 13605 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 13606 BlockScope = BlockScope->getParent(); 13607 13608 Scope *ContextScope = BlockScope; 13609 while (!ContextScope->getEntity()) 13610 ContextScope = ContextScope->getParent(); 13611 ContextRAII SavedContext(*this, ContextScope->getEntity()); 13612 13613 // Before we produce a declaration for an implicitly defined 13614 // function, see whether there was a locally-scoped declaration of 13615 // this name as a function or variable. If so, use that 13616 // (non-visible) declaration, and complain about it. 13617 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 13618 if (ExternCPrev) { 13619 // We still need to inject the function into the enclosing block scope so 13620 // that later (non-call) uses can see it. 13621 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13622 13623 // C89 footnote 38: 13624 // If in fact it is not defined as having type "function returning int", 13625 // the behavior is undefined. 13626 if (!isa<FunctionDecl>(ExternCPrev) || 13627 !Context.typesAreCompatible( 13628 cast<FunctionDecl>(ExternCPrev)->getType(), 13629 Context.getFunctionNoProtoType(Context.IntTy))) { 13630 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13631 << ExternCPrev << !getLangOpts().C99; 13632 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13633 return ExternCPrev; 13634 } 13635 } 13636 13637 // Extension in C99. Legal in C90, but warn about it. 13638 unsigned diag_id; 13639 if (II.getName().startswith("__builtin_")) 13640 diag_id = diag::warn_builtin_unknown; 13641 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13642 else if (getLangOpts().OpenCL) 13643 diag_id = diag::err_opencl_implicit_function_decl; 13644 else if (getLangOpts().C99) 13645 diag_id = diag::ext_implicit_function_decl; 13646 else 13647 diag_id = diag::warn_implicit_function_decl; 13648 Diag(Loc, diag_id) << &II; 13649 13650 // If we found a prior declaration of this function, don't bother building 13651 // another one. We've already pushed that one into scope, so there's nothing 13652 // more to do. 13653 if (ExternCPrev) 13654 return ExternCPrev; 13655 13656 // Because typo correction is expensive, only do it if the implicit 13657 // function declaration is going to be treated as an error. 13658 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13659 TypoCorrection Corrected; 13660 DeclFilterCCC<FunctionDecl> CCC{}; 13661 if (S && (Corrected = 13662 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 13663 S, nullptr, CCC, CTK_NonError))) 13664 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13665 /*ErrorRecovery*/false); 13666 } 13667 13668 // Set a Declarator for the implicit definition: int foo(); 13669 const char *Dummy; 13670 AttributeFactory attrFactory; 13671 DeclSpec DS(attrFactory); 13672 unsigned DiagID; 13673 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13674 Context.getPrintingPolicy()); 13675 (void)Error; // Silence warning. 13676 assert(!Error && "Error setting up implicit decl!"); 13677 SourceLocation NoLoc; 13678 Declarator D(DS, DeclaratorContext::BlockContext); 13679 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13680 /*IsAmbiguous=*/false, 13681 /*LParenLoc=*/NoLoc, 13682 /*Params=*/nullptr, 13683 /*NumParams=*/0, 13684 /*EllipsisLoc=*/NoLoc, 13685 /*RParenLoc=*/NoLoc, 13686 /*RefQualifierIsLvalueRef=*/true, 13687 /*RefQualifierLoc=*/NoLoc, 13688 /*MutableLoc=*/NoLoc, EST_None, 13689 /*ESpecRange=*/SourceRange(), 13690 /*Exceptions=*/nullptr, 13691 /*ExceptionRanges=*/nullptr, 13692 /*NumExceptions=*/0, 13693 /*NoexceptExpr=*/nullptr, 13694 /*ExceptionSpecTokens=*/nullptr, 13695 /*DeclsInPrototype=*/None, Loc, 13696 Loc, D), 13697 std::move(DS.getAttributes()), SourceLocation()); 13698 D.SetIdentifier(&II, Loc); 13699 13700 // Insert this function into the enclosing block scope. 13701 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13702 FD->setImplicit(); 13703 13704 AddKnownFunctionAttributes(FD); 13705 13706 return FD; 13707 } 13708 13709 /// Adds any function attributes that we know a priori based on 13710 /// the declaration of this function. 13711 /// 13712 /// These attributes can apply both to implicitly-declared builtins 13713 /// (like __builtin___printf_chk) or to library-declared functions 13714 /// like NSLog or printf. 13715 /// 13716 /// We need to check for duplicate attributes both here and where user-written 13717 /// attributes are applied to declarations. 13718 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13719 if (FD->isInvalidDecl()) 13720 return; 13721 13722 // If this is a built-in function, map its builtin attributes to 13723 // actual attributes. 13724 if (unsigned BuiltinID = FD->getBuiltinID()) { 13725 // Handle printf-formatting attributes. 13726 unsigned FormatIdx; 13727 bool HasVAListArg; 13728 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13729 if (!FD->hasAttr<FormatAttr>()) { 13730 const char *fmt = "printf"; 13731 unsigned int NumParams = FD->getNumParams(); 13732 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13733 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13734 fmt = "NSString"; 13735 FD->addAttr(FormatAttr::CreateImplicit(Context, 13736 &Context.Idents.get(fmt), 13737 FormatIdx+1, 13738 HasVAListArg ? 0 : FormatIdx+2, 13739 FD->getLocation())); 13740 } 13741 } 13742 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13743 HasVAListArg)) { 13744 if (!FD->hasAttr<FormatAttr>()) 13745 FD->addAttr(FormatAttr::CreateImplicit(Context, 13746 &Context.Idents.get("scanf"), 13747 FormatIdx+1, 13748 HasVAListArg ? 0 : FormatIdx+2, 13749 FD->getLocation())); 13750 } 13751 13752 // Handle automatically recognized callbacks. 13753 SmallVector<int, 4> Encoding; 13754 if (!FD->hasAttr<CallbackAttr>() && 13755 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 13756 FD->addAttr(CallbackAttr::CreateImplicit( 13757 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 13758 13759 // Mark const if we don't care about errno and that is the only thing 13760 // preventing the function from being const. This allows IRgen to use LLVM 13761 // intrinsics for such functions. 13762 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13763 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13764 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13765 13766 // We make "fma" on some platforms const because we know it does not set 13767 // errno in those environments even though it could set errno based on the 13768 // C standard. 13769 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13770 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13771 !FD->hasAttr<ConstAttr>()) { 13772 switch (BuiltinID) { 13773 case Builtin::BI__builtin_fma: 13774 case Builtin::BI__builtin_fmaf: 13775 case Builtin::BI__builtin_fmal: 13776 case Builtin::BIfma: 13777 case Builtin::BIfmaf: 13778 case Builtin::BIfmal: 13779 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13780 break; 13781 default: 13782 break; 13783 } 13784 } 13785 13786 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13787 !FD->hasAttr<ReturnsTwiceAttr>()) 13788 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13789 FD->getLocation())); 13790 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13791 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13792 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13793 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13794 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13795 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13796 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13797 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13798 // Add the appropriate attribute, depending on the CUDA compilation mode 13799 // and which target the builtin belongs to. For example, during host 13800 // compilation, aux builtins are __device__, while the rest are __host__. 13801 if (getLangOpts().CUDAIsDevice != 13802 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13803 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13804 else 13805 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13806 } 13807 } 13808 13809 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13810 // throw, add an implicit nothrow attribute to any extern "C" function we come 13811 // across. 13812 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13813 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13814 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13815 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13816 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13817 } 13818 13819 IdentifierInfo *Name = FD->getIdentifier(); 13820 if (!Name) 13821 return; 13822 if ((!getLangOpts().CPlusPlus && 13823 FD->getDeclContext()->isTranslationUnit()) || 13824 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13825 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13826 LinkageSpecDecl::lang_c)) { 13827 // Okay: this could be a libc/libm/Objective-C function we know 13828 // about. 13829 } else 13830 return; 13831 13832 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13833 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13834 // target-specific builtins, perhaps? 13835 if (!FD->hasAttr<FormatAttr>()) 13836 FD->addAttr(FormatAttr::CreateImplicit(Context, 13837 &Context.Idents.get("printf"), 2, 13838 Name->isStr("vasprintf") ? 0 : 3, 13839 FD->getLocation())); 13840 } 13841 13842 if (Name->isStr("__CFStringMakeConstantString")) { 13843 // We already have a __builtin___CFStringMakeConstantString, 13844 // but builds that use -fno-constant-cfstrings don't go through that. 13845 if (!FD->hasAttr<FormatArgAttr>()) 13846 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13847 FD->getLocation())); 13848 } 13849 } 13850 13851 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13852 TypeSourceInfo *TInfo) { 13853 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13854 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13855 13856 if (!TInfo) { 13857 assert(D.isInvalidType() && "no declarator info for valid type"); 13858 TInfo = Context.getTrivialTypeSourceInfo(T); 13859 } 13860 13861 // Scope manipulation handled by caller. 13862 TypedefDecl *NewTD = 13863 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 13864 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 13865 13866 // Bail out immediately if we have an invalid declaration. 13867 if (D.isInvalidType()) { 13868 NewTD->setInvalidDecl(); 13869 return NewTD; 13870 } 13871 13872 if (D.getDeclSpec().isModulePrivateSpecified()) { 13873 if (CurContext->isFunctionOrMethod()) 13874 Diag(NewTD->getLocation(), diag::err_module_private_local) 13875 << 2 << NewTD->getDeclName() 13876 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13877 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13878 else 13879 NewTD->setModulePrivate(); 13880 } 13881 13882 // C++ [dcl.typedef]p8: 13883 // If the typedef declaration defines an unnamed class (or 13884 // enum), the first typedef-name declared by the declaration 13885 // to be that class type (or enum type) is used to denote the 13886 // class type (or enum type) for linkage purposes only. 13887 // We need to check whether the type was declared in the declaration. 13888 switch (D.getDeclSpec().getTypeSpecType()) { 13889 case TST_enum: 13890 case TST_struct: 13891 case TST_interface: 13892 case TST_union: 13893 case TST_class: { 13894 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13895 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13896 break; 13897 } 13898 13899 default: 13900 break; 13901 } 13902 13903 return NewTD; 13904 } 13905 13906 /// Check that this is a valid underlying type for an enum declaration. 13907 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13908 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13909 QualType T = TI->getType(); 13910 13911 if (T->isDependentType()) 13912 return false; 13913 13914 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13915 if (BT->isInteger()) 13916 return false; 13917 13918 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13919 return true; 13920 } 13921 13922 /// Check whether this is a valid redeclaration of a previous enumeration. 13923 /// \return true if the redeclaration was invalid. 13924 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13925 QualType EnumUnderlyingTy, bool IsFixed, 13926 const EnumDecl *Prev) { 13927 if (IsScoped != Prev->isScoped()) { 13928 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13929 << Prev->isScoped(); 13930 Diag(Prev->getLocation(), diag::note_previous_declaration); 13931 return true; 13932 } 13933 13934 if (IsFixed && Prev->isFixed()) { 13935 if (!EnumUnderlyingTy->isDependentType() && 13936 !Prev->getIntegerType()->isDependentType() && 13937 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13938 Prev->getIntegerType())) { 13939 // TODO: Highlight the underlying type of the redeclaration. 13940 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13941 << EnumUnderlyingTy << Prev->getIntegerType(); 13942 Diag(Prev->getLocation(), diag::note_previous_declaration) 13943 << Prev->getIntegerTypeRange(); 13944 return true; 13945 } 13946 } else if (IsFixed != Prev->isFixed()) { 13947 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13948 << Prev->isFixed(); 13949 Diag(Prev->getLocation(), diag::note_previous_declaration); 13950 return true; 13951 } 13952 13953 return false; 13954 } 13955 13956 /// Get diagnostic %select index for tag kind for 13957 /// redeclaration diagnostic message. 13958 /// WARNING: Indexes apply to particular diagnostics only! 13959 /// 13960 /// \returns diagnostic %select index. 13961 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13962 switch (Tag) { 13963 case TTK_Struct: return 0; 13964 case TTK_Interface: return 1; 13965 case TTK_Class: return 2; 13966 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13967 } 13968 } 13969 13970 /// Determine if tag kind is a class-key compatible with 13971 /// class for redeclaration (class, struct, or __interface). 13972 /// 13973 /// \returns true iff the tag kind is compatible. 13974 static bool isClassCompatTagKind(TagTypeKind Tag) 13975 { 13976 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13977 } 13978 13979 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13980 TagTypeKind TTK) { 13981 if (isa<TypedefDecl>(PrevDecl)) 13982 return NTK_Typedef; 13983 else if (isa<TypeAliasDecl>(PrevDecl)) 13984 return NTK_TypeAlias; 13985 else if (isa<ClassTemplateDecl>(PrevDecl)) 13986 return NTK_Template; 13987 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13988 return NTK_TypeAliasTemplate; 13989 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13990 return NTK_TemplateTemplateArgument; 13991 switch (TTK) { 13992 case TTK_Struct: 13993 case TTK_Interface: 13994 case TTK_Class: 13995 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13996 case TTK_Union: 13997 return NTK_NonUnion; 13998 case TTK_Enum: 13999 return NTK_NonEnum; 14000 } 14001 llvm_unreachable("invalid TTK"); 14002 } 14003 14004 /// Determine whether a tag with a given kind is acceptable 14005 /// as a redeclaration of the given tag declaration. 14006 /// 14007 /// \returns true if the new tag kind is acceptable, false otherwise. 14008 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14009 TagTypeKind NewTag, bool isDefinition, 14010 SourceLocation NewTagLoc, 14011 const IdentifierInfo *Name) { 14012 // C++ [dcl.type.elab]p3: 14013 // The class-key or enum keyword present in the 14014 // elaborated-type-specifier shall agree in kind with the 14015 // declaration to which the name in the elaborated-type-specifier 14016 // refers. This rule also applies to the form of 14017 // elaborated-type-specifier that declares a class-name or 14018 // friend class since it can be construed as referring to the 14019 // definition of the class. Thus, in any 14020 // elaborated-type-specifier, the enum keyword shall be used to 14021 // refer to an enumeration (7.2), the union class-key shall be 14022 // used to refer to a union (clause 9), and either the class or 14023 // struct class-key shall be used to refer to a class (clause 9) 14024 // declared using the class or struct class-key. 14025 TagTypeKind OldTag = Previous->getTagKind(); 14026 if (OldTag != NewTag && 14027 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14028 return false; 14029 14030 // Tags are compatible, but we might still want to warn on mismatched tags. 14031 // Non-class tags can't be mismatched at this point. 14032 if (!isClassCompatTagKind(NewTag)) 14033 return true; 14034 14035 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14036 // by our warning analysis. We don't want to warn about mismatches with (eg) 14037 // declarations in system headers that are designed to be specialized, but if 14038 // a user asks us to warn, we should warn if their code contains mismatched 14039 // declarations. 14040 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14041 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14042 Loc); 14043 }; 14044 if (IsIgnoredLoc(NewTagLoc)) 14045 return true; 14046 14047 auto IsIgnored = [&](const TagDecl *Tag) { 14048 return IsIgnoredLoc(Tag->getLocation()); 14049 }; 14050 while (IsIgnored(Previous)) { 14051 Previous = Previous->getPreviousDecl(); 14052 if (!Previous) 14053 return true; 14054 OldTag = Previous->getTagKind(); 14055 } 14056 14057 bool isTemplate = false; 14058 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 14059 isTemplate = Record->getDescribedClassTemplate(); 14060 14061 if (inTemplateInstantiation()) { 14062 if (OldTag != NewTag) { 14063 // In a template instantiation, do not offer fix-its for tag mismatches 14064 // since they usually mess up the template instead of fixing the problem. 14065 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14066 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14067 << getRedeclDiagFromTagKind(OldTag); 14068 // FIXME: Note previous location? 14069 } 14070 return true; 14071 } 14072 14073 if (isDefinition) { 14074 // On definitions, check all previous tags and issue a fix-it for each 14075 // one that doesn't match the current tag. 14076 if (Previous->getDefinition()) { 14077 // Don't suggest fix-its for redefinitions. 14078 return true; 14079 } 14080 14081 bool previousMismatch = false; 14082 for (const TagDecl *I : Previous->redecls()) { 14083 if (I->getTagKind() != NewTag) { 14084 // Ignore previous declarations for which the warning was disabled. 14085 if (IsIgnored(I)) 14086 continue; 14087 14088 if (!previousMismatch) { 14089 previousMismatch = true; 14090 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 14091 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14092 << getRedeclDiagFromTagKind(I->getTagKind()); 14093 } 14094 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 14095 << getRedeclDiagFromTagKind(NewTag) 14096 << FixItHint::CreateReplacement(I->getInnerLocStart(), 14097 TypeWithKeyword::getTagTypeKindName(NewTag)); 14098 } 14099 } 14100 return true; 14101 } 14102 14103 // Identify the prevailing tag kind: this is the kind of the definition (if 14104 // there is a non-ignored definition), or otherwise the kind of the prior 14105 // (non-ignored) declaration. 14106 const TagDecl *PrevDef = Previous->getDefinition(); 14107 if (PrevDef && IsIgnored(PrevDef)) 14108 PrevDef = nullptr; 14109 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 14110 if (Redecl->getTagKind() != NewTag) { 14111 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14112 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14113 << getRedeclDiagFromTagKind(OldTag); 14114 Diag(Redecl->getLocation(), diag::note_previous_use); 14115 14116 // If there is a previous definition, suggest a fix-it. 14117 if (PrevDef) { 14118 Diag(NewTagLoc, diag::note_struct_class_suggestion) 14119 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 14120 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 14121 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 14122 } 14123 } 14124 14125 return true; 14126 } 14127 14128 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 14129 /// from an outer enclosing namespace or file scope inside a friend declaration. 14130 /// This should provide the commented out code in the following snippet: 14131 /// namespace N { 14132 /// struct X; 14133 /// namespace M { 14134 /// struct Y { friend struct /*N::*/ X; }; 14135 /// } 14136 /// } 14137 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 14138 SourceLocation NameLoc) { 14139 // While the decl is in a namespace, do repeated lookup of that name and see 14140 // if we get the same namespace back. If we do not, continue until 14141 // translation unit scope, at which point we have a fully qualified NNS. 14142 SmallVector<IdentifierInfo *, 4> Namespaces; 14143 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14144 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 14145 // This tag should be declared in a namespace, which can only be enclosed by 14146 // other namespaces. Bail if there's an anonymous namespace in the chain. 14147 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 14148 if (!Namespace || Namespace->isAnonymousNamespace()) 14149 return FixItHint(); 14150 IdentifierInfo *II = Namespace->getIdentifier(); 14151 Namespaces.push_back(II); 14152 NamedDecl *Lookup = SemaRef.LookupSingleName( 14153 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 14154 if (Lookup == Namespace) 14155 break; 14156 } 14157 14158 // Once we have all the namespaces, reverse them to go outermost first, and 14159 // build an NNS. 14160 SmallString<64> Insertion; 14161 llvm::raw_svector_ostream OS(Insertion); 14162 if (DC->isTranslationUnit()) 14163 OS << "::"; 14164 std::reverse(Namespaces.begin(), Namespaces.end()); 14165 for (auto *II : Namespaces) 14166 OS << II->getName() << "::"; 14167 return FixItHint::CreateInsertion(NameLoc, Insertion); 14168 } 14169 14170 /// Determine whether a tag originally declared in context \p OldDC can 14171 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 14172 /// found a declaration in \p OldDC as a previous decl, perhaps through a 14173 /// using-declaration). 14174 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 14175 DeclContext *NewDC) { 14176 OldDC = OldDC->getRedeclContext(); 14177 NewDC = NewDC->getRedeclContext(); 14178 14179 if (OldDC->Equals(NewDC)) 14180 return true; 14181 14182 // In MSVC mode, we allow a redeclaration if the contexts are related (either 14183 // encloses the other). 14184 if (S.getLangOpts().MSVCCompat && 14185 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 14186 return true; 14187 14188 return false; 14189 } 14190 14191 /// This is invoked when we see 'struct foo' or 'struct {'. In the 14192 /// former case, Name will be non-null. In the later case, Name will be null. 14193 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 14194 /// reference/declaration/definition of a tag. 14195 /// 14196 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 14197 /// trailing-type-specifier) other than one in an alias-declaration. 14198 /// 14199 /// \param SkipBody If non-null, will be set to indicate if the caller should 14200 /// skip the definition of this tag and treat it as if it were a declaration. 14201 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 14202 SourceLocation KWLoc, CXXScopeSpec &SS, 14203 IdentifierInfo *Name, SourceLocation NameLoc, 14204 const ParsedAttributesView &Attrs, AccessSpecifier AS, 14205 SourceLocation ModulePrivateLoc, 14206 MultiTemplateParamsArg TemplateParameterLists, 14207 bool &OwnedDecl, bool &IsDependent, 14208 SourceLocation ScopedEnumKWLoc, 14209 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 14210 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 14211 SkipBodyInfo *SkipBody) { 14212 // If this is not a definition, it must have a name. 14213 IdentifierInfo *OrigName = Name; 14214 assert((Name != nullptr || TUK == TUK_Definition) && 14215 "Nameless record must be a definition!"); 14216 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 14217 14218 OwnedDecl = false; 14219 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14220 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 14221 14222 // FIXME: Check member specializations more carefully. 14223 bool isMemberSpecialization = false; 14224 bool Invalid = false; 14225 14226 // We only need to do this matching if we have template parameters 14227 // or a scope specifier, which also conveniently avoids this work 14228 // for non-C++ cases. 14229 if (TemplateParameterLists.size() > 0 || 14230 (SS.isNotEmpty() && TUK != TUK_Reference)) { 14231 if (TemplateParameterList *TemplateParams = 14232 MatchTemplateParametersToScopeSpecifier( 14233 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 14234 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 14235 if (Kind == TTK_Enum) { 14236 Diag(KWLoc, diag::err_enum_template); 14237 return nullptr; 14238 } 14239 14240 if (TemplateParams->size() > 0) { 14241 // This is a declaration or definition of a class template (which may 14242 // be a member of another template). 14243 14244 if (Invalid) 14245 return nullptr; 14246 14247 OwnedDecl = false; 14248 DeclResult Result = CheckClassTemplate( 14249 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 14250 AS, ModulePrivateLoc, 14251 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 14252 TemplateParameterLists.data(), SkipBody); 14253 return Result.get(); 14254 } else { 14255 // The "template<>" header is extraneous. 14256 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14257 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14258 isMemberSpecialization = true; 14259 } 14260 } 14261 } 14262 14263 // Figure out the underlying type if this a enum declaration. We need to do 14264 // this early, because it's needed to detect if this is an incompatible 14265 // redeclaration. 14266 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 14267 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 14268 14269 if (Kind == TTK_Enum) { 14270 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 14271 // No underlying type explicitly specified, or we failed to parse the 14272 // type, default to int. 14273 EnumUnderlying = Context.IntTy.getTypePtr(); 14274 } else if (UnderlyingType.get()) { 14275 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 14276 // integral type; any cv-qualification is ignored. 14277 TypeSourceInfo *TI = nullptr; 14278 GetTypeFromParser(UnderlyingType.get(), &TI); 14279 EnumUnderlying = TI; 14280 14281 if (CheckEnumUnderlyingType(TI)) 14282 // Recover by falling back to int. 14283 EnumUnderlying = Context.IntTy.getTypePtr(); 14284 14285 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 14286 UPPC_FixedUnderlyingType)) 14287 EnumUnderlying = Context.IntTy.getTypePtr(); 14288 14289 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14290 // For MSVC ABI compatibility, unfixed enums must use an underlying type 14291 // of 'int'. However, if this is an unfixed forward declaration, don't set 14292 // the underlying type unless the user enables -fms-compatibility. This 14293 // makes unfixed forward declared enums incomplete and is more conforming. 14294 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 14295 EnumUnderlying = Context.IntTy.getTypePtr(); 14296 } 14297 } 14298 14299 DeclContext *SearchDC = CurContext; 14300 DeclContext *DC = CurContext; 14301 bool isStdBadAlloc = false; 14302 bool isStdAlignValT = false; 14303 14304 RedeclarationKind Redecl = forRedeclarationInCurContext(); 14305 if (TUK == TUK_Friend || TUK == TUK_Reference) 14306 Redecl = NotForRedeclaration; 14307 14308 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 14309 /// implemented asks for structural equivalence checking, the returned decl 14310 /// here is passed back to the parser, allowing the tag body to be parsed. 14311 auto createTagFromNewDecl = [&]() -> TagDecl * { 14312 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 14313 // If there is an identifier, use the location of the identifier as the 14314 // location of the decl, otherwise use the location of the struct/union 14315 // keyword. 14316 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14317 TagDecl *New = nullptr; 14318 14319 if (Kind == TTK_Enum) { 14320 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 14321 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 14322 // If this is an undefined enum, bail. 14323 if (TUK != TUK_Definition && !Invalid) 14324 return nullptr; 14325 if (EnumUnderlying) { 14326 EnumDecl *ED = cast<EnumDecl>(New); 14327 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 14328 ED->setIntegerTypeSourceInfo(TI); 14329 else 14330 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 14331 ED->setPromotionType(ED->getIntegerType()); 14332 } 14333 } else { // struct/union 14334 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14335 nullptr); 14336 } 14337 14338 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14339 // Add alignment attributes if necessary; these attributes are checked 14340 // when the ASTContext lays out the structure. 14341 // 14342 // It is important for implementing the correct semantics that this 14343 // happen here (in ActOnTag). The #pragma pack stack is 14344 // maintained as a result of parser callbacks which can occur at 14345 // many points during the parsing of a struct declaration (because 14346 // the #pragma tokens are effectively skipped over during the 14347 // parsing of the struct). 14348 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14349 AddAlignmentAttributesForRecord(RD); 14350 AddMsStructLayoutForRecord(RD); 14351 } 14352 } 14353 New->setLexicalDeclContext(CurContext); 14354 return New; 14355 }; 14356 14357 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 14358 if (Name && SS.isNotEmpty()) { 14359 // We have a nested-name tag ('struct foo::bar'). 14360 14361 // Check for invalid 'foo::'. 14362 if (SS.isInvalid()) { 14363 Name = nullptr; 14364 goto CreateNewDecl; 14365 } 14366 14367 // If this is a friend or a reference to a class in a dependent 14368 // context, don't try to make a decl for it. 14369 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14370 DC = computeDeclContext(SS, false); 14371 if (!DC) { 14372 IsDependent = true; 14373 return nullptr; 14374 } 14375 } else { 14376 DC = computeDeclContext(SS, true); 14377 if (!DC) { 14378 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 14379 << SS.getRange(); 14380 return nullptr; 14381 } 14382 } 14383 14384 if (RequireCompleteDeclContext(SS, DC)) 14385 return nullptr; 14386 14387 SearchDC = DC; 14388 // Look-up name inside 'foo::'. 14389 LookupQualifiedName(Previous, DC); 14390 14391 if (Previous.isAmbiguous()) 14392 return nullptr; 14393 14394 if (Previous.empty()) { 14395 // Name lookup did not find anything. However, if the 14396 // nested-name-specifier refers to the current instantiation, 14397 // and that current instantiation has any dependent base 14398 // classes, we might find something at instantiation time: treat 14399 // this as a dependent elaborated-type-specifier. 14400 // But this only makes any sense for reference-like lookups. 14401 if (Previous.wasNotFoundInCurrentInstantiation() && 14402 (TUK == TUK_Reference || TUK == TUK_Friend)) { 14403 IsDependent = true; 14404 return nullptr; 14405 } 14406 14407 // A tag 'foo::bar' must already exist. 14408 Diag(NameLoc, diag::err_not_tag_in_scope) 14409 << Kind << Name << DC << SS.getRange(); 14410 Name = nullptr; 14411 Invalid = true; 14412 goto CreateNewDecl; 14413 } 14414 } else if (Name) { 14415 // C++14 [class.mem]p14: 14416 // If T is the name of a class, then each of the following shall have a 14417 // name different from T: 14418 // -- every member of class T that is itself a type 14419 if (TUK != TUK_Reference && TUK != TUK_Friend && 14420 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 14421 return nullptr; 14422 14423 // If this is a named struct, check to see if there was a previous forward 14424 // declaration or definition. 14425 // FIXME: We're looking into outer scopes here, even when we 14426 // shouldn't be. Doing so can result in ambiguities that we 14427 // shouldn't be diagnosing. 14428 LookupName(Previous, S); 14429 14430 // When declaring or defining a tag, ignore ambiguities introduced 14431 // by types using'ed into this scope. 14432 if (Previous.isAmbiguous() && 14433 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 14434 LookupResult::Filter F = Previous.makeFilter(); 14435 while (F.hasNext()) { 14436 NamedDecl *ND = F.next(); 14437 if (!ND->getDeclContext()->getRedeclContext()->Equals( 14438 SearchDC->getRedeclContext())) 14439 F.erase(); 14440 } 14441 F.done(); 14442 } 14443 14444 // C++11 [namespace.memdef]p3: 14445 // If the name in a friend declaration is neither qualified nor 14446 // a template-id and the declaration is a function or an 14447 // elaborated-type-specifier, the lookup to determine whether 14448 // the entity has been previously declared shall not consider 14449 // any scopes outside the innermost enclosing namespace. 14450 // 14451 // MSVC doesn't implement the above rule for types, so a friend tag 14452 // declaration may be a redeclaration of a type declared in an enclosing 14453 // scope. They do implement this rule for friend functions. 14454 // 14455 // Does it matter that this should be by scope instead of by 14456 // semantic context? 14457 if (!Previous.empty() && TUK == TUK_Friend) { 14458 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 14459 LookupResult::Filter F = Previous.makeFilter(); 14460 bool FriendSawTagOutsideEnclosingNamespace = false; 14461 while (F.hasNext()) { 14462 NamedDecl *ND = F.next(); 14463 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14464 if (DC->isFileContext() && 14465 !EnclosingNS->Encloses(ND->getDeclContext())) { 14466 if (getLangOpts().MSVCCompat) 14467 FriendSawTagOutsideEnclosingNamespace = true; 14468 else 14469 F.erase(); 14470 } 14471 } 14472 F.done(); 14473 14474 // Diagnose this MSVC extension in the easy case where lookup would have 14475 // unambiguously found something outside the enclosing namespace. 14476 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 14477 NamedDecl *ND = Previous.getFoundDecl(); 14478 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 14479 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 14480 } 14481 } 14482 14483 // Note: there used to be some attempt at recovery here. 14484 if (Previous.isAmbiguous()) 14485 return nullptr; 14486 14487 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 14488 // FIXME: This makes sure that we ignore the contexts associated 14489 // with C structs, unions, and enums when looking for a matching 14490 // tag declaration or definition. See the similar lookup tweak 14491 // in Sema::LookupName; is there a better way to deal with this? 14492 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 14493 SearchDC = SearchDC->getParent(); 14494 } 14495 } 14496 14497 if (Previous.isSingleResult() && 14498 Previous.getFoundDecl()->isTemplateParameter()) { 14499 // Maybe we will complain about the shadowed template parameter. 14500 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 14501 // Just pretend that we didn't see the previous declaration. 14502 Previous.clear(); 14503 } 14504 14505 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 14506 DC->Equals(getStdNamespace())) { 14507 if (Name->isStr("bad_alloc")) { 14508 // This is a declaration of or a reference to "std::bad_alloc". 14509 isStdBadAlloc = true; 14510 14511 // If std::bad_alloc has been implicitly declared (but made invisible to 14512 // name lookup), fill in this implicit declaration as the previous 14513 // declaration, so that the declarations get chained appropriately. 14514 if (Previous.empty() && StdBadAlloc) 14515 Previous.addDecl(getStdBadAlloc()); 14516 } else if (Name->isStr("align_val_t")) { 14517 isStdAlignValT = true; 14518 if (Previous.empty() && StdAlignValT) 14519 Previous.addDecl(getStdAlignValT()); 14520 } 14521 } 14522 14523 // If we didn't find a previous declaration, and this is a reference 14524 // (or friend reference), move to the correct scope. In C++, we 14525 // also need to do a redeclaration lookup there, just in case 14526 // there's a shadow friend decl. 14527 if (Name && Previous.empty() && 14528 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 14529 if (Invalid) goto CreateNewDecl; 14530 assert(SS.isEmpty()); 14531 14532 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 14533 // C++ [basic.scope.pdecl]p5: 14534 // -- for an elaborated-type-specifier of the form 14535 // 14536 // class-key identifier 14537 // 14538 // if the elaborated-type-specifier is used in the 14539 // decl-specifier-seq or parameter-declaration-clause of a 14540 // function defined in namespace scope, the identifier is 14541 // declared as a class-name in the namespace that contains 14542 // the declaration; otherwise, except as a friend 14543 // declaration, the identifier is declared in the smallest 14544 // non-class, non-function-prototype scope that contains the 14545 // declaration. 14546 // 14547 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 14548 // C structs and unions. 14549 // 14550 // It is an error in C++ to declare (rather than define) an enum 14551 // type, including via an elaborated type specifier. We'll 14552 // diagnose that later; for now, declare the enum in the same 14553 // scope as we would have picked for any other tag type. 14554 // 14555 // GNU C also supports this behavior as part of its incomplete 14556 // enum types extension, while GNU C++ does not. 14557 // 14558 // Find the context where we'll be declaring the tag. 14559 // FIXME: We would like to maintain the current DeclContext as the 14560 // lexical context, 14561 SearchDC = getTagInjectionContext(SearchDC); 14562 14563 // Find the scope where we'll be declaring the tag. 14564 S = getTagInjectionScope(S, getLangOpts()); 14565 } else { 14566 assert(TUK == TUK_Friend); 14567 // C++ [namespace.memdef]p3: 14568 // If a friend declaration in a non-local class first declares a 14569 // class or function, the friend class or function is a member of 14570 // the innermost enclosing namespace. 14571 SearchDC = SearchDC->getEnclosingNamespaceContext(); 14572 } 14573 14574 // In C++, we need to do a redeclaration lookup to properly 14575 // diagnose some problems. 14576 // FIXME: redeclaration lookup is also used (with and without C++) to find a 14577 // hidden declaration so that we don't get ambiguity errors when using a 14578 // type declared by an elaborated-type-specifier. In C that is not correct 14579 // and we should instead merge compatible types found by lookup. 14580 if (getLangOpts().CPlusPlus) { 14581 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14582 LookupQualifiedName(Previous, SearchDC); 14583 } else { 14584 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14585 LookupName(Previous, S); 14586 } 14587 } 14588 14589 // If we have a known previous declaration to use, then use it. 14590 if (Previous.empty() && SkipBody && SkipBody->Previous) 14591 Previous.addDecl(SkipBody->Previous); 14592 14593 if (!Previous.empty()) { 14594 NamedDecl *PrevDecl = Previous.getFoundDecl(); 14595 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 14596 14597 // It's okay to have a tag decl in the same scope as a typedef 14598 // which hides a tag decl in the same scope. Finding this 14599 // insanity with a redeclaration lookup can only actually happen 14600 // in C++. 14601 // 14602 // This is also okay for elaborated-type-specifiers, which is 14603 // technically forbidden by the current standard but which is 14604 // okay according to the likely resolution of an open issue; 14605 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 14606 if (getLangOpts().CPlusPlus) { 14607 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14608 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 14609 TagDecl *Tag = TT->getDecl(); 14610 if (Tag->getDeclName() == Name && 14611 Tag->getDeclContext()->getRedeclContext() 14612 ->Equals(TD->getDeclContext()->getRedeclContext())) { 14613 PrevDecl = Tag; 14614 Previous.clear(); 14615 Previous.addDecl(Tag); 14616 Previous.resolveKind(); 14617 } 14618 } 14619 } 14620 } 14621 14622 // If this is a redeclaration of a using shadow declaration, it must 14623 // declare a tag in the same context. In MSVC mode, we allow a 14624 // redefinition if either context is within the other. 14625 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 14626 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 14627 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 14628 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 14629 !(OldTag && isAcceptableTagRedeclContext( 14630 *this, OldTag->getDeclContext(), SearchDC))) { 14631 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 14632 Diag(Shadow->getTargetDecl()->getLocation(), 14633 diag::note_using_decl_target); 14634 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 14635 << 0; 14636 // Recover by ignoring the old declaration. 14637 Previous.clear(); 14638 goto CreateNewDecl; 14639 } 14640 } 14641 14642 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 14643 // If this is a use of a previous tag, or if the tag is already declared 14644 // in the same scope (so that the definition/declaration completes or 14645 // rementions the tag), reuse the decl. 14646 if (TUK == TUK_Reference || TUK == TUK_Friend || 14647 isDeclInScope(DirectPrevDecl, SearchDC, S, 14648 SS.isNotEmpty() || isMemberSpecialization)) { 14649 // Make sure that this wasn't declared as an enum and now used as a 14650 // struct or something similar. 14651 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14652 TUK == TUK_Definition, KWLoc, 14653 Name)) { 14654 bool SafeToContinue 14655 = (PrevTagDecl->getTagKind() != TTK_Enum && 14656 Kind != TTK_Enum); 14657 if (SafeToContinue) 14658 Diag(KWLoc, diag::err_use_with_wrong_tag) 14659 << Name 14660 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14661 PrevTagDecl->getKindName()); 14662 else 14663 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14664 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14665 14666 if (SafeToContinue) 14667 Kind = PrevTagDecl->getTagKind(); 14668 else { 14669 // Recover by making this an anonymous redefinition. 14670 Name = nullptr; 14671 Previous.clear(); 14672 Invalid = true; 14673 } 14674 } 14675 14676 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14677 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14678 14679 // If this is an elaborated-type-specifier for a scoped enumeration, 14680 // the 'class' keyword is not necessary and not permitted. 14681 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14682 if (ScopedEnum) 14683 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14684 << PrevEnum->isScoped() 14685 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14686 return PrevTagDecl; 14687 } 14688 14689 QualType EnumUnderlyingTy; 14690 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14691 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14692 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14693 EnumUnderlyingTy = QualType(T, 0); 14694 14695 // All conflicts with previous declarations are recovered by 14696 // returning the previous declaration, unless this is a definition, 14697 // in which case we want the caller to bail out. 14698 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14699 ScopedEnum, EnumUnderlyingTy, 14700 IsFixed, PrevEnum)) 14701 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14702 } 14703 14704 // C++11 [class.mem]p1: 14705 // A member shall not be declared twice in the member-specification, 14706 // except that a nested class or member class template can be declared 14707 // and then later defined. 14708 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14709 S->isDeclScope(PrevDecl)) { 14710 Diag(NameLoc, diag::ext_member_redeclared); 14711 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14712 } 14713 14714 if (!Invalid) { 14715 // If this is a use, just return the declaration we found, unless 14716 // we have attributes. 14717 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14718 if (!Attrs.empty()) { 14719 // FIXME: Diagnose these attributes. For now, we create a new 14720 // declaration to hold them. 14721 } else if (TUK == TUK_Reference && 14722 (PrevTagDecl->getFriendObjectKind() == 14723 Decl::FOK_Undeclared || 14724 PrevDecl->getOwningModule() != getCurrentModule()) && 14725 SS.isEmpty()) { 14726 // This declaration is a reference to an existing entity, but 14727 // has different visibility from that entity: it either makes 14728 // a friend visible or it makes a type visible in a new module. 14729 // In either case, create a new declaration. We only do this if 14730 // the declaration would have meant the same thing if no prior 14731 // declaration were found, that is, if it was found in the same 14732 // scope where we would have injected a declaration. 14733 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14734 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14735 return PrevTagDecl; 14736 // This is in the injected scope, create a new declaration in 14737 // that scope. 14738 S = getTagInjectionScope(S, getLangOpts()); 14739 } else { 14740 return PrevTagDecl; 14741 } 14742 } 14743 14744 // Diagnose attempts to redefine a tag. 14745 if (TUK == TUK_Definition) { 14746 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14747 // If we're defining a specialization and the previous definition 14748 // is from an implicit instantiation, don't emit an error 14749 // here; we'll catch this in the general case below. 14750 bool IsExplicitSpecializationAfterInstantiation = false; 14751 if (isMemberSpecialization) { 14752 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14753 IsExplicitSpecializationAfterInstantiation = 14754 RD->getTemplateSpecializationKind() != 14755 TSK_ExplicitSpecialization; 14756 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14757 IsExplicitSpecializationAfterInstantiation = 14758 ED->getTemplateSpecializationKind() != 14759 TSK_ExplicitSpecialization; 14760 } 14761 14762 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14763 // not keep more that one definition around (merge them). However, 14764 // ensure the decl passes the structural compatibility check in 14765 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14766 NamedDecl *Hidden = nullptr; 14767 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14768 // There is a definition of this tag, but it is not visible. We 14769 // explicitly make use of C++'s one definition rule here, and 14770 // assume that this definition is identical to the hidden one 14771 // we already have. Make the existing definition visible and 14772 // use it in place of this one. 14773 if (!getLangOpts().CPlusPlus) { 14774 // Postpone making the old definition visible until after we 14775 // complete parsing the new one and do the structural 14776 // comparison. 14777 SkipBody->CheckSameAsPrevious = true; 14778 SkipBody->New = createTagFromNewDecl(); 14779 SkipBody->Previous = Def; 14780 return Def; 14781 } else { 14782 SkipBody->ShouldSkip = true; 14783 SkipBody->Previous = Def; 14784 makeMergedDefinitionVisible(Hidden); 14785 // Carry on and handle it like a normal definition. We'll 14786 // skip starting the definitiion later. 14787 } 14788 } else if (!IsExplicitSpecializationAfterInstantiation) { 14789 // A redeclaration in function prototype scope in C isn't 14790 // visible elsewhere, so merely issue a warning. 14791 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14792 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14793 else 14794 Diag(NameLoc, diag::err_redefinition) << Name; 14795 notePreviousDefinition(Def, 14796 NameLoc.isValid() ? NameLoc : KWLoc); 14797 // If this is a redefinition, recover by making this 14798 // struct be anonymous, which will make any later 14799 // references get the previous definition. 14800 Name = nullptr; 14801 Previous.clear(); 14802 Invalid = true; 14803 } 14804 } else { 14805 // If the type is currently being defined, complain 14806 // about a nested redefinition. 14807 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14808 if (TD->isBeingDefined()) { 14809 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14810 Diag(PrevTagDecl->getLocation(), 14811 diag::note_previous_definition); 14812 Name = nullptr; 14813 Previous.clear(); 14814 Invalid = true; 14815 } 14816 } 14817 14818 // Okay, this is definition of a previously declared or referenced 14819 // tag. We're going to create a new Decl for it. 14820 } 14821 14822 // Okay, we're going to make a redeclaration. If this is some kind 14823 // of reference, make sure we build the redeclaration in the same DC 14824 // as the original, and ignore the current access specifier. 14825 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14826 SearchDC = PrevTagDecl->getDeclContext(); 14827 AS = AS_none; 14828 } 14829 } 14830 // If we get here we have (another) forward declaration or we 14831 // have a definition. Just create a new decl. 14832 14833 } else { 14834 // If we get here, this is a definition of a new tag type in a nested 14835 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14836 // new decl/type. We set PrevDecl to NULL so that the entities 14837 // have distinct types. 14838 Previous.clear(); 14839 } 14840 // If we get here, we're going to create a new Decl. If PrevDecl 14841 // is non-NULL, it's a definition of the tag declared by 14842 // PrevDecl. If it's NULL, we have a new definition. 14843 14844 // Otherwise, PrevDecl is not a tag, but was found with tag 14845 // lookup. This is only actually possible in C++, where a few 14846 // things like templates still live in the tag namespace. 14847 } else { 14848 // Use a better diagnostic if an elaborated-type-specifier 14849 // found the wrong kind of type on the first 14850 // (non-redeclaration) lookup. 14851 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14852 !Previous.isForRedeclaration()) { 14853 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14854 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14855 << Kind; 14856 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14857 Invalid = true; 14858 14859 // Otherwise, only diagnose if the declaration is in scope. 14860 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14861 SS.isNotEmpty() || isMemberSpecialization)) { 14862 // do nothing 14863 14864 // Diagnose implicit declarations introduced by elaborated types. 14865 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14866 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14867 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14868 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14869 Invalid = true; 14870 14871 // Otherwise it's a declaration. Call out a particularly common 14872 // case here. 14873 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14874 unsigned Kind = 0; 14875 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14876 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14877 << Name << Kind << TND->getUnderlyingType(); 14878 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14879 Invalid = true; 14880 14881 // Otherwise, diagnose. 14882 } else { 14883 // The tag name clashes with something else in the target scope, 14884 // issue an error and recover by making this tag be anonymous. 14885 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14886 notePreviousDefinition(PrevDecl, NameLoc); 14887 Name = nullptr; 14888 Invalid = true; 14889 } 14890 14891 // The existing declaration isn't relevant to us; we're in a 14892 // new scope, so clear out the previous declaration. 14893 Previous.clear(); 14894 } 14895 } 14896 14897 CreateNewDecl: 14898 14899 TagDecl *PrevDecl = nullptr; 14900 if (Previous.isSingleResult()) 14901 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14902 14903 // If there is an identifier, use the location of the identifier as the 14904 // location of the decl, otherwise use the location of the struct/union 14905 // keyword. 14906 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14907 14908 // Otherwise, create a new declaration. If there is a previous 14909 // declaration of the same entity, the two will be linked via 14910 // PrevDecl. 14911 TagDecl *New; 14912 14913 if (Kind == TTK_Enum) { 14914 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14915 // enum X { A, B, C } D; D should chain to X. 14916 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14917 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14918 ScopedEnumUsesClassTag, IsFixed); 14919 14920 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14921 StdAlignValT = cast<EnumDecl>(New); 14922 14923 // If this is an undefined enum, warn. 14924 if (TUK != TUK_Definition && !Invalid) { 14925 TagDecl *Def; 14926 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 14927 // C++0x: 7.2p2: opaque-enum-declaration. 14928 // Conflicts are diagnosed above. Do nothing. 14929 } 14930 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14931 Diag(Loc, diag::ext_forward_ref_enum_def) 14932 << New; 14933 Diag(Def->getLocation(), diag::note_previous_definition); 14934 } else { 14935 unsigned DiagID = diag::ext_forward_ref_enum; 14936 if (getLangOpts().MSVCCompat) 14937 DiagID = diag::ext_ms_forward_ref_enum; 14938 else if (getLangOpts().CPlusPlus) 14939 DiagID = diag::err_forward_ref_enum; 14940 Diag(Loc, DiagID); 14941 } 14942 } 14943 14944 if (EnumUnderlying) { 14945 EnumDecl *ED = cast<EnumDecl>(New); 14946 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14947 ED->setIntegerTypeSourceInfo(TI); 14948 else 14949 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14950 ED->setPromotionType(ED->getIntegerType()); 14951 assert(ED->isComplete() && "enum with type should be complete"); 14952 } 14953 } else { 14954 // struct/union/class 14955 14956 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14957 // struct X { int A; } D; D should chain to X. 14958 if (getLangOpts().CPlusPlus) { 14959 // FIXME: Look for a way to use RecordDecl for simple structs. 14960 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14961 cast_or_null<CXXRecordDecl>(PrevDecl)); 14962 14963 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14964 StdBadAlloc = cast<CXXRecordDecl>(New); 14965 } else 14966 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14967 cast_or_null<RecordDecl>(PrevDecl)); 14968 } 14969 14970 // C++11 [dcl.type]p3: 14971 // A type-specifier-seq shall not define a class or enumeration [...]. 14972 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14973 TUK == TUK_Definition) { 14974 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14975 << Context.getTagDeclType(New); 14976 Invalid = true; 14977 } 14978 14979 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14980 DC->getDeclKind() == Decl::Enum) { 14981 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14982 << Context.getTagDeclType(New); 14983 Invalid = true; 14984 } 14985 14986 // Maybe add qualifier info. 14987 if (SS.isNotEmpty()) { 14988 if (SS.isSet()) { 14989 // If this is either a declaration or a definition, check the 14990 // nested-name-specifier against the current context. 14991 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14992 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14993 isMemberSpecialization)) 14994 Invalid = true; 14995 14996 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14997 if (TemplateParameterLists.size() > 0) { 14998 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14999 } 15000 } 15001 else 15002 Invalid = true; 15003 } 15004 15005 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15006 // Add alignment attributes if necessary; these attributes are checked when 15007 // the ASTContext lays out the structure. 15008 // 15009 // It is important for implementing the correct semantics that this 15010 // happen here (in ActOnTag). The #pragma pack stack is 15011 // maintained as a result of parser callbacks which can occur at 15012 // many points during the parsing of a struct declaration (because 15013 // the #pragma tokens are effectively skipped over during the 15014 // parsing of the struct). 15015 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15016 AddAlignmentAttributesForRecord(RD); 15017 AddMsStructLayoutForRecord(RD); 15018 } 15019 } 15020 15021 if (ModulePrivateLoc.isValid()) { 15022 if (isMemberSpecialization) 15023 Diag(New->getLocation(), diag::err_module_private_specialization) 15024 << 2 15025 << FixItHint::CreateRemoval(ModulePrivateLoc); 15026 // __module_private__ does not apply to local classes. However, we only 15027 // diagnose this as an error when the declaration specifiers are 15028 // freestanding. Here, we just ignore the __module_private__. 15029 else if (!SearchDC->isFunctionOrMethod()) 15030 New->setModulePrivate(); 15031 } 15032 15033 // If this is a specialization of a member class (of a class template), 15034 // check the specialization. 15035 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15036 Invalid = true; 15037 15038 // If we're declaring or defining a tag in function prototype scope in C, 15039 // note that this type can only be used within the function and add it to 15040 // the list of decls to inject into the function definition scope. 15041 if ((Name || Kind == TTK_Enum) && 15042 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15043 if (getLangOpts().CPlusPlus) { 15044 // C++ [dcl.fct]p6: 15045 // Types shall not be defined in return or parameter types. 15046 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15047 Diag(Loc, diag::err_type_defined_in_param_type) 15048 << Name; 15049 Invalid = true; 15050 } 15051 } else if (!PrevDecl) { 15052 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15053 } 15054 } 15055 15056 if (Invalid) 15057 New->setInvalidDecl(); 15058 15059 // Set the lexical context. If the tag has a C++ scope specifier, the 15060 // lexical context will be different from the semantic context. 15061 New->setLexicalDeclContext(CurContext); 15062 15063 // Mark this as a friend decl if applicable. 15064 // In Microsoft mode, a friend declaration also acts as a forward 15065 // declaration so we always pass true to setObjectOfFriendDecl to make 15066 // the tag name visible. 15067 if (TUK == TUK_Friend) 15068 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 15069 15070 // Set the access specifier. 15071 if (!Invalid && SearchDC->isRecord()) 15072 SetMemberAccessSpecifier(New, PrevDecl, AS); 15073 15074 if (PrevDecl) 15075 CheckRedeclarationModuleOwnership(New, PrevDecl); 15076 15077 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 15078 New->startDefinition(); 15079 15080 ProcessDeclAttributeList(S, New, Attrs); 15081 AddPragmaAttributes(S, New); 15082 15083 // If this has an identifier, add it to the scope stack. 15084 if (TUK == TUK_Friend) { 15085 // We might be replacing an existing declaration in the lookup tables; 15086 // if so, borrow its access specifier. 15087 if (PrevDecl) 15088 New->setAccess(PrevDecl->getAccess()); 15089 15090 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 15091 DC->makeDeclVisibleInContext(New); 15092 if (Name) // can be null along some error paths 15093 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15094 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 15095 } else if (Name) { 15096 S = getNonFieldDeclScope(S); 15097 PushOnScopeChains(New, S, true); 15098 } else { 15099 CurContext->addDecl(New); 15100 } 15101 15102 // If this is the C FILE type, notify the AST context. 15103 if (IdentifierInfo *II = New->getIdentifier()) 15104 if (!New->isInvalidDecl() && 15105 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 15106 II->isStr("FILE")) 15107 Context.setFILEDecl(New); 15108 15109 if (PrevDecl) 15110 mergeDeclAttributes(New, PrevDecl); 15111 15112 // If there's a #pragma GCC visibility in scope, set the visibility of this 15113 // record. 15114 AddPushedVisibilityAttribute(New); 15115 15116 if (isMemberSpecialization && !New->isInvalidDecl()) 15117 CompleteMemberSpecialization(New, Previous); 15118 15119 OwnedDecl = true; 15120 // In C++, don't return an invalid declaration. We can't recover well from 15121 // the cases where we make the type anonymous. 15122 if (Invalid && getLangOpts().CPlusPlus) { 15123 if (New->isBeingDefined()) 15124 if (auto RD = dyn_cast<RecordDecl>(New)) 15125 RD->completeDefinition(); 15126 return nullptr; 15127 } else if (SkipBody && SkipBody->ShouldSkip) { 15128 return SkipBody->Previous; 15129 } else { 15130 return New; 15131 } 15132 } 15133 15134 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 15135 AdjustDeclIfTemplate(TagD); 15136 TagDecl *Tag = cast<TagDecl>(TagD); 15137 15138 // Enter the tag context. 15139 PushDeclContext(S, Tag); 15140 15141 ActOnDocumentableDecl(TagD); 15142 15143 // If there's a #pragma GCC visibility in scope, set the visibility of this 15144 // record. 15145 AddPushedVisibilityAttribute(Tag); 15146 } 15147 15148 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 15149 SkipBodyInfo &SkipBody) { 15150 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 15151 return false; 15152 15153 // Make the previous decl visible. 15154 makeMergedDefinitionVisible(SkipBody.Previous); 15155 return true; 15156 } 15157 15158 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 15159 assert(isa<ObjCContainerDecl>(IDecl) && 15160 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 15161 DeclContext *OCD = cast<DeclContext>(IDecl); 15162 assert(getContainingDC(OCD) == CurContext && 15163 "The next DeclContext should be lexically contained in the current one."); 15164 CurContext = OCD; 15165 return IDecl; 15166 } 15167 15168 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 15169 SourceLocation FinalLoc, 15170 bool IsFinalSpelledSealed, 15171 SourceLocation LBraceLoc) { 15172 AdjustDeclIfTemplate(TagD); 15173 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 15174 15175 FieldCollector->StartClass(); 15176 15177 if (!Record->getIdentifier()) 15178 return; 15179 15180 if (FinalLoc.isValid()) 15181 Record->addAttr(new (Context) 15182 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 15183 15184 // C++ [class]p2: 15185 // [...] The class-name is also inserted into the scope of the 15186 // class itself; this is known as the injected-class-name. For 15187 // purposes of access checking, the injected-class-name is treated 15188 // as if it were a public member name. 15189 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 15190 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 15191 Record->getLocation(), Record->getIdentifier(), 15192 /*PrevDecl=*/nullptr, 15193 /*DelayTypeCreation=*/true); 15194 Context.getTypeDeclType(InjectedClassName, Record); 15195 InjectedClassName->setImplicit(); 15196 InjectedClassName->setAccess(AS_public); 15197 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 15198 InjectedClassName->setDescribedClassTemplate(Template); 15199 PushOnScopeChains(InjectedClassName, S); 15200 assert(InjectedClassName->isInjectedClassName() && 15201 "Broken injected-class-name"); 15202 } 15203 15204 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 15205 SourceRange BraceRange) { 15206 AdjustDeclIfTemplate(TagD); 15207 TagDecl *Tag = cast<TagDecl>(TagD); 15208 Tag->setBraceRange(BraceRange); 15209 15210 // Make sure we "complete" the definition even it is invalid. 15211 if (Tag->isBeingDefined()) { 15212 assert(Tag->isInvalidDecl() && "We should already have completed it"); 15213 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15214 RD->completeDefinition(); 15215 } 15216 15217 if (isa<CXXRecordDecl>(Tag)) { 15218 FieldCollector->FinishClass(); 15219 } 15220 15221 // Exit this scope of this tag's definition. 15222 PopDeclContext(); 15223 15224 if (getCurLexicalContext()->isObjCContainer() && 15225 Tag->getDeclContext()->isFileContext()) 15226 Tag->setTopLevelDeclInObjCContainer(); 15227 15228 // Notify the consumer that we've defined a tag. 15229 if (!Tag->isInvalidDecl()) 15230 Consumer.HandleTagDeclDefinition(Tag); 15231 } 15232 15233 void Sema::ActOnObjCContainerFinishDefinition() { 15234 // Exit this scope of this interface definition. 15235 PopDeclContext(); 15236 } 15237 15238 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 15239 assert(DC == CurContext && "Mismatch of container contexts"); 15240 OriginalLexicalContext = DC; 15241 ActOnObjCContainerFinishDefinition(); 15242 } 15243 15244 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 15245 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 15246 OriginalLexicalContext = nullptr; 15247 } 15248 15249 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 15250 AdjustDeclIfTemplate(TagD); 15251 TagDecl *Tag = cast<TagDecl>(TagD); 15252 Tag->setInvalidDecl(); 15253 15254 // Make sure we "complete" the definition even it is invalid. 15255 if (Tag->isBeingDefined()) { 15256 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15257 RD->completeDefinition(); 15258 } 15259 15260 // We're undoing ActOnTagStartDefinition here, not 15261 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 15262 // the FieldCollector. 15263 15264 PopDeclContext(); 15265 } 15266 15267 // Note that FieldName may be null for anonymous bitfields. 15268 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 15269 IdentifierInfo *FieldName, 15270 QualType FieldTy, bool IsMsStruct, 15271 Expr *BitWidth, bool *ZeroWidth) { 15272 // Default to true; that shouldn't confuse checks for emptiness 15273 if (ZeroWidth) 15274 *ZeroWidth = true; 15275 15276 // C99 6.7.2.1p4 - verify the field type. 15277 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 15278 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 15279 // Handle incomplete types with specific error. 15280 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 15281 return ExprError(); 15282 if (FieldName) 15283 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 15284 << FieldName << FieldTy << BitWidth->getSourceRange(); 15285 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 15286 << FieldTy << BitWidth->getSourceRange(); 15287 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 15288 UPPC_BitFieldWidth)) 15289 return ExprError(); 15290 15291 // If the bit-width is type- or value-dependent, don't try to check 15292 // it now. 15293 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 15294 return BitWidth; 15295 15296 llvm::APSInt Value; 15297 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 15298 if (ICE.isInvalid()) 15299 return ICE; 15300 BitWidth = ICE.get(); 15301 15302 if (Value != 0 && ZeroWidth) 15303 *ZeroWidth = false; 15304 15305 // Zero-width bitfield is ok for anonymous field. 15306 if (Value == 0 && FieldName) 15307 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 15308 15309 if (Value.isSigned() && Value.isNegative()) { 15310 if (FieldName) 15311 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 15312 << FieldName << Value.toString(10); 15313 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 15314 << Value.toString(10); 15315 } 15316 15317 if (!FieldTy->isDependentType()) { 15318 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 15319 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 15320 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 15321 15322 // Over-wide bitfields are an error in C or when using the MSVC bitfield 15323 // ABI. 15324 bool CStdConstraintViolation = 15325 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 15326 bool MSBitfieldViolation = 15327 Value.ugt(TypeStorageSize) && 15328 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 15329 if (CStdConstraintViolation || MSBitfieldViolation) { 15330 unsigned DiagWidth = 15331 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 15332 if (FieldName) 15333 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 15334 << FieldName << (unsigned)Value.getZExtValue() 15335 << !CStdConstraintViolation << DiagWidth; 15336 15337 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 15338 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 15339 << DiagWidth; 15340 } 15341 15342 // Warn on types where the user might conceivably expect to get all 15343 // specified bits as value bits: that's all integral types other than 15344 // 'bool'. 15345 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 15346 if (FieldName) 15347 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 15348 << FieldName << (unsigned)Value.getZExtValue() 15349 << (unsigned)TypeWidth; 15350 else 15351 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 15352 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 15353 } 15354 } 15355 15356 return BitWidth; 15357 } 15358 15359 /// ActOnField - Each field of a C struct/union is passed into this in order 15360 /// to create a FieldDecl object for it. 15361 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 15362 Declarator &D, Expr *BitfieldWidth) { 15363 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 15364 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 15365 /*InitStyle=*/ICIS_NoInit, AS_public); 15366 return Res; 15367 } 15368 15369 /// HandleField - Analyze a field of a C struct or a C++ data member. 15370 /// 15371 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 15372 SourceLocation DeclStart, 15373 Declarator &D, Expr *BitWidth, 15374 InClassInitStyle InitStyle, 15375 AccessSpecifier AS) { 15376 if (D.isDecompositionDeclarator()) { 15377 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 15378 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 15379 << Decomp.getSourceRange(); 15380 return nullptr; 15381 } 15382 15383 IdentifierInfo *II = D.getIdentifier(); 15384 SourceLocation Loc = DeclStart; 15385 if (II) Loc = D.getIdentifierLoc(); 15386 15387 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15388 QualType T = TInfo->getType(); 15389 if (getLangOpts().CPlusPlus) { 15390 CheckExtraCXXDefaultArguments(D); 15391 15392 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15393 UPPC_DataMemberType)) { 15394 D.setInvalidType(); 15395 T = Context.IntTy; 15396 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15397 } 15398 } 15399 15400 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15401 15402 if (D.getDeclSpec().isInlineSpecified()) 15403 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15404 << getLangOpts().CPlusPlus17; 15405 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15406 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15407 diag::err_invalid_thread) 15408 << DeclSpec::getSpecifierName(TSCS); 15409 15410 // Check to see if this name was declared as a member previously 15411 NamedDecl *PrevDecl = nullptr; 15412 LookupResult Previous(*this, II, Loc, LookupMemberName, 15413 ForVisibleRedeclaration); 15414 LookupName(Previous, S); 15415 switch (Previous.getResultKind()) { 15416 case LookupResult::Found: 15417 case LookupResult::FoundUnresolvedValue: 15418 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15419 break; 15420 15421 case LookupResult::FoundOverloaded: 15422 PrevDecl = Previous.getRepresentativeDecl(); 15423 break; 15424 15425 case LookupResult::NotFound: 15426 case LookupResult::NotFoundInCurrentInstantiation: 15427 case LookupResult::Ambiguous: 15428 break; 15429 } 15430 Previous.suppressDiagnostics(); 15431 15432 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15433 // Maybe we will complain about the shadowed template parameter. 15434 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15435 // Just pretend that we didn't see the previous declaration. 15436 PrevDecl = nullptr; 15437 } 15438 15439 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15440 PrevDecl = nullptr; 15441 15442 bool Mutable 15443 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 15444 SourceLocation TSSL = D.getBeginLoc(); 15445 FieldDecl *NewFD 15446 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 15447 TSSL, AS, PrevDecl, &D); 15448 15449 if (NewFD->isInvalidDecl()) 15450 Record->setInvalidDecl(); 15451 15452 if (D.getDeclSpec().isModulePrivateSpecified()) 15453 NewFD->setModulePrivate(); 15454 15455 if (NewFD->isInvalidDecl() && PrevDecl) { 15456 // Don't introduce NewFD into scope; there's already something 15457 // with the same name in the same scope. 15458 } else if (II) { 15459 PushOnScopeChains(NewFD, S); 15460 } else 15461 Record->addDecl(NewFD); 15462 15463 return NewFD; 15464 } 15465 15466 /// Build a new FieldDecl and check its well-formedness. 15467 /// 15468 /// This routine builds a new FieldDecl given the fields name, type, 15469 /// record, etc. \p PrevDecl should refer to any previous declaration 15470 /// with the same name and in the same scope as the field to be 15471 /// created. 15472 /// 15473 /// \returns a new FieldDecl. 15474 /// 15475 /// \todo The Declarator argument is a hack. It will be removed once 15476 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 15477 TypeSourceInfo *TInfo, 15478 RecordDecl *Record, SourceLocation Loc, 15479 bool Mutable, Expr *BitWidth, 15480 InClassInitStyle InitStyle, 15481 SourceLocation TSSL, 15482 AccessSpecifier AS, NamedDecl *PrevDecl, 15483 Declarator *D) { 15484 IdentifierInfo *II = Name.getAsIdentifierInfo(); 15485 bool InvalidDecl = false; 15486 if (D) InvalidDecl = D->isInvalidType(); 15487 15488 // If we receive a broken type, recover by assuming 'int' and 15489 // marking this declaration as invalid. 15490 if (T.isNull()) { 15491 InvalidDecl = true; 15492 T = Context.IntTy; 15493 } 15494 15495 QualType EltTy = Context.getBaseElementType(T); 15496 if (!EltTy->isDependentType()) { 15497 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 15498 // Fields of incomplete type force their record to be invalid. 15499 Record->setInvalidDecl(); 15500 InvalidDecl = true; 15501 } else { 15502 NamedDecl *Def; 15503 EltTy->isIncompleteType(&Def); 15504 if (Def && Def->isInvalidDecl()) { 15505 Record->setInvalidDecl(); 15506 InvalidDecl = true; 15507 } 15508 } 15509 } 15510 15511 // TR 18037 does not allow fields to be declared with address space 15512 if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || 15513 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 15514 Diag(Loc, diag::err_field_with_address_space); 15515 Record->setInvalidDecl(); 15516 InvalidDecl = true; 15517 } 15518 15519 if (LangOpts.OpenCL) { 15520 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 15521 // used as structure or union field: image, sampler, event or block types. 15522 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 15523 T->isBlockPointerType()) { 15524 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 15525 Record->setInvalidDecl(); 15526 InvalidDecl = true; 15527 } 15528 // OpenCL v1.2 s6.9.c: bitfields are not supported. 15529 if (BitWidth) { 15530 Diag(Loc, diag::err_opencl_bitfields); 15531 InvalidDecl = true; 15532 } 15533 } 15534 15535 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 15536 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 15537 T.hasQualifiers()) { 15538 InvalidDecl = true; 15539 Diag(Loc, diag::err_anon_bitfield_qualifiers); 15540 } 15541 15542 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15543 // than a variably modified type. 15544 if (!InvalidDecl && T->isVariablyModifiedType()) { 15545 bool SizeIsNegative; 15546 llvm::APSInt Oversized; 15547 15548 TypeSourceInfo *FixedTInfo = 15549 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 15550 SizeIsNegative, 15551 Oversized); 15552 if (FixedTInfo) { 15553 Diag(Loc, diag::warn_illegal_constant_array_size); 15554 TInfo = FixedTInfo; 15555 T = FixedTInfo->getType(); 15556 } else { 15557 if (SizeIsNegative) 15558 Diag(Loc, diag::err_typecheck_negative_array_size); 15559 else if (Oversized.getBoolValue()) 15560 Diag(Loc, diag::err_array_too_large) 15561 << Oversized.toString(10); 15562 else 15563 Diag(Loc, diag::err_typecheck_field_variable_size); 15564 InvalidDecl = true; 15565 } 15566 } 15567 15568 // Fields can not have abstract class types 15569 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 15570 diag::err_abstract_type_in_decl, 15571 AbstractFieldType)) 15572 InvalidDecl = true; 15573 15574 bool ZeroWidth = false; 15575 if (InvalidDecl) 15576 BitWidth = nullptr; 15577 // If this is declared as a bit-field, check the bit-field. 15578 if (BitWidth) { 15579 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 15580 &ZeroWidth).get(); 15581 if (!BitWidth) { 15582 InvalidDecl = true; 15583 BitWidth = nullptr; 15584 ZeroWidth = false; 15585 } 15586 } 15587 15588 // Check that 'mutable' is consistent with the type of the declaration. 15589 if (!InvalidDecl && Mutable) { 15590 unsigned DiagID = 0; 15591 if (T->isReferenceType()) 15592 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 15593 : diag::err_mutable_reference; 15594 else if (T.isConstQualified()) 15595 DiagID = diag::err_mutable_const; 15596 15597 if (DiagID) { 15598 SourceLocation ErrLoc = Loc; 15599 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 15600 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 15601 Diag(ErrLoc, DiagID); 15602 if (DiagID != diag::ext_mutable_reference) { 15603 Mutable = false; 15604 InvalidDecl = true; 15605 } 15606 } 15607 } 15608 15609 // C++11 [class.union]p8 (DR1460): 15610 // At most one variant member of a union may have a 15611 // brace-or-equal-initializer. 15612 if (InitStyle != ICIS_NoInit) 15613 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 15614 15615 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 15616 BitWidth, Mutable, InitStyle); 15617 if (InvalidDecl) 15618 NewFD->setInvalidDecl(); 15619 15620 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 15621 Diag(Loc, diag::err_duplicate_member) << II; 15622 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15623 NewFD->setInvalidDecl(); 15624 } 15625 15626 if (!InvalidDecl && getLangOpts().CPlusPlus) { 15627 if (Record->isUnion()) { 15628 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15629 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15630 if (RDecl->getDefinition()) { 15631 // C++ [class.union]p1: An object of a class with a non-trivial 15632 // constructor, a non-trivial copy constructor, a non-trivial 15633 // destructor, or a non-trivial copy assignment operator 15634 // cannot be a member of a union, nor can an array of such 15635 // objects. 15636 if (CheckNontrivialField(NewFD)) 15637 NewFD->setInvalidDecl(); 15638 } 15639 } 15640 15641 // C++ [class.union]p1: If a union contains a member of reference type, 15642 // the program is ill-formed, except when compiling with MSVC extensions 15643 // enabled. 15644 if (EltTy->isReferenceType()) { 15645 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15646 diag::ext_union_member_of_reference_type : 15647 diag::err_union_member_of_reference_type) 15648 << NewFD->getDeclName() << EltTy; 15649 if (!getLangOpts().MicrosoftExt) 15650 NewFD->setInvalidDecl(); 15651 } 15652 } 15653 } 15654 15655 // FIXME: We need to pass in the attributes given an AST 15656 // representation, not a parser representation. 15657 if (D) { 15658 // FIXME: The current scope is almost... but not entirely... correct here. 15659 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15660 15661 if (NewFD->hasAttrs()) 15662 CheckAlignasUnderalignment(NewFD); 15663 } 15664 15665 // In auto-retain/release, infer strong retension for fields of 15666 // retainable type. 15667 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15668 NewFD->setInvalidDecl(); 15669 15670 if (T.isObjCGCWeak()) 15671 Diag(Loc, diag::warn_attribute_weak_on_field); 15672 15673 NewFD->setAccess(AS); 15674 return NewFD; 15675 } 15676 15677 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15678 assert(FD); 15679 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15680 15681 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15682 return false; 15683 15684 QualType EltTy = Context.getBaseElementType(FD->getType()); 15685 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15686 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15687 if (RDecl->getDefinition()) { 15688 // We check for copy constructors before constructors 15689 // because otherwise we'll never get complaints about 15690 // copy constructors. 15691 15692 CXXSpecialMember member = CXXInvalid; 15693 // We're required to check for any non-trivial constructors. Since the 15694 // implicit default constructor is suppressed if there are any 15695 // user-declared constructors, we just need to check that there is a 15696 // trivial default constructor and a trivial copy constructor. (We don't 15697 // worry about move constructors here, since this is a C++98 check.) 15698 if (RDecl->hasNonTrivialCopyConstructor()) 15699 member = CXXCopyConstructor; 15700 else if (!RDecl->hasTrivialDefaultConstructor()) 15701 member = CXXDefaultConstructor; 15702 else if (RDecl->hasNonTrivialCopyAssignment()) 15703 member = CXXCopyAssignment; 15704 else if (RDecl->hasNonTrivialDestructor()) 15705 member = CXXDestructor; 15706 15707 if (member != CXXInvalid) { 15708 if (!getLangOpts().CPlusPlus11 && 15709 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15710 // Objective-C++ ARC: it is an error to have a non-trivial field of 15711 // a union. However, system headers in Objective-C programs 15712 // occasionally have Objective-C lifetime objects within unions, 15713 // and rather than cause the program to fail, we make those 15714 // members unavailable. 15715 SourceLocation Loc = FD->getLocation(); 15716 if (getSourceManager().isInSystemHeader(Loc)) { 15717 if (!FD->hasAttr<UnavailableAttr>()) 15718 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15719 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15720 return false; 15721 } 15722 } 15723 15724 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15725 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15726 diag::err_illegal_union_or_anon_struct_member) 15727 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15728 DiagnoseNontrivial(RDecl, member); 15729 return !getLangOpts().CPlusPlus11; 15730 } 15731 } 15732 } 15733 15734 return false; 15735 } 15736 15737 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15738 /// AST enum value. 15739 static ObjCIvarDecl::AccessControl 15740 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15741 switch (ivarVisibility) { 15742 default: llvm_unreachable("Unknown visitibility kind"); 15743 case tok::objc_private: return ObjCIvarDecl::Private; 15744 case tok::objc_public: return ObjCIvarDecl::Public; 15745 case tok::objc_protected: return ObjCIvarDecl::Protected; 15746 case tok::objc_package: return ObjCIvarDecl::Package; 15747 } 15748 } 15749 15750 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15751 /// in order to create an IvarDecl object for it. 15752 Decl *Sema::ActOnIvar(Scope *S, 15753 SourceLocation DeclStart, 15754 Declarator &D, Expr *BitfieldWidth, 15755 tok::ObjCKeywordKind Visibility) { 15756 15757 IdentifierInfo *II = D.getIdentifier(); 15758 Expr *BitWidth = (Expr*)BitfieldWidth; 15759 SourceLocation Loc = DeclStart; 15760 if (II) Loc = D.getIdentifierLoc(); 15761 15762 // FIXME: Unnamed fields can be handled in various different ways, for 15763 // example, unnamed unions inject all members into the struct namespace! 15764 15765 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15766 QualType T = TInfo->getType(); 15767 15768 if (BitWidth) { 15769 // 6.7.2.1p3, 6.7.2.1p4 15770 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15771 if (!BitWidth) 15772 D.setInvalidType(); 15773 } else { 15774 // Not a bitfield. 15775 15776 // validate II. 15777 15778 } 15779 if (T->isReferenceType()) { 15780 Diag(Loc, diag::err_ivar_reference_type); 15781 D.setInvalidType(); 15782 } 15783 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15784 // than a variably modified type. 15785 else if (T->isVariablyModifiedType()) { 15786 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15787 D.setInvalidType(); 15788 } 15789 15790 // Get the visibility (access control) for this ivar. 15791 ObjCIvarDecl::AccessControl ac = 15792 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15793 : ObjCIvarDecl::None; 15794 // Must set ivar's DeclContext to its enclosing interface. 15795 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15796 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15797 return nullptr; 15798 ObjCContainerDecl *EnclosingContext; 15799 if (ObjCImplementationDecl *IMPDecl = 15800 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15801 if (LangOpts.ObjCRuntime.isFragile()) { 15802 // Case of ivar declared in an implementation. Context is that of its class. 15803 EnclosingContext = IMPDecl->getClassInterface(); 15804 assert(EnclosingContext && "Implementation has no class interface!"); 15805 } 15806 else 15807 EnclosingContext = EnclosingDecl; 15808 } else { 15809 if (ObjCCategoryDecl *CDecl = 15810 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15811 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15812 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15813 return nullptr; 15814 } 15815 } 15816 EnclosingContext = EnclosingDecl; 15817 } 15818 15819 // Construct the decl. 15820 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15821 DeclStart, Loc, II, T, 15822 TInfo, ac, (Expr *)BitfieldWidth); 15823 15824 if (II) { 15825 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15826 ForVisibleRedeclaration); 15827 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15828 && !isa<TagDecl>(PrevDecl)) { 15829 Diag(Loc, diag::err_duplicate_member) << II; 15830 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15831 NewID->setInvalidDecl(); 15832 } 15833 } 15834 15835 // Process attributes attached to the ivar. 15836 ProcessDeclAttributes(S, NewID, D); 15837 15838 if (D.isInvalidType()) 15839 NewID->setInvalidDecl(); 15840 15841 // In ARC, infer 'retaining' for ivars of retainable type. 15842 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15843 NewID->setInvalidDecl(); 15844 15845 if (D.getDeclSpec().isModulePrivateSpecified()) 15846 NewID->setModulePrivate(); 15847 15848 if (II) { 15849 // FIXME: When interfaces are DeclContexts, we'll need to add 15850 // these to the interface. 15851 S->AddDecl(NewID); 15852 IdResolver.AddDecl(NewID); 15853 } 15854 15855 if (LangOpts.ObjCRuntime.isNonFragile() && 15856 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15857 Diag(Loc, diag::warn_ivars_in_interface); 15858 15859 return NewID; 15860 } 15861 15862 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15863 /// class and class extensions. For every class \@interface and class 15864 /// extension \@interface, if the last ivar is a bitfield of any type, 15865 /// then add an implicit `char :0` ivar to the end of that interface. 15866 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15867 SmallVectorImpl<Decl *> &AllIvarDecls) { 15868 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15869 return; 15870 15871 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15872 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15873 15874 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15875 return; 15876 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15877 if (!ID) { 15878 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15879 if (!CD->IsClassExtension()) 15880 return; 15881 } 15882 // No need to add this to end of @implementation. 15883 else 15884 return; 15885 } 15886 // All conditions are met. Add a new bitfield to the tail end of ivars. 15887 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15888 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15889 15890 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15891 DeclLoc, DeclLoc, nullptr, 15892 Context.CharTy, 15893 Context.getTrivialTypeSourceInfo(Context.CharTy, 15894 DeclLoc), 15895 ObjCIvarDecl::Private, BW, 15896 true); 15897 AllIvarDecls.push_back(Ivar); 15898 } 15899 15900 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15901 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15902 SourceLocation RBrac, 15903 const ParsedAttributesView &Attrs) { 15904 assert(EnclosingDecl && "missing record or interface decl"); 15905 15906 // If this is an Objective-C @implementation or category and we have 15907 // new fields here we should reset the layout of the interface since 15908 // it will now change. 15909 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15910 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15911 switch (DC->getKind()) { 15912 default: break; 15913 case Decl::ObjCCategory: 15914 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15915 break; 15916 case Decl::ObjCImplementation: 15917 Context. 15918 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15919 break; 15920 } 15921 } 15922 15923 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15924 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 15925 15926 // Start counting up the number of named members; make sure to include 15927 // members of anonymous structs and unions in the total. 15928 unsigned NumNamedMembers = 0; 15929 if (Record) { 15930 for (const auto *I : Record->decls()) { 15931 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15932 if (IFD->getDeclName()) 15933 ++NumNamedMembers; 15934 } 15935 } 15936 15937 // Verify that all the fields are okay. 15938 SmallVector<FieldDecl*, 32> RecFields; 15939 15940 bool ObjCFieldLifetimeErrReported = false; 15941 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15942 i != end; ++i) { 15943 FieldDecl *FD = cast<FieldDecl>(*i); 15944 15945 // Get the type for the field. 15946 const Type *FDTy = FD->getType().getTypePtr(); 15947 15948 if (!FD->isAnonymousStructOrUnion()) { 15949 // Remember all fields written by the user. 15950 RecFields.push_back(FD); 15951 } 15952 15953 // If the field is already invalid for some reason, don't emit more 15954 // diagnostics about it. 15955 if (FD->isInvalidDecl()) { 15956 EnclosingDecl->setInvalidDecl(); 15957 continue; 15958 } 15959 15960 // C99 6.7.2.1p2: 15961 // A structure or union shall not contain a member with 15962 // incomplete or function type (hence, a structure shall not 15963 // contain an instance of itself, but may contain a pointer to 15964 // an instance of itself), except that the last member of a 15965 // structure with more than one named member may have incomplete 15966 // array type; such a structure (and any union containing, 15967 // possibly recursively, a member that is such a structure) 15968 // shall not be a member of a structure or an element of an 15969 // array. 15970 bool IsLastField = (i + 1 == Fields.end()); 15971 if (FDTy->isFunctionType()) { 15972 // Field declared as a function. 15973 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15974 << FD->getDeclName(); 15975 FD->setInvalidDecl(); 15976 EnclosingDecl->setInvalidDecl(); 15977 continue; 15978 } else if (FDTy->isIncompleteArrayType() && 15979 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15980 if (Record) { 15981 // Flexible array member. 15982 // Microsoft and g++ is more permissive regarding flexible array. 15983 // It will accept flexible array in union and also 15984 // as the sole element of a struct/class. 15985 unsigned DiagID = 0; 15986 if (!Record->isUnion() && !IsLastField) { 15987 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15988 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15989 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15990 FD->setInvalidDecl(); 15991 EnclosingDecl->setInvalidDecl(); 15992 continue; 15993 } else if (Record->isUnion()) 15994 DiagID = getLangOpts().MicrosoftExt 15995 ? diag::ext_flexible_array_union_ms 15996 : getLangOpts().CPlusPlus 15997 ? diag::ext_flexible_array_union_gnu 15998 : diag::err_flexible_array_union; 15999 else if (NumNamedMembers < 1) 16000 DiagID = getLangOpts().MicrosoftExt 16001 ? diag::ext_flexible_array_empty_aggregate_ms 16002 : getLangOpts().CPlusPlus 16003 ? diag::ext_flexible_array_empty_aggregate_gnu 16004 : diag::err_flexible_array_empty_aggregate; 16005 16006 if (DiagID) 16007 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16008 << Record->getTagKind(); 16009 // While the layout of types that contain virtual bases is not specified 16010 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16011 // virtual bases after the derived members. This would make a flexible 16012 // array member declared at the end of an object not adjacent to the end 16013 // of the type. 16014 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16015 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16016 << FD->getDeclName() << Record->getTagKind(); 16017 if (!getLangOpts().C99) 16018 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16019 << FD->getDeclName() << Record->getTagKind(); 16020 16021 // If the element type has a non-trivial destructor, we would not 16022 // implicitly destroy the elements, so disallow it for now. 16023 // 16024 // FIXME: GCC allows this. We should probably either implicitly delete 16025 // the destructor of the containing class, or just allow this. 16026 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16027 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16028 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16029 << FD->getDeclName() << FD->getType(); 16030 FD->setInvalidDecl(); 16031 EnclosingDecl->setInvalidDecl(); 16032 continue; 16033 } 16034 // Okay, we have a legal flexible array member at the end of the struct. 16035 Record->setHasFlexibleArrayMember(true); 16036 } else { 16037 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16038 // unless they are followed by another ivar. That check is done 16039 // elsewhere, after synthesized ivars are known. 16040 } 16041 } else if (!FDTy->isDependentType() && 16042 RequireCompleteType(FD->getLocation(), FD->getType(), 16043 diag::err_field_incomplete)) { 16044 // Incomplete type 16045 FD->setInvalidDecl(); 16046 EnclosingDecl->setInvalidDecl(); 16047 continue; 16048 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 16049 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 16050 // A type which contains a flexible array member is considered to be a 16051 // flexible array member. 16052 Record->setHasFlexibleArrayMember(true); 16053 if (!Record->isUnion()) { 16054 // If this is a struct/class and this is not the last element, reject 16055 // it. Note that GCC supports variable sized arrays in the middle of 16056 // structures. 16057 if (!IsLastField) 16058 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 16059 << FD->getDeclName() << FD->getType(); 16060 else { 16061 // We support flexible arrays at the end of structs in 16062 // other structs as an extension. 16063 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 16064 << FD->getDeclName(); 16065 } 16066 } 16067 } 16068 if (isa<ObjCContainerDecl>(EnclosingDecl) && 16069 RequireNonAbstractType(FD->getLocation(), FD->getType(), 16070 diag::err_abstract_type_in_decl, 16071 AbstractIvarType)) { 16072 // Ivars can not have abstract class types 16073 FD->setInvalidDecl(); 16074 } 16075 if (Record && FDTTy->getDecl()->hasObjectMember()) 16076 Record->setHasObjectMember(true); 16077 if (Record && FDTTy->getDecl()->hasVolatileMember()) 16078 Record->setHasVolatileMember(true); 16079 if (Record && Record->isUnion() && 16080 FD->getType().isNonTrivialPrimitiveCType(Context)) 16081 Diag(FD->getLocation(), 16082 diag::err_nontrivial_primitive_type_in_union); 16083 } else if (FDTy->isObjCObjectType()) { 16084 /// A field cannot be an Objective-c object 16085 Diag(FD->getLocation(), diag::err_statically_allocated_object) 16086 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 16087 QualType T = Context.getObjCObjectPointerType(FD->getType()); 16088 FD->setType(T); 16089 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 16090 Record && !ObjCFieldLifetimeErrReported && Record->isUnion() && 16091 !getLangOpts().CPlusPlus) { 16092 // It's an error in ARC or Weak if a field has lifetime. 16093 // We don't want to report this in a system header, though, 16094 // so we just make the field unavailable. 16095 // FIXME: that's really not sufficient; we need to make the type 16096 // itself invalid to, say, initialize or copy. 16097 QualType T = FD->getType(); 16098 if (T.hasNonTrivialObjCLifetime()) { 16099 SourceLocation loc = FD->getLocation(); 16100 if (getSourceManager().isInSystemHeader(loc)) { 16101 if (!FD->hasAttr<UnavailableAttr>()) { 16102 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16103 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 16104 } 16105 } else { 16106 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 16107 << T->isBlockPointerType() << Record->getTagKind(); 16108 } 16109 ObjCFieldLifetimeErrReported = true; 16110 } 16111 } else if (getLangOpts().ObjC && 16112 getLangOpts().getGC() != LangOptions::NonGC && 16113 Record && !Record->hasObjectMember()) { 16114 if (FD->getType()->isObjCObjectPointerType() || 16115 FD->getType().isObjCGCStrong()) 16116 Record->setHasObjectMember(true); 16117 else if (Context.getAsArrayType(FD->getType())) { 16118 QualType BaseType = Context.getBaseElementType(FD->getType()); 16119 if (BaseType->isRecordType() && 16120 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 16121 Record->setHasObjectMember(true); 16122 else if (BaseType->isObjCObjectPointerType() || 16123 BaseType.isObjCGCStrong()) 16124 Record->setHasObjectMember(true); 16125 } 16126 } 16127 16128 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 16129 QualType FT = FD->getType(); 16130 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 16131 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 16132 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 16133 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 16134 Record->setNonTrivialToPrimitiveCopy(true); 16135 if (FT.isDestructedType()) { 16136 Record->setNonTrivialToPrimitiveDestroy(true); 16137 Record->setParamDestroyedInCallee(true); 16138 } 16139 16140 if (const auto *RT = FT->getAs<RecordType>()) { 16141 if (RT->getDecl()->getArgPassingRestrictions() == 16142 RecordDecl::APK_CanNeverPassInRegs) 16143 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16144 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 16145 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16146 } 16147 16148 if (Record && FD->getType().isVolatileQualified()) 16149 Record->setHasVolatileMember(true); 16150 // Keep track of the number of named members. 16151 if (FD->getIdentifier()) 16152 ++NumNamedMembers; 16153 } 16154 16155 // Okay, we successfully defined 'Record'. 16156 if (Record) { 16157 bool Completed = false; 16158 if (CXXRecord) { 16159 if (!CXXRecord->isInvalidDecl()) { 16160 // Set access bits correctly on the directly-declared conversions. 16161 for (CXXRecordDecl::conversion_iterator 16162 I = CXXRecord->conversion_begin(), 16163 E = CXXRecord->conversion_end(); I != E; ++I) 16164 I.setAccess((*I)->getAccess()); 16165 } 16166 16167 if (!CXXRecord->isDependentType()) { 16168 // Add any implicitly-declared members to this class. 16169 AddImplicitlyDeclaredMembersToClass(CXXRecord); 16170 16171 if (!CXXRecord->isInvalidDecl()) { 16172 // If we have virtual base classes, we may end up finding multiple 16173 // final overriders for a given virtual function. Check for this 16174 // problem now. 16175 if (CXXRecord->getNumVBases()) { 16176 CXXFinalOverriderMap FinalOverriders; 16177 CXXRecord->getFinalOverriders(FinalOverriders); 16178 16179 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 16180 MEnd = FinalOverriders.end(); 16181 M != MEnd; ++M) { 16182 for (OverridingMethods::iterator SO = M->second.begin(), 16183 SOEnd = M->second.end(); 16184 SO != SOEnd; ++SO) { 16185 assert(SO->second.size() > 0 && 16186 "Virtual function without overriding functions?"); 16187 if (SO->second.size() == 1) 16188 continue; 16189 16190 // C++ [class.virtual]p2: 16191 // In a derived class, if a virtual member function of a base 16192 // class subobject has more than one final overrider the 16193 // program is ill-formed. 16194 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 16195 << (const NamedDecl *)M->first << Record; 16196 Diag(M->first->getLocation(), 16197 diag::note_overridden_virtual_function); 16198 for (OverridingMethods::overriding_iterator 16199 OM = SO->second.begin(), 16200 OMEnd = SO->second.end(); 16201 OM != OMEnd; ++OM) 16202 Diag(OM->Method->getLocation(), diag::note_final_overrider) 16203 << (const NamedDecl *)M->first << OM->Method->getParent(); 16204 16205 Record->setInvalidDecl(); 16206 } 16207 } 16208 CXXRecord->completeDefinition(&FinalOverriders); 16209 Completed = true; 16210 } 16211 } 16212 } 16213 } 16214 16215 if (!Completed) 16216 Record->completeDefinition(); 16217 16218 // Handle attributes before checking the layout. 16219 ProcessDeclAttributeList(S, Record, Attrs); 16220 16221 // We may have deferred checking for a deleted destructor. Check now. 16222 if (CXXRecord) { 16223 auto *Dtor = CXXRecord->getDestructor(); 16224 if (Dtor && Dtor->isImplicit() && 16225 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 16226 CXXRecord->setImplicitDestructorIsDeleted(); 16227 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 16228 } 16229 } 16230 16231 if (Record->hasAttrs()) { 16232 CheckAlignasUnderalignment(Record); 16233 16234 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 16235 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 16236 IA->getRange(), IA->getBestCase(), 16237 IA->getSemanticSpelling()); 16238 } 16239 16240 // Check if the structure/union declaration is a type that can have zero 16241 // size in C. For C this is a language extension, for C++ it may cause 16242 // compatibility problems. 16243 bool CheckForZeroSize; 16244 if (!getLangOpts().CPlusPlus) { 16245 CheckForZeroSize = true; 16246 } else { 16247 // For C++ filter out types that cannot be referenced in C code. 16248 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 16249 CheckForZeroSize = 16250 CXXRecord->getLexicalDeclContext()->isExternCContext() && 16251 !CXXRecord->isDependentType() && 16252 CXXRecord->isCLike(); 16253 } 16254 if (CheckForZeroSize) { 16255 bool ZeroSize = true; 16256 bool IsEmpty = true; 16257 unsigned NonBitFields = 0; 16258 for (RecordDecl::field_iterator I = Record->field_begin(), 16259 E = Record->field_end(); 16260 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 16261 IsEmpty = false; 16262 if (I->isUnnamedBitfield()) { 16263 if (!I->isZeroLengthBitField(Context)) 16264 ZeroSize = false; 16265 } else { 16266 ++NonBitFields; 16267 QualType FieldType = I->getType(); 16268 if (FieldType->isIncompleteType() || 16269 !Context.getTypeSizeInChars(FieldType).isZero()) 16270 ZeroSize = false; 16271 } 16272 } 16273 16274 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 16275 // allowed in C++, but warn if its declaration is inside 16276 // extern "C" block. 16277 if (ZeroSize) { 16278 Diag(RecLoc, getLangOpts().CPlusPlus ? 16279 diag::warn_zero_size_struct_union_in_extern_c : 16280 diag::warn_zero_size_struct_union_compat) 16281 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 16282 } 16283 16284 // Structs without named members are extension in C (C99 6.7.2.1p7), 16285 // but are accepted by GCC. 16286 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 16287 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 16288 diag::ext_no_named_members_in_struct_union) 16289 << Record->isUnion(); 16290 } 16291 } 16292 } else { 16293 ObjCIvarDecl **ClsFields = 16294 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 16295 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 16296 ID->setEndOfDefinitionLoc(RBrac); 16297 // Add ivar's to class's DeclContext. 16298 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16299 ClsFields[i]->setLexicalDeclContext(ID); 16300 ID->addDecl(ClsFields[i]); 16301 } 16302 // Must enforce the rule that ivars in the base classes may not be 16303 // duplicates. 16304 if (ID->getSuperClass()) 16305 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 16306 } else if (ObjCImplementationDecl *IMPDecl = 16307 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16308 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 16309 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 16310 // Ivar declared in @implementation never belongs to the implementation. 16311 // Only it is in implementation's lexical context. 16312 ClsFields[I]->setLexicalDeclContext(IMPDecl); 16313 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 16314 IMPDecl->setIvarLBraceLoc(LBrac); 16315 IMPDecl->setIvarRBraceLoc(RBrac); 16316 } else if (ObjCCategoryDecl *CDecl = 16317 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16318 // case of ivars in class extension; all other cases have been 16319 // reported as errors elsewhere. 16320 // FIXME. Class extension does not have a LocEnd field. 16321 // CDecl->setLocEnd(RBrac); 16322 // Add ivar's to class extension's DeclContext. 16323 // Diagnose redeclaration of private ivars. 16324 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 16325 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16326 if (IDecl) { 16327 if (const ObjCIvarDecl *ClsIvar = 16328 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 16329 Diag(ClsFields[i]->getLocation(), 16330 diag::err_duplicate_ivar_declaration); 16331 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 16332 continue; 16333 } 16334 for (const auto *Ext : IDecl->known_extensions()) { 16335 if (const ObjCIvarDecl *ClsExtIvar 16336 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 16337 Diag(ClsFields[i]->getLocation(), 16338 diag::err_duplicate_ivar_declaration); 16339 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 16340 continue; 16341 } 16342 } 16343 } 16344 ClsFields[i]->setLexicalDeclContext(CDecl); 16345 CDecl->addDecl(ClsFields[i]); 16346 } 16347 CDecl->setIvarLBraceLoc(LBrac); 16348 CDecl->setIvarRBraceLoc(RBrac); 16349 } 16350 } 16351 } 16352 16353 /// Determine whether the given integral value is representable within 16354 /// the given type T. 16355 static bool isRepresentableIntegerValue(ASTContext &Context, 16356 llvm::APSInt &Value, 16357 QualType T) { 16358 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 16359 "Integral type required!"); 16360 unsigned BitWidth = Context.getIntWidth(T); 16361 16362 if (Value.isUnsigned() || Value.isNonNegative()) { 16363 if (T->isSignedIntegerOrEnumerationType()) 16364 --BitWidth; 16365 return Value.getActiveBits() <= BitWidth; 16366 } 16367 return Value.getMinSignedBits() <= BitWidth; 16368 } 16369 16370 // Given an integral type, return the next larger integral type 16371 // (or a NULL type of no such type exists). 16372 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 16373 // FIXME: Int128/UInt128 support, which also needs to be introduced into 16374 // enum checking below. 16375 assert((T->isIntegralType(Context) || 16376 T->isEnumeralType()) && "Integral type required!"); 16377 const unsigned NumTypes = 4; 16378 QualType SignedIntegralTypes[NumTypes] = { 16379 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 16380 }; 16381 QualType UnsignedIntegralTypes[NumTypes] = { 16382 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 16383 Context.UnsignedLongLongTy 16384 }; 16385 16386 unsigned BitWidth = Context.getTypeSize(T); 16387 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 16388 : UnsignedIntegralTypes; 16389 for (unsigned I = 0; I != NumTypes; ++I) 16390 if (Context.getTypeSize(Types[I]) > BitWidth) 16391 return Types[I]; 16392 16393 return QualType(); 16394 } 16395 16396 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 16397 EnumConstantDecl *LastEnumConst, 16398 SourceLocation IdLoc, 16399 IdentifierInfo *Id, 16400 Expr *Val) { 16401 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16402 llvm::APSInt EnumVal(IntWidth); 16403 QualType EltTy; 16404 16405 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 16406 Val = nullptr; 16407 16408 if (Val) 16409 Val = DefaultLvalueConversion(Val).get(); 16410 16411 if (Val) { 16412 if (Enum->isDependentType() || Val->isTypeDependent()) 16413 EltTy = Context.DependentTy; 16414 else { 16415 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 16416 !getLangOpts().MSVCCompat) { 16417 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 16418 // constant-expression in the enumerator-definition shall be a converted 16419 // constant expression of the underlying type. 16420 EltTy = Enum->getIntegerType(); 16421 ExprResult Converted = 16422 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 16423 CCEK_Enumerator); 16424 if (Converted.isInvalid()) 16425 Val = nullptr; 16426 else 16427 Val = Converted.get(); 16428 } else if (!Val->isValueDependent() && 16429 !(Val = VerifyIntegerConstantExpression(Val, 16430 &EnumVal).get())) { 16431 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 16432 } else { 16433 if (Enum->isComplete()) { 16434 EltTy = Enum->getIntegerType(); 16435 16436 // In Obj-C and Microsoft mode, require the enumeration value to be 16437 // representable in the underlying type of the enumeration. In C++11, 16438 // we perform a non-narrowing conversion as part of converted constant 16439 // expression checking. 16440 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16441 if (getLangOpts().MSVCCompat) { 16442 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 16443 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 16444 } else 16445 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 16446 } else 16447 Val = ImpCastExprToType(Val, EltTy, 16448 EltTy->isBooleanType() ? 16449 CK_IntegralToBoolean : CK_IntegralCast) 16450 .get(); 16451 } else if (getLangOpts().CPlusPlus) { 16452 // C++11 [dcl.enum]p5: 16453 // If the underlying type is not fixed, the type of each enumerator 16454 // is the type of its initializing value: 16455 // - If an initializer is specified for an enumerator, the 16456 // initializing value has the same type as the expression. 16457 EltTy = Val->getType(); 16458 } else { 16459 // C99 6.7.2.2p2: 16460 // The expression that defines the value of an enumeration constant 16461 // shall be an integer constant expression that has a value 16462 // representable as an int. 16463 16464 // Complain if the value is not representable in an int. 16465 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 16466 Diag(IdLoc, diag::ext_enum_value_not_int) 16467 << EnumVal.toString(10) << Val->getSourceRange() 16468 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 16469 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 16470 // Force the type of the expression to 'int'. 16471 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 16472 } 16473 EltTy = Val->getType(); 16474 } 16475 } 16476 } 16477 } 16478 16479 if (!Val) { 16480 if (Enum->isDependentType()) 16481 EltTy = Context.DependentTy; 16482 else if (!LastEnumConst) { 16483 // C++0x [dcl.enum]p5: 16484 // If the underlying type is not fixed, the type of each enumerator 16485 // is the type of its initializing value: 16486 // - If no initializer is specified for the first enumerator, the 16487 // initializing value has an unspecified integral type. 16488 // 16489 // GCC uses 'int' for its unspecified integral type, as does 16490 // C99 6.7.2.2p3. 16491 if (Enum->isFixed()) { 16492 EltTy = Enum->getIntegerType(); 16493 } 16494 else { 16495 EltTy = Context.IntTy; 16496 } 16497 } else { 16498 // Assign the last value + 1. 16499 EnumVal = LastEnumConst->getInitVal(); 16500 ++EnumVal; 16501 EltTy = LastEnumConst->getType(); 16502 16503 // Check for overflow on increment. 16504 if (EnumVal < LastEnumConst->getInitVal()) { 16505 // C++0x [dcl.enum]p5: 16506 // If the underlying type is not fixed, the type of each enumerator 16507 // is the type of its initializing value: 16508 // 16509 // - Otherwise the type of the initializing value is the same as 16510 // the type of the initializing value of the preceding enumerator 16511 // unless the incremented value is not representable in that type, 16512 // in which case the type is an unspecified integral type 16513 // sufficient to contain the incremented value. If no such type 16514 // exists, the program is ill-formed. 16515 QualType T = getNextLargerIntegralType(Context, EltTy); 16516 if (T.isNull() || Enum->isFixed()) { 16517 // There is no integral type larger enough to represent this 16518 // value. Complain, then allow the value to wrap around. 16519 EnumVal = LastEnumConst->getInitVal(); 16520 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 16521 ++EnumVal; 16522 if (Enum->isFixed()) 16523 // When the underlying type is fixed, this is ill-formed. 16524 Diag(IdLoc, diag::err_enumerator_wrapped) 16525 << EnumVal.toString(10) 16526 << EltTy; 16527 else 16528 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 16529 << EnumVal.toString(10); 16530 } else { 16531 EltTy = T; 16532 } 16533 16534 // Retrieve the last enumerator's value, extent that type to the 16535 // type that is supposed to be large enough to represent the incremented 16536 // value, then increment. 16537 EnumVal = LastEnumConst->getInitVal(); 16538 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16539 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 16540 ++EnumVal; 16541 16542 // If we're not in C++, diagnose the overflow of enumerator values, 16543 // which in C99 means that the enumerator value is not representable in 16544 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 16545 // permits enumerator values that are representable in some larger 16546 // integral type. 16547 if (!getLangOpts().CPlusPlus && !T.isNull()) 16548 Diag(IdLoc, diag::warn_enum_value_overflow); 16549 } else if (!getLangOpts().CPlusPlus && 16550 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16551 // Enforce C99 6.7.2.2p2 even when we compute the next value. 16552 Diag(IdLoc, diag::ext_enum_value_not_int) 16553 << EnumVal.toString(10) << 1; 16554 } 16555 } 16556 } 16557 16558 if (!EltTy->isDependentType()) { 16559 // Make the enumerator value match the signedness and size of the 16560 // enumerator's type. 16561 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 16562 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16563 } 16564 16565 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 16566 Val, EnumVal); 16567 } 16568 16569 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 16570 SourceLocation IILoc) { 16571 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 16572 !getLangOpts().CPlusPlus) 16573 return SkipBodyInfo(); 16574 16575 // We have an anonymous enum definition. Look up the first enumerator to 16576 // determine if we should merge the definition with an existing one and 16577 // skip the body. 16578 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 16579 forRedeclarationInCurContext()); 16580 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 16581 if (!PrevECD) 16582 return SkipBodyInfo(); 16583 16584 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 16585 NamedDecl *Hidden; 16586 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 16587 SkipBodyInfo Skip; 16588 Skip.Previous = Hidden; 16589 return Skip; 16590 } 16591 16592 return SkipBodyInfo(); 16593 } 16594 16595 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 16596 SourceLocation IdLoc, IdentifierInfo *Id, 16597 const ParsedAttributesView &Attrs, 16598 SourceLocation EqualLoc, Expr *Val) { 16599 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 16600 EnumConstantDecl *LastEnumConst = 16601 cast_or_null<EnumConstantDecl>(lastEnumConst); 16602 16603 // The scope passed in may not be a decl scope. Zip up the scope tree until 16604 // we find one that is. 16605 S = getNonFieldDeclScope(S); 16606 16607 // Verify that there isn't already something declared with this name in this 16608 // scope. 16609 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 16610 LookupName(R, S); 16611 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 16612 16613 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16614 // Maybe we will complain about the shadowed template parameter. 16615 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 16616 // Just pretend that we didn't see the previous declaration. 16617 PrevDecl = nullptr; 16618 } 16619 16620 // C++ [class.mem]p15: 16621 // If T is the name of a class, then each of the following shall have a name 16622 // different from T: 16623 // - every enumerator of every member of class T that is an unscoped 16624 // enumerated type 16625 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 16626 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 16627 DeclarationNameInfo(Id, IdLoc)); 16628 16629 EnumConstantDecl *New = 16630 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 16631 if (!New) 16632 return nullptr; 16633 16634 if (PrevDecl) { 16635 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 16636 // Check for other kinds of shadowing not already handled. 16637 CheckShadow(New, PrevDecl, R); 16638 } 16639 16640 // When in C++, we may get a TagDecl with the same name; in this case the 16641 // enum constant will 'hide' the tag. 16642 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 16643 "Received TagDecl when not in C++!"); 16644 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 16645 if (isa<EnumConstantDecl>(PrevDecl)) 16646 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 16647 else 16648 Diag(IdLoc, diag::err_redefinition) << Id; 16649 notePreviousDefinition(PrevDecl, IdLoc); 16650 return nullptr; 16651 } 16652 } 16653 16654 // Process attributes. 16655 ProcessDeclAttributeList(S, New, Attrs); 16656 AddPragmaAttributes(S, New); 16657 16658 // Register this decl in the current scope stack. 16659 New->setAccess(TheEnumDecl->getAccess()); 16660 PushOnScopeChains(New, S); 16661 16662 ActOnDocumentableDecl(New); 16663 16664 return New; 16665 } 16666 16667 // Returns true when the enum initial expression does not trigger the 16668 // duplicate enum warning. A few common cases are exempted as follows: 16669 // Element2 = Element1 16670 // Element2 = Element1 + 1 16671 // Element2 = Element1 - 1 16672 // Where Element2 and Element1 are from the same enum. 16673 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16674 Expr *InitExpr = ECD->getInitExpr(); 16675 if (!InitExpr) 16676 return true; 16677 InitExpr = InitExpr->IgnoreImpCasts(); 16678 16679 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16680 if (!BO->isAdditiveOp()) 16681 return true; 16682 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16683 if (!IL) 16684 return true; 16685 if (IL->getValue() != 1) 16686 return true; 16687 16688 InitExpr = BO->getLHS(); 16689 } 16690 16691 // This checks if the elements are from the same enum. 16692 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16693 if (!DRE) 16694 return true; 16695 16696 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16697 if (!EnumConstant) 16698 return true; 16699 16700 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16701 Enum) 16702 return true; 16703 16704 return false; 16705 } 16706 16707 // Emits a warning when an element is implicitly set a value that 16708 // a previous element has already been set to. 16709 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16710 EnumDecl *Enum, QualType EnumType) { 16711 // Avoid anonymous enums 16712 if (!Enum->getIdentifier()) 16713 return; 16714 16715 // Only check for small enums. 16716 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16717 return; 16718 16719 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16720 return; 16721 16722 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16723 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16724 16725 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16726 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 16727 16728 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16729 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16730 llvm::APSInt Val = D->getInitVal(); 16731 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16732 }; 16733 16734 DuplicatesVector DupVector; 16735 ValueToVectorMap EnumMap; 16736 16737 // Populate the EnumMap with all values represented by enum constants without 16738 // an initializer. 16739 for (auto *Element : Elements) { 16740 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16741 16742 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16743 // this constant. Skip this enum since it may be ill-formed. 16744 if (!ECD) { 16745 return; 16746 } 16747 16748 // Constants with initalizers are handled in the next loop. 16749 if (ECD->getInitExpr()) 16750 continue; 16751 16752 // Duplicate values are handled in the next loop. 16753 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16754 } 16755 16756 if (EnumMap.size() == 0) 16757 return; 16758 16759 // Create vectors for any values that has duplicates. 16760 for (auto *Element : Elements) { 16761 // The last loop returned if any constant was null. 16762 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16763 if (!ValidDuplicateEnum(ECD, Enum)) 16764 continue; 16765 16766 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16767 if (Iter == EnumMap.end()) 16768 continue; 16769 16770 DeclOrVector& Entry = Iter->second; 16771 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16772 // Ensure constants are different. 16773 if (D == ECD) 16774 continue; 16775 16776 // Create new vector and push values onto it. 16777 auto Vec = llvm::make_unique<ECDVector>(); 16778 Vec->push_back(D); 16779 Vec->push_back(ECD); 16780 16781 // Update entry to point to the duplicates vector. 16782 Entry = Vec.get(); 16783 16784 // Store the vector somewhere we can consult later for quick emission of 16785 // diagnostics. 16786 DupVector.emplace_back(std::move(Vec)); 16787 continue; 16788 } 16789 16790 ECDVector *Vec = Entry.get<ECDVector*>(); 16791 // Make sure constants are not added more than once. 16792 if (*Vec->begin() == ECD) 16793 continue; 16794 16795 Vec->push_back(ECD); 16796 } 16797 16798 // Emit diagnostics. 16799 for (const auto &Vec : DupVector) { 16800 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16801 16802 // Emit warning for one enum constant. 16803 auto *FirstECD = Vec->front(); 16804 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16805 << FirstECD << FirstECD->getInitVal().toString(10) 16806 << FirstECD->getSourceRange(); 16807 16808 // Emit one note for each of the remaining enum constants with 16809 // the same value. 16810 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16811 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16812 << ECD << ECD->getInitVal().toString(10) 16813 << ECD->getSourceRange(); 16814 } 16815 } 16816 16817 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16818 bool AllowMask) const { 16819 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16820 assert(ED->isCompleteDefinition() && "expected enum definition"); 16821 16822 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16823 llvm::APInt &FlagBits = R.first->second; 16824 16825 if (R.second) { 16826 for (auto *E : ED->enumerators()) { 16827 const auto &EVal = E->getInitVal(); 16828 // Only single-bit enumerators introduce new flag values. 16829 if (EVal.isPowerOf2()) 16830 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16831 } 16832 } 16833 16834 // A value is in a flag enum if either its bits are a subset of the enum's 16835 // flag bits (the first condition) or we are allowing masks and the same is 16836 // true of its complement (the second condition). When masks are allowed, we 16837 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16838 // 16839 // While it's true that any value could be used as a mask, the assumption is 16840 // that a mask will have all of the insignificant bits set. Anything else is 16841 // likely a logic error. 16842 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16843 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16844 } 16845 16846 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16847 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 16848 const ParsedAttributesView &Attrs) { 16849 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16850 QualType EnumType = Context.getTypeDeclType(Enum); 16851 16852 ProcessDeclAttributeList(S, Enum, Attrs); 16853 16854 if (Enum->isDependentType()) { 16855 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16856 EnumConstantDecl *ECD = 16857 cast_or_null<EnumConstantDecl>(Elements[i]); 16858 if (!ECD) continue; 16859 16860 ECD->setType(EnumType); 16861 } 16862 16863 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16864 return; 16865 } 16866 16867 // TODO: If the result value doesn't fit in an int, it must be a long or long 16868 // long value. ISO C does not support this, but GCC does as an extension, 16869 // emit a warning. 16870 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16871 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16872 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16873 16874 // Verify that all the values are okay, compute the size of the values, and 16875 // reverse the list. 16876 unsigned NumNegativeBits = 0; 16877 unsigned NumPositiveBits = 0; 16878 16879 // Keep track of whether all elements have type int. 16880 bool AllElementsInt = true; 16881 16882 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16883 EnumConstantDecl *ECD = 16884 cast_or_null<EnumConstantDecl>(Elements[i]); 16885 if (!ECD) continue; // Already issued a diagnostic. 16886 16887 const llvm::APSInt &InitVal = ECD->getInitVal(); 16888 16889 // Keep track of the size of positive and negative values. 16890 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16891 NumPositiveBits = std::max(NumPositiveBits, 16892 (unsigned)InitVal.getActiveBits()); 16893 else 16894 NumNegativeBits = std::max(NumNegativeBits, 16895 (unsigned)InitVal.getMinSignedBits()); 16896 16897 // Keep track of whether every enum element has type int (very common). 16898 if (AllElementsInt) 16899 AllElementsInt = ECD->getType() == Context.IntTy; 16900 } 16901 16902 // Figure out the type that should be used for this enum. 16903 QualType BestType; 16904 unsigned BestWidth; 16905 16906 // C++0x N3000 [conv.prom]p3: 16907 // An rvalue of an unscoped enumeration type whose underlying 16908 // type is not fixed can be converted to an rvalue of the first 16909 // of the following types that can represent all the values of 16910 // the enumeration: int, unsigned int, long int, unsigned long 16911 // int, long long int, or unsigned long long int. 16912 // C99 6.4.4.3p2: 16913 // An identifier declared as an enumeration constant has type int. 16914 // The C99 rule is modified by a gcc extension 16915 QualType BestPromotionType; 16916 16917 bool Packed = Enum->hasAttr<PackedAttr>(); 16918 // -fshort-enums is the equivalent to specifying the packed attribute on all 16919 // enum definitions. 16920 if (LangOpts.ShortEnums) 16921 Packed = true; 16922 16923 // If the enum already has a type because it is fixed or dictated by the 16924 // target, promote that type instead of analyzing the enumerators. 16925 if (Enum->isComplete()) { 16926 BestType = Enum->getIntegerType(); 16927 if (BestType->isPromotableIntegerType()) 16928 BestPromotionType = Context.getPromotedIntegerType(BestType); 16929 else 16930 BestPromotionType = BestType; 16931 16932 BestWidth = Context.getIntWidth(BestType); 16933 } 16934 else if (NumNegativeBits) { 16935 // If there is a negative value, figure out the smallest integer type (of 16936 // int/long/longlong) that fits. 16937 // If it's packed, check also if it fits a char or a short. 16938 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16939 BestType = Context.SignedCharTy; 16940 BestWidth = CharWidth; 16941 } else if (Packed && NumNegativeBits <= ShortWidth && 16942 NumPositiveBits < ShortWidth) { 16943 BestType = Context.ShortTy; 16944 BestWidth = ShortWidth; 16945 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16946 BestType = Context.IntTy; 16947 BestWidth = IntWidth; 16948 } else { 16949 BestWidth = Context.getTargetInfo().getLongWidth(); 16950 16951 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16952 BestType = Context.LongTy; 16953 } else { 16954 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16955 16956 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16957 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16958 BestType = Context.LongLongTy; 16959 } 16960 } 16961 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16962 } else { 16963 // If there is no negative value, figure out the smallest type that fits 16964 // all of the enumerator values. 16965 // If it's packed, check also if it fits a char or a short. 16966 if (Packed && NumPositiveBits <= CharWidth) { 16967 BestType = Context.UnsignedCharTy; 16968 BestPromotionType = Context.IntTy; 16969 BestWidth = CharWidth; 16970 } else if (Packed && NumPositiveBits <= ShortWidth) { 16971 BestType = Context.UnsignedShortTy; 16972 BestPromotionType = Context.IntTy; 16973 BestWidth = ShortWidth; 16974 } else if (NumPositiveBits <= IntWidth) { 16975 BestType = Context.UnsignedIntTy; 16976 BestWidth = IntWidth; 16977 BestPromotionType 16978 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16979 ? Context.UnsignedIntTy : Context.IntTy; 16980 } else if (NumPositiveBits <= 16981 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16982 BestType = Context.UnsignedLongTy; 16983 BestPromotionType 16984 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16985 ? Context.UnsignedLongTy : Context.LongTy; 16986 } else { 16987 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16988 assert(NumPositiveBits <= BestWidth && 16989 "How could an initializer get larger than ULL?"); 16990 BestType = Context.UnsignedLongLongTy; 16991 BestPromotionType 16992 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16993 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16994 } 16995 } 16996 16997 // Loop over all of the enumerator constants, changing their types to match 16998 // the type of the enum if needed. 16999 for (auto *D : Elements) { 17000 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17001 if (!ECD) continue; // Already issued a diagnostic. 17002 17003 // Standard C says the enumerators have int type, but we allow, as an 17004 // extension, the enumerators to be larger than int size. If each 17005 // enumerator value fits in an int, type it as an int, otherwise type it the 17006 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17007 // that X has type 'int', not 'unsigned'. 17008 17009 // Determine whether the value fits into an int. 17010 llvm::APSInt InitVal = ECD->getInitVal(); 17011 17012 // If it fits into an integer type, force it. Otherwise force it to match 17013 // the enum decl type. 17014 QualType NewTy; 17015 unsigned NewWidth; 17016 bool NewSign; 17017 if (!getLangOpts().CPlusPlus && 17018 !Enum->isFixed() && 17019 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17020 NewTy = Context.IntTy; 17021 NewWidth = IntWidth; 17022 NewSign = true; 17023 } else if (ECD->getType() == BestType) { 17024 // Already the right type! 17025 if (getLangOpts().CPlusPlus) 17026 // C++ [dcl.enum]p4: Following the closing brace of an 17027 // enum-specifier, each enumerator has the type of its 17028 // enumeration. 17029 ECD->setType(EnumType); 17030 continue; 17031 } else { 17032 NewTy = BestType; 17033 NewWidth = BestWidth; 17034 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17035 } 17036 17037 // Adjust the APSInt value. 17038 InitVal = InitVal.extOrTrunc(NewWidth); 17039 InitVal.setIsSigned(NewSign); 17040 ECD->setInitVal(InitVal); 17041 17042 // Adjust the Expr initializer and type. 17043 if (ECD->getInitExpr() && 17044 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 17045 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 17046 CK_IntegralCast, 17047 ECD->getInitExpr(), 17048 /*base paths*/ nullptr, 17049 VK_RValue)); 17050 if (getLangOpts().CPlusPlus) 17051 // C++ [dcl.enum]p4: Following the closing brace of an 17052 // enum-specifier, each enumerator has the type of its 17053 // enumeration. 17054 ECD->setType(EnumType); 17055 else 17056 ECD->setType(NewTy); 17057 } 17058 17059 Enum->completeDefinition(BestType, BestPromotionType, 17060 NumPositiveBits, NumNegativeBits); 17061 17062 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 17063 17064 if (Enum->isClosedFlag()) { 17065 for (Decl *D : Elements) { 17066 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 17067 if (!ECD) continue; // Already issued a diagnostic. 17068 17069 llvm::APSInt InitVal = ECD->getInitVal(); 17070 if (InitVal != 0 && !InitVal.isPowerOf2() && 17071 !IsValueInFlagEnum(Enum, InitVal, true)) 17072 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 17073 << ECD << Enum; 17074 } 17075 } 17076 17077 // Now that the enum type is defined, ensure it's not been underaligned. 17078 if (Enum->hasAttrs()) 17079 CheckAlignasUnderalignment(Enum); 17080 } 17081 17082 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 17083 SourceLocation StartLoc, 17084 SourceLocation EndLoc) { 17085 StringLiteral *AsmString = cast<StringLiteral>(expr); 17086 17087 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 17088 AsmString, StartLoc, 17089 EndLoc); 17090 CurContext->addDecl(New); 17091 return New; 17092 } 17093 17094 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17095 IdentifierInfo* AliasName, 17096 SourceLocation PragmaLoc, 17097 SourceLocation NameLoc, 17098 SourceLocation AliasNameLoc) { 17099 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17100 LookupOrdinaryName); 17101 AsmLabelAttr *Attr = 17102 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 17103 17104 // If a declaration that: 17105 // 1) declares a function or a variable 17106 // 2) has external linkage 17107 // already exists, add a label attribute to it. 17108 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17109 if (isDeclExternC(PrevDecl)) 17110 PrevDecl->addAttr(Attr); 17111 else 17112 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17113 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17114 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17115 } else 17116 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17117 } 17118 17119 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17120 SourceLocation PragmaLoc, 17121 SourceLocation NameLoc) { 17122 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17123 17124 if (PrevDecl) { 17125 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 17126 } else { 17127 (void)WeakUndeclaredIdentifiers.insert( 17128 std::pair<IdentifierInfo*,WeakInfo> 17129 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17130 } 17131 } 17132 17133 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17134 IdentifierInfo* AliasName, 17135 SourceLocation PragmaLoc, 17136 SourceLocation NameLoc, 17137 SourceLocation AliasNameLoc) { 17138 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17139 LookupOrdinaryName); 17140 WeakInfo W = WeakInfo(Name, NameLoc); 17141 17142 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17143 if (!PrevDecl->hasAttr<AliasAttr>()) 17144 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17145 DeclApplyPragmaWeak(TUScope, ND, W); 17146 } else { 17147 (void)WeakUndeclaredIdentifiers.insert( 17148 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 17149 } 17150 } 17151 17152 Decl *Sema::getObjCDeclContext() const { 17153 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 17154 } 17155