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 // In C, we first see whether there is a tag type by the same name, in 921 // which case it's likely that the user just forgot to write "enum", 922 // "struct", or "union". 923 if (!getLangOpts().CPlusPlus && !SecondTry && 924 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 925 break; 926 } 927 928 // Perform typo correction to determine if there is another name that is 929 // close to this name. 930 if (!SecondTry && CCC) { 931 SecondTry = true; 932 if (TypoCorrection Corrected = 933 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 934 &SS, *CCC, CTK_ErrorRecovery)) { 935 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 936 unsigned QualifiedDiag = diag::err_no_member_suggest; 937 938 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 939 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 940 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 941 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 942 UnqualifiedDiag = diag::err_no_template_suggest; 943 QualifiedDiag = diag::err_no_member_template_suggest; 944 } else if (UnderlyingFirstDecl && 945 (isa<TypeDecl>(UnderlyingFirstDecl) || 946 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 947 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 948 UnqualifiedDiag = diag::err_unknown_typename_suggest; 949 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 950 } 951 952 if (SS.isEmpty()) { 953 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 954 } else {// FIXME: is this even reachable? Test it. 955 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 956 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 957 Name->getName().equals(CorrectedStr); 958 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 959 << Name << computeDeclContext(SS, false) 960 << DroppedSpecifier << SS.getRange()); 961 } 962 963 // Update the name, so that the caller has the new name. 964 Name = Corrected.getCorrectionAsIdentifierInfo(); 965 966 // Typo correction corrected to a keyword. 967 if (Corrected.isKeyword()) 968 return Name; 969 970 // Also update the LookupResult... 971 // FIXME: This should probably go away at some point 972 Result.clear(); 973 Result.setLookupName(Corrected.getCorrection()); 974 if (FirstDecl) 975 Result.addDecl(FirstDecl); 976 977 // If we found an Objective-C instance variable, let 978 // LookupInObjCMethod build the appropriate expression to 979 // reference the ivar. 980 // FIXME: This is a gross hack. 981 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 982 Result.clear(); 983 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 984 return E; 985 } 986 987 goto Corrected; 988 } 989 } 990 991 // We failed to correct; just fall through and let the parser deal with it. 992 Result.suppressDiagnostics(); 993 return NameClassification::Unknown(); 994 995 case LookupResult::NotFoundInCurrentInstantiation: { 996 // We performed name lookup into the current instantiation, and there were 997 // dependent bases, so we treat this result the same way as any other 998 // dependent nested-name-specifier. 999 1000 // C++ [temp.res]p2: 1001 // A name used in a template declaration or definition and that is 1002 // dependent on a template-parameter is assumed not to name a type 1003 // unless the applicable name lookup finds a type name or the name is 1004 // qualified by the keyword typename. 1005 // 1006 // FIXME: If the next token is '<', we might want to ask the parser to 1007 // perform some heroics to see if we actually have a 1008 // template-argument-list, which would indicate a missing 'template' 1009 // keyword here. 1010 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1011 NameInfo, IsAddressOfOperand, 1012 /*TemplateArgs=*/nullptr); 1013 } 1014 1015 case LookupResult::Found: 1016 case LookupResult::FoundOverloaded: 1017 case LookupResult::FoundUnresolvedValue: 1018 break; 1019 1020 case LookupResult::Ambiguous: 1021 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1022 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1023 /*AllowDependent=*/false)) { 1024 // C++ [temp.local]p3: 1025 // A lookup that finds an injected-class-name (10.2) can result in an 1026 // ambiguity in certain cases (for example, if it is found in more than 1027 // one base class). If all of the injected-class-names that are found 1028 // refer to specializations of the same class template, and if the name 1029 // is followed by a template-argument-list, the reference refers to the 1030 // class template itself and not a specialization thereof, and is not 1031 // ambiguous. 1032 // 1033 // This filtering can make an ambiguous result into an unambiguous one, 1034 // so try again after filtering out template names. 1035 FilterAcceptableTemplateNames(Result); 1036 if (!Result.isAmbiguous()) { 1037 IsFilteredTemplateName = true; 1038 break; 1039 } 1040 } 1041 1042 // Diagnose the ambiguity and return an error. 1043 return NameClassification::Error(); 1044 } 1045 1046 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1047 (IsFilteredTemplateName || 1048 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1049 /*AllowDependent=*/false))) { 1050 // C++ [temp.names]p3: 1051 // After name lookup (3.4) finds that a name is a template-name or that 1052 // an operator-function-id or a literal- operator-id refers to a set of 1053 // overloaded functions any member of which is a function template if 1054 // this is followed by a <, the < is always taken as the delimiter of a 1055 // template-argument-list and never as the less-than operator. 1056 if (!IsFilteredTemplateName) 1057 FilterAcceptableTemplateNames(Result); 1058 1059 if (!Result.empty()) { 1060 bool IsFunctionTemplate; 1061 bool IsVarTemplate; 1062 TemplateName Template; 1063 if (Result.end() - Result.begin() > 1) { 1064 IsFunctionTemplate = true; 1065 Template = Context.getOverloadedTemplateName(Result.begin(), 1066 Result.end()); 1067 } else { 1068 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1069 *Result.begin(), /*AllowFunctionTemplates=*/true, 1070 /*AllowDependent=*/false)); 1071 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1072 IsVarTemplate = isa<VarTemplateDecl>(TD); 1073 1074 if (SS.isSet() && !SS.isInvalid()) 1075 Template = 1076 Context.getQualifiedTemplateName(SS.getScopeRep(), 1077 /*TemplateKeyword=*/false, TD); 1078 else 1079 Template = TemplateName(TD); 1080 } 1081 1082 if (IsFunctionTemplate) { 1083 // Function templates always go through overload resolution, at which 1084 // point we'll perform the various checks (e.g., accessibility) we need 1085 // to based on which function we selected. 1086 Result.suppressDiagnostics(); 1087 1088 return NameClassification::FunctionTemplate(Template); 1089 } 1090 1091 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1092 : NameClassification::TypeTemplate(Template); 1093 } 1094 } 1095 1096 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1097 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1098 DiagnoseUseOfDecl(Type, NameLoc); 1099 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1100 QualType T = Context.getTypeDeclType(Type); 1101 if (SS.isNotEmpty()) 1102 return buildNestedType(*this, SS, T, NameLoc); 1103 return ParsedType::make(T); 1104 } 1105 1106 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1107 if (!Class) { 1108 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1109 if (ObjCCompatibleAliasDecl *Alias = 1110 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1111 Class = Alias->getClassInterface(); 1112 } 1113 1114 if (Class) { 1115 DiagnoseUseOfDecl(Class, NameLoc); 1116 1117 if (NextToken.is(tok::period)) { 1118 // Interface. <something> is parsed as a property reference expression. 1119 // Just return "unknown" as a fall-through for now. 1120 Result.suppressDiagnostics(); 1121 return NameClassification::Unknown(); 1122 } 1123 1124 QualType T = Context.getObjCInterfaceType(Class); 1125 return ParsedType::make(T); 1126 } 1127 1128 // We can have a type template here if we're classifying a template argument. 1129 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1130 !isa<VarTemplateDecl>(FirstDecl)) 1131 return NameClassification::TypeTemplate( 1132 TemplateName(cast<TemplateDecl>(FirstDecl))); 1133 1134 // Check for a tag type hidden by a non-type decl in a few cases where it 1135 // seems likely a type is wanted instead of the non-type that was found. 1136 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1137 if ((NextToken.is(tok::identifier) || 1138 (NextIsOp && 1139 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1140 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1141 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1142 DiagnoseUseOfDecl(Type, NameLoc); 1143 QualType T = Context.getTypeDeclType(Type); 1144 if (SS.isNotEmpty()) 1145 return buildNestedType(*this, SS, T, NameLoc); 1146 return ParsedType::make(T); 1147 } 1148 1149 if (FirstDecl->isCXXClassMember()) 1150 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1151 nullptr, S); 1152 1153 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1154 return BuildDeclarationNameExpr(SS, Result, ADL); 1155 } 1156 1157 Sema::TemplateNameKindForDiagnostics 1158 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1159 auto *TD = Name.getAsTemplateDecl(); 1160 if (!TD) 1161 return TemplateNameKindForDiagnostics::DependentTemplate; 1162 if (isa<ClassTemplateDecl>(TD)) 1163 return TemplateNameKindForDiagnostics::ClassTemplate; 1164 if (isa<FunctionTemplateDecl>(TD)) 1165 return TemplateNameKindForDiagnostics::FunctionTemplate; 1166 if (isa<VarTemplateDecl>(TD)) 1167 return TemplateNameKindForDiagnostics::VarTemplate; 1168 if (isa<TypeAliasTemplateDecl>(TD)) 1169 return TemplateNameKindForDiagnostics::AliasTemplate; 1170 if (isa<TemplateTemplateParmDecl>(TD)) 1171 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1172 return TemplateNameKindForDiagnostics::DependentTemplate; 1173 } 1174 1175 // Determines the context to return to after temporarily entering a 1176 // context. This depends in an unnecessarily complicated way on the 1177 // exact ordering of callbacks from the parser. 1178 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1179 1180 // Functions defined inline within classes aren't parsed until we've 1181 // finished parsing the top-level class, so the top-level class is 1182 // the context we'll need to return to. 1183 // A Lambda call operator whose parent is a class must not be treated 1184 // as an inline member function. A Lambda can be used legally 1185 // either as an in-class member initializer or a default argument. These 1186 // are parsed once the class has been marked complete and so the containing 1187 // context would be the nested class (when the lambda is defined in one); 1188 // If the class is not complete, then the lambda is being used in an 1189 // ill-formed fashion (such as to specify the width of a bit-field, or 1190 // in an array-bound) - in which case we still want to return the 1191 // lexically containing DC (which could be a nested class). 1192 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1193 DC = DC->getLexicalParent(); 1194 1195 // A function not defined within a class will always return to its 1196 // lexical context. 1197 if (!isa<CXXRecordDecl>(DC)) 1198 return DC; 1199 1200 // A C++ inline method/friend is parsed *after* the topmost class 1201 // it was declared in is fully parsed ("complete"); the topmost 1202 // class is the context we need to return to. 1203 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1204 DC = RD; 1205 1206 // Return the declaration context of the topmost class the inline method is 1207 // declared in. 1208 return DC; 1209 } 1210 1211 return DC->getLexicalParent(); 1212 } 1213 1214 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1215 assert(getContainingDC(DC) == CurContext && 1216 "The next DeclContext should be lexically contained in the current one."); 1217 CurContext = DC; 1218 S->setEntity(DC); 1219 } 1220 1221 void Sema::PopDeclContext() { 1222 assert(CurContext && "DeclContext imbalance!"); 1223 1224 CurContext = getContainingDC(CurContext); 1225 assert(CurContext && "Popped translation unit!"); 1226 } 1227 1228 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1229 Decl *D) { 1230 // Unlike PushDeclContext, the context to which we return is not necessarily 1231 // the containing DC of TD, because the new context will be some pre-existing 1232 // TagDecl definition instead of a fresh one. 1233 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1234 CurContext = cast<TagDecl>(D)->getDefinition(); 1235 assert(CurContext && "skipping definition of undefined tag"); 1236 // Start lookups from the parent of the current context; we don't want to look 1237 // into the pre-existing complete definition. 1238 S->setEntity(CurContext->getLookupParent()); 1239 return Result; 1240 } 1241 1242 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1243 CurContext = static_cast<decltype(CurContext)>(Context); 1244 } 1245 1246 /// EnterDeclaratorContext - Used when we must lookup names in the context 1247 /// of a declarator's nested name specifier. 1248 /// 1249 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1250 // C++0x [basic.lookup.unqual]p13: 1251 // A name used in the definition of a static data member of class 1252 // X (after the qualified-id of the static member) is looked up as 1253 // if the name was used in a member function of X. 1254 // C++0x [basic.lookup.unqual]p14: 1255 // If a variable member of a namespace is defined outside of the 1256 // scope of its namespace then any name used in the definition of 1257 // the variable member (after the declarator-id) is looked up as 1258 // if the definition of the variable member occurred in its 1259 // namespace. 1260 // Both of these imply that we should push a scope whose context 1261 // is the semantic context of the declaration. We can't use 1262 // PushDeclContext here because that context is not necessarily 1263 // lexically contained in the current context. Fortunately, 1264 // the containing scope should have the appropriate information. 1265 1266 assert(!S->getEntity() && "scope already has entity"); 1267 1268 #ifndef NDEBUG 1269 Scope *Ancestor = S->getParent(); 1270 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1271 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1272 #endif 1273 1274 CurContext = DC; 1275 S->setEntity(DC); 1276 } 1277 1278 void Sema::ExitDeclaratorContext(Scope *S) { 1279 assert(S->getEntity() == CurContext && "Context imbalance!"); 1280 1281 // Switch back to the lexical context. The safety of this is 1282 // enforced by an assert in EnterDeclaratorContext. 1283 Scope *Ancestor = S->getParent(); 1284 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1285 CurContext = Ancestor->getEntity(); 1286 1287 // We don't need to do anything with the scope, which is going to 1288 // disappear. 1289 } 1290 1291 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1292 // We assume that the caller has already called 1293 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1294 FunctionDecl *FD = D->getAsFunction(); 1295 if (!FD) 1296 return; 1297 1298 // Same implementation as PushDeclContext, but enters the context 1299 // from the lexical parent, rather than the top-level class. 1300 assert(CurContext == FD->getLexicalParent() && 1301 "The next DeclContext should be lexically contained in the current one."); 1302 CurContext = FD; 1303 S->setEntity(CurContext); 1304 1305 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1306 ParmVarDecl *Param = FD->getParamDecl(P); 1307 // If the parameter has an identifier, then add it to the scope 1308 if (Param->getIdentifier()) { 1309 S->AddDecl(Param); 1310 IdResolver.AddDecl(Param); 1311 } 1312 } 1313 } 1314 1315 void Sema::ActOnExitFunctionContext() { 1316 // Same implementation as PopDeclContext, but returns to the lexical parent, 1317 // rather than the top-level class. 1318 assert(CurContext && "DeclContext imbalance!"); 1319 CurContext = CurContext->getLexicalParent(); 1320 assert(CurContext && "Popped translation unit!"); 1321 } 1322 1323 /// Determine whether we allow overloading of the function 1324 /// PrevDecl with another declaration. 1325 /// 1326 /// This routine determines whether overloading is possible, not 1327 /// whether some new function is actually an overload. It will return 1328 /// true in C++ (where we can always provide overloads) or, as an 1329 /// extension, in C when the previous function is already an 1330 /// overloaded function declaration or has the "overloadable" 1331 /// attribute. 1332 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1333 ASTContext &Context, 1334 const FunctionDecl *New) { 1335 if (Context.getLangOpts().CPlusPlus) 1336 return true; 1337 1338 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1339 return true; 1340 1341 return Previous.getResultKind() == LookupResult::Found && 1342 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1343 New->hasAttr<OverloadableAttr>()); 1344 } 1345 1346 /// Add this decl to the scope shadowed decl chains. 1347 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1348 // Move up the scope chain until we find the nearest enclosing 1349 // non-transparent context. The declaration will be introduced into this 1350 // scope. 1351 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1352 S = S->getParent(); 1353 1354 // Add scoped declarations into their context, so that they can be 1355 // found later. Declarations without a context won't be inserted 1356 // into any context. 1357 if (AddToContext) 1358 CurContext->addDecl(D); 1359 1360 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1361 // are function-local declarations. 1362 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1363 !D->getDeclContext()->getRedeclContext()->Equals( 1364 D->getLexicalDeclContext()->getRedeclContext()) && 1365 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1366 return; 1367 1368 // Template instantiations should also not be pushed into scope. 1369 if (isa<FunctionDecl>(D) && 1370 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1371 return; 1372 1373 // If this replaces anything in the current scope, 1374 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1375 IEnd = IdResolver.end(); 1376 for (; I != IEnd; ++I) { 1377 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1378 S->RemoveDecl(*I); 1379 IdResolver.RemoveDecl(*I); 1380 1381 // Should only need to replace one decl. 1382 break; 1383 } 1384 } 1385 1386 S->AddDecl(D); 1387 1388 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1389 // Implicitly-generated labels may end up getting generated in an order that 1390 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1391 // the label at the appropriate place in the identifier chain. 1392 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1393 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1394 if (IDC == CurContext) { 1395 if (!S->isDeclScope(*I)) 1396 continue; 1397 } else if (IDC->Encloses(CurContext)) 1398 break; 1399 } 1400 1401 IdResolver.InsertDeclAfter(I, D); 1402 } else { 1403 IdResolver.AddDecl(D); 1404 } 1405 } 1406 1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1408 bool AllowInlineNamespace) { 1409 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1410 } 1411 1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1413 DeclContext *TargetDC = DC->getPrimaryContext(); 1414 do { 1415 if (DeclContext *ScopeDC = S->getEntity()) 1416 if (ScopeDC->getPrimaryContext() == TargetDC) 1417 return S; 1418 } while ((S = S->getParent())); 1419 1420 return nullptr; 1421 } 1422 1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1424 DeclContext*, 1425 ASTContext&); 1426 1427 /// Filters out lookup results that don't fall within the given scope 1428 /// as determined by isDeclInScope. 1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1430 bool ConsiderLinkage, 1431 bool AllowInlineNamespace) { 1432 LookupResult::Filter F = R.makeFilter(); 1433 while (F.hasNext()) { 1434 NamedDecl *D = F.next(); 1435 1436 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1437 continue; 1438 1439 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1440 continue; 1441 1442 F.erase(); 1443 } 1444 1445 F.done(); 1446 } 1447 1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1449 /// have compatible owning modules. 1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1451 // FIXME: The Modules TS is not clear about how friend declarations are 1452 // to be treated. It's not meaningful to have different owning modules for 1453 // linkage in redeclarations of the same entity, so for now allow the 1454 // redeclaration and change the owning modules to match. 1455 if (New->getFriendObjectKind() && 1456 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1457 New->setLocalOwningModule(Old->getOwningModule()); 1458 makeMergedDefinitionVisible(New); 1459 return false; 1460 } 1461 1462 Module *NewM = New->getOwningModule(); 1463 Module *OldM = Old->getOwningModule(); 1464 1465 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1466 NewM = NewM->Parent; 1467 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1468 OldM = OldM->Parent; 1469 1470 if (NewM == OldM) 1471 return false; 1472 1473 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1474 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1475 if (NewIsModuleInterface || OldIsModuleInterface) { 1476 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1477 // if a declaration of D [...] appears in the purview of a module, all 1478 // other such declarations shall appear in the purview of the same module 1479 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1480 << New 1481 << NewIsModuleInterface 1482 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1483 << OldIsModuleInterface 1484 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1485 Diag(Old->getLocation(), diag::note_previous_declaration); 1486 New->setInvalidDecl(); 1487 return true; 1488 } 1489 1490 return false; 1491 } 1492 1493 static bool isUsingDecl(NamedDecl *D) { 1494 return isa<UsingShadowDecl>(D) || 1495 isa<UnresolvedUsingTypenameDecl>(D) || 1496 isa<UnresolvedUsingValueDecl>(D); 1497 } 1498 1499 /// Removes using shadow declarations from the lookup results. 1500 static void RemoveUsingDecls(LookupResult &R) { 1501 LookupResult::Filter F = R.makeFilter(); 1502 while (F.hasNext()) 1503 if (isUsingDecl(F.next())) 1504 F.erase(); 1505 1506 F.done(); 1507 } 1508 1509 /// Check for this common pattern: 1510 /// @code 1511 /// class S { 1512 /// S(const S&); // DO NOT IMPLEMENT 1513 /// void operator=(const S&); // DO NOT IMPLEMENT 1514 /// }; 1515 /// @endcode 1516 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1517 // FIXME: Should check for private access too but access is set after we get 1518 // the decl here. 1519 if (D->doesThisDeclarationHaveABody()) 1520 return false; 1521 1522 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1523 return CD->isCopyConstructor(); 1524 return D->isCopyAssignmentOperator(); 1525 } 1526 1527 // We need this to handle 1528 // 1529 // typedef struct { 1530 // void *foo() { return 0; } 1531 // } A; 1532 // 1533 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1534 // for example. If 'A', foo will have external linkage. If we have '*A', 1535 // foo will have no linkage. Since we can't know until we get to the end 1536 // of the typedef, this function finds out if D might have non-external linkage. 1537 // Callers should verify at the end of the TU if it D has external linkage or 1538 // not. 1539 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1540 const DeclContext *DC = D->getDeclContext(); 1541 while (!DC->isTranslationUnit()) { 1542 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1543 if (!RD->hasNameForLinkage()) 1544 return true; 1545 } 1546 DC = DC->getParent(); 1547 } 1548 1549 return !D->isExternallyVisible(); 1550 } 1551 1552 // FIXME: This needs to be refactored; some other isInMainFile users want 1553 // these semantics. 1554 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1555 if (S.TUKind != TU_Complete) 1556 return false; 1557 return S.SourceMgr.isInMainFile(Loc); 1558 } 1559 1560 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1561 assert(D); 1562 1563 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1564 return false; 1565 1566 // Ignore all entities declared within templates, and out-of-line definitions 1567 // of members of class templates. 1568 if (D->getDeclContext()->isDependentContext() || 1569 D->getLexicalDeclContext()->isDependentContext()) 1570 return false; 1571 1572 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1573 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1574 return false; 1575 // A non-out-of-line declaration of a member specialization was implicitly 1576 // instantiated; it's the out-of-line declaration that we're interested in. 1577 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1578 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1579 return false; 1580 1581 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1582 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1583 return false; 1584 } else { 1585 // 'static inline' functions are defined in headers; don't warn. 1586 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1587 return false; 1588 } 1589 1590 if (FD->doesThisDeclarationHaveABody() && 1591 Context.DeclMustBeEmitted(FD)) 1592 return false; 1593 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1594 // Constants and utility variables are defined in headers with internal 1595 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1596 // like "inline".) 1597 if (!isMainFileLoc(*this, VD->getLocation())) 1598 return false; 1599 1600 if (Context.DeclMustBeEmitted(VD)) 1601 return false; 1602 1603 if (VD->isStaticDataMember() && 1604 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1605 return false; 1606 if (VD->isStaticDataMember() && 1607 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1608 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1609 return false; 1610 1611 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1612 return false; 1613 } else { 1614 return false; 1615 } 1616 1617 // Only warn for unused decls internal to the translation unit. 1618 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1619 // for inline functions defined in the main source file, for instance. 1620 return mightHaveNonExternalLinkage(D); 1621 } 1622 1623 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1624 if (!D) 1625 return; 1626 1627 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1628 const FunctionDecl *First = FD->getFirstDecl(); 1629 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1630 return; // First should already be in the vector. 1631 } 1632 1633 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1634 const VarDecl *First = VD->getFirstDecl(); 1635 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1636 return; // First should already be in the vector. 1637 } 1638 1639 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1640 UnusedFileScopedDecls.push_back(D); 1641 } 1642 1643 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1644 if (D->isInvalidDecl()) 1645 return false; 1646 1647 bool Referenced = false; 1648 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1649 // For a decomposition declaration, warn if none of the bindings are 1650 // referenced, instead of if the variable itself is referenced (which 1651 // it is, by the bindings' expressions). 1652 for (auto *BD : DD->bindings()) { 1653 if (BD->isReferenced()) { 1654 Referenced = true; 1655 break; 1656 } 1657 } 1658 } else if (!D->getDeclName()) { 1659 return false; 1660 } else if (D->isReferenced() || D->isUsed()) { 1661 Referenced = true; 1662 } 1663 1664 if (Referenced || D->hasAttr<UnusedAttr>() || 1665 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1666 return false; 1667 1668 if (isa<LabelDecl>(D)) 1669 return true; 1670 1671 // Except for labels, we only care about unused decls that are local to 1672 // functions. 1673 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1674 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1675 // For dependent types, the diagnostic is deferred. 1676 WithinFunction = 1677 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1678 if (!WithinFunction) 1679 return false; 1680 1681 if (isa<TypedefNameDecl>(D)) 1682 return true; 1683 1684 // White-list anything that isn't a local variable. 1685 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1686 return false; 1687 1688 // Types of valid local variables should be complete, so this should succeed. 1689 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1690 1691 // White-list anything with an __attribute__((unused)) type. 1692 const auto *Ty = VD->getType().getTypePtr(); 1693 1694 // Only look at the outermost level of typedef. 1695 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1696 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1697 return false; 1698 } 1699 1700 // If we failed to complete the type for some reason, or if the type is 1701 // dependent, don't diagnose the variable. 1702 if (Ty->isIncompleteType() || Ty->isDependentType()) 1703 return false; 1704 1705 // Look at the element type to ensure that the warning behaviour is 1706 // consistent for both scalars and arrays. 1707 Ty = Ty->getBaseElementTypeUnsafe(); 1708 1709 if (const TagType *TT = Ty->getAs<TagType>()) { 1710 const TagDecl *Tag = TT->getDecl(); 1711 if (Tag->hasAttr<UnusedAttr>()) 1712 return false; 1713 1714 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1715 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1716 return false; 1717 1718 if (const Expr *Init = VD->getInit()) { 1719 if (const ExprWithCleanups *Cleanups = 1720 dyn_cast<ExprWithCleanups>(Init)) 1721 Init = Cleanups->getSubExpr(); 1722 const CXXConstructExpr *Construct = 1723 dyn_cast<CXXConstructExpr>(Init); 1724 if (Construct && !Construct->isElidable()) { 1725 CXXConstructorDecl *CD = Construct->getConstructor(); 1726 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1727 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1728 return false; 1729 } 1730 } 1731 } 1732 } 1733 1734 // TODO: __attribute__((unused)) templates? 1735 } 1736 1737 return true; 1738 } 1739 1740 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1741 FixItHint &Hint) { 1742 if (isa<LabelDecl>(D)) { 1743 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1744 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1745 true); 1746 if (AfterColon.isInvalid()) 1747 return; 1748 Hint = FixItHint::CreateRemoval( 1749 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1750 } 1751 } 1752 1753 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1754 if (D->getTypeForDecl()->isDependentType()) 1755 return; 1756 1757 for (auto *TmpD : D->decls()) { 1758 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1759 DiagnoseUnusedDecl(T); 1760 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1761 DiagnoseUnusedNestedTypedefs(R); 1762 } 1763 } 1764 1765 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1766 /// unless they are marked attr(unused). 1767 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1768 if (!ShouldDiagnoseUnusedDecl(D)) 1769 return; 1770 1771 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1772 // typedefs can be referenced later on, so the diagnostics are emitted 1773 // at end-of-translation-unit. 1774 UnusedLocalTypedefNameCandidates.insert(TD); 1775 return; 1776 } 1777 1778 FixItHint Hint; 1779 GenerateFixForUnusedDecl(D, Context, Hint); 1780 1781 unsigned DiagID; 1782 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1783 DiagID = diag::warn_unused_exception_param; 1784 else if (isa<LabelDecl>(D)) 1785 DiagID = diag::warn_unused_label; 1786 else 1787 DiagID = diag::warn_unused_variable; 1788 1789 Diag(D->getLocation(), DiagID) << D << Hint; 1790 } 1791 1792 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1793 // Verify that we have no forward references left. If so, there was a goto 1794 // or address of a label taken, but no definition of it. Label fwd 1795 // definitions are indicated with a null substmt which is also not a resolved 1796 // MS inline assembly label name. 1797 bool Diagnose = false; 1798 if (L->isMSAsmLabel()) 1799 Diagnose = !L->isResolvedMSAsmLabel(); 1800 else 1801 Diagnose = L->getStmt() == nullptr; 1802 if (Diagnose) 1803 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1804 } 1805 1806 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1807 S->mergeNRVOIntoParent(); 1808 1809 if (S->decl_empty()) return; 1810 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1811 "Scope shouldn't contain decls!"); 1812 1813 for (auto *TmpD : S->decls()) { 1814 assert(TmpD && "This decl didn't get pushed??"); 1815 1816 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1817 NamedDecl *D = cast<NamedDecl>(TmpD); 1818 1819 // Diagnose unused variables in this scope. 1820 if (!S->hasUnrecoverableErrorOccurred()) { 1821 DiagnoseUnusedDecl(D); 1822 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1823 DiagnoseUnusedNestedTypedefs(RD); 1824 } 1825 1826 if (!D->getDeclName()) continue; 1827 1828 // If this was a forward reference to a label, verify it was defined. 1829 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1830 CheckPoppedLabel(LD, *this); 1831 1832 // Remove this name from our lexical scope, and warn on it if we haven't 1833 // already. 1834 IdResolver.RemoveDecl(D); 1835 auto ShadowI = ShadowingDecls.find(D); 1836 if (ShadowI != ShadowingDecls.end()) { 1837 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1838 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1839 << D << FD << FD->getParent(); 1840 Diag(FD->getLocation(), diag::note_previous_declaration); 1841 } 1842 ShadowingDecls.erase(ShadowI); 1843 } 1844 } 1845 } 1846 1847 /// Look for an Objective-C class in the translation unit. 1848 /// 1849 /// \param Id The name of the Objective-C class we're looking for. If 1850 /// typo-correction fixes this name, the Id will be updated 1851 /// to the fixed name. 1852 /// 1853 /// \param IdLoc The location of the name in the translation unit. 1854 /// 1855 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1856 /// if there is no class with the given name. 1857 /// 1858 /// \returns The declaration of the named Objective-C class, or NULL if the 1859 /// class could not be found. 1860 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1861 SourceLocation IdLoc, 1862 bool DoTypoCorrection) { 1863 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1864 // creation from this context. 1865 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1866 1867 if (!IDecl && DoTypoCorrection) { 1868 // Perform typo correction at the given location, but only if we 1869 // find an Objective-C class name. 1870 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1871 if (TypoCorrection C = 1872 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1873 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1874 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1875 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1876 Id = IDecl->getIdentifier(); 1877 } 1878 } 1879 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1880 // This routine must always return a class definition, if any. 1881 if (Def && Def->getDefinition()) 1882 Def = Def->getDefinition(); 1883 return Def; 1884 } 1885 1886 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1887 /// from S, where a non-field would be declared. This routine copes 1888 /// with the difference between C and C++ scoping rules in structs and 1889 /// unions. For example, the following code is well-formed in C but 1890 /// ill-formed in C++: 1891 /// @code 1892 /// struct S6 { 1893 /// enum { BAR } e; 1894 /// }; 1895 /// 1896 /// void test_S6() { 1897 /// struct S6 a; 1898 /// a.e = BAR; 1899 /// } 1900 /// @endcode 1901 /// For the declaration of BAR, this routine will return a different 1902 /// scope. The scope S will be the scope of the unnamed enumeration 1903 /// within S6. In C++, this routine will return the scope associated 1904 /// with S6, because the enumeration's scope is a transparent 1905 /// context but structures can contain non-field names. In C, this 1906 /// routine will return the translation unit scope, since the 1907 /// enumeration's scope is a transparent context and structures cannot 1908 /// contain non-field names. 1909 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1910 while (((S->getFlags() & Scope::DeclScope) == 0) || 1911 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1912 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1913 S = S->getParent(); 1914 return S; 1915 } 1916 1917 /// Looks up the declaration of "struct objc_super" and 1918 /// saves it for later use in building builtin declaration of 1919 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1920 /// pre-existing declaration exists no action takes place. 1921 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1922 IdentifierInfo *II) { 1923 if (!II->isStr("objc_msgSendSuper")) 1924 return; 1925 ASTContext &Context = ThisSema.Context; 1926 1927 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1928 SourceLocation(), Sema::LookupTagName); 1929 ThisSema.LookupName(Result, S); 1930 if (Result.getResultKind() == LookupResult::Found) 1931 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1932 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1933 } 1934 1935 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 1936 ASTContext::GetBuiltinTypeError Error) { 1937 switch (Error) { 1938 case ASTContext::GE_None: 1939 return ""; 1940 case ASTContext::GE_Missing_type: 1941 return BuiltinInfo.getHeaderName(ID); 1942 case ASTContext::GE_Missing_stdio: 1943 return "stdio.h"; 1944 case ASTContext::GE_Missing_setjmp: 1945 return "setjmp.h"; 1946 case ASTContext::GE_Missing_ucontext: 1947 return "ucontext.h"; 1948 } 1949 llvm_unreachable("unhandled error kind"); 1950 } 1951 1952 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1953 /// file scope. lazily create a decl for it. ForRedeclaration is true 1954 /// if we're creating this built-in in anticipation of redeclaring the 1955 /// built-in. 1956 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1957 Scope *S, bool ForRedeclaration, 1958 SourceLocation Loc) { 1959 LookupPredefedObjCSuperType(*this, S, II); 1960 1961 ASTContext::GetBuiltinTypeError Error; 1962 QualType R = Context.GetBuiltinType(ID, Error); 1963 if (Error) { 1964 if (ForRedeclaration) 1965 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1966 << getHeaderName(Context.BuiltinInfo, ID, Error) 1967 << Context.BuiltinInfo.getName(ID); 1968 return nullptr; 1969 } 1970 1971 if (!ForRedeclaration && 1972 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1973 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1974 Diag(Loc, diag::ext_implicit_lib_function_decl) 1975 << Context.BuiltinInfo.getName(ID) << R; 1976 if (Context.BuiltinInfo.getHeaderName(ID) && 1977 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1978 Diag(Loc, diag::note_include_header_or_declare) 1979 << Context.BuiltinInfo.getHeaderName(ID) 1980 << Context.BuiltinInfo.getName(ID); 1981 } 1982 1983 if (R.isNull()) 1984 return nullptr; 1985 1986 DeclContext *Parent = Context.getTranslationUnitDecl(); 1987 if (getLangOpts().CPlusPlus) { 1988 LinkageSpecDecl *CLinkageDecl = 1989 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1990 LinkageSpecDecl::lang_c, false); 1991 CLinkageDecl->setImplicit(); 1992 Parent->addDecl(CLinkageDecl); 1993 Parent = CLinkageDecl; 1994 } 1995 1996 FunctionDecl *New = FunctionDecl::Create(Context, 1997 Parent, 1998 Loc, Loc, II, R, /*TInfo=*/nullptr, 1999 SC_Extern, 2000 false, 2001 R->isFunctionProtoType()); 2002 New->setImplicit(); 2003 2004 // Create Decl objects for each parameter, adding them to the 2005 // FunctionDecl. 2006 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2007 SmallVector<ParmVarDecl*, 16> Params; 2008 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2009 ParmVarDecl *parm = 2010 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2011 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2012 SC_None, nullptr); 2013 parm->setScopeInfo(0, i); 2014 Params.push_back(parm); 2015 } 2016 New->setParams(Params); 2017 } 2018 2019 AddKnownFunctionAttributes(New); 2020 RegisterLocallyScopedExternCDecl(New, S); 2021 2022 // TUScope is the translation-unit scope to insert this function into. 2023 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2024 // relate Scopes to DeclContexts, and probably eliminate CurContext 2025 // entirely, but we're not there yet. 2026 DeclContext *SavedContext = CurContext; 2027 CurContext = Parent; 2028 PushOnScopeChains(New, TUScope); 2029 CurContext = SavedContext; 2030 return New; 2031 } 2032 2033 /// Typedef declarations don't have linkage, but they still denote the same 2034 /// entity if their types are the same. 2035 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2036 /// isSameEntity. 2037 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2038 TypedefNameDecl *Decl, 2039 LookupResult &Previous) { 2040 // This is only interesting when modules are enabled. 2041 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2042 return; 2043 2044 // Empty sets are uninteresting. 2045 if (Previous.empty()) 2046 return; 2047 2048 LookupResult::Filter Filter = Previous.makeFilter(); 2049 while (Filter.hasNext()) { 2050 NamedDecl *Old = Filter.next(); 2051 2052 // Non-hidden declarations are never ignored. 2053 if (S.isVisible(Old)) 2054 continue; 2055 2056 // Declarations of the same entity are not ignored, even if they have 2057 // different linkages. 2058 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2059 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2060 Decl->getUnderlyingType())) 2061 continue; 2062 2063 // If both declarations give a tag declaration a typedef name for linkage 2064 // purposes, then they declare the same entity. 2065 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2066 Decl->getAnonDeclWithTypedefName()) 2067 continue; 2068 } 2069 2070 Filter.erase(); 2071 } 2072 2073 Filter.done(); 2074 } 2075 2076 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2077 QualType OldType; 2078 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2079 OldType = OldTypedef->getUnderlyingType(); 2080 else 2081 OldType = Context.getTypeDeclType(Old); 2082 QualType NewType = New->getUnderlyingType(); 2083 2084 if (NewType->isVariablyModifiedType()) { 2085 // Must not redefine a typedef with a variably-modified type. 2086 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2087 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2088 << Kind << NewType; 2089 if (Old->getLocation().isValid()) 2090 notePreviousDefinition(Old, New->getLocation()); 2091 New->setInvalidDecl(); 2092 return true; 2093 } 2094 2095 if (OldType != NewType && 2096 !OldType->isDependentType() && 2097 !NewType->isDependentType() && 2098 !Context.hasSameType(OldType, NewType)) { 2099 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2100 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2101 << Kind << NewType << OldType; 2102 if (Old->getLocation().isValid()) 2103 notePreviousDefinition(Old, New->getLocation()); 2104 New->setInvalidDecl(); 2105 return true; 2106 } 2107 return false; 2108 } 2109 2110 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2111 /// same name and scope as a previous declaration 'Old'. Figure out 2112 /// how to resolve this situation, merging decls or emitting 2113 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2114 /// 2115 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2116 LookupResult &OldDecls) { 2117 // If the new decl is known invalid already, don't bother doing any 2118 // merging checks. 2119 if (New->isInvalidDecl()) return; 2120 2121 // Allow multiple definitions for ObjC built-in typedefs. 2122 // FIXME: Verify the underlying types are equivalent! 2123 if (getLangOpts().ObjC) { 2124 const IdentifierInfo *TypeID = New->getIdentifier(); 2125 switch (TypeID->getLength()) { 2126 default: break; 2127 case 2: 2128 { 2129 if (!TypeID->isStr("id")) 2130 break; 2131 QualType T = New->getUnderlyingType(); 2132 if (!T->isPointerType()) 2133 break; 2134 if (!T->isVoidPointerType()) { 2135 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2136 if (!PT->isStructureType()) 2137 break; 2138 } 2139 Context.setObjCIdRedefinitionType(T); 2140 // Install the built-in type for 'id', ignoring the current definition. 2141 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2142 return; 2143 } 2144 case 5: 2145 if (!TypeID->isStr("Class")) 2146 break; 2147 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2148 // Install the built-in type for 'Class', ignoring the current definition. 2149 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2150 return; 2151 case 3: 2152 if (!TypeID->isStr("SEL")) 2153 break; 2154 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2155 // Install the built-in type for 'SEL', ignoring the current definition. 2156 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2157 return; 2158 } 2159 // Fall through - the typedef name was not a builtin type. 2160 } 2161 2162 // Verify the old decl was also a type. 2163 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2164 if (!Old) { 2165 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2166 << New->getDeclName(); 2167 2168 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2169 if (OldD->getLocation().isValid()) 2170 notePreviousDefinition(OldD, New->getLocation()); 2171 2172 return New->setInvalidDecl(); 2173 } 2174 2175 // If the old declaration is invalid, just give up here. 2176 if (Old->isInvalidDecl()) 2177 return New->setInvalidDecl(); 2178 2179 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2180 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2181 auto *NewTag = New->getAnonDeclWithTypedefName(); 2182 NamedDecl *Hidden = nullptr; 2183 if (OldTag && NewTag && 2184 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2185 !hasVisibleDefinition(OldTag, &Hidden)) { 2186 // There is a definition of this tag, but it is not visible. Use it 2187 // instead of our tag. 2188 New->setTypeForDecl(OldTD->getTypeForDecl()); 2189 if (OldTD->isModed()) 2190 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2191 OldTD->getUnderlyingType()); 2192 else 2193 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2194 2195 // Make the old tag definition visible. 2196 makeMergedDefinitionVisible(Hidden); 2197 2198 // If this was an unscoped enumeration, yank all of its enumerators 2199 // out of the scope. 2200 if (isa<EnumDecl>(NewTag)) { 2201 Scope *EnumScope = getNonFieldDeclScope(S); 2202 for (auto *D : NewTag->decls()) { 2203 auto *ED = cast<EnumConstantDecl>(D); 2204 assert(EnumScope->isDeclScope(ED)); 2205 EnumScope->RemoveDecl(ED); 2206 IdResolver.RemoveDecl(ED); 2207 ED->getLexicalDeclContext()->removeDecl(ED); 2208 } 2209 } 2210 } 2211 } 2212 2213 // If the typedef types are not identical, reject them in all languages and 2214 // with any extensions enabled. 2215 if (isIncompatibleTypedef(Old, New)) 2216 return; 2217 2218 // The types match. Link up the redeclaration chain and merge attributes if 2219 // the old declaration was a typedef. 2220 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2221 New->setPreviousDecl(Typedef); 2222 mergeDeclAttributes(New, Old); 2223 } 2224 2225 if (getLangOpts().MicrosoftExt) 2226 return; 2227 2228 if (getLangOpts().CPlusPlus) { 2229 // C++ [dcl.typedef]p2: 2230 // In a given non-class scope, a typedef specifier can be used to 2231 // redefine the name of any type declared in that scope to refer 2232 // to the type to which it already refers. 2233 if (!isa<CXXRecordDecl>(CurContext)) 2234 return; 2235 2236 // C++0x [dcl.typedef]p4: 2237 // In a given class scope, a typedef specifier can be used to redefine 2238 // any class-name declared in that scope that is not also a typedef-name 2239 // to refer to the type to which it already refers. 2240 // 2241 // This wording came in via DR424, which was a correction to the 2242 // wording in DR56, which accidentally banned code like: 2243 // 2244 // struct S { 2245 // typedef struct A { } A; 2246 // }; 2247 // 2248 // in the C++03 standard. We implement the C++0x semantics, which 2249 // allow the above but disallow 2250 // 2251 // struct S { 2252 // typedef int I; 2253 // typedef int I; 2254 // }; 2255 // 2256 // since that was the intent of DR56. 2257 if (!isa<TypedefNameDecl>(Old)) 2258 return; 2259 2260 Diag(New->getLocation(), diag::err_redefinition) 2261 << New->getDeclName(); 2262 notePreviousDefinition(Old, New->getLocation()); 2263 return New->setInvalidDecl(); 2264 } 2265 2266 // Modules always permit redefinition of typedefs, as does C11. 2267 if (getLangOpts().Modules || getLangOpts().C11) 2268 return; 2269 2270 // If we have a redefinition of a typedef in C, emit a warning. This warning 2271 // is normally mapped to an error, but can be controlled with 2272 // -Wtypedef-redefinition. If either the original or the redefinition is 2273 // in a system header, don't emit this for compatibility with GCC. 2274 if (getDiagnostics().getSuppressSystemWarnings() && 2275 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2276 (Old->isImplicit() || 2277 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2278 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2279 return; 2280 2281 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2282 << New->getDeclName(); 2283 notePreviousDefinition(Old, New->getLocation()); 2284 } 2285 2286 /// DeclhasAttr - returns true if decl Declaration already has the target 2287 /// attribute. 2288 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2289 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2290 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2291 for (const auto *i : D->attrs()) 2292 if (i->getKind() == A->getKind()) { 2293 if (Ann) { 2294 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2295 return true; 2296 continue; 2297 } 2298 // FIXME: Don't hardcode this check 2299 if (OA && isa<OwnershipAttr>(i)) 2300 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2301 return true; 2302 } 2303 2304 return false; 2305 } 2306 2307 static bool isAttributeTargetADefinition(Decl *D) { 2308 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2309 return VD->isThisDeclarationADefinition(); 2310 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2311 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2312 return true; 2313 } 2314 2315 /// Merge alignment attributes from \p Old to \p New, taking into account the 2316 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2317 /// 2318 /// \return \c true if any attributes were added to \p New. 2319 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2320 // Look for alignas attributes on Old, and pick out whichever attribute 2321 // specifies the strictest alignment requirement. 2322 AlignedAttr *OldAlignasAttr = nullptr; 2323 AlignedAttr *OldStrictestAlignAttr = nullptr; 2324 unsigned OldAlign = 0; 2325 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2326 // FIXME: We have no way of representing inherited dependent alignments 2327 // in a case like: 2328 // template<int A, int B> struct alignas(A) X; 2329 // template<int A, int B> struct alignas(B) X {}; 2330 // For now, we just ignore any alignas attributes which are not on the 2331 // definition in such a case. 2332 if (I->isAlignmentDependent()) 2333 return false; 2334 2335 if (I->isAlignas()) 2336 OldAlignasAttr = I; 2337 2338 unsigned Align = I->getAlignment(S.Context); 2339 if (Align > OldAlign) { 2340 OldAlign = Align; 2341 OldStrictestAlignAttr = I; 2342 } 2343 } 2344 2345 // Look for alignas attributes on New. 2346 AlignedAttr *NewAlignasAttr = nullptr; 2347 unsigned NewAlign = 0; 2348 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2349 if (I->isAlignmentDependent()) 2350 return false; 2351 2352 if (I->isAlignas()) 2353 NewAlignasAttr = I; 2354 2355 unsigned Align = I->getAlignment(S.Context); 2356 if (Align > NewAlign) 2357 NewAlign = Align; 2358 } 2359 2360 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2361 // Both declarations have 'alignas' attributes. We require them to match. 2362 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2363 // fall short. (If two declarations both have alignas, they must both match 2364 // every definition, and so must match each other if there is a definition.) 2365 2366 // If either declaration only contains 'alignas(0)' specifiers, then it 2367 // specifies the natural alignment for the type. 2368 if (OldAlign == 0 || NewAlign == 0) { 2369 QualType Ty; 2370 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2371 Ty = VD->getType(); 2372 else 2373 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2374 2375 if (OldAlign == 0) 2376 OldAlign = S.Context.getTypeAlign(Ty); 2377 if (NewAlign == 0) 2378 NewAlign = S.Context.getTypeAlign(Ty); 2379 } 2380 2381 if (OldAlign != NewAlign) { 2382 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2383 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2384 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2385 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2386 } 2387 } 2388 2389 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2390 // C++11 [dcl.align]p6: 2391 // if any declaration of an entity has an alignment-specifier, 2392 // every defining declaration of that entity shall specify an 2393 // equivalent alignment. 2394 // C11 6.7.5/7: 2395 // If the definition of an object does not have an alignment 2396 // specifier, any other declaration of that object shall also 2397 // have no alignment specifier. 2398 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2399 << OldAlignasAttr; 2400 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2401 << OldAlignasAttr; 2402 } 2403 2404 bool AnyAdded = false; 2405 2406 // Ensure we have an attribute representing the strictest alignment. 2407 if (OldAlign > NewAlign) { 2408 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2409 Clone->setInherited(true); 2410 New->addAttr(Clone); 2411 AnyAdded = true; 2412 } 2413 2414 // Ensure we have an alignas attribute if the old declaration had one. 2415 if (OldAlignasAttr && !NewAlignasAttr && 2416 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2417 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2418 Clone->setInherited(true); 2419 New->addAttr(Clone); 2420 AnyAdded = true; 2421 } 2422 2423 return AnyAdded; 2424 } 2425 2426 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2427 const InheritableAttr *Attr, 2428 Sema::AvailabilityMergeKind AMK) { 2429 // This function copies an attribute Attr from a previous declaration to the 2430 // new declaration D if the new declaration doesn't itself have that attribute 2431 // yet or if that attribute allows duplicates. 2432 // If you're adding a new attribute that requires logic different from 2433 // "use explicit attribute on decl if present, else use attribute from 2434 // previous decl", for example if the attribute needs to be consistent 2435 // between redeclarations, you need to call a custom merge function here. 2436 InheritableAttr *NewAttr = nullptr; 2437 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2438 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2439 NewAttr = S.mergeAvailabilityAttr( 2440 D, AA->getRange(), AA->getPlatform(), AA->isImplicit(), 2441 AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(), 2442 AA->getUnavailable(), AA->getMessage(), AA->getStrict(), 2443 AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex); 2444 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2445 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2446 AttrSpellingListIndex); 2447 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2448 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2449 AttrSpellingListIndex); 2450 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2451 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2452 AttrSpellingListIndex); 2453 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2454 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2455 AttrSpellingListIndex); 2456 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2457 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2458 FA->getFormatIdx(), FA->getFirstArg(), 2459 AttrSpellingListIndex); 2460 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2461 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2462 AttrSpellingListIndex); 2463 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2464 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(), 2465 AttrSpellingListIndex); 2466 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2467 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2468 AttrSpellingListIndex, 2469 IA->getSemanticSpelling()); 2470 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2471 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2472 &S.Context.Idents.get(AA->getSpelling()), 2473 AttrSpellingListIndex); 2474 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2475 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2476 isa<CUDAGlobalAttr>(Attr))) { 2477 // CUDA target attributes are part of function signature for 2478 // overloading purposes and must not be merged. 2479 return false; 2480 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2481 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2482 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2483 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2484 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2485 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2486 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2487 NewAttr = S.mergeCommonAttr(D, *CommonA); 2488 else if (isa<AlignedAttr>(Attr)) 2489 // AlignedAttrs are handled separately, because we need to handle all 2490 // such attributes on a declaration at the same time. 2491 NewAttr = nullptr; 2492 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2493 (AMK == Sema::AMK_Override || 2494 AMK == Sema::AMK_ProtocolImplementation)) 2495 NewAttr = nullptr; 2496 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2497 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2498 UA->getGuid()); 2499 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2500 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2501 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2502 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2503 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2504 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2505 2506 if (NewAttr) { 2507 NewAttr->setInherited(true); 2508 D->addAttr(NewAttr); 2509 if (isa<MSInheritanceAttr>(NewAttr)) 2510 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2511 return true; 2512 } 2513 2514 return false; 2515 } 2516 2517 static const NamedDecl *getDefinition(const Decl *D) { 2518 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2519 return TD->getDefinition(); 2520 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2521 const VarDecl *Def = VD->getDefinition(); 2522 if (Def) 2523 return Def; 2524 return VD->getActingDefinition(); 2525 } 2526 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2527 return FD->getDefinition(); 2528 return nullptr; 2529 } 2530 2531 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2532 for (const auto *Attribute : D->attrs()) 2533 if (Attribute->getKind() == Kind) 2534 return true; 2535 return false; 2536 } 2537 2538 /// checkNewAttributesAfterDef - If we already have a definition, check that 2539 /// there are no new attributes in this declaration. 2540 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2541 if (!New->hasAttrs()) 2542 return; 2543 2544 const NamedDecl *Def = getDefinition(Old); 2545 if (!Def || Def == New) 2546 return; 2547 2548 AttrVec &NewAttributes = New->getAttrs(); 2549 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2550 const Attr *NewAttribute = NewAttributes[I]; 2551 2552 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2553 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2554 Sema::SkipBodyInfo SkipBody; 2555 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2556 2557 // If we're skipping this definition, drop the "alias" attribute. 2558 if (SkipBody.ShouldSkip) { 2559 NewAttributes.erase(NewAttributes.begin() + I); 2560 --E; 2561 continue; 2562 } 2563 } else { 2564 VarDecl *VD = cast<VarDecl>(New); 2565 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2566 VarDecl::TentativeDefinition 2567 ? diag::err_alias_after_tentative 2568 : diag::err_redefinition; 2569 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2570 if (Diag == diag::err_redefinition) 2571 S.notePreviousDefinition(Def, VD->getLocation()); 2572 else 2573 S.Diag(Def->getLocation(), diag::note_previous_definition); 2574 VD->setInvalidDecl(); 2575 } 2576 ++I; 2577 continue; 2578 } 2579 2580 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2581 // Tentative definitions are only interesting for the alias check above. 2582 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2583 ++I; 2584 continue; 2585 } 2586 } 2587 2588 if (hasAttribute(Def, NewAttribute->getKind())) { 2589 ++I; 2590 continue; // regular attr merging will take care of validating this. 2591 } 2592 2593 if (isa<C11NoReturnAttr>(NewAttribute)) { 2594 // C's _Noreturn is allowed to be added to a function after it is defined. 2595 ++I; 2596 continue; 2597 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2598 if (AA->isAlignas()) { 2599 // C++11 [dcl.align]p6: 2600 // if any declaration of an entity has an alignment-specifier, 2601 // every defining declaration of that entity shall specify an 2602 // equivalent alignment. 2603 // C11 6.7.5/7: 2604 // If the definition of an object does not have an alignment 2605 // specifier, any other declaration of that object shall also 2606 // have no alignment specifier. 2607 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2608 << AA; 2609 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2610 << AA; 2611 NewAttributes.erase(NewAttributes.begin() + I); 2612 --E; 2613 continue; 2614 } 2615 } 2616 2617 S.Diag(NewAttribute->getLocation(), 2618 diag::warn_attribute_precede_definition); 2619 S.Diag(Def->getLocation(), diag::note_previous_definition); 2620 NewAttributes.erase(NewAttributes.begin() + I); 2621 --E; 2622 } 2623 } 2624 2625 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2626 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2627 AvailabilityMergeKind AMK) { 2628 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2629 UsedAttr *NewAttr = OldAttr->clone(Context); 2630 NewAttr->setInherited(true); 2631 New->addAttr(NewAttr); 2632 } 2633 2634 if (!Old->hasAttrs() && !New->hasAttrs()) 2635 return; 2636 2637 // Attributes declared post-definition are currently ignored. 2638 checkNewAttributesAfterDef(*this, New, Old); 2639 2640 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2641 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2642 if (OldA->getLabel() != NewA->getLabel()) { 2643 // This redeclaration changes __asm__ label. 2644 Diag(New->getLocation(), diag::err_different_asm_label); 2645 Diag(OldA->getLocation(), diag::note_previous_declaration); 2646 } 2647 } else if (Old->isUsed()) { 2648 // This redeclaration adds an __asm__ label to a declaration that has 2649 // already been ODR-used. 2650 Diag(New->getLocation(), diag::err_late_asm_label_name) 2651 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2652 } 2653 } 2654 2655 // Re-declaration cannot add abi_tag's. 2656 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2657 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2658 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2659 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2660 NewTag) == OldAbiTagAttr->tags_end()) { 2661 Diag(NewAbiTagAttr->getLocation(), 2662 diag::err_new_abi_tag_on_redeclaration) 2663 << NewTag; 2664 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2665 } 2666 } 2667 } else { 2668 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2669 Diag(Old->getLocation(), diag::note_previous_declaration); 2670 } 2671 } 2672 2673 // This redeclaration adds a section attribute. 2674 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2675 if (auto *VD = dyn_cast<VarDecl>(New)) { 2676 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2677 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2678 Diag(Old->getLocation(), diag::note_previous_declaration); 2679 } 2680 } 2681 } 2682 2683 // Redeclaration adds code-seg attribute. 2684 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2685 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2686 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2687 Diag(New->getLocation(), diag::warn_mismatched_section) 2688 << 0 /*codeseg*/; 2689 Diag(Old->getLocation(), diag::note_previous_declaration); 2690 } 2691 2692 if (!Old->hasAttrs()) 2693 return; 2694 2695 bool foundAny = New->hasAttrs(); 2696 2697 // Ensure that any moving of objects within the allocated map is done before 2698 // we process them. 2699 if (!foundAny) New->setAttrs(AttrVec()); 2700 2701 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2702 // Ignore deprecated/unavailable/availability attributes if requested. 2703 AvailabilityMergeKind LocalAMK = AMK_None; 2704 if (isa<DeprecatedAttr>(I) || 2705 isa<UnavailableAttr>(I) || 2706 isa<AvailabilityAttr>(I)) { 2707 switch (AMK) { 2708 case AMK_None: 2709 continue; 2710 2711 case AMK_Redeclaration: 2712 case AMK_Override: 2713 case AMK_ProtocolImplementation: 2714 LocalAMK = AMK; 2715 break; 2716 } 2717 } 2718 2719 // Already handled. 2720 if (isa<UsedAttr>(I)) 2721 continue; 2722 2723 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2724 foundAny = true; 2725 } 2726 2727 if (mergeAlignedAttrs(*this, New, Old)) 2728 foundAny = true; 2729 2730 if (!foundAny) New->dropAttrs(); 2731 } 2732 2733 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2734 /// to the new one. 2735 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2736 const ParmVarDecl *oldDecl, 2737 Sema &S) { 2738 // C++11 [dcl.attr.depend]p2: 2739 // The first declaration of a function shall specify the 2740 // carries_dependency attribute for its declarator-id if any declaration 2741 // of the function specifies the carries_dependency attribute. 2742 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2743 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2744 S.Diag(CDA->getLocation(), 2745 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2746 // Find the first declaration of the parameter. 2747 // FIXME: Should we build redeclaration chains for function parameters? 2748 const FunctionDecl *FirstFD = 2749 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2750 const ParmVarDecl *FirstVD = 2751 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2752 S.Diag(FirstVD->getLocation(), 2753 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2754 } 2755 2756 if (!oldDecl->hasAttrs()) 2757 return; 2758 2759 bool foundAny = newDecl->hasAttrs(); 2760 2761 // Ensure that any moving of objects within the allocated map is 2762 // done before we process them. 2763 if (!foundAny) newDecl->setAttrs(AttrVec()); 2764 2765 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2766 if (!DeclHasAttr(newDecl, I)) { 2767 InheritableAttr *newAttr = 2768 cast<InheritableParamAttr>(I->clone(S.Context)); 2769 newAttr->setInherited(true); 2770 newDecl->addAttr(newAttr); 2771 foundAny = true; 2772 } 2773 } 2774 2775 if (!foundAny) newDecl->dropAttrs(); 2776 } 2777 2778 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2779 const ParmVarDecl *OldParam, 2780 Sema &S) { 2781 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2782 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2783 if (*Oldnullability != *Newnullability) { 2784 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2785 << DiagNullabilityKind( 2786 *Newnullability, 2787 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2788 != 0)) 2789 << DiagNullabilityKind( 2790 *Oldnullability, 2791 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2792 != 0)); 2793 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2794 } 2795 } else { 2796 QualType NewT = NewParam->getType(); 2797 NewT = S.Context.getAttributedType( 2798 AttributedType::getNullabilityAttrKind(*Oldnullability), 2799 NewT, NewT); 2800 NewParam->setType(NewT); 2801 } 2802 } 2803 } 2804 2805 namespace { 2806 2807 /// Used in MergeFunctionDecl to keep track of function parameters in 2808 /// C. 2809 struct GNUCompatibleParamWarning { 2810 ParmVarDecl *OldParm; 2811 ParmVarDecl *NewParm; 2812 QualType PromotedType; 2813 }; 2814 2815 } // end anonymous namespace 2816 2817 /// getSpecialMember - get the special member enum for a method. 2818 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2819 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2820 if (Ctor->isDefaultConstructor()) 2821 return Sema::CXXDefaultConstructor; 2822 2823 if (Ctor->isCopyConstructor()) 2824 return Sema::CXXCopyConstructor; 2825 2826 if (Ctor->isMoveConstructor()) 2827 return Sema::CXXMoveConstructor; 2828 } else if (isa<CXXDestructorDecl>(MD)) { 2829 return Sema::CXXDestructor; 2830 } else if (MD->isCopyAssignmentOperator()) { 2831 return Sema::CXXCopyAssignment; 2832 } else if (MD->isMoveAssignmentOperator()) { 2833 return Sema::CXXMoveAssignment; 2834 } 2835 2836 return Sema::CXXInvalid; 2837 } 2838 2839 // Determine whether the previous declaration was a definition, implicit 2840 // declaration, or a declaration. 2841 template <typename T> 2842 static std::pair<diag::kind, SourceLocation> 2843 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2844 diag::kind PrevDiag; 2845 SourceLocation OldLocation = Old->getLocation(); 2846 if (Old->isThisDeclarationADefinition()) 2847 PrevDiag = diag::note_previous_definition; 2848 else if (Old->isImplicit()) { 2849 PrevDiag = diag::note_previous_implicit_declaration; 2850 if (OldLocation.isInvalid()) 2851 OldLocation = New->getLocation(); 2852 } else 2853 PrevDiag = diag::note_previous_declaration; 2854 return std::make_pair(PrevDiag, OldLocation); 2855 } 2856 2857 /// canRedefineFunction - checks if a function can be redefined. Currently, 2858 /// only extern inline functions can be redefined, and even then only in 2859 /// GNU89 mode. 2860 static bool canRedefineFunction(const FunctionDecl *FD, 2861 const LangOptions& LangOpts) { 2862 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2863 !LangOpts.CPlusPlus && 2864 FD->isInlineSpecified() && 2865 FD->getStorageClass() == SC_Extern); 2866 } 2867 2868 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2869 const AttributedType *AT = T->getAs<AttributedType>(); 2870 while (AT && !AT->isCallingConv()) 2871 AT = AT->getModifiedType()->getAs<AttributedType>(); 2872 return AT; 2873 } 2874 2875 template <typename T> 2876 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2877 const DeclContext *DC = Old->getDeclContext(); 2878 if (DC->isRecord()) 2879 return false; 2880 2881 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2882 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2883 return true; 2884 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2885 return true; 2886 return false; 2887 } 2888 2889 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2890 static bool isExternC(VarTemplateDecl *) { return false; } 2891 2892 /// Check whether a redeclaration of an entity introduced by a 2893 /// using-declaration is valid, given that we know it's not an overload 2894 /// (nor a hidden tag declaration). 2895 template<typename ExpectedDecl> 2896 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2897 ExpectedDecl *New) { 2898 // C++11 [basic.scope.declarative]p4: 2899 // Given a set of declarations in a single declarative region, each of 2900 // which specifies the same unqualified name, 2901 // -- they shall all refer to the same entity, or all refer to functions 2902 // and function templates; or 2903 // -- exactly one declaration shall declare a class name or enumeration 2904 // name that is not a typedef name and the other declarations shall all 2905 // refer to the same variable or enumerator, or all refer to functions 2906 // and function templates; in this case the class name or enumeration 2907 // name is hidden (3.3.10). 2908 2909 // C++11 [namespace.udecl]p14: 2910 // If a function declaration in namespace scope or block scope has the 2911 // same name and the same parameter-type-list as a function introduced 2912 // by a using-declaration, and the declarations do not declare the same 2913 // function, the program is ill-formed. 2914 2915 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2916 if (Old && 2917 !Old->getDeclContext()->getRedeclContext()->Equals( 2918 New->getDeclContext()->getRedeclContext()) && 2919 !(isExternC(Old) && isExternC(New))) 2920 Old = nullptr; 2921 2922 if (!Old) { 2923 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2924 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2925 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2926 return true; 2927 } 2928 return false; 2929 } 2930 2931 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2932 const FunctionDecl *B) { 2933 assert(A->getNumParams() == B->getNumParams()); 2934 2935 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2936 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2937 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2938 if (AttrA == AttrB) 2939 return true; 2940 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 2941 AttrA->isDynamic() == AttrB->isDynamic(); 2942 }; 2943 2944 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2945 } 2946 2947 /// If necessary, adjust the semantic declaration context for a qualified 2948 /// declaration to name the correct inline namespace within the qualifier. 2949 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2950 DeclaratorDecl *OldD) { 2951 // The only case where we need to update the DeclContext is when 2952 // redeclaration lookup for a qualified name finds a declaration 2953 // in an inline namespace within the context named by the qualifier: 2954 // 2955 // inline namespace N { int f(); } 2956 // int ::f(); // Sema DC needs adjusting from :: to N::. 2957 // 2958 // For unqualified declarations, the semantic context *can* change 2959 // along the redeclaration chain (for local extern declarations, 2960 // extern "C" declarations, and friend declarations in particular). 2961 if (!NewD->getQualifier()) 2962 return; 2963 2964 // NewD is probably already in the right context. 2965 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2966 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2967 if (NamedDC->Equals(SemaDC)) 2968 return; 2969 2970 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2971 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2972 "unexpected context for redeclaration"); 2973 2974 auto *LexDC = NewD->getLexicalDeclContext(); 2975 auto FixSemaDC = [=](NamedDecl *D) { 2976 if (!D) 2977 return; 2978 D->setDeclContext(SemaDC); 2979 D->setLexicalDeclContext(LexDC); 2980 }; 2981 2982 FixSemaDC(NewD); 2983 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 2984 FixSemaDC(FD->getDescribedFunctionTemplate()); 2985 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 2986 FixSemaDC(VD->getDescribedVarTemplate()); 2987 } 2988 2989 /// MergeFunctionDecl - We just parsed a function 'New' from 2990 /// declarator D which has the same name and scope as a previous 2991 /// declaration 'Old'. Figure out how to resolve this situation, 2992 /// merging decls or emitting diagnostics as appropriate. 2993 /// 2994 /// In C++, New and Old must be declarations that are not 2995 /// overloaded. Use IsOverload to determine whether New and Old are 2996 /// overloaded, and to select the Old declaration that New should be 2997 /// merged with. 2998 /// 2999 /// Returns true if there was an error, false otherwise. 3000 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3001 Scope *S, bool MergeTypeWithOld) { 3002 // Verify the old decl was also a function. 3003 FunctionDecl *Old = OldD->getAsFunction(); 3004 if (!Old) { 3005 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3006 if (New->getFriendObjectKind()) { 3007 Diag(New->getLocation(), diag::err_using_decl_friend); 3008 Diag(Shadow->getTargetDecl()->getLocation(), 3009 diag::note_using_decl_target); 3010 Diag(Shadow->getUsingDecl()->getLocation(), 3011 diag::note_using_decl) << 0; 3012 return true; 3013 } 3014 3015 // Check whether the two declarations might declare the same function. 3016 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3017 return true; 3018 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3019 } else { 3020 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3021 << New->getDeclName(); 3022 notePreviousDefinition(OldD, New->getLocation()); 3023 return true; 3024 } 3025 } 3026 3027 // If the old declaration is invalid, just give up here. 3028 if (Old->isInvalidDecl()) 3029 return true; 3030 3031 // Disallow redeclaration of some builtins. 3032 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3033 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3034 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3035 << Old << Old->getType(); 3036 return true; 3037 } 3038 3039 diag::kind PrevDiag; 3040 SourceLocation OldLocation; 3041 std::tie(PrevDiag, OldLocation) = 3042 getNoteDiagForInvalidRedeclaration(Old, New); 3043 3044 // Don't complain about this if we're in GNU89 mode and the old function 3045 // is an extern inline function. 3046 // Don't complain about specializations. They are not supposed to have 3047 // storage classes. 3048 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3049 New->getStorageClass() == SC_Static && 3050 Old->hasExternalFormalLinkage() && 3051 !New->getTemplateSpecializationInfo() && 3052 !canRedefineFunction(Old, getLangOpts())) { 3053 if (getLangOpts().MicrosoftExt) { 3054 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3055 Diag(OldLocation, PrevDiag); 3056 } else { 3057 Diag(New->getLocation(), diag::err_static_non_static) << New; 3058 Diag(OldLocation, PrevDiag); 3059 return true; 3060 } 3061 } 3062 3063 if (New->hasAttr<InternalLinkageAttr>() && 3064 !Old->hasAttr<InternalLinkageAttr>()) { 3065 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3066 << New->getDeclName(); 3067 notePreviousDefinition(Old, New->getLocation()); 3068 New->dropAttr<InternalLinkageAttr>(); 3069 } 3070 3071 if (CheckRedeclarationModuleOwnership(New, Old)) 3072 return true; 3073 3074 if (!getLangOpts().CPlusPlus) { 3075 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3076 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3077 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3078 << New << OldOvl; 3079 3080 // Try our best to find a decl that actually has the overloadable 3081 // attribute for the note. In most cases (e.g. programs with only one 3082 // broken declaration/definition), this won't matter. 3083 // 3084 // FIXME: We could do this if we juggled some extra state in 3085 // OverloadableAttr, rather than just removing it. 3086 const Decl *DiagOld = Old; 3087 if (OldOvl) { 3088 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3089 const auto *A = D->getAttr<OverloadableAttr>(); 3090 return A && !A->isImplicit(); 3091 }); 3092 // If we've implicitly added *all* of the overloadable attrs to this 3093 // chain, emitting a "previous redecl" note is pointless. 3094 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3095 } 3096 3097 if (DiagOld) 3098 Diag(DiagOld->getLocation(), 3099 diag::note_attribute_overloadable_prev_overload) 3100 << OldOvl; 3101 3102 if (OldOvl) 3103 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3104 else 3105 New->dropAttr<OverloadableAttr>(); 3106 } 3107 } 3108 3109 // If a function is first declared with a calling convention, but is later 3110 // declared or defined without one, all following decls assume the calling 3111 // convention of the first. 3112 // 3113 // It's OK if a function is first declared without a calling convention, 3114 // but is later declared or defined with the default calling convention. 3115 // 3116 // To test if either decl has an explicit calling convention, we look for 3117 // AttributedType sugar nodes on the type as written. If they are missing or 3118 // were canonicalized away, we assume the calling convention was implicit. 3119 // 3120 // Note also that we DO NOT return at this point, because we still have 3121 // other tests to run. 3122 QualType OldQType = Context.getCanonicalType(Old->getType()); 3123 QualType NewQType = Context.getCanonicalType(New->getType()); 3124 const FunctionType *OldType = cast<FunctionType>(OldQType); 3125 const FunctionType *NewType = cast<FunctionType>(NewQType); 3126 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3127 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3128 bool RequiresAdjustment = false; 3129 3130 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3131 FunctionDecl *First = Old->getFirstDecl(); 3132 const FunctionType *FT = 3133 First->getType().getCanonicalType()->castAs<FunctionType>(); 3134 FunctionType::ExtInfo FI = FT->getExtInfo(); 3135 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3136 if (!NewCCExplicit) { 3137 // Inherit the CC from the previous declaration if it was specified 3138 // there but not here. 3139 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3140 RequiresAdjustment = true; 3141 } else if (New->getBuiltinID()) { 3142 // Calling Conventions on a Builtin aren't really useful and setting a 3143 // default calling convention and cdecl'ing some builtin redeclarations is 3144 // common, so warn and ignore the calling convention on the redeclaration. 3145 Diag(New->getLocation(), diag::warn_cconv_ignored) 3146 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3147 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3148 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3149 RequiresAdjustment = true; 3150 } else { 3151 // Calling conventions aren't compatible, so complain. 3152 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3153 Diag(New->getLocation(), diag::err_cconv_change) 3154 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3155 << !FirstCCExplicit 3156 << (!FirstCCExplicit ? "" : 3157 FunctionType::getNameForCallConv(FI.getCC())); 3158 3159 // Put the note on the first decl, since it is the one that matters. 3160 Diag(First->getLocation(), diag::note_previous_declaration); 3161 return true; 3162 } 3163 } 3164 3165 // FIXME: diagnose the other way around? 3166 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3167 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3168 RequiresAdjustment = true; 3169 } 3170 3171 // Merge regparm attribute. 3172 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3173 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3174 if (NewTypeInfo.getHasRegParm()) { 3175 Diag(New->getLocation(), diag::err_regparm_mismatch) 3176 << NewType->getRegParmType() 3177 << OldType->getRegParmType(); 3178 Diag(OldLocation, diag::note_previous_declaration); 3179 return true; 3180 } 3181 3182 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3183 RequiresAdjustment = true; 3184 } 3185 3186 // Merge ns_returns_retained attribute. 3187 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3188 if (NewTypeInfo.getProducesResult()) { 3189 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3190 << "'ns_returns_retained'"; 3191 Diag(OldLocation, diag::note_previous_declaration); 3192 return true; 3193 } 3194 3195 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3196 RequiresAdjustment = true; 3197 } 3198 3199 if (OldTypeInfo.getNoCallerSavedRegs() != 3200 NewTypeInfo.getNoCallerSavedRegs()) { 3201 if (NewTypeInfo.getNoCallerSavedRegs()) { 3202 AnyX86NoCallerSavedRegistersAttr *Attr = 3203 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3204 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3205 Diag(OldLocation, diag::note_previous_declaration); 3206 return true; 3207 } 3208 3209 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3210 RequiresAdjustment = true; 3211 } 3212 3213 if (RequiresAdjustment) { 3214 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3215 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3216 New->setType(QualType(AdjustedType, 0)); 3217 NewQType = Context.getCanonicalType(New->getType()); 3218 NewType = cast<FunctionType>(NewQType); 3219 } 3220 3221 // If this redeclaration makes the function inline, we may need to add it to 3222 // UndefinedButUsed. 3223 if (!Old->isInlined() && New->isInlined() && 3224 !New->hasAttr<GNUInlineAttr>() && 3225 !getLangOpts().GNUInline && 3226 Old->isUsed(false) && 3227 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3228 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3229 SourceLocation())); 3230 3231 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3232 // about it. 3233 if (New->hasAttr<GNUInlineAttr>() && 3234 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3235 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3236 } 3237 3238 // If pass_object_size params don't match up perfectly, this isn't a valid 3239 // redeclaration. 3240 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3241 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3242 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3243 << New->getDeclName(); 3244 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3245 return true; 3246 } 3247 3248 if (getLangOpts().CPlusPlus) { 3249 // C++1z [over.load]p2 3250 // Certain function declarations cannot be overloaded: 3251 // -- Function declarations that differ only in the return type, 3252 // the exception specification, or both cannot be overloaded. 3253 3254 // Check the exception specifications match. This may recompute the type of 3255 // both Old and New if it resolved exception specifications, so grab the 3256 // types again after this. Because this updates the type, we do this before 3257 // any of the other checks below, which may update the "de facto" NewQType 3258 // but do not necessarily update the type of New. 3259 if (CheckEquivalentExceptionSpec(Old, New)) 3260 return true; 3261 OldQType = Context.getCanonicalType(Old->getType()); 3262 NewQType = Context.getCanonicalType(New->getType()); 3263 3264 // Go back to the type source info to compare the declared return types, 3265 // per C++1y [dcl.type.auto]p13: 3266 // Redeclarations or specializations of a function or function template 3267 // with a declared return type that uses a placeholder type shall also 3268 // use that placeholder, not a deduced type. 3269 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3270 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3271 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3272 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3273 OldDeclaredReturnType)) { 3274 QualType ResQT; 3275 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3276 OldDeclaredReturnType->isObjCObjectPointerType()) 3277 // FIXME: This does the wrong thing for a deduced return type. 3278 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3279 if (ResQT.isNull()) { 3280 if (New->isCXXClassMember() && New->isOutOfLine()) 3281 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3282 << New << New->getReturnTypeSourceRange(); 3283 else 3284 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3285 << New->getReturnTypeSourceRange(); 3286 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3287 << Old->getReturnTypeSourceRange(); 3288 return true; 3289 } 3290 else 3291 NewQType = ResQT; 3292 } 3293 3294 QualType OldReturnType = OldType->getReturnType(); 3295 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3296 if (OldReturnType != NewReturnType) { 3297 // If this function has a deduced return type and has already been 3298 // defined, copy the deduced value from the old declaration. 3299 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3300 if (OldAT && OldAT->isDeduced()) { 3301 New->setType( 3302 SubstAutoType(New->getType(), 3303 OldAT->isDependentType() ? Context.DependentTy 3304 : OldAT->getDeducedType())); 3305 NewQType = Context.getCanonicalType( 3306 SubstAutoType(NewQType, 3307 OldAT->isDependentType() ? Context.DependentTy 3308 : OldAT->getDeducedType())); 3309 } 3310 } 3311 3312 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3313 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3314 if (OldMethod && NewMethod) { 3315 // Preserve triviality. 3316 NewMethod->setTrivial(OldMethod->isTrivial()); 3317 3318 // MSVC allows explicit template specialization at class scope: 3319 // 2 CXXMethodDecls referring to the same function will be injected. 3320 // We don't want a redeclaration error. 3321 bool IsClassScopeExplicitSpecialization = 3322 OldMethod->isFunctionTemplateSpecialization() && 3323 NewMethod->isFunctionTemplateSpecialization(); 3324 bool isFriend = NewMethod->getFriendObjectKind(); 3325 3326 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3327 !IsClassScopeExplicitSpecialization) { 3328 // -- Member function declarations with the same name and the 3329 // same parameter types cannot be overloaded if any of them 3330 // is a static member function declaration. 3331 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3332 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3333 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3334 return true; 3335 } 3336 3337 // C++ [class.mem]p1: 3338 // [...] A member shall not be declared twice in the 3339 // member-specification, except that a nested class or member 3340 // class template can be declared and then later defined. 3341 if (!inTemplateInstantiation()) { 3342 unsigned NewDiag; 3343 if (isa<CXXConstructorDecl>(OldMethod)) 3344 NewDiag = diag::err_constructor_redeclared; 3345 else if (isa<CXXDestructorDecl>(NewMethod)) 3346 NewDiag = diag::err_destructor_redeclared; 3347 else if (isa<CXXConversionDecl>(NewMethod)) 3348 NewDiag = diag::err_conv_function_redeclared; 3349 else 3350 NewDiag = diag::err_member_redeclared; 3351 3352 Diag(New->getLocation(), NewDiag); 3353 } else { 3354 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3355 << New << New->getType(); 3356 } 3357 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3358 return true; 3359 3360 // Complain if this is an explicit declaration of a special 3361 // member that was initially declared implicitly. 3362 // 3363 // As an exception, it's okay to befriend such methods in order 3364 // to permit the implicit constructor/destructor/operator calls. 3365 } else if (OldMethod->isImplicit()) { 3366 if (isFriend) { 3367 NewMethod->setImplicit(); 3368 } else { 3369 Diag(NewMethod->getLocation(), 3370 diag::err_definition_of_implicitly_declared_member) 3371 << New << getSpecialMember(OldMethod); 3372 return true; 3373 } 3374 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3375 Diag(NewMethod->getLocation(), 3376 diag::err_definition_of_explicitly_defaulted_member) 3377 << getSpecialMember(OldMethod); 3378 return true; 3379 } 3380 } 3381 3382 // C++11 [dcl.attr.noreturn]p1: 3383 // The first declaration of a function shall specify the noreturn 3384 // attribute if any declaration of that function specifies the noreturn 3385 // attribute. 3386 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3387 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3388 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3389 Diag(Old->getFirstDecl()->getLocation(), 3390 diag::note_noreturn_missing_first_decl); 3391 } 3392 3393 // C++11 [dcl.attr.depend]p2: 3394 // The first declaration of a function shall specify the 3395 // carries_dependency attribute for its declarator-id if any declaration 3396 // of the function specifies the carries_dependency attribute. 3397 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3398 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3399 Diag(CDA->getLocation(), 3400 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3401 Diag(Old->getFirstDecl()->getLocation(), 3402 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3403 } 3404 3405 // (C++98 8.3.5p3): 3406 // All declarations for a function shall agree exactly in both the 3407 // return type and the parameter-type-list. 3408 // We also want to respect all the extended bits except noreturn. 3409 3410 // noreturn should now match unless the old type info didn't have it. 3411 QualType OldQTypeForComparison = OldQType; 3412 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3413 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3414 const FunctionType *OldTypeForComparison 3415 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3416 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3417 assert(OldQTypeForComparison.isCanonical()); 3418 } 3419 3420 if (haveIncompatibleLanguageLinkages(Old, New)) { 3421 // As a special case, retain the language linkage from previous 3422 // declarations of a friend function as an extension. 3423 // 3424 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3425 // and is useful because there's otherwise no way to specify language 3426 // linkage within class scope. 3427 // 3428 // Check cautiously as the friend object kind isn't yet complete. 3429 if (New->getFriendObjectKind() != Decl::FOK_None) { 3430 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3431 Diag(OldLocation, PrevDiag); 3432 } else { 3433 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3434 Diag(OldLocation, PrevDiag); 3435 return true; 3436 } 3437 } 3438 3439 if (OldQTypeForComparison == NewQType) 3440 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3441 3442 // If the types are imprecise (due to dependent constructs in friends or 3443 // local extern declarations), it's OK if they differ. We'll check again 3444 // during instantiation. 3445 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3446 return false; 3447 3448 // Fall through for conflicting redeclarations and redefinitions. 3449 } 3450 3451 // C: Function types need to be compatible, not identical. This handles 3452 // duplicate function decls like "void f(int); void f(enum X);" properly. 3453 if (!getLangOpts().CPlusPlus && 3454 Context.typesAreCompatible(OldQType, NewQType)) { 3455 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3456 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3457 const FunctionProtoType *OldProto = nullptr; 3458 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3459 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3460 // The old declaration provided a function prototype, but the 3461 // new declaration does not. Merge in the prototype. 3462 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3463 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3464 NewQType = 3465 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3466 OldProto->getExtProtoInfo()); 3467 New->setType(NewQType); 3468 New->setHasInheritedPrototype(); 3469 3470 // Synthesize parameters with the same types. 3471 SmallVector<ParmVarDecl*, 16> Params; 3472 for (const auto &ParamType : OldProto->param_types()) { 3473 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3474 SourceLocation(), nullptr, 3475 ParamType, /*TInfo=*/nullptr, 3476 SC_None, nullptr); 3477 Param->setScopeInfo(0, Params.size()); 3478 Param->setImplicit(); 3479 Params.push_back(Param); 3480 } 3481 3482 New->setParams(Params); 3483 } 3484 3485 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3486 } 3487 3488 // GNU C permits a K&R definition to follow a prototype declaration 3489 // if the declared types of the parameters in the K&R definition 3490 // match the types in the prototype declaration, even when the 3491 // promoted types of the parameters from the K&R definition differ 3492 // from the types in the prototype. GCC then keeps the types from 3493 // the prototype. 3494 // 3495 // If a variadic prototype is followed by a non-variadic K&R definition, 3496 // the K&R definition becomes variadic. This is sort of an edge case, but 3497 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3498 // C99 6.9.1p8. 3499 if (!getLangOpts().CPlusPlus && 3500 Old->hasPrototype() && !New->hasPrototype() && 3501 New->getType()->getAs<FunctionProtoType>() && 3502 Old->getNumParams() == New->getNumParams()) { 3503 SmallVector<QualType, 16> ArgTypes; 3504 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3505 const FunctionProtoType *OldProto 3506 = Old->getType()->getAs<FunctionProtoType>(); 3507 const FunctionProtoType *NewProto 3508 = New->getType()->getAs<FunctionProtoType>(); 3509 3510 // Determine whether this is the GNU C extension. 3511 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3512 NewProto->getReturnType()); 3513 bool LooseCompatible = !MergedReturn.isNull(); 3514 for (unsigned Idx = 0, End = Old->getNumParams(); 3515 LooseCompatible && Idx != End; ++Idx) { 3516 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3517 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3518 if (Context.typesAreCompatible(OldParm->getType(), 3519 NewProto->getParamType(Idx))) { 3520 ArgTypes.push_back(NewParm->getType()); 3521 } else if (Context.typesAreCompatible(OldParm->getType(), 3522 NewParm->getType(), 3523 /*CompareUnqualified=*/true)) { 3524 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3525 NewProto->getParamType(Idx) }; 3526 Warnings.push_back(Warn); 3527 ArgTypes.push_back(NewParm->getType()); 3528 } else 3529 LooseCompatible = false; 3530 } 3531 3532 if (LooseCompatible) { 3533 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3534 Diag(Warnings[Warn].NewParm->getLocation(), 3535 diag::ext_param_promoted_not_compatible_with_prototype) 3536 << Warnings[Warn].PromotedType 3537 << Warnings[Warn].OldParm->getType(); 3538 if (Warnings[Warn].OldParm->getLocation().isValid()) 3539 Diag(Warnings[Warn].OldParm->getLocation(), 3540 diag::note_previous_declaration); 3541 } 3542 3543 if (MergeTypeWithOld) 3544 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3545 OldProto->getExtProtoInfo())); 3546 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3547 } 3548 3549 // Fall through to diagnose conflicting types. 3550 } 3551 3552 // A function that has already been declared has been redeclared or 3553 // defined with a different type; show an appropriate diagnostic. 3554 3555 // If the previous declaration was an implicitly-generated builtin 3556 // declaration, then at the very least we should use a specialized note. 3557 unsigned BuiltinID; 3558 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3559 // If it's actually a library-defined builtin function like 'malloc' 3560 // or 'printf', just warn about the incompatible redeclaration. 3561 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3562 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3563 Diag(OldLocation, diag::note_previous_builtin_declaration) 3564 << Old << Old->getType(); 3565 3566 // If this is a global redeclaration, just forget hereafter 3567 // about the "builtin-ness" of the function. 3568 // 3569 // Doing this for local extern declarations is problematic. If 3570 // the builtin declaration remains visible, a second invalid 3571 // local declaration will produce a hard error; if it doesn't 3572 // remain visible, a single bogus local redeclaration (which is 3573 // actually only a warning) could break all the downstream code. 3574 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3575 New->getIdentifier()->revertBuiltin(); 3576 3577 return false; 3578 } 3579 3580 PrevDiag = diag::note_previous_builtin_declaration; 3581 } 3582 3583 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3584 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3585 return true; 3586 } 3587 3588 /// Completes the merge of two function declarations that are 3589 /// known to be compatible. 3590 /// 3591 /// This routine handles the merging of attributes and other 3592 /// properties of function declarations from the old declaration to 3593 /// the new declaration, once we know that New is in fact a 3594 /// redeclaration of Old. 3595 /// 3596 /// \returns false 3597 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3598 Scope *S, bool MergeTypeWithOld) { 3599 // Merge the attributes 3600 mergeDeclAttributes(New, Old); 3601 3602 // Merge "pure" flag. 3603 if (Old->isPure()) 3604 New->setPure(); 3605 3606 // Merge "used" flag. 3607 if (Old->getMostRecentDecl()->isUsed(false)) 3608 New->setIsUsed(); 3609 3610 // Merge attributes from the parameters. These can mismatch with K&R 3611 // declarations. 3612 if (New->getNumParams() == Old->getNumParams()) 3613 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3614 ParmVarDecl *NewParam = New->getParamDecl(i); 3615 ParmVarDecl *OldParam = Old->getParamDecl(i); 3616 mergeParamDeclAttributes(NewParam, OldParam, *this); 3617 mergeParamDeclTypes(NewParam, OldParam, *this); 3618 } 3619 3620 if (getLangOpts().CPlusPlus) 3621 return MergeCXXFunctionDecl(New, Old, S); 3622 3623 // Merge the function types so the we get the composite types for the return 3624 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3625 // was visible. 3626 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3627 if (!Merged.isNull() && MergeTypeWithOld) 3628 New->setType(Merged); 3629 3630 return false; 3631 } 3632 3633 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3634 ObjCMethodDecl *oldMethod) { 3635 // Merge the attributes, including deprecated/unavailable 3636 AvailabilityMergeKind MergeKind = 3637 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3638 ? AMK_ProtocolImplementation 3639 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3640 : AMK_Override; 3641 3642 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3643 3644 // Merge attributes from the parameters. 3645 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3646 oe = oldMethod->param_end(); 3647 for (ObjCMethodDecl::param_iterator 3648 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3649 ni != ne && oi != oe; ++ni, ++oi) 3650 mergeParamDeclAttributes(*ni, *oi, *this); 3651 3652 CheckObjCMethodOverride(newMethod, oldMethod); 3653 } 3654 3655 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3656 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3657 3658 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3659 ? diag::err_redefinition_different_type 3660 : diag::err_redeclaration_different_type) 3661 << New->getDeclName() << New->getType() << Old->getType(); 3662 3663 diag::kind PrevDiag; 3664 SourceLocation OldLocation; 3665 std::tie(PrevDiag, OldLocation) 3666 = getNoteDiagForInvalidRedeclaration(Old, New); 3667 S.Diag(OldLocation, PrevDiag); 3668 New->setInvalidDecl(); 3669 } 3670 3671 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3672 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3673 /// emitting diagnostics as appropriate. 3674 /// 3675 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3676 /// to here in AddInitializerToDecl. We can't check them before the initializer 3677 /// is attached. 3678 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3679 bool MergeTypeWithOld) { 3680 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3681 return; 3682 3683 QualType MergedT; 3684 if (getLangOpts().CPlusPlus) { 3685 if (New->getType()->isUndeducedType()) { 3686 // We don't know what the new type is until the initializer is attached. 3687 return; 3688 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3689 // These could still be something that needs exception specs checked. 3690 return MergeVarDeclExceptionSpecs(New, Old); 3691 } 3692 // C++ [basic.link]p10: 3693 // [...] the types specified by all declarations referring to a given 3694 // object or function shall be identical, except that declarations for an 3695 // array object can specify array types that differ by the presence or 3696 // absence of a major array bound (8.3.4). 3697 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3698 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3699 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3700 3701 // We are merging a variable declaration New into Old. If it has an array 3702 // bound, and that bound differs from Old's bound, we should diagnose the 3703 // mismatch. 3704 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3705 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3706 PrevVD = PrevVD->getPreviousDecl()) { 3707 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3708 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3709 continue; 3710 3711 if (!Context.hasSameType(NewArray, PrevVDTy)) 3712 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3713 } 3714 } 3715 3716 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3717 if (Context.hasSameType(OldArray->getElementType(), 3718 NewArray->getElementType())) 3719 MergedT = New->getType(); 3720 } 3721 // FIXME: Check visibility. New is hidden but has a complete type. If New 3722 // has no array bound, it should not inherit one from Old, if Old is not 3723 // visible. 3724 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3725 if (Context.hasSameType(OldArray->getElementType(), 3726 NewArray->getElementType())) 3727 MergedT = Old->getType(); 3728 } 3729 } 3730 else if (New->getType()->isObjCObjectPointerType() && 3731 Old->getType()->isObjCObjectPointerType()) { 3732 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3733 Old->getType()); 3734 } 3735 } else { 3736 // C 6.2.7p2: 3737 // All declarations that refer to the same object or function shall have 3738 // compatible type. 3739 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3740 } 3741 if (MergedT.isNull()) { 3742 // It's OK if we couldn't merge types if either type is dependent, for a 3743 // block-scope variable. In other cases (static data members of class 3744 // templates, variable templates, ...), we require the types to be 3745 // equivalent. 3746 // FIXME: The C++ standard doesn't say anything about this. 3747 if ((New->getType()->isDependentType() || 3748 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3749 // If the old type was dependent, we can't merge with it, so the new type 3750 // becomes dependent for now. We'll reproduce the original type when we 3751 // instantiate the TypeSourceInfo for the variable. 3752 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3753 New->setType(Context.DependentTy); 3754 return; 3755 } 3756 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3757 } 3758 3759 // Don't actually update the type on the new declaration if the old 3760 // declaration was an extern declaration in a different scope. 3761 if (MergeTypeWithOld) 3762 New->setType(MergedT); 3763 } 3764 3765 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3766 LookupResult &Previous) { 3767 // C11 6.2.7p4: 3768 // For an identifier with internal or external linkage declared 3769 // in a scope in which a prior declaration of that identifier is 3770 // visible, if the prior declaration specifies internal or 3771 // external linkage, the type of the identifier at the later 3772 // declaration becomes the composite type. 3773 // 3774 // If the variable isn't visible, we do not merge with its type. 3775 if (Previous.isShadowed()) 3776 return false; 3777 3778 if (S.getLangOpts().CPlusPlus) { 3779 // C++11 [dcl.array]p3: 3780 // If there is a preceding declaration of the entity in the same 3781 // scope in which the bound was specified, an omitted array bound 3782 // is taken to be the same as in that earlier declaration. 3783 return NewVD->isPreviousDeclInSameBlockScope() || 3784 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3785 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3786 } else { 3787 // If the old declaration was function-local, don't merge with its 3788 // type unless we're in the same function. 3789 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3790 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3791 } 3792 } 3793 3794 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3795 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3796 /// situation, merging decls or emitting diagnostics as appropriate. 3797 /// 3798 /// Tentative definition rules (C99 6.9.2p2) are checked by 3799 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3800 /// definitions here, since the initializer hasn't been attached. 3801 /// 3802 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3803 // If the new decl is already invalid, don't do any other checking. 3804 if (New->isInvalidDecl()) 3805 return; 3806 3807 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3808 return; 3809 3810 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3811 3812 // Verify the old decl was also a variable or variable template. 3813 VarDecl *Old = nullptr; 3814 VarTemplateDecl *OldTemplate = nullptr; 3815 if (Previous.isSingleResult()) { 3816 if (NewTemplate) { 3817 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3818 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3819 3820 if (auto *Shadow = 3821 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3822 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3823 return New->setInvalidDecl(); 3824 } else { 3825 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3826 3827 if (auto *Shadow = 3828 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3829 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3830 return New->setInvalidDecl(); 3831 } 3832 } 3833 if (!Old) { 3834 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3835 << New->getDeclName(); 3836 notePreviousDefinition(Previous.getRepresentativeDecl(), 3837 New->getLocation()); 3838 return New->setInvalidDecl(); 3839 } 3840 3841 // Ensure the template parameters are compatible. 3842 if (NewTemplate && 3843 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3844 OldTemplate->getTemplateParameters(), 3845 /*Complain=*/true, TPL_TemplateMatch)) 3846 return New->setInvalidDecl(); 3847 3848 // C++ [class.mem]p1: 3849 // A member shall not be declared twice in the member-specification [...] 3850 // 3851 // Here, we need only consider static data members. 3852 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3853 Diag(New->getLocation(), diag::err_duplicate_member) 3854 << New->getIdentifier(); 3855 Diag(Old->getLocation(), diag::note_previous_declaration); 3856 New->setInvalidDecl(); 3857 } 3858 3859 mergeDeclAttributes(New, Old); 3860 // Warn if an already-declared variable is made a weak_import in a subsequent 3861 // declaration 3862 if (New->hasAttr<WeakImportAttr>() && 3863 Old->getStorageClass() == SC_None && 3864 !Old->hasAttr<WeakImportAttr>()) { 3865 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3866 notePreviousDefinition(Old, New->getLocation()); 3867 // Remove weak_import attribute on new declaration. 3868 New->dropAttr<WeakImportAttr>(); 3869 } 3870 3871 if (New->hasAttr<InternalLinkageAttr>() && 3872 !Old->hasAttr<InternalLinkageAttr>()) { 3873 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3874 << New->getDeclName(); 3875 notePreviousDefinition(Old, New->getLocation()); 3876 New->dropAttr<InternalLinkageAttr>(); 3877 } 3878 3879 // Merge the types. 3880 VarDecl *MostRecent = Old->getMostRecentDecl(); 3881 if (MostRecent != Old) { 3882 MergeVarDeclTypes(New, MostRecent, 3883 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3884 if (New->isInvalidDecl()) 3885 return; 3886 } 3887 3888 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3889 if (New->isInvalidDecl()) 3890 return; 3891 3892 diag::kind PrevDiag; 3893 SourceLocation OldLocation; 3894 std::tie(PrevDiag, OldLocation) = 3895 getNoteDiagForInvalidRedeclaration(Old, New); 3896 3897 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3898 if (New->getStorageClass() == SC_Static && 3899 !New->isStaticDataMember() && 3900 Old->hasExternalFormalLinkage()) { 3901 if (getLangOpts().MicrosoftExt) { 3902 Diag(New->getLocation(), diag::ext_static_non_static) 3903 << New->getDeclName(); 3904 Diag(OldLocation, PrevDiag); 3905 } else { 3906 Diag(New->getLocation(), diag::err_static_non_static) 3907 << New->getDeclName(); 3908 Diag(OldLocation, PrevDiag); 3909 return New->setInvalidDecl(); 3910 } 3911 } 3912 // C99 6.2.2p4: 3913 // For an identifier declared with the storage-class specifier 3914 // extern in a scope in which a prior declaration of that 3915 // identifier is visible,23) if the prior declaration specifies 3916 // internal or external linkage, the linkage of the identifier at 3917 // the later declaration is the same as the linkage specified at 3918 // the prior declaration. If no prior declaration is visible, or 3919 // if the prior declaration specifies no linkage, then the 3920 // identifier has external linkage. 3921 if (New->hasExternalStorage() && Old->hasLinkage()) 3922 /* Okay */; 3923 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3924 !New->isStaticDataMember() && 3925 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3926 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3927 Diag(OldLocation, PrevDiag); 3928 return New->setInvalidDecl(); 3929 } 3930 3931 // Check if extern is followed by non-extern and vice-versa. 3932 if (New->hasExternalStorage() && 3933 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3934 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3935 Diag(OldLocation, PrevDiag); 3936 return New->setInvalidDecl(); 3937 } 3938 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3939 !New->hasExternalStorage()) { 3940 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3941 Diag(OldLocation, PrevDiag); 3942 return New->setInvalidDecl(); 3943 } 3944 3945 if (CheckRedeclarationModuleOwnership(New, Old)) 3946 return; 3947 3948 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3949 3950 // FIXME: The test for external storage here seems wrong? We still 3951 // need to check for mismatches. 3952 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3953 // Don't complain about out-of-line definitions of static members. 3954 !(Old->getLexicalDeclContext()->isRecord() && 3955 !New->getLexicalDeclContext()->isRecord())) { 3956 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3957 Diag(OldLocation, PrevDiag); 3958 return New->setInvalidDecl(); 3959 } 3960 3961 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3962 if (VarDecl *Def = Old->getDefinition()) { 3963 // C++1z [dcl.fcn.spec]p4: 3964 // If the definition of a variable appears in a translation unit before 3965 // its first declaration as inline, the program is ill-formed. 3966 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3967 Diag(Def->getLocation(), diag::note_previous_definition); 3968 } 3969 } 3970 3971 // If this redeclaration makes the variable inline, we may need to add it to 3972 // UndefinedButUsed. 3973 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3974 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3975 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3976 SourceLocation())); 3977 3978 if (New->getTLSKind() != Old->getTLSKind()) { 3979 if (!Old->getTLSKind()) { 3980 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3981 Diag(OldLocation, PrevDiag); 3982 } else if (!New->getTLSKind()) { 3983 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3984 Diag(OldLocation, PrevDiag); 3985 } else { 3986 // Do not allow redeclaration to change the variable between requiring 3987 // static and dynamic initialization. 3988 // FIXME: GCC allows this, but uses the TLS keyword on the first 3989 // declaration to determine the kind. Do we need to be compatible here? 3990 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3991 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3992 Diag(OldLocation, PrevDiag); 3993 } 3994 } 3995 3996 // C++ doesn't have tentative definitions, so go right ahead and check here. 3997 if (getLangOpts().CPlusPlus && 3998 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3999 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4000 Old->getCanonicalDecl()->isConstexpr()) { 4001 // This definition won't be a definition any more once it's been merged. 4002 Diag(New->getLocation(), 4003 diag::warn_deprecated_redundant_constexpr_static_def); 4004 } else if (VarDecl *Def = Old->getDefinition()) { 4005 if (checkVarDeclRedefinition(Def, New)) 4006 return; 4007 } 4008 } 4009 4010 if (haveIncompatibleLanguageLinkages(Old, New)) { 4011 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4012 Diag(OldLocation, PrevDiag); 4013 New->setInvalidDecl(); 4014 return; 4015 } 4016 4017 // Merge "used" flag. 4018 if (Old->getMostRecentDecl()->isUsed(false)) 4019 New->setIsUsed(); 4020 4021 // Keep a chain of previous declarations. 4022 New->setPreviousDecl(Old); 4023 if (NewTemplate) 4024 NewTemplate->setPreviousDecl(OldTemplate); 4025 adjustDeclContextForDeclaratorDecl(New, Old); 4026 4027 // Inherit access appropriately. 4028 New->setAccess(Old->getAccess()); 4029 if (NewTemplate) 4030 NewTemplate->setAccess(New->getAccess()); 4031 4032 if (Old->isInline()) 4033 New->setImplicitlyInline(); 4034 } 4035 4036 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4037 SourceManager &SrcMgr = getSourceManager(); 4038 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4039 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4040 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4041 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4042 auto &HSI = PP.getHeaderSearchInfo(); 4043 StringRef HdrFilename = 4044 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4045 4046 auto noteFromModuleOrInclude = [&](Module *Mod, 4047 SourceLocation IncLoc) -> bool { 4048 // Redefinition errors with modules are common with non modular mapped 4049 // headers, example: a non-modular header H in module A that also gets 4050 // included directly in a TU. Pointing twice to the same header/definition 4051 // is confusing, try to get better diagnostics when modules is on. 4052 if (IncLoc.isValid()) { 4053 if (Mod) { 4054 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4055 << HdrFilename.str() << Mod->getFullModuleName(); 4056 if (!Mod->DefinitionLoc.isInvalid()) 4057 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4058 << Mod->getFullModuleName(); 4059 } else { 4060 Diag(IncLoc, diag::note_redefinition_include_same_file) 4061 << HdrFilename.str(); 4062 } 4063 return true; 4064 } 4065 4066 return false; 4067 }; 4068 4069 // Is it the same file and same offset? Provide more information on why 4070 // this leads to a redefinition error. 4071 bool EmittedDiag = false; 4072 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4073 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4074 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4075 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4076 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4077 4078 // If the header has no guards, emit a note suggesting one. 4079 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4080 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4081 4082 if (EmittedDiag) 4083 return; 4084 } 4085 4086 // Redefinition coming from different files or couldn't do better above. 4087 if (Old->getLocation().isValid()) 4088 Diag(Old->getLocation(), diag::note_previous_definition); 4089 } 4090 4091 /// We've just determined that \p Old and \p New both appear to be definitions 4092 /// of the same variable. Either diagnose or fix the problem. 4093 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4094 if (!hasVisibleDefinition(Old) && 4095 (New->getFormalLinkage() == InternalLinkage || 4096 New->isInline() || 4097 New->getDescribedVarTemplate() || 4098 New->getNumTemplateParameterLists() || 4099 New->getDeclContext()->isDependentContext())) { 4100 // The previous definition is hidden, and multiple definitions are 4101 // permitted (in separate TUs). Demote this to a declaration. 4102 New->demoteThisDefinitionToDeclaration(); 4103 4104 // Make the canonical definition visible. 4105 if (auto *OldTD = Old->getDescribedVarTemplate()) 4106 makeMergedDefinitionVisible(OldTD); 4107 makeMergedDefinitionVisible(Old); 4108 return false; 4109 } else { 4110 Diag(New->getLocation(), diag::err_redefinition) << New; 4111 notePreviousDefinition(Old, New->getLocation()); 4112 New->setInvalidDecl(); 4113 return true; 4114 } 4115 } 4116 4117 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4118 /// no declarator (e.g. "struct foo;") is parsed. 4119 Decl * 4120 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4121 RecordDecl *&AnonRecord) { 4122 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4123 AnonRecord); 4124 } 4125 4126 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4127 // disambiguate entities defined in different scopes. 4128 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4129 // compatibility. 4130 // We will pick our mangling number depending on which version of MSVC is being 4131 // targeted. 4132 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4133 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4134 ? S->getMSCurManglingNumber() 4135 : S->getMSLastManglingNumber(); 4136 } 4137 4138 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4139 if (!Context.getLangOpts().CPlusPlus) 4140 return; 4141 4142 if (isa<CXXRecordDecl>(Tag->getParent())) { 4143 // If this tag is the direct child of a class, number it if 4144 // it is anonymous. 4145 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4146 return; 4147 MangleNumberingContext &MCtx = 4148 Context.getManglingNumberContext(Tag->getParent()); 4149 Context.setManglingNumber( 4150 Tag, MCtx.getManglingNumber( 4151 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4152 return; 4153 } 4154 4155 // If this tag isn't a direct child of a class, number it if it is local. 4156 Decl *ManglingContextDecl; 4157 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4158 Tag->getDeclContext(), ManglingContextDecl)) { 4159 Context.setManglingNumber( 4160 Tag, MCtx->getManglingNumber( 4161 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4162 } 4163 } 4164 4165 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4166 TypedefNameDecl *NewTD) { 4167 if (TagFromDeclSpec->isInvalidDecl()) 4168 return; 4169 4170 // Do nothing if the tag already has a name for linkage purposes. 4171 if (TagFromDeclSpec->hasNameForLinkage()) 4172 return; 4173 4174 // A well-formed anonymous tag must always be a TUK_Definition. 4175 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4176 4177 // The type must match the tag exactly; no qualifiers allowed. 4178 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4179 Context.getTagDeclType(TagFromDeclSpec))) { 4180 if (getLangOpts().CPlusPlus) 4181 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4182 return; 4183 } 4184 4185 // If we've already computed linkage for the anonymous tag, then 4186 // adding a typedef name for the anonymous decl can change that 4187 // linkage, which might be a serious problem. Diagnose this as 4188 // unsupported and ignore the typedef name. TODO: we should 4189 // pursue this as a language defect and establish a formal rule 4190 // for how to handle it. 4191 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4192 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4193 4194 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4195 tagLoc = getLocForEndOfToken(tagLoc); 4196 4197 llvm::SmallString<40> textToInsert; 4198 textToInsert += ' '; 4199 textToInsert += NewTD->getIdentifier()->getName(); 4200 Diag(tagLoc, diag::note_typedef_changes_linkage) 4201 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4202 return; 4203 } 4204 4205 // Otherwise, set this is the anon-decl typedef for the tag. 4206 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4207 } 4208 4209 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4210 switch (T) { 4211 case DeclSpec::TST_class: 4212 return 0; 4213 case DeclSpec::TST_struct: 4214 return 1; 4215 case DeclSpec::TST_interface: 4216 return 2; 4217 case DeclSpec::TST_union: 4218 return 3; 4219 case DeclSpec::TST_enum: 4220 return 4; 4221 default: 4222 llvm_unreachable("unexpected type specifier"); 4223 } 4224 } 4225 4226 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4227 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4228 /// parameters to cope with template friend declarations. 4229 Decl * 4230 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4231 MultiTemplateParamsArg TemplateParams, 4232 bool IsExplicitInstantiation, 4233 RecordDecl *&AnonRecord) { 4234 Decl *TagD = nullptr; 4235 TagDecl *Tag = nullptr; 4236 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4237 DS.getTypeSpecType() == DeclSpec::TST_struct || 4238 DS.getTypeSpecType() == DeclSpec::TST_interface || 4239 DS.getTypeSpecType() == DeclSpec::TST_union || 4240 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4241 TagD = DS.getRepAsDecl(); 4242 4243 if (!TagD) // We probably had an error 4244 return nullptr; 4245 4246 // Note that the above type specs guarantee that the 4247 // type rep is a Decl, whereas in many of the others 4248 // it's a Type. 4249 if (isa<TagDecl>(TagD)) 4250 Tag = cast<TagDecl>(TagD); 4251 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4252 Tag = CTD->getTemplatedDecl(); 4253 } 4254 4255 if (Tag) { 4256 handleTagNumbering(Tag, S); 4257 Tag->setFreeStanding(); 4258 if (Tag->isInvalidDecl()) 4259 return Tag; 4260 } 4261 4262 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4263 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4264 // or incomplete types shall not be restrict-qualified." 4265 if (TypeQuals & DeclSpec::TQ_restrict) 4266 Diag(DS.getRestrictSpecLoc(), 4267 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4268 << DS.getSourceRange(); 4269 } 4270 4271 if (DS.isInlineSpecified()) 4272 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4273 << getLangOpts().CPlusPlus17; 4274 4275 if (DS.isConstexprSpecified()) { 4276 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4277 // and definitions of functions and variables. 4278 if (Tag) 4279 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4280 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4281 else 4282 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4283 // Don't emit warnings after this error. 4284 return TagD; 4285 } 4286 4287 DiagnoseFunctionSpecifiers(DS); 4288 4289 if (DS.isFriendSpecified()) { 4290 // If we're dealing with a decl but not a TagDecl, assume that 4291 // whatever routines created it handled the friendship aspect. 4292 if (TagD && !Tag) 4293 return nullptr; 4294 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4295 } 4296 4297 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4298 bool IsExplicitSpecialization = 4299 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4300 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4301 !IsExplicitInstantiation && !IsExplicitSpecialization && 4302 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4303 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4304 // nested-name-specifier unless it is an explicit instantiation 4305 // or an explicit specialization. 4306 // 4307 // FIXME: We allow class template partial specializations here too, per the 4308 // obvious intent of DR1819. 4309 // 4310 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4311 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4312 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4313 return nullptr; 4314 } 4315 4316 // Track whether this decl-specifier declares anything. 4317 bool DeclaresAnything = true; 4318 4319 // Handle anonymous struct definitions. 4320 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4321 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4322 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4323 if (getLangOpts().CPlusPlus || 4324 Record->getDeclContext()->isRecord()) { 4325 // If CurContext is a DeclContext that can contain statements, 4326 // RecursiveASTVisitor won't visit the decls that 4327 // BuildAnonymousStructOrUnion() will put into CurContext. 4328 // Also store them here so that they can be part of the 4329 // DeclStmt that gets created in this case. 4330 // FIXME: Also return the IndirectFieldDecls created by 4331 // BuildAnonymousStructOr union, for the same reason? 4332 if (CurContext->isFunctionOrMethod()) 4333 AnonRecord = Record; 4334 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4335 Context.getPrintingPolicy()); 4336 } 4337 4338 DeclaresAnything = false; 4339 } 4340 } 4341 4342 // C11 6.7.2.1p2: 4343 // A struct-declaration that does not declare an anonymous structure or 4344 // anonymous union shall contain a struct-declarator-list. 4345 // 4346 // This rule also existed in C89 and C99; the grammar for struct-declaration 4347 // did not permit a struct-declaration without a struct-declarator-list. 4348 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4349 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4350 // Check for Microsoft C extension: anonymous struct/union member. 4351 // Handle 2 kinds of anonymous struct/union: 4352 // struct STRUCT; 4353 // union UNION; 4354 // and 4355 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4356 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4357 if ((Tag && Tag->getDeclName()) || 4358 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4359 RecordDecl *Record = nullptr; 4360 if (Tag) 4361 Record = dyn_cast<RecordDecl>(Tag); 4362 else if (const RecordType *RT = 4363 DS.getRepAsType().get()->getAsStructureType()) 4364 Record = RT->getDecl(); 4365 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4366 Record = UT->getDecl(); 4367 4368 if (Record && getLangOpts().MicrosoftExt) { 4369 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4370 << Record->isUnion() << DS.getSourceRange(); 4371 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4372 } 4373 4374 DeclaresAnything = false; 4375 } 4376 } 4377 4378 // Skip all the checks below if we have a type error. 4379 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4380 (TagD && TagD->isInvalidDecl())) 4381 return TagD; 4382 4383 if (getLangOpts().CPlusPlus && 4384 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4385 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4386 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4387 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4388 DeclaresAnything = false; 4389 4390 if (!DS.isMissingDeclaratorOk()) { 4391 // Customize diagnostic for a typedef missing a name. 4392 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4393 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4394 << DS.getSourceRange(); 4395 else 4396 DeclaresAnything = false; 4397 } 4398 4399 if (DS.isModulePrivateSpecified() && 4400 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4401 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4402 << Tag->getTagKind() 4403 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4404 4405 ActOnDocumentableDecl(TagD); 4406 4407 // C 6.7/2: 4408 // A declaration [...] shall declare at least a declarator [...], a tag, 4409 // or the members of an enumeration. 4410 // C++ [dcl.dcl]p3: 4411 // [If there are no declarators], and except for the declaration of an 4412 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4413 // names into the program, or shall redeclare a name introduced by a 4414 // previous declaration. 4415 if (!DeclaresAnything) { 4416 // In C, we allow this as a (popular) extension / bug. Don't bother 4417 // producing further diagnostics for redundant qualifiers after this. 4418 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4419 return TagD; 4420 } 4421 4422 // C++ [dcl.stc]p1: 4423 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4424 // init-declarator-list of the declaration shall not be empty. 4425 // C++ [dcl.fct.spec]p1: 4426 // If a cv-qualifier appears in a decl-specifier-seq, the 4427 // init-declarator-list of the declaration shall not be empty. 4428 // 4429 // Spurious qualifiers here appear to be valid in C. 4430 unsigned DiagID = diag::warn_standalone_specifier; 4431 if (getLangOpts().CPlusPlus) 4432 DiagID = diag::ext_standalone_specifier; 4433 4434 // Note that a linkage-specification sets a storage class, but 4435 // 'extern "C" struct foo;' is actually valid and not theoretically 4436 // useless. 4437 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4438 if (SCS == DeclSpec::SCS_mutable) 4439 // Since mutable is not a viable storage class specifier in C, there is 4440 // no reason to treat it as an extension. Instead, diagnose as an error. 4441 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4442 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4443 Diag(DS.getStorageClassSpecLoc(), DiagID) 4444 << DeclSpec::getSpecifierName(SCS); 4445 } 4446 4447 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4448 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4449 << DeclSpec::getSpecifierName(TSCS); 4450 if (DS.getTypeQualifiers()) { 4451 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4452 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4453 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4454 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4455 // Restrict is covered above. 4456 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4457 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4458 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4459 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4460 } 4461 4462 // Warn about ignored type attributes, for example: 4463 // __attribute__((aligned)) struct A; 4464 // Attributes should be placed after tag to apply to type declaration. 4465 if (!DS.getAttributes().empty()) { 4466 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4467 if (TypeSpecType == DeclSpec::TST_class || 4468 TypeSpecType == DeclSpec::TST_struct || 4469 TypeSpecType == DeclSpec::TST_interface || 4470 TypeSpecType == DeclSpec::TST_union || 4471 TypeSpecType == DeclSpec::TST_enum) { 4472 for (const ParsedAttr &AL : DS.getAttributes()) 4473 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4474 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4475 } 4476 } 4477 4478 return TagD; 4479 } 4480 4481 /// We are trying to inject an anonymous member into the given scope; 4482 /// check if there's an existing declaration that can't be overloaded. 4483 /// 4484 /// \return true if this is a forbidden redeclaration 4485 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4486 Scope *S, 4487 DeclContext *Owner, 4488 DeclarationName Name, 4489 SourceLocation NameLoc, 4490 bool IsUnion) { 4491 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4492 Sema::ForVisibleRedeclaration); 4493 if (!SemaRef.LookupName(R, S)) return false; 4494 4495 // Pick a representative declaration. 4496 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4497 assert(PrevDecl && "Expected a non-null Decl"); 4498 4499 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4500 return false; 4501 4502 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4503 << IsUnion << Name; 4504 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4505 4506 return true; 4507 } 4508 4509 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4510 /// anonymous struct or union AnonRecord into the owning context Owner 4511 /// and scope S. This routine will be invoked just after we realize 4512 /// that an unnamed union or struct is actually an anonymous union or 4513 /// struct, e.g., 4514 /// 4515 /// @code 4516 /// union { 4517 /// int i; 4518 /// float f; 4519 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4520 /// // f into the surrounding scope.x 4521 /// @endcode 4522 /// 4523 /// This routine is recursive, injecting the names of nested anonymous 4524 /// structs/unions into the owning context and scope as well. 4525 static bool 4526 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4527 RecordDecl *AnonRecord, AccessSpecifier AS, 4528 SmallVectorImpl<NamedDecl *> &Chaining) { 4529 bool Invalid = false; 4530 4531 // Look every FieldDecl and IndirectFieldDecl with a name. 4532 for (auto *D : AnonRecord->decls()) { 4533 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4534 cast<NamedDecl>(D)->getDeclName()) { 4535 ValueDecl *VD = cast<ValueDecl>(D); 4536 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4537 VD->getLocation(), 4538 AnonRecord->isUnion())) { 4539 // C++ [class.union]p2: 4540 // The names of the members of an anonymous union shall be 4541 // distinct from the names of any other entity in the 4542 // scope in which the anonymous union is declared. 4543 Invalid = true; 4544 } else { 4545 // C++ [class.union]p2: 4546 // For the purpose of name lookup, after the anonymous union 4547 // definition, the members of the anonymous union are 4548 // considered to have been defined in the scope in which the 4549 // anonymous union is declared. 4550 unsigned OldChainingSize = Chaining.size(); 4551 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4552 Chaining.append(IF->chain_begin(), IF->chain_end()); 4553 else 4554 Chaining.push_back(VD); 4555 4556 assert(Chaining.size() >= 2); 4557 NamedDecl **NamedChain = 4558 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4559 for (unsigned i = 0; i < Chaining.size(); i++) 4560 NamedChain[i] = Chaining[i]; 4561 4562 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4563 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4564 VD->getType(), {NamedChain, Chaining.size()}); 4565 4566 for (const auto *Attr : VD->attrs()) 4567 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4568 4569 IndirectField->setAccess(AS); 4570 IndirectField->setImplicit(); 4571 SemaRef.PushOnScopeChains(IndirectField, S); 4572 4573 // That includes picking up the appropriate access specifier. 4574 if (AS != AS_none) IndirectField->setAccess(AS); 4575 4576 Chaining.resize(OldChainingSize); 4577 } 4578 } 4579 } 4580 4581 return Invalid; 4582 } 4583 4584 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4585 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4586 /// illegal input values are mapped to SC_None. 4587 static StorageClass 4588 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4589 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4590 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4591 "Parser allowed 'typedef' as storage class VarDecl."); 4592 switch (StorageClassSpec) { 4593 case DeclSpec::SCS_unspecified: return SC_None; 4594 case DeclSpec::SCS_extern: 4595 if (DS.isExternInLinkageSpec()) 4596 return SC_None; 4597 return SC_Extern; 4598 case DeclSpec::SCS_static: return SC_Static; 4599 case DeclSpec::SCS_auto: return SC_Auto; 4600 case DeclSpec::SCS_register: return SC_Register; 4601 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4602 // Illegal SCSs map to None: error reporting is up to the caller. 4603 case DeclSpec::SCS_mutable: // Fall through. 4604 case DeclSpec::SCS_typedef: return SC_None; 4605 } 4606 llvm_unreachable("unknown storage class specifier"); 4607 } 4608 4609 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4610 assert(Record->hasInClassInitializer()); 4611 4612 for (const auto *I : Record->decls()) { 4613 const auto *FD = dyn_cast<FieldDecl>(I); 4614 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4615 FD = IFD->getAnonField(); 4616 if (FD && FD->hasInClassInitializer()) 4617 return FD->getLocation(); 4618 } 4619 4620 llvm_unreachable("couldn't find in-class initializer"); 4621 } 4622 4623 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4624 SourceLocation DefaultInitLoc) { 4625 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4626 return; 4627 4628 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4629 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4630 } 4631 4632 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4633 CXXRecordDecl *AnonUnion) { 4634 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4635 return; 4636 4637 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4638 } 4639 4640 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4641 /// anonymous structure or union. Anonymous unions are a C++ feature 4642 /// (C++ [class.union]) and a C11 feature; anonymous structures 4643 /// are a C11 feature and GNU C++ extension. 4644 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4645 AccessSpecifier AS, 4646 RecordDecl *Record, 4647 const PrintingPolicy &Policy) { 4648 DeclContext *Owner = Record->getDeclContext(); 4649 4650 // Diagnose whether this anonymous struct/union is an extension. 4651 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4652 Diag(Record->getLocation(), diag::ext_anonymous_union); 4653 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4654 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4655 else if (!Record->isUnion() && !getLangOpts().C11) 4656 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4657 4658 // C and C++ require different kinds of checks for anonymous 4659 // structs/unions. 4660 bool Invalid = false; 4661 if (getLangOpts().CPlusPlus) { 4662 const char *PrevSpec = nullptr; 4663 unsigned DiagID; 4664 if (Record->isUnion()) { 4665 // C++ [class.union]p6: 4666 // C++17 [class.union.anon]p2: 4667 // Anonymous unions declared in a named namespace or in the 4668 // global namespace shall be declared static. 4669 DeclContext *OwnerScope = Owner->getRedeclContext(); 4670 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4671 (OwnerScope->isTranslationUnit() || 4672 (OwnerScope->isNamespace() && 4673 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4674 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4675 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4676 4677 // Recover by adding 'static'. 4678 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4679 PrevSpec, DiagID, Policy); 4680 } 4681 // C++ [class.union]p6: 4682 // A storage class is not allowed in a declaration of an 4683 // anonymous union in a class scope. 4684 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4685 isa<RecordDecl>(Owner)) { 4686 Diag(DS.getStorageClassSpecLoc(), 4687 diag::err_anonymous_union_with_storage_spec) 4688 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4689 4690 // Recover by removing the storage specifier. 4691 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4692 SourceLocation(), 4693 PrevSpec, DiagID, Context.getPrintingPolicy()); 4694 } 4695 } 4696 4697 // Ignore const/volatile/restrict qualifiers. 4698 if (DS.getTypeQualifiers()) { 4699 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4700 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4701 << Record->isUnion() << "const" 4702 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4703 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4704 Diag(DS.getVolatileSpecLoc(), 4705 diag::ext_anonymous_struct_union_qualified) 4706 << Record->isUnion() << "volatile" 4707 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4708 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4709 Diag(DS.getRestrictSpecLoc(), 4710 diag::ext_anonymous_struct_union_qualified) 4711 << Record->isUnion() << "restrict" 4712 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4713 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4714 Diag(DS.getAtomicSpecLoc(), 4715 diag::ext_anonymous_struct_union_qualified) 4716 << Record->isUnion() << "_Atomic" 4717 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4718 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4719 Diag(DS.getUnalignedSpecLoc(), 4720 diag::ext_anonymous_struct_union_qualified) 4721 << Record->isUnion() << "__unaligned" 4722 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4723 4724 DS.ClearTypeQualifiers(); 4725 } 4726 4727 // C++ [class.union]p2: 4728 // The member-specification of an anonymous union shall only 4729 // define non-static data members. [Note: nested types and 4730 // functions cannot be declared within an anonymous union. ] 4731 for (auto *Mem : Record->decls()) { 4732 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4733 // C++ [class.union]p3: 4734 // An anonymous union shall not have private or protected 4735 // members (clause 11). 4736 assert(FD->getAccess() != AS_none); 4737 if (FD->getAccess() != AS_public) { 4738 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4739 << Record->isUnion() << (FD->getAccess() == AS_protected); 4740 Invalid = true; 4741 } 4742 4743 // C++ [class.union]p1 4744 // An object of a class with a non-trivial constructor, a non-trivial 4745 // copy constructor, a non-trivial destructor, or a non-trivial copy 4746 // assignment operator cannot be a member of a union, nor can an 4747 // array of such objects. 4748 if (CheckNontrivialField(FD)) 4749 Invalid = true; 4750 } else if (Mem->isImplicit()) { 4751 // Any implicit members are fine. 4752 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4753 // This is a type that showed up in an 4754 // elaborated-type-specifier inside the anonymous struct or 4755 // union, but which actually declares a type outside of the 4756 // anonymous struct or union. It's okay. 4757 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4758 if (!MemRecord->isAnonymousStructOrUnion() && 4759 MemRecord->getDeclName()) { 4760 // Visual C++ allows type definition in anonymous struct or union. 4761 if (getLangOpts().MicrosoftExt) 4762 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4763 << Record->isUnion(); 4764 else { 4765 // This is a nested type declaration. 4766 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4767 << Record->isUnion(); 4768 Invalid = true; 4769 } 4770 } else { 4771 // This is an anonymous type definition within another anonymous type. 4772 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4773 // not part of standard C++. 4774 Diag(MemRecord->getLocation(), 4775 diag::ext_anonymous_record_with_anonymous_type) 4776 << Record->isUnion(); 4777 } 4778 } else if (isa<AccessSpecDecl>(Mem)) { 4779 // Any access specifier is fine. 4780 } else if (isa<StaticAssertDecl>(Mem)) { 4781 // In C++1z, static_assert declarations are also fine. 4782 } else { 4783 // We have something that isn't a non-static data 4784 // member. Complain about it. 4785 unsigned DK = diag::err_anonymous_record_bad_member; 4786 if (isa<TypeDecl>(Mem)) 4787 DK = diag::err_anonymous_record_with_type; 4788 else if (isa<FunctionDecl>(Mem)) 4789 DK = diag::err_anonymous_record_with_function; 4790 else if (isa<VarDecl>(Mem)) 4791 DK = diag::err_anonymous_record_with_static; 4792 4793 // Visual C++ allows type definition in anonymous struct or union. 4794 if (getLangOpts().MicrosoftExt && 4795 DK == diag::err_anonymous_record_with_type) 4796 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4797 << Record->isUnion(); 4798 else { 4799 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4800 Invalid = true; 4801 } 4802 } 4803 } 4804 4805 // C++11 [class.union]p8 (DR1460): 4806 // At most one variant member of a union may have a 4807 // brace-or-equal-initializer. 4808 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4809 Owner->isRecord()) 4810 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4811 cast<CXXRecordDecl>(Record)); 4812 } 4813 4814 if (!Record->isUnion() && !Owner->isRecord()) { 4815 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4816 << getLangOpts().CPlusPlus; 4817 Invalid = true; 4818 } 4819 4820 // C++ [dcl.dcl]p3: 4821 // [If there are no declarators], and except for the declaration of an 4822 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4823 // names into the program 4824 // C++ [class.mem]p2: 4825 // each such member-declaration shall either declare at least one member 4826 // name of the class or declare at least one unnamed bit-field 4827 // 4828 // For C this is an error even for a named struct, and is diagnosed elsewhere. 4829 if (getLangOpts().CPlusPlus && Record->field_empty()) 4830 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4831 4832 // Mock up a declarator. 4833 Declarator Dc(DS, DeclaratorContext::MemberContext); 4834 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4835 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4836 4837 // Create a declaration for this anonymous struct/union. 4838 NamedDecl *Anon = nullptr; 4839 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4840 Anon = FieldDecl::Create( 4841 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 4842 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 4843 /*BitWidth=*/nullptr, /*Mutable=*/false, 4844 /*InitStyle=*/ICIS_NoInit); 4845 Anon->setAccess(AS); 4846 if (getLangOpts().CPlusPlus) 4847 FieldCollector->Add(cast<FieldDecl>(Anon)); 4848 } else { 4849 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4850 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4851 if (SCSpec == DeclSpec::SCS_mutable) { 4852 // mutable can only appear on non-static class members, so it's always 4853 // an error here 4854 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4855 Invalid = true; 4856 SC = SC_None; 4857 } 4858 4859 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 4860 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4861 Context.getTypeDeclType(Record), TInfo, SC); 4862 4863 // Default-initialize the implicit variable. This initialization will be 4864 // trivial in almost all cases, except if a union member has an in-class 4865 // initializer: 4866 // union { int n = 0; }; 4867 ActOnUninitializedDecl(Anon); 4868 } 4869 Anon->setImplicit(); 4870 4871 // Mark this as an anonymous struct/union type. 4872 Record->setAnonymousStructOrUnion(true); 4873 4874 // Add the anonymous struct/union object to the current 4875 // context. We'll be referencing this object when we refer to one of 4876 // its members. 4877 Owner->addDecl(Anon); 4878 4879 // Inject the members of the anonymous struct/union into the owning 4880 // context and into the identifier resolver chain for name lookup 4881 // purposes. 4882 SmallVector<NamedDecl*, 2> Chain; 4883 Chain.push_back(Anon); 4884 4885 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4886 Invalid = true; 4887 4888 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4889 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4890 Decl *ManglingContextDecl; 4891 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4892 NewVD->getDeclContext(), ManglingContextDecl)) { 4893 Context.setManglingNumber( 4894 NewVD, MCtx->getManglingNumber( 4895 NewVD, getMSManglingNumber(getLangOpts(), S))); 4896 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4897 } 4898 } 4899 } 4900 4901 if (Invalid) 4902 Anon->setInvalidDecl(); 4903 4904 return Anon; 4905 } 4906 4907 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4908 /// Microsoft C anonymous structure. 4909 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4910 /// Example: 4911 /// 4912 /// struct A { int a; }; 4913 /// struct B { struct A; int b; }; 4914 /// 4915 /// void foo() { 4916 /// B var; 4917 /// var.a = 3; 4918 /// } 4919 /// 4920 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4921 RecordDecl *Record) { 4922 assert(Record && "expected a record!"); 4923 4924 // Mock up a declarator. 4925 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4926 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4927 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4928 4929 auto *ParentDecl = cast<RecordDecl>(CurContext); 4930 QualType RecTy = Context.getTypeDeclType(Record); 4931 4932 // Create a declaration for this anonymous struct. 4933 NamedDecl *Anon = 4934 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 4935 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 4936 /*BitWidth=*/nullptr, /*Mutable=*/false, 4937 /*InitStyle=*/ICIS_NoInit); 4938 Anon->setImplicit(); 4939 4940 // Add the anonymous struct object to the current context. 4941 CurContext->addDecl(Anon); 4942 4943 // Inject the members of the anonymous struct into the current 4944 // context and into the identifier resolver chain for name lookup 4945 // purposes. 4946 SmallVector<NamedDecl*, 2> Chain; 4947 Chain.push_back(Anon); 4948 4949 RecordDecl *RecordDef = Record->getDefinition(); 4950 if (RequireCompleteType(Anon->getLocation(), RecTy, 4951 diag::err_field_incomplete) || 4952 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4953 AS_none, Chain)) { 4954 Anon->setInvalidDecl(); 4955 ParentDecl->setInvalidDecl(); 4956 } 4957 4958 return Anon; 4959 } 4960 4961 /// GetNameForDeclarator - Determine the full declaration name for the 4962 /// given Declarator. 4963 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4964 return GetNameFromUnqualifiedId(D.getName()); 4965 } 4966 4967 /// Retrieves the declaration name from a parsed unqualified-id. 4968 DeclarationNameInfo 4969 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4970 DeclarationNameInfo NameInfo; 4971 NameInfo.setLoc(Name.StartLocation); 4972 4973 switch (Name.getKind()) { 4974 4975 case UnqualifiedIdKind::IK_ImplicitSelfParam: 4976 case UnqualifiedIdKind::IK_Identifier: 4977 NameInfo.setName(Name.Identifier); 4978 return NameInfo; 4979 4980 case UnqualifiedIdKind::IK_DeductionGuideName: { 4981 // C++ [temp.deduct.guide]p3: 4982 // The simple-template-id shall name a class template specialization. 4983 // The template-name shall be the same identifier as the template-name 4984 // of the simple-template-id. 4985 // These together intend to imply that the template-name shall name a 4986 // class template. 4987 // FIXME: template<typename T> struct X {}; 4988 // template<typename T> using Y = X<T>; 4989 // Y(int) -> Y<int>; 4990 // satisfies these rules but does not name a class template. 4991 TemplateName TN = Name.TemplateName.get().get(); 4992 auto *Template = TN.getAsTemplateDecl(); 4993 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4994 Diag(Name.StartLocation, 4995 diag::err_deduction_guide_name_not_class_template) 4996 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4997 if (Template) 4998 Diag(Template->getLocation(), diag::note_template_decl_here); 4999 return DeclarationNameInfo(); 5000 } 5001 5002 NameInfo.setName( 5003 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5004 return NameInfo; 5005 } 5006 5007 case UnqualifiedIdKind::IK_OperatorFunctionId: 5008 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5009 Name.OperatorFunctionId.Operator)); 5010 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5011 = Name.OperatorFunctionId.SymbolLocations[0]; 5012 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5013 = Name.EndLocation.getRawEncoding(); 5014 return NameInfo; 5015 5016 case UnqualifiedIdKind::IK_LiteralOperatorId: 5017 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5018 Name.Identifier)); 5019 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5020 return NameInfo; 5021 5022 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5023 TypeSourceInfo *TInfo; 5024 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5025 if (Ty.isNull()) 5026 return DeclarationNameInfo(); 5027 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5028 Context.getCanonicalType(Ty))); 5029 NameInfo.setNamedTypeInfo(TInfo); 5030 return NameInfo; 5031 } 5032 5033 case UnqualifiedIdKind::IK_ConstructorName: { 5034 TypeSourceInfo *TInfo; 5035 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5036 if (Ty.isNull()) 5037 return DeclarationNameInfo(); 5038 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5039 Context.getCanonicalType(Ty))); 5040 NameInfo.setNamedTypeInfo(TInfo); 5041 return NameInfo; 5042 } 5043 5044 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5045 // In well-formed code, we can only have a constructor 5046 // template-id that refers to the current context, so go there 5047 // to find the actual type being constructed. 5048 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5049 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5050 return DeclarationNameInfo(); 5051 5052 // Determine the type of the class being constructed. 5053 QualType CurClassType = Context.getTypeDeclType(CurClass); 5054 5055 // FIXME: Check two things: that the template-id names the same type as 5056 // CurClassType, and that the template-id does not occur when the name 5057 // was qualified. 5058 5059 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5060 Context.getCanonicalType(CurClassType))); 5061 // FIXME: should we retrieve TypeSourceInfo? 5062 NameInfo.setNamedTypeInfo(nullptr); 5063 return NameInfo; 5064 } 5065 5066 case UnqualifiedIdKind::IK_DestructorName: { 5067 TypeSourceInfo *TInfo; 5068 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5069 if (Ty.isNull()) 5070 return DeclarationNameInfo(); 5071 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5072 Context.getCanonicalType(Ty))); 5073 NameInfo.setNamedTypeInfo(TInfo); 5074 return NameInfo; 5075 } 5076 5077 case UnqualifiedIdKind::IK_TemplateId: { 5078 TemplateName TName = Name.TemplateId->Template.get(); 5079 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5080 return Context.getNameForTemplate(TName, TNameLoc); 5081 } 5082 5083 } // switch (Name.getKind()) 5084 5085 llvm_unreachable("Unknown name kind"); 5086 } 5087 5088 static QualType getCoreType(QualType Ty) { 5089 do { 5090 if (Ty->isPointerType() || Ty->isReferenceType()) 5091 Ty = Ty->getPointeeType(); 5092 else if (Ty->isArrayType()) 5093 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5094 else 5095 return Ty.withoutLocalFastQualifiers(); 5096 } while (true); 5097 } 5098 5099 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5100 /// and Definition have "nearly" matching parameters. This heuristic is 5101 /// used to improve diagnostics in the case where an out-of-line function 5102 /// definition doesn't match any declaration within the class or namespace. 5103 /// Also sets Params to the list of indices to the parameters that differ 5104 /// between the declaration and the definition. If hasSimilarParameters 5105 /// returns true and Params is empty, then all of the parameters match. 5106 static bool hasSimilarParameters(ASTContext &Context, 5107 FunctionDecl *Declaration, 5108 FunctionDecl *Definition, 5109 SmallVectorImpl<unsigned> &Params) { 5110 Params.clear(); 5111 if (Declaration->param_size() != Definition->param_size()) 5112 return false; 5113 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5114 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5115 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5116 5117 // The parameter types are identical 5118 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5119 continue; 5120 5121 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5122 QualType DefParamBaseTy = getCoreType(DefParamTy); 5123 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5124 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5125 5126 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5127 (DeclTyName && DeclTyName == DefTyName)) 5128 Params.push_back(Idx); 5129 else // The two parameters aren't even close 5130 return false; 5131 } 5132 5133 return true; 5134 } 5135 5136 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5137 /// declarator needs to be rebuilt in the current instantiation. 5138 /// Any bits of declarator which appear before the name are valid for 5139 /// consideration here. That's specifically the type in the decl spec 5140 /// and the base type in any member-pointer chunks. 5141 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5142 DeclarationName Name) { 5143 // The types we specifically need to rebuild are: 5144 // - typenames, typeofs, and decltypes 5145 // - types which will become injected class names 5146 // Of course, we also need to rebuild any type referencing such a 5147 // type. It's safest to just say "dependent", but we call out a 5148 // few cases here. 5149 5150 DeclSpec &DS = D.getMutableDeclSpec(); 5151 switch (DS.getTypeSpecType()) { 5152 case DeclSpec::TST_typename: 5153 case DeclSpec::TST_typeofType: 5154 case DeclSpec::TST_underlyingType: 5155 case DeclSpec::TST_atomic: { 5156 // Grab the type from the parser. 5157 TypeSourceInfo *TSI = nullptr; 5158 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5159 if (T.isNull() || !T->isDependentType()) break; 5160 5161 // Make sure there's a type source info. This isn't really much 5162 // of a waste; most dependent types should have type source info 5163 // attached already. 5164 if (!TSI) 5165 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5166 5167 // Rebuild the type in the current instantiation. 5168 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5169 if (!TSI) return true; 5170 5171 // Store the new type back in the decl spec. 5172 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5173 DS.UpdateTypeRep(LocType); 5174 break; 5175 } 5176 5177 case DeclSpec::TST_decltype: 5178 case DeclSpec::TST_typeofExpr: { 5179 Expr *E = DS.getRepAsExpr(); 5180 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5181 if (Result.isInvalid()) return true; 5182 DS.UpdateExprRep(Result.get()); 5183 break; 5184 } 5185 5186 default: 5187 // Nothing to do for these decl specs. 5188 break; 5189 } 5190 5191 // It doesn't matter what order we do this in. 5192 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5193 DeclaratorChunk &Chunk = D.getTypeObject(I); 5194 5195 // The only type information in the declarator which can come 5196 // before the declaration name is the base type of a member 5197 // pointer. 5198 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5199 continue; 5200 5201 // Rebuild the scope specifier in-place. 5202 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5203 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5204 return true; 5205 } 5206 5207 return false; 5208 } 5209 5210 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5211 D.setFunctionDefinitionKind(FDK_Declaration); 5212 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5213 5214 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5215 Dcl && Dcl->getDeclContext()->isFileContext()) 5216 Dcl->setTopLevelDeclInObjCContainer(); 5217 5218 if (getLangOpts().OpenCL) 5219 setCurrentOpenCLExtensionForDecl(Dcl); 5220 5221 return Dcl; 5222 } 5223 5224 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5225 /// If T is the name of a class, then each of the following shall have a 5226 /// name different from T: 5227 /// - every static data member of class T; 5228 /// - every member function of class T 5229 /// - every member of class T that is itself a type; 5230 /// \returns true if the declaration name violates these rules. 5231 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5232 DeclarationNameInfo NameInfo) { 5233 DeclarationName Name = NameInfo.getName(); 5234 5235 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5236 while (Record && Record->isAnonymousStructOrUnion()) 5237 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5238 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5239 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5240 return true; 5241 } 5242 5243 return false; 5244 } 5245 5246 /// Diagnose a declaration whose declarator-id has the given 5247 /// nested-name-specifier. 5248 /// 5249 /// \param SS The nested-name-specifier of the declarator-id. 5250 /// 5251 /// \param DC The declaration context to which the nested-name-specifier 5252 /// resolves. 5253 /// 5254 /// \param Name The name of the entity being declared. 5255 /// 5256 /// \param Loc The location of the name of the entity being declared. 5257 /// 5258 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5259 /// we're declaring an explicit / partial specialization / instantiation. 5260 /// 5261 /// \returns true if we cannot safely recover from this error, false otherwise. 5262 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5263 DeclarationName Name, 5264 SourceLocation Loc, bool IsTemplateId) { 5265 DeclContext *Cur = CurContext; 5266 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5267 Cur = Cur->getParent(); 5268 5269 // If the user provided a superfluous scope specifier that refers back to the 5270 // class in which the entity is already declared, diagnose and ignore it. 5271 // 5272 // class X { 5273 // void X::f(); 5274 // }; 5275 // 5276 // Note, it was once ill-formed to give redundant qualification in all 5277 // contexts, but that rule was removed by DR482. 5278 if (Cur->Equals(DC)) { 5279 if (Cur->isRecord()) { 5280 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5281 : diag::err_member_extra_qualification) 5282 << Name << FixItHint::CreateRemoval(SS.getRange()); 5283 SS.clear(); 5284 } else { 5285 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5286 } 5287 return false; 5288 } 5289 5290 // Check whether the qualifying scope encloses the scope of the original 5291 // declaration. For a template-id, we perform the checks in 5292 // CheckTemplateSpecializationScope. 5293 if (!Cur->Encloses(DC) && !IsTemplateId) { 5294 if (Cur->isRecord()) 5295 Diag(Loc, diag::err_member_qualification) 5296 << Name << SS.getRange(); 5297 else if (isa<TranslationUnitDecl>(DC)) 5298 Diag(Loc, diag::err_invalid_declarator_global_scope) 5299 << Name << SS.getRange(); 5300 else if (isa<FunctionDecl>(Cur)) 5301 Diag(Loc, diag::err_invalid_declarator_in_function) 5302 << Name << SS.getRange(); 5303 else if (isa<BlockDecl>(Cur)) 5304 Diag(Loc, diag::err_invalid_declarator_in_block) 5305 << Name << SS.getRange(); 5306 else 5307 Diag(Loc, diag::err_invalid_declarator_scope) 5308 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5309 5310 return true; 5311 } 5312 5313 if (Cur->isRecord()) { 5314 // Cannot qualify members within a class. 5315 Diag(Loc, diag::err_member_qualification) 5316 << Name << SS.getRange(); 5317 SS.clear(); 5318 5319 // C++ constructors and destructors with incorrect scopes can break 5320 // our AST invariants by having the wrong underlying types. If 5321 // that's the case, then drop this declaration entirely. 5322 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5323 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5324 !Context.hasSameType(Name.getCXXNameType(), 5325 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5326 return true; 5327 5328 return false; 5329 } 5330 5331 // C++11 [dcl.meaning]p1: 5332 // [...] "The nested-name-specifier of the qualified declarator-id shall 5333 // not begin with a decltype-specifer" 5334 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5335 while (SpecLoc.getPrefix()) 5336 SpecLoc = SpecLoc.getPrefix(); 5337 if (dyn_cast_or_null<DecltypeType>( 5338 SpecLoc.getNestedNameSpecifier()->getAsType())) 5339 Diag(Loc, diag::err_decltype_in_declarator) 5340 << SpecLoc.getTypeLoc().getSourceRange(); 5341 5342 return false; 5343 } 5344 5345 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5346 MultiTemplateParamsArg TemplateParamLists) { 5347 // TODO: consider using NameInfo for diagnostic. 5348 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5349 DeclarationName Name = NameInfo.getName(); 5350 5351 // All of these full declarators require an identifier. If it doesn't have 5352 // one, the ParsedFreeStandingDeclSpec action should be used. 5353 if (D.isDecompositionDeclarator()) { 5354 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5355 } else if (!Name) { 5356 if (!D.isInvalidType()) // Reject this if we think it is valid. 5357 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5358 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5359 return nullptr; 5360 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5361 return nullptr; 5362 5363 // The scope passed in may not be a decl scope. Zip up the scope tree until 5364 // we find one that is. 5365 while ((S->getFlags() & Scope::DeclScope) == 0 || 5366 (S->getFlags() & Scope::TemplateParamScope) != 0) 5367 S = S->getParent(); 5368 5369 DeclContext *DC = CurContext; 5370 if (D.getCXXScopeSpec().isInvalid()) 5371 D.setInvalidType(); 5372 else if (D.getCXXScopeSpec().isSet()) { 5373 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5374 UPPC_DeclarationQualifier)) 5375 return nullptr; 5376 5377 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5378 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5379 if (!DC || isa<EnumDecl>(DC)) { 5380 // If we could not compute the declaration context, it's because the 5381 // declaration context is dependent but does not refer to a class, 5382 // class template, or class template partial specialization. Complain 5383 // and return early, to avoid the coming semantic disaster. 5384 Diag(D.getIdentifierLoc(), 5385 diag::err_template_qualified_declarator_no_match) 5386 << D.getCXXScopeSpec().getScopeRep() 5387 << D.getCXXScopeSpec().getRange(); 5388 return nullptr; 5389 } 5390 bool IsDependentContext = DC->isDependentContext(); 5391 5392 if (!IsDependentContext && 5393 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5394 return nullptr; 5395 5396 // If a class is incomplete, do not parse entities inside it. 5397 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5398 Diag(D.getIdentifierLoc(), 5399 diag::err_member_def_undefined_record) 5400 << Name << DC << D.getCXXScopeSpec().getRange(); 5401 return nullptr; 5402 } 5403 if (!D.getDeclSpec().isFriendSpecified()) { 5404 if (diagnoseQualifiedDeclaration( 5405 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5406 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5407 if (DC->isRecord()) 5408 return nullptr; 5409 5410 D.setInvalidType(); 5411 } 5412 } 5413 5414 // Check whether we need to rebuild the type of the given 5415 // declaration in the current instantiation. 5416 if (EnteringContext && IsDependentContext && 5417 TemplateParamLists.size() != 0) { 5418 ContextRAII SavedContext(*this, DC); 5419 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5420 D.setInvalidType(); 5421 } 5422 } 5423 5424 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5425 QualType R = TInfo->getType(); 5426 5427 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5428 UPPC_DeclarationType)) 5429 D.setInvalidType(); 5430 5431 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5432 forRedeclarationInCurContext()); 5433 5434 // See if this is a redefinition of a variable in the same scope. 5435 if (!D.getCXXScopeSpec().isSet()) { 5436 bool IsLinkageLookup = false; 5437 bool CreateBuiltins = false; 5438 5439 // If the declaration we're planning to build will be a function 5440 // or object with linkage, then look for another declaration with 5441 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5442 // 5443 // If the declaration we're planning to build will be declared with 5444 // external linkage in the translation unit, create any builtin with 5445 // the same name. 5446 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5447 /* Do nothing*/; 5448 else if (CurContext->isFunctionOrMethod() && 5449 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5450 R->isFunctionType())) { 5451 IsLinkageLookup = true; 5452 CreateBuiltins = 5453 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5454 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5455 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5456 CreateBuiltins = true; 5457 5458 if (IsLinkageLookup) { 5459 Previous.clear(LookupRedeclarationWithLinkage); 5460 Previous.setRedeclarationKind(ForExternalRedeclaration); 5461 } 5462 5463 LookupName(Previous, S, CreateBuiltins); 5464 } else { // Something like "int foo::x;" 5465 LookupQualifiedName(Previous, DC); 5466 5467 // C++ [dcl.meaning]p1: 5468 // When the declarator-id is qualified, the declaration shall refer to a 5469 // previously declared member of the class or namespace to which the 5470 // qualifier refers (or, in the case of a namespace, of an element of the 5471 // inline namespace set of that namespace (7.3.1)) or to a specialization 5472 // thereof; [...] 5473 // 5474 // Note that we already checked the context above, and that we do not have 5475 // enough information to make sure that Previous contains the declaration 5476 // we want to match. For example, given: 5477 // 5478 // class X { 5479 // void f(); 5480 // void f(float); 5481 // }; 5482 // 5483 // void X::f(int) { } // ill-formed 5484 // 5485 // In this case, Previous will point to the overload set 5486 // containing the two f's declared in X, but neither of them 5487 // matches. 5488 5489 // C++ [dcl.meaning]p1: 5490 // [...] the member shall not merely have been introduced by a 5491 // using-declaration in the scope of the class or namespace nominated by 5492 // the nested-name-specifier of the declarator-id. 5493 RemoveUsingDecls(Previous); 5494 } 5495 5496 if (Previous.isSingleResult() && 5497 Previous.getFoundDecl()->isTemplateParameter()) { 5498 // Maybe we will complain about the shadowed template parameter. 5499 if (!D.isInvalidType()) 5500 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5501 Previous.getFoundDecl()); 5502 5503 // Just pretend that we didn't see the previous declaration. 5504 Previous.clear(); 5505 } 5506 5507 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5508 // Forget that the previous declaration is the injected-class-name. 5509 Previous.clear(); 5510 5511 // In C++, the previous declaration we find might be a tag type 5512 // (class or enum). In this case, the new declaration will hide the 5513 // tag type. Note that this applies to functions, function templates, and 5514 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5515 if (Previous.isSingleTagDecl() && 5516 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5517 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5518 Previous.clear(); 5519 5520 // Check that there are no default arguments other than in the parameters 5521 // of a function declaration (C++ only). 5522 if (getLangOpts().CPlusPlus) 5523 CheckExtraCXXDefaultArguments(D); 5524 5525 NamedDecl *New; 5526 5527 bool AddToScope = true; 5528 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5529 if (TemplateParamLists.size()) { 5530 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5531 return nullptr; 5532 } 5533 5534 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5535 } else if (R->isFunctionType()) { 5536 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5537 TemplateParamLists, 5538 AddToScope); 5539 } else { 5540 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5541 AddToScope); 5542 } 5543 5544 if (!New) 5545 return nullptr; 5546 5547 // If this has an identifier and is not a function template specialization, 5548 // add it to the scope stack. 5549 if (New->getDeclName() && AddToScope) 5550 PushOnScopeChains(New, S); 5551 5552 if (isInOpenMPDeclareTargetContext()) 5553 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5554 5555 return New; 5556 } 5557 5558 /// Helper method to turn variable array types into constant array 5559 /// types in certain situations which would otherwise be errors (for 5560 /// GCC compatibility). 5561 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5562 ASTContext &Context, 5563 bool &SizeIsNegative, 5564 llvm::APSInt &Oversized) { 5565 // This method tries to turn a variable array into a constant 5566 // array even when the size isn't an ICE. This is necessary 5567 // for compatibility with code that depends on gcc's buggy 5568 // constant expression folding, like struct {char x[(int)(char*)2];} 5569 SizeIsNegative = false; 5570 Oversized = 0; 5571 5572 if (T->isDependentType()) 5573 return QualType(); 5574 5575 QualifierCollector Qs; 5576 const Type *Ty = Qs.strip(T); 5577 5578 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5579 QualType Pointee = PTy->getPointeeType(); 5580 QualType FixedType = 5581 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5582 Oversized); 5583 if (FixedType.isNull()) return FixedType; 5584 FixedType = Context.getPointerType(FixedType); 5585 return Qs.apply(Context, FixedType); 5586 } 5587 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5588 QualType Inner = PTy->getInnerType(); 5589 QualType FixedType = 5590 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5591 Oversized); 5592 if (FixedType.isNull()) return FixedType; 5593 FixedType = Context.getParenType(FixedType); 5594 return Qs.apply(Context, FixedType); 5595 } 5596 5597 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5598 if (!VLATy) 5599 return QualType(); 5600 // FIXME: We should probably handle this case 5601 if (VLATy->getElementType()->isVariablyModifiedType()) 5602 return QualType(); 5603 5604 Expr::EvalResult Result; 5605 if (!VLATy->getSizeExpr() || 5606 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5607 return QualType(); 5608 5609 llvm::APSInt Res = Result.Val.getInt(); 5610 5611 // Check whether the array size is negative. 5612 if (Res.isSigned() && Res.isNegative()) { 5613 SizeIsNegative = true; 5614 return QualType(); 5615 } 5616 5617 // Check whether the array is too large to be addressed. 5618 unsigned ActiveSizeBits 5619 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5620 Res); 5621 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5622 Oversized = Res; 5623 return QualType(); 5624 } 5625 5626 return Context.getConstantArrayType(VLATy->getElementType(), 5627 Res, ArrayType::Normal, 0); 5628 } 5629 5630 static void 5631 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5632 SrcTL = SrcTL.getUnqualifiedLoc(); 5633 DstTL = DstTL.getUnqualifiedLoc(); 5634 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5635 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5636 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5637 DstPTL.getPointeeLoc()); 5638 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5639 return; 5640 } 5641 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5642 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5643 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5644 DstPTL.getInnerLoc()); 5645 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5646 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5647 return; 5648 } 5649 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5650 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5651 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5652 TypeLoc DstElemTL = DstATL.getElementLoc(); 5653 DstElemTL.initializeFullCopy(SrcElemTL); 5654 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5655 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5656 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5657 } 5658 5659 /// Helper method to turn variable array types into constant array 5660 /// types in certain situations which would otherwise be errors (for 5661 /// GCC compatibility). 5662 static TypeSourceInfo* 5663 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5664 ASTContext &Context, 5665 bool &SizeIsNegative, 5666 llvm::APSInt &Oversized) { 5667 QualType FixedTy 5668 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5669 SizeIsNegative, Oversized); 5670 if (FixedTy.isNull()) 5671 return nullptr; 5672 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5673 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5674 FixedTInfo->getTypeLoc()); 5675 return FixedTInfo; 5676 } 5677 5678 /// Register the given locally-scoped extern "C" declaration so 5679 /// that it can be found later for redeclarations. We include any extern "C" 5680 /// declaration that is not visible in the translation unit here, not just 5681 /// function-scope declarations. 5682 void 5683 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5684 if (!getLangOpts().CPlusPlus && 5685 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5686 // Don't need to track declarations in the TU in C. 5687 return; 5688 5689 // Note that we have a locally-scoped external with this name. 5690 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5691 } 5692 5693 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5694 // FIXME: We can have multiple results via __attribute__((overloadable)). 5695 auto Result = Context.getExternCContextDecl()->lookup(Name); 5696 return Result.empty() ? nullptr : *Result.begin(); 5697 } 5698 5699 /// Diagnose function specifiers on a declaration of an identifier that 5700 /// does not identify a function. 5701 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5702 // FIXME: We should probably indicate the identifier in question to avoid 5703 // confusion for constructs like "virtual int a(), b;" 5704 if (DS.isVirtualSpecified()) 5705 Diag(DS.getVirtualSpecLoc(), 5706 diag::err_virtual_non_function); 5707 5708 if (DS.isExplicitSpecified()) 5709 Diag(DS.getExplicitSpecLoc(), 5710 diag::err_explicit_non_function); 5711 5712 if (DS.isNoreturnSpecified()) 5713 Diag(DS.getNoreturnSpecLoc(), 5714 diag::err_noreturn_non_function); 5715 } 5716 5717 NamedDecl* 5718 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5719 TypeSourceInfo *TInfo, LookupResult &Previous) { 5720 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5721 if (D.getCXXScopeSpec().isSet()) { 5722 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5723 << D.getCXXScopeSpec().getRange(); 5724 D.setInvalidType(); 5725 // Pretend we didn't see the scope specifier. 5726 DC = CurContext; 5727 Previous.clear(); 5728 } 5729 5730 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5731 5732 if (D.getDeclSpec().isInlineSpecified()) 5733 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5734 << getLangOpts().CPlusPlus17; 5735 if (D.getDeclSpec().isConstexprSpecified()) 5736 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5737 << 1; 5738 5739 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5740 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5741 Diag(D.getName().StartLocation, 5742 diag::err_deduction_guide_invalid_specifier) 5743 << "typedef"; 5744 else 5745 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5746 << D.getName().getSourceRange(); 5747 return nullptr; 5748 } 5749 5750 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5751 if (!NewTD) return nullptr; 5752 5753 // Handle attributes prior to checking for duplicates in MergeVarDecl 5754 ProcessDeclAttributes(S, NewTD, D); 5755 5756 CheckTypedefForVariablyModifiedType(S, NewTD); 5757 5758 bool Redeclaration = D.isRedeclaration(); 5759 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5760 D.setRedeclaration(Redeclaration); 5761 return ND; 5762 } 5763 5764 void 5765 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5766 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5767 // then it shall have block scope. 5768 // Note that variably modified types must be fixed before merging the decl so 5769 // that redeclarations will match. 5770 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5771 QualType T = TInfo->getType(); 5772 if (T->isVariablyModifiedType()) { 5773 setFunctionHasBranchProtectedScope(); 5774 5775 if (S->getFnParent() == nullptr) { 5776 bool SizeIsNegative; 5777 llvm::APSInt Oversized; 5778 TypeSourceInfo *FixedTInfo = 5779 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5780 SizeIsNegative, 5781 Oversized); 5782 if (FixedTInfo) { 5783 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5784 NewTD->setTypeSourceInfo(FixedTInfo); 5785 } else { 5786 if (SizeIsNegative) 5787 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5788 else if (T->isVariableArrayType()) 5789 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5790 else if (Oversized.getBoolValue()) 5791 Diag(NewTD->getLocation(), diag::err_array_too_large) 5792 << Oversized.toString(10); 5793 else 5794 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5795 NewTD->setInvalidDecl(); 5796 } 5797 } 5798 } 5799 } 5800 5801 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5802 /// declares a typedef-name, either using the 'typedef' type specifier or via 5803 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5804 NamedDecl* 5805 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5806 LookupResult &Previous, bool &Redeclaration) { 5807 5808 // Find the shadowed declaration before filtering for scope. 5809 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5810 5811 // Merge the decl with the existing one if appropriate. If the decl is 5812 // in an outer scope, it isn't the same thing. 5813 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5814 /*AllowInlineNamespace*/false); 5815 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5816 if (!Previous.empty()) { 5817 Redeclaration = true; 5818 MergeTypedefNameDecl(S, NewTD, Previous); 5819 } 5820 5821 if (ShadowedDecl && !Redeclaration) 5822 CheckShadow(NewTD, ShadowedDecl, Previous); 5823 5824 // If this is the C FILE type, notify the AST context. 5825 if (IdentifierInfo *II = NewTD->getIdentifier()) 5826 if (!NewTD->isInvalidDecl() && 5827 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5828 if (II->isStr("FILE")) 5829 Context.setFILEDecl(NewTD); 5830 else if (II->isStr("jmp_buf")) 5831 Context.setjmp_bufDecl(NewTD); 5832 else if (II->isStr("sigjmp_buf")) 5833 Context.setsigjmp_bufDecl(NewTD); 5834 else if (II->isStr("ucontext_t")) 5835 Context.setucontext_tDecl(NewTD); 5836 } 5837 5838 return NewTD; 5839 } 5840 5841 /// Determines whether the given declaration is an out-of-scope 5842 /// previous declaration. 5843 /// 5844 /// This routine should be invoked when name lookup has found a 5845 /// previous declaration (PrevDecl) that is not in the scope where a 5846 /// new declaration by the same name is being introduced. If the new 5847 /// declaration occurs in a local scope, previous declarations with 5848 /// linkage may still be considered previous declarations (C99 5849 /// 6.2.2p4-5, C++ [basic.link]p6). 5850 /// 5851 /// \param PrevDecl the previous declaration found by name 5852 /// lookup 5853 /// 5854 /// \param DC the context in which the new declaration is being 5855 /// declared. 5856 /// 5857 /// \returns true if PrevDecl is an out-of-scope previous declaration 5858 /// for a new delcaration with the same name. 5859 static bool 5860 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5861 ASTContext &Context) { 5862 if (!PrevDecl) 5863 return false; 5864 5865 if (!PrevDecl->hasLinkage()) 5866 return false; 5867 5868 if (Context.getLangOpts().CPlusPlus) { 5869 // C++ [basic.link]p6: 5870 // If there is a visible declaration of an entity with linkage 5871 // having the same name and type, ignoring entities declared 5872 // outside the innermost enclosing namespace scope, the block 5873 // scope declaration declares that same entity and receives the 5874 // linkage of the previous declaration. 5875 DeclContext *OuterContext = DC->getRedeclContext(); 5876 if (!OuterContext->isFunctionOrMethod()) 5877 // This rule only applies to block-scope declarations. 5878 return false; 5879 5880 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5881 if (PrevOuterContext->isRecord()) 5882 // We found a member function: ignore it. 5883 return false; 5884 5885 // Find the innermost enclosing namespace for the new and 5886 // previous declarations. 5887 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5888 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5889 5890 // The previous declaration is in a different namespace, so it 5891 // isn't the same function. 5892 if (!OuterContext->Equals(PrevOuterContext)) 5893 return false; 5894 } 5895 5896 return true; 5897 } 5898 5899 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 5900 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5901 if (!SS.isSet()) return; 5902 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 5903 } 5904 5905 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5906 QualType type = decl->getType(); 5907 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5908 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5909 // Various kinds of declaration aren't allowed to be __autoreleasing. 5910 unsigned kind = -1U; 5911 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5912 if (var->hasAttr<BlocksAttr>()) 5913 kind = 0; // __block 5914 else if (!var->hasLocalStorage()) 5915 kind = 1; // global 5916 } else if (isa<ObjCIvarDecl>(decl)) { 5917 kind = 3; // ivar 5918 } else if (isa<FieldDecl>(decl)) { 5919 kind = 2; // field 5920 } 5921 5922 if (kind != -1U) { 5923 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5924 << kind; 5925 } 5926 } else if (lifetime == Qualifiers::OCL_None) { 5927 // Try to infer lifetime. 5928 if (!type->isObjCLifetimeType()) 5929 return false; 5930 5931 lifetime = type->getObjCARCImplicitLifetime(); 5932 type = Context.getLifetimeQualifiedType(type, lifetime); 5933 decl->setType(type); 5934 } 5935 5936 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5937 // Thread-local variables cannot have lifetime. 5938 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5939 var->getTLSKind()) { 5940 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5941 << var->getType(); 5942 return true; 5943 } 5944 } 5945 5946 return false; 5947 } 5948 5949 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5950 // Ensure that an auto decl is deduced otherwise the checks below might cache 5951 // the wrong linkage. 5952 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5953 5954 // 'weak' only applies to declarations with external linkage. 5955 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5956 if (!ND.isExternallyVisible()) { 5957 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5958 ND.dropAttr<WeakAttr>(); 5959 } 5960 } 5961 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5962 if (ND.isExternallyVisible()) { 5963 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5964 ND.dropAttr<WeakRefAttr>(); 5965 ND.dropAttr<AliasAttr>(); 5966 } 5967 } 5968 5969 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5970 if (VD->hasInit()) { 5971 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5972 assert(VD->isThisDeclarationADefinition() && 5973 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5974 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5975 VD->dropAttr<AliasAttr>(); 5976 } 5977 } 5978 } 5979 5980 // 'selectany' only applies to externally visible variable declarations. 5981 // It does not apply to functions. 5982 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5983 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5984 S.Diag(Attr->getLocation(), 5985 diag::err_attribute_selectany_non_extern_data); 5986 ND.dropAttr<SelectAnyAttr>(); 5987 } 5988 } 5989 5990 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5991 auto *VD = dyn_cast<VarDecl>(&ND); 5992 bool IsAnonymousNS = false; 5993 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5994 if (VD) { 5995 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 5996 while (NS && !IsAnonymousNS) { 5997 IsAnonymousNS = NS->isAnonymousNamespace(); 5998 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 5999 } 6000 } 6001 // dll attributes require external linkage. Static locals may have external 6002 // linkage but still cannot be explicitly imported or exported. 6003 // In Microsoft mode, a variable defined in anonymous namespace must have 6004 // external linkage in order to be exported. 6005 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6006 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6007 (!AnonNSInMicrosoftMode && 6008 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6009 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6010 << &ND << Attr; 6011 ND.setInvalidDecl(); 6012 } 6013 } 6014 6015 // Virtual functions cannot be marked as 'notail'. 6016 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6017 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6018 if (MD->isVirtual()) { 6019 S.Diag(ND.getLocation(), 6020 diag::err_invalid_attribute_on_virtual_function) 6021 << Attr; 6022 ND.dropAttr<NotTailCalledAttr>(); 6023 } 6024 6025 // Check the attributes on the function type, if any. 6026 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6027 // Don't declare this variable in the second operand of the for-statement; 6028 // GCC miscompiles that by ending its lifetime before evaluating the 6029 // third operand. See gcc.gnu.org/PR86769. 6030 AttributedTypeLoc ATL; 6031 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6032 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6033 TL = ATL.getModifiedLoc()) { 6034 // The [[lifetimebound]] attribute can be applied to the implicit object 6035 // parameter of a non-static member function (other than a ctor or dtor) 6036 // by applying it to the function type. 6037 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6038 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6039 if (!MD || MD->isStatic()) { 6040 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6041 << !MD << A->getRange(); 6042 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6043 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6044 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6045 } 6046 } 6047 } 6048 } 6049 } 6050 6051 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6052 NamedDecl *NewDecl, 6053 bool IsSpecialization, 6054 bool IsDefinition) { 6055 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6056 return; 6057 6058 bool IsTemplate = false; 6059 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6060 OldDecl = OldTD->getTemplatedDecl(); 6061 IsTemplate = true; 6062 if (!IsSpecialization) 6063 IsDefinition = false; 6064 } 6065 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6066 NewDecl = NewTD->getTemplatedDecl(); 6067 IsTemplate = true; 6068 } 6069 6070 if (!OldDecl || !NewDecl) 6071 return; 6072 6073 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6074 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6075 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6076 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6077 6078 // dllimport and dllexport are inheritable attributes so we have to exclude 6079 // inherited attribute instances. 6080 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6081 (NewExportAttr && !NewExportAttr->isInherited()); 6082 6083 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6084 // the only exception being explicit specializations. 6085 // Implicitly generated declarations are also excluded for now because there 6086 // is no other way to switch these to use dllimport or dllexport. 6087 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6088 6089 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6090 // Allow with a warning for free functions and global variables. 6091 bool JustWarn = false; 6092 if (!OldDecl->isCXXClassMember()) { 6093 auto *VD = dyn_cast<VarDecl>(OldDecl); 6094 if (VD && !VD->getDescribedVarTemplate()) 6095 JustWarn = true; 6096 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6097 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6098 JustWarn = true; 6099 } 6100 6101 // We cannot change a declaration that's been used because IR has already 6102 // been emitted. Dllimported functions will still work though (modulo 6103 // address equality) as they can use the thunk. 6104 if (OldDecl->isUsed()) 6105 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6106 JustWarn = false; 6107 6108 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6109 : diag::err_attribute_dll_redeclaration; 6110 S.Diag(NewDecl->getLocation(), DiagID) 6111 << NewDecl 6112 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6113 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6114 if (!JustWarn) { 6115 NewDecl->setInvalidDecl(); 6116 return; 6117 } 6118 } 6119 6120 // A redeclaration is not allowed to drop a dllimport attribute, the only 6121 // exceptions being inline function definitions (except for function 6122 // templates), local extern declarations, qualified friend declarations or 6123 // special MSVC extension: in the last case, the declaration is treated as if 6124 // it were marked dllexport. 6125 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6126 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6127 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6128 // Ignore static data because out-of-line definitions are diagnosed 6129 // separately. 6130 IsStaticDataMember = VD->isStaticDataMember(); 6131 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6132 VarDecl::DeclarationOnly; 6133 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6134 IsInline = FD->isInlined(); 6135 IsQualifiedFriend = FD->getQualifier() && 6136 FD->getFriendObjectKind() == Decl::FOK_Declared; 6137 } 6138 6139 if (OldImportAttr && !HasNewAttr && 6140 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6141 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6142 if (IsMicrosoft && IsDefinition) { 6143 S.Diag(NewDecl->getLocation(), 6144 diag::warn_redeclaration_without_import_attribute) 6145 << NewDecl; 6146 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6147 NewDecl->dropAttr<DLLImportAttr>(); 6148 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6149 NewImportAttr->getRange(), S.Context, 6150 NewImportAttr->getSpellingListIndex())); 6151 } else { 6152 S.Diag(NewDecl->getLocation(), 6153 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6154 << NewDecl << OldImportAttr; 6155 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6156 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6157 OldDecl->dropAttr<DLLImportAttr>(); 6158 NewDecl->dropAttr<DLLImportAttr>(); 6159 } 6160 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6161 // In MinGW, seeing a function declared inline drops the dllimport 6162 // attribute. 6163 OldDecl->dropAttr<DLLImportAttr>(); 6164 NewDecl->dropAttr<DLLImportAttr>(); 6165 S.Diag(NewDecl->getLocation(), 6166 diag::warn_dllimport_dropped_from_inline_function) 6167 << NewDecl << OldImportAttr; 6168 } 6169 6170 // A specialization of a class template member function is processed here 6171 // since it's a redeclaration. If the parent class is dllexport, the 6172 // specialization inherits that attribute. This doesn't happen automatically 6173 // since the parent class isn't instantiated until later. 6174 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6175 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6176 !NewImportAttr && !NewExportAttr) { 6177 if (const DLLExportAttr *ParentExportAttr = 6178 MD->getParent()->getAttr<DLLExportAttr>()) { 6179 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6180 NewAttr->setInherited(true); 6181 NewDecl->addAttr(NewAttr); 6182 } 6183 } 6184 } 6185 } 6186 6187 /// Given that we are within the definition of the given function, 6188 /// will that definition behave like C99's 'inline', where the 6189 /// definition is discarded except for optimization purposes? 6190 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6191 // Try to avoid calling GetGVALinkageForFunction. 6192 6193 // All cases of this require the 'inline' keyword. 6194 if (!FD->isInlined()) return false; 6195 6196 // This is only possible in C++ with the gnu_inline attribute. 6197 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6198 return false; 6199 6200 // Okay, go ahead and call the relatively-more-expensive function. 6201 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6202 } 6203 6204 /// Determine whether a variable is extern "C" prior to attaching 6205 /// an initializer. We can't just call isExternC() here, because that 6206 /// will also compute and cache whether the declaration is externally 6207 /// visible, which might change when we attach the initializer. 6208 /// 6209 /// This can only be used if the declaration is known to not be a 6210 /// redeclaration of an internal linkage declaration. 6211 /// 6212 /// For instance: 6213 /// 6214 /// auto x = []{}; 6215 /// 6216 /// Attaching the initializer here makes this declaration not externally 6217 /// visible, because its type has internal linkage. 6218 /// 6219 /// FIXME: This is a hack. 6220 template<typename T> 6221 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6222 if (S.getLangOpts().CPlusPlus) { 6223 // In C++, the overloadable attribute negates the effects of extern "C". 6224 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6225 return false; 6226 6227 // So do CUDA's host/device attributes. 6228 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6229 D->template hasAttr<CUDAHostAttr>())) 6230 return false; 6231 } 6232 return D->isExternC(); 6233 } 6234 6235 static bool shouldConsiderLinkage(const VarDecl *VD) { 6236 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6237 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6238 isa<OMPDeclareMapperDecl>(DC)) 6239 return VD->hasExternalStorage(); 6240 if (DC->isFileContext()) 6241 return true; 6242 if (DC->isRecord()) 6243 return false; 6244 llvm_unreachable("Unexpected context"); 6245 } 6246 6247 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6248 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6249 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6250 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6251 return true; 6252 if (DC->isRecord()) 6253 return false; 6254 llvm_unreachable("Unexpected context"); 6255 } 6256 6257 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6258 ParsedAttr::Kind Kind) { 6259 // Check decl attributes on the DeclSpec. 6260 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6261 return true; 6262 6263 // Walk the declarator structure, checking decl attributes that were in a type 6264 // position to the decl itself. 6265 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6266 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6267 return true; 6268 } 6269 6270 // Finally, check attributes on the decl itself. 6271 return PD.getAttributes().hasAttribute(Kind); 6272 } 6273 6274 /// Adjust the \c DeclContext for a function or variable that might be a 6275 /// function-local external declaration. 6276 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6277 if (!DC->isFunctionOrMethod()) 6278 return false; 6279 6280 // If this is a local extern function or variable declared within a function 6281 // template, don't add it into the enclosing namespace scope until it is 6282 // instantiated; it might have a dependent type right now. 6283 if (DC->isDependentContext()) 6284 return true; 6285 6286 // C++11 [basic.link]p7: 6287 // When a block scope declaration of an entity with linkage is not found to 6288 // refer to some other declaration, then that entity is a member of the 6289 // innermost enclosing namespace. 6290 // 6291 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6292 // semantically-enclosing namespace, not a lexically-enclosing one. 6293 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6294 DC = DC->getParent(); 6295 return true; 6296 } 6297 6298 /// Returns true if given declaration has external C language linkage. 6299 static bool isDeclExternC(const Decl *D) { 6300 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6301 return FD->isExternC(); 6302 if (const auto *VD = dyn_cast<VarDecl>(D)) 6303 return VD->isExternC(); 6304 6305 llvm_unreachable("Unknown type of decl!"); 6306 } 6307 6308 NamedDecl *Sema::ActOnVariableDeclarator( 6309 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6310 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6311 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6312 QualType R = TInfo->getType(); 6313 DeclarationName Name = GetNameForDeclarator(D).getName(); 6314 6315 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6316 6317 if (D.isDecompositionDeclarator()) { 6318 // Take the name of the first declarator as our name for diagnostic 6319 // purposes. 6320 auto &Decomp = D.getDecompositionDeclarator(); 6321 if (!Decomp.bindings().empty()) { 6322 II = Decomp.bindings()[0].Name; 6323 Name = II; 6324 } 6325 } else if (!II) { 6326 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6327 return nullptr; 6328 } 6329 6330 if (getLangOpts().OpenCL) { 6331 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6332 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6333 // argument. 6334 if (R->isImageType() || R->isPipeType()) { 6335 Diag(D.getIdentifierLoc(), 6336 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6337 << R; 6338 D.setInvalidType(); 6339 return nullptr; 6340 } 6341 6342 // OpenCL v1.2 s6.9.r: 6343 // The event type cannot be used to declare a program scope variable. 6344 // OpenCL v2.0 s6.9.q: 6345 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6346 if (NULL == S->getParent()) { 6347 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6348 Diag(D.getIdentifierLoc(), 6349 diag::err_invalid_type_for_program_scope_var) << R; 6350 D.setInvalidType(); 6351 return nullptr; 6352 } 6353 } 6354 6355 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6356 QualType NR = R; 6357 while (NR->isPointerType()) { 6358 if (NR->isFunctionPointerType()) { 6359 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6360 D.setInvalidType(); 6361 break; 6362 } 6363 NR = NR->getPointeeType(); 6364 } 6365 6366 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6367 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6368 // half array type (unless the cl_khr_fp16 extension is enabled). 6369 if (Context.getBaseElementType(R)->isHalfType()) { 6370 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6371 D.setInvalidType(); 6372 } 6373 } 6374 6375 if (R->isSamplerT()) { 6376 // OpenCL v1.2 s6.9.b p4: 6377 // The sampler type cannot be used with the __local and __global address 6378 // space qualifiers. 6379 if (R.getAddressSpace() == LangAS::opencl_local || 6380 R.getAddressSpace() == LangAS::opencl_global) { 6381 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6382 } 6383 6384 // OpenCL v1.2 s6.12.14.1: 6385 // A global sampler must be declared with either the constant address 6386 // space qualifier or with the const qualifier. 6387 if (DC->isTranslationUnit() && 6388 !(R.getAddressSpace() == LangAS::opencl_constant || 6389 R.isConstQualified())) { 6390 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6391 D.setInvalidType(); 6392 } 6393 } 6394 6395 // OpenCL v1.2 s6.9.r: 6396 // The event type cannot be used with the __local, __constant and __global 6397 // address space qualifiers. 6398 if (R->isEventT()) { 6399 if (R.getAddressSpace() != LangAS::opencl_private) { 6400 Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6401 D.setInvalidType(); 6402 } 6403 } 6404 6405 // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not 6406 // supported. OpenCL C does not support thread_local either, and 6407 // also reject all other thread storage class specifiers. 6408 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6409 if (TSC != TSCS_unspecified) { 6410 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6411 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6412 diag::err_opencl_unknown_type_specifier) 6413 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6414 << DeclSpec::getSpecifierName(TSC) << 1; 6415 D.setInvalidType(); 6416 return nullptr; 6417 } 6418 } 6419 6420 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6421 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6422 6423 // dllimport globals without explicit storage class are treated as extern. We 6424 // have to change the storage class this early to get the right DeclContext. 6425 if (SC == SC_None && !DC->isRecord() && 6426 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6427 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6428 SC = SC_Extern; 6429 6430 DeclContext *OriginalDC = DC; 6431 bool IsLocalExternDecl = SC == SC_Extern && 6432 adjustContextForLocalExternDecl(DC); 6433 6434 if (SCSpec == DeclSpec::SCS_mutable) { 6435 // mutable can only appear on non-static class members, so it's always 6436 // an error here 6437 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6438 D.setInvalidType(); 6439 SC = SC_None; 6440 } 6441 6442 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6443 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6444 D.getDeclSpec().getStorageClassSpecLoc())) { 6445 // In C++11, the 'register' storage class specifier is deprecated. 6446 // Suppress the warning in system macros, it's used in macros in some 6447 // popular C system headers, such as in glibc's htonl() macro. 6448 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6449 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6450 : diag::warn_deprecated_register) 6451 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6452 } 6453 6454 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6455 6456 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6457 // C99 6.9p2: The storage-class specifiers auto and register shall not 6458 // appear in the declaration specifiers in an external declaration. 6459 // Global Register+Asm is a GNU extension we support. 6460 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6461 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6462 D.setInvalidType(); 6463 } 6464 } 6465 6466 bool IsMemberSpecialization = false; 6467 bool IsVariableTemplateSpecialization = false; 6468 bool IsPartialSpecialization = false; 6469 bool IsVariableTemplate = false; 6470 VarDecl *NewVD = nullptr; 6471 VarTemplateDecl *NewTemplate = nullptr; 6472 TemplateParameterList *TemplateParams = nullptr; 6473 if (!getLangOpts().CPlusPlus) { 6474 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6475 II, R, TInfo, SC); 6476 6477 if (R->getContainedDeducedType()) 6478 ParsingInitForAutoVars.insert(NewVD); 6479 6480 if (D.isInvalidType()) 6481 NewVD->setInvalidDecl(); 6482 } else { 6483 bool Invalid = false; 6484 6485 if (DC->isRecord() && !CurContext->isRecord()) { 6486 // This is an out-of-line definition of a static data member. 6487 switch (SC) { 6488 case SC_None: 6489 break; 6490 case SC_Static: 6491 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6492 diag::err_static_out_of_line) 6493 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6494 break; 6495 case SC_Auto: 6496 case SC_Register: 6497 case SC_Extern: 6498 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6499 // to names of variables declared in a block or to function parameters. 6500 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6501 // of class members 6502 6503 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6504 diag::err_storage_class_for_static_member) 6505 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6506 break; 6507 case SC_PrivateExtern: 6508 llvm_unreachable("C storage class in c++!"); 6509 } 6510 } 6511 6512 if (SC == SC_Static && CurContext->isRecord()) { 6513 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6514 if (RD->isLocalClass()) 6515 Diag(D.getIdentifierLoc(), 6516 diag::err_static_data_member_not_allowed_in_local_class) 6517 << Name << RD->getDeclName(); 6518 6519 // C++98 [class.union]p1: If a union contains a static data member, 6520 // the program is ill-formed. C++11 drops this restriction. 6521 if (RD->isUnion()) 6522 Diag(D.getIdentifierLoc(), 6523 getLangOpts().CPlusPlus11 6524 ? diag::warn_cxx98_compat_static_data_member_in_union 6525 : diag::ext_static_data_member_in_union) << Name; 6526 // We conservatively disallow static data members in anonymous structs. 6527 else if (!RD->getDeclName()) 6528 Diag(D.getIdentifierLoc(), 6529 diag::err_static_data_member_not_allowed_in_anon_struct) 6530 << Name << RD->isUnion(); 6531 } 6532 } 6533 6534 // Match up the template parameter lists with the scope specifier, then 6535 // determine whether we have a template or a template specialization. 6536 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6537 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6538 D.getCXXScopeSpec(), 6539 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6540 ? D.getName().TemplateId 6541 : nullptr, 6542 TemplateParamLists, 6543 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6544 6545 if (TemplateParams) { 6546 if (!TemplateParams->size() && 6547 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6548 // There is an extraneous 'template<>' for this variable. Complain 6549 // about it, but allow the declaration of the variable. 6550 Diag(TemplateParams->getTemplateLoc(), 6551 diag::err_template_variable_noparams) 6552 << II 6553 << SourceRange(TemplateParams->getTemplateLoc(), 6554 TemplateParams->getRAngleLoc()); 6555 TemplateParams = nullptr; 6556 } else { 6557 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6558 // This is an explicit specialization or a partial specialization. 6559 // FIXME: Check that we can declare a specialization here. 6560 IsVariableTemplateSpecialization = true; 6561 IsPartialSpecialization = TemplateParams->size() > 0; 6562 } else { // if (TemplateParams->size() > 0) 6563 // This is a template declaration. 6564 IsVariableTemplate = true; 6565 6566 // Check that we can declare a template here. 6567 if (CheckTemplateDeclScope(S, TemplateParams)) 6568 return nullptr; 6569 6570 // Only C++1y supports variable templates (N3651). 6571 Diag(D.getIdentifierLoc(), 6572 getLangOpts().CPlusPlus14 6573 ? diag::warn_cxx11_compat_variable_template 6574 : diag::ext_variable_template); 6575 } 6576 } 6577 } else { 6578 assert((Invalid || 6579 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6580 "should have a 'template<>' for this decl"); 6581 } 6582 6583 if (IsVariableTemplateSpecialization) { 6584 SourceLocation TemplateKWLoc = 6585 TemplateParamLists.size() > 0 6586 ? TemplateParamLists[0]->getTemplateLoc() 6587 : SourceLocation(); 6588 DeclResult Res = ActOnVarTemplateSpecialization( 6589 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6590 IsPartialSpecialization); 6591 if (Res.isInvalid()) 6592 return nullptr; 6593 NewVD = cast<VarDecl>(Res.get()); 6594 AddToScope = false; 6595 } else if (D.isDecompositionDeclarator()) { 6596 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6597 D.getIdentifierLoc(), R, TInfo, SC, 6598 Bindings); 6599 } else 6600 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6601 D.getIdentifierLoc(), II, R, TInfo, SC); 6602 6603 // If this is supposed to be a variable template, create it as such. 6604 if (IsVariableTemplate) { 6605 NewTemplate = 6606 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6607 TemplateParams, NewVD); 6608 NewVD->setDescribedVarTemplate(NewTemplate); 6609 } 6610 6611 // If this decl has an auto type in need of deduction, make a note of the 6612 // Decl so we can diagnose uses of it in its own initializer. 6613 if (R->getContainedDeducedType()) 6614 ParsingInitForAutoVars.insert(NewVD); 6615 6616 if (D.isInvalidType() || Invalid) { 6617 NewVD->setInvalidDecl(); 6618 if (NewTemplate) 6619 NewTemplate->setInvalidDecl(); 6620 } 6621 6622 SetNestedNameSpecifier(*this, NewVD, D); 6623 6624 // If we have any template parameter lists that don't directly belong to 6625 // the variable (matching the scope specifier), store them. 6626 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6627 if (TemplateParamLists.size() > VDTemplateParamLists) 6628 NewVD->setTemplateParameterListsInfo( 6629 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6630 6631 if (D.getDeclSpec().isConstexprSpecified()) { 6632 NewVD->setConstexpr(true); 6633 // C++1z [dcl.spec.constexpr]p1: 6634 // A static data member declared with the constexpr specifier is 6635 // implicitly an inline variable. 6636 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6637 NewVD->setImplicitlyInline(); 6638 } 6639 } 6640 6641 if (D.getDeclSpec().isInlineSpecified()) { 6642 if (!getLangOpts().CPlusPlus) { 6643 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6644 << 0; 6645 } else if (CurContext->isFunctionOrMethod()) { 6646 // 'inline' is not allowed on block scope variable declaration. 6647 Diag(D.getDeclSpec().getInlineSpecLoc(), 6648 diag::err_inline_declaration_block_scope) << Name 6649 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6650 } else { 6651 Diag(D.getDeclSpec().getInlineSpecLoc(), 6652 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6653 : diag::ext_inline_variable); 6654 NewVD->setInlineSpecified(); 6655 } 6656 } 6657 6658 // Set the lexical context. If the declarator has a C++ scope specifier, the 6659 // lexical context will be different from the semantic context. 6660 NewVD->setLexicalDeclContext(CurContext); 6661 if (NewTemplate) 6662 NewTemplate->setLexicalDeclContext(CurContext); 6663 6664 if (IsLocalExternDecl) { 6665 if (D.isDecompositionDeclarator()) 6666 for (auto *B : Bindings) 6667 B->setLocalExternDecl(); 6668 else 6669 NewVD->setLocalExternDecl(); 6670 } 6671 6672 bool EmitTLSUnsupportedError = false; 6673 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6674 // C++11 [dcl.stc]p4: 6675 // When thread_local is applied to a variable of block scope the 6676 // storage-class-specifier static is implied if it does not appear 6677 // explicitly. 6678 // Core issue: 'static' is not implied if the variable is declared 6679 // 'extern'. 6680 if (NewVD->hasLocalStorage() && 6681 (SCSpec != DeclSpec::SCS_unspecified || 6682 TSCS != DeclSpec::TSCS_thread_local || 6683 !DC->isFunctionOrMethod())) 6684 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6685 diag::err_thread_non_global) 6686 << DeclSpec::getSpecifierName(TSCS); 6687 else if (!Context.getTargetInfo().isTLSSupported()) { 6688 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6689 // Postpone error emission until we've collected attributes required to 6690 // figure out whether it's a host or device variable and whether the 6691 // error should be ignored. 6692 EmitTLSUnsupportedError = true; 6693 // We still need to mark the variable as TLS so it shows up in AST with 6694 // proper storage class for other tools to use even if we're not going 6695 // to emit any code for it. 6696 NewVD->setTSCSpec(TSCS); 6697 } else 6698 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6699 diag::err_thread_unsupported); 6700 } else 6701 NewVD->setTSCSpec(TSCS); 6702 } 6703 6704 // C99 6.7.4p3 6705 // An inline definition of a function with external linkage shall 6706 // not contain a definition of a modifiable object with static or 6707 // thread storage duration... 6708 // We only apply this when the function is required to be defined 6709 // elsewhere, i.e. when the function is not 'extern inline'. Note 6710 // that a local variable with thread storage duration still has to 6711 // be marked 'static'. Also note that it's possible to get these 6712 // semantics in C++ using __attribute__((gnu_inline)). 6713 if (SC == SC_Static && S->getFnParent() != nullptr && 6714 !NewVD->getType().isConstQualified()) { 6715 FunctionDecl *CurFD = getCurFunctionDecl(); 6716 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6717 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6718 diag::warn_static_local_in_extern_inline); 6719 MaybeSuggestAddingStaticToDecl(CurFD); 6720 } 6721 } 6722 6723 if (D.getDeclSpec().isModulePrivateSpecified()) { 6724 if (IsVariableTemplateSpecialization) 6725 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6726 << (IsPartialSpecialization ? 1 : 0) 6727 << FixItHint::CreateRemoval( 6728 D.getDeclSpec().getModulePrivateSpecLoc()); 6729 else if (IsMemberSpecialization) 6730 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6731 << 2 6732 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6733 else if (NewVD->hasLocalStorage()) 6734 Diag(NewVD->getLocation(), diag::err_module_private_local) 6735 << 0 << NewVD->getDeclName() 6736 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6737 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6738 else { 6739 NewVD->setModulePrivate(); 6740 if (NewTemplate) 6741 NewTemplate->setModulePrivate(); 6742 for (auto *B : Bindings) 6743 B->setModulePrivate(); 6744 } 6745 } 6746 6747 // Handle attributes prior to checking for duplicates in MergeVarDecl 6748 ProcessDeclAttributes(S, NewVD, D); 6749 6750 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6751 if (EmitTLSUnsupportedError && 6752 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6753 (getLangOpts().OpenMPIsDevice && 6754 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6755 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6756 diag::err_thread_unsupported); 6757 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6758 // storage [duration]." 6759 if (SC == SC_None && S->getFnParent() != nullptr && 6760 (NewVD->hasAttr<CUDASharedAttr>() || 6761 NewVD->hasAttr<CUDAConstantAttr>())) { 6762 NewVD->setStorageClass(SC_Static); 6763 } 6764 } 6765 6766 // Ensure that dllimport globals without explicit storage class are treated as 6767 // extern. The storage class is set above using parsed attributes. Now we can 6768 // check the VarDecl itself. 6769 assert(!NewVD->hasAttr<DLLImportAttr>() || 6770 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6771 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6772 6773 // In auto-retain/release, infer strong retension for variables of 6774 // retainable type. 6775 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6776 NewVD->setInvalidDecl(); 6777 6778 // Handle GNU asm-label extension (encoded as an attribute). 6779 if (Expr *E = (Expr*)D.getAsmLabel()) { 6780 // The parser guarantees this is a string. 6781 StringLiteral *SE = cast<StringLiteral>(E); 6782 StringRef Label = SE->getString(); 6783 if (S->getFnParent() != nullptr) { 6784 switch (SC) { 6785 case SC_None: 6786 case SC_Auto: 6787 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6788 break; 6789 case SC_Register: 6790 // Local Named register 6791 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6792 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6793 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6794 break; 6795 case SC_Static: 6796 case SC_Extern: 6797 case SC_PrivateExtern: 6798 break; 6799 } 6800 } else if (SC == SC_Register) { 6801 // Global Named register 6802 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6803 const auto &TI = Context.getTargetInfo(); 6804 bool HasSizeMismatch; 6805 6806 if (!TI.isValidGCCRegisterName(Label)) 6807 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6808 else if (!TI.validateGlobalRegisterVariable(Label, 6809 Context.getTypeSize(R), 6810 HasSizeMismatch)) 6811 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6812 else if (HasSizeMismatch) 6813 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6814 } 6815 6816 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6817 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 6818 NewVD->setInvalidDecl(true); 6819 } 6820 } 6821 6822 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6823 Context, Label, 0)); 6824 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6825 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6826 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6827 if (I != ExtnameUndeclaredIdentifiers.end()) { 6828 if (isDeclExternC(NewVD)) { 6829 NewVD->addAttr(I->second); 6830 ExtnameUndeclaredIdentifiers.erase(I); 6831 } else 6832 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6833 << /*Variable*/1 << NewVD; 6834 } 6835 } 6836 6837 // Find the shadowed declaration before filtering for scope. 6838 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6839 ? getShadowedDeclaration(NewVD, Previous) 6840 : nullptr; 6841 6842 // Don't consider existing declarations that are in a different 6843 // scope and are out-of-semantic-context declarations (if the new 6844 // declaration has linkage). 6845 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6846 D.getCXXScopeSpec().isNotEmpty() || 6847 IsMemberSpecialization || 6848 IsVariableTemplateSpecialization); 6849 6850 // Check whether the previous declaration is in the same block scope. This 6851 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6852 if (getLangOpts().CPlusPlus && 6853 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6854 NewVD->setPreviousDeclInSameBlockScope( 6855 Previous.isSingleResult() && !Previous.isShadowed() && 6856 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6857 6858 if (!getLangOpts().CPlusPlus) { 6859 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6860 } else { 6861 // If this is an explicit specialization of a static data member, check it. 6862 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6863 CheckMemberSpecialization(NewVD, Previous)) 6864 NewVD->setInvalidDecl(); 6865 6866 // Merge the decl with the existing one if appropriate. 6867 if (!Previous.empty()) { 6868 if (Previous.isSingleResult() && 6869 isa<FieldDecl>(Previous.getFoundDecl()) && 6870 D.getCXXScopeSpec().isSet()) { 6871 // The user tried to define a non-static data member 6872 // out-of-line (C++ [dcl.meaning]p1). 6873 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6874 << D.getCXXScopeSpec().getRange(); 6875 Previous.clear(); 6876 NewVD->setInvalidDecl(); 6877 } 6878 } else if (D.getCXXScopeSpec().isSet()) { 6879 // No previous declaration in the qualifying scope. 6880 Diag(D.getIdentifierLoc(), diag::err_no_member) 6881 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6882 << D.getCXXScopeSpec().getRange(); 6883 NewVD->setInvalidDecl(); 6884 } 6885 6886 if (!IsVariableTemplateSpecialization) 6887 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6888 6889 if (NewTemplate) { 6890 VarTemplateDecl *PrevVarTemplate = 6891 NewVD->getPreviousDecl() 6892 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6893 : nullptr; 6894 6895 // Check the template parameter list of this declaration, possibly 6896 // merging in the template parameter list from the previous variable 6897 // template declaration. 6898 if (CheckTemplateParameterList( 6899 TemplateParams, 6900 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6901 : nullptr, 6902 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6903 DC->isDependentContext()) 6904 ? TPC_ClassTemplateMember 6905 : TPC_VarTemplate)) 6906 NewVD->setInvalidDecl(); 6907 6908 // If we are providing an explicit specialization of a static variable 6909 // template, make a note of that. 6910 if (PrevVarTemplate && 6911 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6912 PrevVarTemplate->setMemberSpecialization(); 6913 } 6914 } 6915 6916 // Diagnose shadowed variables iff this isn't a redeclaration. 6917 if (ShadowedDecl && !D.isRedeclaration()) 6918 CheckShadow(NewVD, ShadowedDecl, Previous); 6919 6920 ProcessPragmaWeak(S, NewVD); 6921 6922 // If this is the first declaration of an extern C variable, update 6923 // the map of such variables. 6924 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6925 isIncompleteDeclExternC(*this, NewVD)) 6926 RegisterLocallyScopedExternCDecl(NewVD, S); 6927 6928 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6929 Decl *ManglingContextDecl; 6930 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6931 NewVD->getDeclContext(), ManglingContextDecl)) { 6932 Context.setManglingNumber( 6933 NewVD, MCtx->getManglingNumber( 6934 NewVD, getMSManglingNumber(getLangOpts(), S))); 6935 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6936 } 6937 } 6938 6939 // Special handling of variable named 'main'. 6940 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6941 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6942 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6943 6944 // C++ [basic.start.main]p3 6945 // A program that declares a variable main at global scope is ill-formed. 6946 if (getLangOpts().CPlusPlus) 6947 Diag(D.getBeginLoc(), diag::err_main_global_variable); 6948 6949 // In C, and external-linkage variable named main results in undefined 6950 // behavior. 6951 else if (NewVD->hasExternalFormalLinkage()) 6952 Diag(D.getBeginLoc(), diag::warn_main_redefined); 6953 } 6954 6955 if (D.isRedeclaration() && !Previous.empty()) { 6956 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6957 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6958 D.isFunctionDefinition()); 6959 } 6960 6961 if (NewTemplate) { 6962 if (NewVD->isInvalidDecl()) 6963 NewTemplate->setInvalidDecl(); 6964 ActOnDocumentableDecl(NewTemplate); 6965 return NewTemplate; 6966 } 6967 6968 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6969 CompleteMemberSpecialization(NewVD, Previous); 6970 6971 return NewVD; 6972 } 6973 6974 /// Enum describing the %select options in diag::warn_decl_shadow. 6975 enum ShadowedDeclKind { 6976 SDK_Local, 6977 SDK_Global, 6978 SDK_StaticMember, 6979 SDK_Field, 6980 SDK_Typedef, 6981 SDK_Using 6982 }; 6983 6984 /// Determine what kind of declaration we're shadowing. 6985 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6986 const DeclContext *OldDC) { 6987 if (isa<TypeAliasDecl>(ShadowedDecl)) 6988 return SDK_Using; 6989 else if (isa<TypedefDecl>(ShadowedDecl)) 6990 return SDK_Typedef; 6991 else if (isa<RecordDecl>(OldDC)) 6992 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6993 6994 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6995 } 6996 6997 /// Return the location of the capture if the given lambda captures the given 6998 /// variable \p VD, or an invalid source location otherwise. 6999 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7000 const VarDecl *VD) { 7001 for (const Capture &Capture : LSI->Captures) { 7002 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7003 return Capture.getLocation(); 7004 } 7005 return SourceLocation(); 7006 } 7007 7008 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7009 const LookupResult &R) { 7010 // Only diagnose if we're shadowing an unambiguous field or variable. 7011 if (R.getResultKind() != LookupResult::Found) 7012 return false; 7013 7014 // Return false if warning is ignored. 7015 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7016 } 7017 7018 /// Return the declaration shadowed by the given variable \p D, or null 7019 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7020 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7021 const LookupResult &R) { 7022 if (!shouldWarnIfShadowedDecl(Diags, R)) 7023 return nullptr; 7024 7025 // Don't diagnose declarations at file scope. 7026 if (D->hasGlobalStorage()) 7027 return nullptr; 7028 7029 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7030 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7031 ? ShadowedDecl 7032 : nullptr; 7033 } 7034 7035 /// Return the declaration shadowed by the given typedef \p D, or null 7036 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7037 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7038 const LookupResult &R) { 7039 // Don't warn if typedef declaration is part of a class 7040 if (D->getDeclContext()->isRecord()) 7041 return nullptr; 7042 7043 if (!shouldWarnIfShadowedDecl(Diags, R)) 7044 return nullptr; 7045 7046 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7047 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7048 } 7049 7050 /// Diagnose variable or built-in function shadowing. Implements 7051 /// -Wshadow. 7052 /// 7053 /// This method is called whenever a VarDecl is added to a "useful" 7054 /// scope. 7055 /// 7056 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7057 /// \param R the lookup of the name 7058 /// 7059 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7060 const LookupResult &R) { 7061 DeclContext *NewDC = D->getDeclContext(); 7062 7063 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7064 // Fields are not shadowed by variables in C++ static methods. 7065 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7066 if (MD->isStatic()) 7067 return; 7068 7069 // Fields shadowed by constructor parameters are a special case. Usually 7070 // the constructor initializes the field with the parameter. 7071 if (isa<CXXConstructorDecl>(NewDC)) 7072 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7073 // Remember that this was shadowed so we can either warn about its 7074 // modification or its existence depending on warning settings. 7075 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7076 return; 7077 } 7078 } 7079 7080 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7081 if (shadowedVar->isExternC()) { 7082 // For shadowing external vars, make sure that we point to the global 7083 // declaration, not a locally scoped extern declaration. 7084 for (auto I : shadowedVar->redecls()) 7085 if (I->isFileVarDecl()) { 7086 ShadowedDecl = I; 7087 break; 7088 } 7089 } 7090 7091 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7092 7093 unsigned WarningDiag = diag::warn_decl_shadow; 7094 SourceLocation CaptureLoc; 7095 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7096 isa<CXXMethodDecl>(NewDC)) { 7097 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7098 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7099 if (RD->getLambdaCaptureDefault() == LCD_None) { 7100 // Try to avoid warnings for lambdas with an explicit capture list. 7101 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7102 // Warn only when the lambda captures the shadowed decl explicitly. 7103 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7104 if (CaptureLoc.isInvalid()) 7105 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7106 } else { 7107 // Remember that this was shadowed so we can avoid the warning if the 7108 // shadowed decl isn't captured and the warning settings allow it. 7109 cast<LambdaScopeInfo>(getCurFunction()) 7110 ->ShadowingDecls.push_back( 7111 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7112 return; 7113 } 7114 } 7115 7116 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7117 // A variable can't shadow a local variable in an enclosing scope, if 7118 // they are separated by a non-capturing declaration context. 7119 for (DeclContext *ParentDC = NewDC; 7120 ParentDC && !ParentDC->Equals(OldDC); 7121 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7122 // Only block literals, captured statements, and lambda expressions 7123 // can capture; other scopes don't. 7124 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7125 !isLambdaCallOperator(ParentDC)) { 7126 return; 7127 } 7128 } 7129 } 7130 } 7131 } 7132 7133 // Only warn about certain kinds of shadowing for class members. 7134 if (NewDC && NewDC->isRecord()) { 7135 // In particular, don't warn about shadowing non-class members. 7136 if (!OldDC->isRecord()) 7137 return; 7138 7139 // TODO: should we warn about static data members shadowing 7140 // static data members from base classes? 7141 7142 // TODO: don't diagnose for inaccessible shadowed members. 7143 // This is hard to do perfectly because we might friend the 7144 // shadowing context, but that's just a false negative. 7145 } 7146 7147 7148 DeclarationName Name = R.getLookupName(); 7149 7150 // Emit warning and note. 7151 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7152 return; 7153 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7154 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7155 if (!CaptureLoc.isInvalid()) 7156 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7157 << Name << /*explicitly*/ 1; 7158 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7159 } 7160 7161 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7162 /// when these variables are captured by the lambda. 7163 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7164 for (const auto &Shadow : LSI->ShadowingDecls) { 7165 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7166 // Try to avoid the warning when the shadowed decl isn't captured. 7167 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7168 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7169 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7170 ? diag::warn_decl_shadow_uncaptured_local 7171 : diag::warn_decl_shadow) 7172 << Shadow.VD->getDeclName() 7173 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7174 if (!CaptureLoc.isInvalid()) 7175 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7176 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7177 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7178 } 7179 } 7180 7181 /// Check -Wshadow without the advantage of a previous lookup. 7182 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7183 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7184 return; 7185 7186 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7187 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7188 LookupName(R, S); 7189 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7190 CheckShadow(D, ShadowedDecl, R); 7191 } 7192 7193 /// Check if 'E', which is an expression that is about to be modified, refers 7194 /// to a constructor parameter that shadows a field. 7195 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7196 // Quickly ignore expressions that can't be shadowing ctor parameters. 7197 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7198 return; 7199 E = E->IgnoreParenImpCasts(); 7200 auto *DRE = dyn_cast<DeclRefExpr>(E); 7201 if (!DRE) 7202 return; 7203 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7204 auto I = ShadowingDecls.find(D); 7205 if (I == ShadowingDecls.end()) 7206 return; 7207 const NamedDecl *ShadowedDecl = I->second; 7208 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7209 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7210 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7211 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7212 7213 // Avoid issuing multiple warnings about the same decl. 7214 ShadowingDecls.erase(I); 7215 } 7216 7217 /// Check for conflict between this global or extern "C" declaration and 7218 /// previous global or extern "C" declarations. This is only used in C++. 7219 template<typename T> 7220 static bool checkGlobalOrExternCConflict( 7221 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7222 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7223 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7224 7225 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7226 // The common case: this global doesn't conflict with any extern "C" 7227 // declaration. 7228 return false; 7229 } 7230 7231 if (Prev) { 7232 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7233 // Both the old and new declarations have C language linkage. This is a 7234 // redeclaration. 7235 Previous.clear(); 7236 Previous.addDecl(Prev); 7237 return true; 7238 } 7239 7240 // This is a global, non-extern "C" declaration, and there is a previous 7241 // non-global extern "C" declaration. Diagnose if this is a variable 7242 // declaration. 7243 if (!isa<VarDecl>(ND)) 7244 return false; 7245 } else { 7246 // The declaration is extern "C". Check for any declaration in the 7247 // translation unit which might conflict. 7248 if (IsGlobal) { 7249 // We have already performed the lookup into the translation unit. 7250 IsGlobal = false; 7251 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7252 I != E; ++I) { 7253 if (isa<VarDecl>(*I)) { 7254 Prev = *I; 7255 break; 7256 } 7257 } 7258 } else { 7259 DeclContext::lookup_result R = 7260 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7261 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7262 I != E; ++I) { 7263 if (isa<VarDecl>(*I)) { 7264 Prev = *I; 7265 break; 7266 } 7267 // FIXME: If we have any other entity with this name in global scope, 7268 // the declaration is ill-formed, but that is a defect: it breaks the 7269 // 'stat' hack, for instance. Only variables can have mangled name 7270 // clashes with extern "C" declarations, so only they deserve a 7271 // diagnostic. 7272 } 7273 } 7274 7275 if (!Prev) 7276 return false; 7277 } 7278 7279 // Use the first declaration's location to ensure we point at something which 7280 // is lexically inside an extern "C" linkage-spec. 7281 assert(Prev && "should have found a previous declaration to diagnose"); 7282 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7283 Prev = FD->getFirstDecl(); 7284 else 7285 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7286 7287 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7288 << IsGlobal << ND; 7289 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7290 << IsGlobal; 7291 return false; 7292 } 7293 7294 /// Apply special rules for handling extern "C" declarations. Returns \c true 7295 /// if we have found that this is a redeclaration of some prior entity. 7296 /// 7297 /// Per C++ [dcl.link]p6: 7298 /// Two declarations [for a function or variable] with C language linkage 7299 /// with the same name that appear in different scopes refer to the same 7300 /// [entity]. An entity with C language linkage shall not be declared with 7301 /// the same name as an entity in global scope. 7302 template<typename T> 7303 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7304 LookupResult &Previous) { 7305 if (!S.getLangOpts().CPlusPlus) { 7306 // In C, when declaring a global variable, look for a corresponding 'extern' 7307 // variable declared in function scope. We don't need this in C++, because 7308 // we find local extern decls in the surrounding file-scope DeclContext. 7309 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7310 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7311 Previous.clear(); 7312 Previous.addDecl(Prev); 7313 return true; 7314 } 7315 } 7316 return false; 7317 } 7318 7319 // A declaration in the translation unit can conflict with an extern "C" 7320 // declaration. 7321 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7322 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7323 7324 // An extern "C" declaration can conflict with a declaration in the 7325 // translation unit or can be a redeclaration of an extern "C" declaration 7326 // in another scope. 7327 if (isIncompleteDeclExternC(S,ND)) 7328 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7329 7330 // Neither global nor extern "C": nothing to do. 7331 return false; 7332 } 7333 7334 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7335 // If the decl is already known invalid, don't check it. 7336 if (NewVD->isInvalidDecl()) 7337 return; 7338 7339 QualType T = NewVD->getType(); 7340 7341 // Defer checking an 'auto' type until its initializer is attached. 7342 if (T->isUndeducedType()) 7343 return; 7344 7345 if (NewVD->hasAttrs()) 7346 CheckAlignasUnderalignment(NewVD); 7347 7348 if (T->isObjCObjectType()) { 7349 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7350 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7351 T = Context.getObjCObjectPointerType(T); 7352 NewVD->setType(T); 7353 } 7354 7355 // Emit an error if an address space was applied to decl with local storage. 7356 // This includes arrays of objects with address space qualifiers, but not 7357 // automatic variables that point to other address spaces. 7358 // ISO/IEC TR 18037 S5.1.2 7359 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7360 T.getAddressSpace() != LangAS::Default) { 7361 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7362 NewVD->setInvalidDecl(); 7363 return; 7364 } 7365 7366 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7367 // scope. 7368 if (getLangOpts().OpenCLVersion == 120 && 7369 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7370 NewVD->isStaticLocal()) { 7371 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7372 NewVD->setInvalidDecl(); 7373 return; 7374 } 7375 7376 if (getLangOpts().OpenCL) { 7377 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7378 if (NewVD->hasAttr<BlocksAttr>()) { 7379 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7380 return; 7381 } 7382 7383 if (T->isBlockPointerType()) { 7384 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7385 // can't use 'extern' storage class. 7386 if (!T.isConstQualified()) { 7387 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7388 << 0 /*const*/; 7389 NewVD->setInvalidDecl(); 7390 return; 7391 } 7392 if (NewVD->hasExternalStorage()) { 7393 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7394 NewVD->setInvalidDecl(); 7395 return; 7396 } 7397 } 7398 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7399 // __constant address space. 7400 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7401 // variables inside a function can also be declared in the global 7402 // address space. 7403 // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local 7404 // address space additionally. 7405 // FIXME: Add local AS for OpenCL C++. 7406 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7407 NewVD->hasExternalStorage()) { 7408 if (!T->isSamplerT() && 7409 !(T.getAddressSpace() == LangAS::opencl_constant || 7410 (T.getAddressSpace() == LangAS::opencl_global && 7411 (getLangOpts().OpenCLVersion == 200 || 7412 getLangOpts().OpenCLCPlusPlus)))) { 7413 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7414 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7415 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7416 << Scope << "global or constant"; 7417 else 7418 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7419 << Scope << "constant"; 7420 NewVD->setInvalidDecl(); 7421 return; 7422 } 7423 } else { 7424 if (T.getAddressSpace() == LangAS::opencl_global) { 7425 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7426 << 1 /*is any function*/ << "global"; 7427 NewVD->setInvalidDecl(); 7428 return; 7429 } 7430 if (T.getAddressSpace() == LangAS::opencl_constant || 7431 T.getAddressSpace() == LangAS::opencl_local) { 7432 FunctionDecl *FD = getCurFunctionDecl(); 7433 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7434 // in functions. 7435 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7436 if (T.getAddressSpace() == LangAS::opencl_constant) 7437 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7438 << 0 /*non-kernel only*/ << "constant"; 7439 else 7440 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7441 << 0 /*non-kernel only*/ << "local"; 7442 NewVD->setInvalidDecl(); 7443 return; 7444 } 7445 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7446 // in the outermost scope of a kernel function. 7447 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7448 if (!getCurScope()->isFunctionScope()) { 7449 if (T.getAddressSpace() == LangAS::opencl_constant) 7450 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7451 << "constant"; 7452 else 7453 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7454 << "local"; 7455 NewVD->setInvalidDecl(); 7456 return; 7457 } 7458 } 7459 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7460 // Do not allow other address spaces on automatic variable. 7461 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7462 NewVD->setInvalidDecl(); 7463 return; 7464 } 7465 } 7466 } 7467 7468 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7469 && !NewVD->hasAttr<BlocksAttr>()) { 7470 if (getLangOpts().getGC() != LangOptions::NonGC) 7471 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7472 else { 7473 assert(!getLangOpts().ObjCAutoRefCount); 7474 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7475 } 7476 } 7477 7478 bool isVM = T->isVariablyModifiedType(); 7479 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7480 NewVD->hasAttr<BlocksAttr>()) 7481 setFunctionHasBranchProtectedScope(); 7482 7483 if ((isVM && NewVD->hasLinkage()) || 7484 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7485 bool SizeIsNegative; 7486 llvm::APSInt Oversized; 7487 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7488 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7489 QualType FixedT; 7490 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7491 FixedT = FixedTInfo->getType(); 7492 else if (FixedTInfo) { 7493 // Type and type-as-written are canonically different. We need to fix up 7494 // both types separately. 7495 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7496 Oversized); 7497 } 7498 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7499 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7500 // FIXME: This won't give the correct result for 7501 // int a[10][n]; 7502 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7503 7504 if (NewVD->isFileVarDecl()) 7505 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7506 << SizeRange; 7507 else if (NewVD->isStaticLocal()) 7508 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7509 << SizeRange; 7510 else 7511 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7512 << SizeRange; 7513 NewVD->setInvalidDecl(); 7514 return; 7515 } 7516 7517 if (!FixedTInfo) { 7518 if (NewVD->isFileVarDecl()) 7519 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7520 else 7521 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7522 NewVD->setInvalidDecl(); 7523 return; 7524 } 7525 7526 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7527 NewVD->setType(FixedT); 7528 NewVD->setTypeSourceInfo(FixedTInfo); 7529 } 7530 7531 if (T->isVoidType()) { 7532 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7533 // of objects and functions. 7534 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7535 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7536 << T; 7537 NewVD->setInvalidDecl(); 7538 return; 7539 } 7540 } 7541 7542 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7543 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7544 NewVD->setInvalidDecl(); 7545 return; 7546 } 7547 7548 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7549 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7550 NewVD->setInvalidDecl(); 7551 return; 7552 } 7553 7554 if (NewVD->isConstexpr() && !T->isDependentType() && 7555 RequireLiteralType(NewVD->getLocation(), T, 7556 diag::err_constexpr_var_non_literal)) { 7557 NewVD->setInvalidDecl(); 7558 return; 7559 } 7560 } 7561 7562 /// Perform semantic checking on a newly-created variable 7563 /// declaration. 7564 /// 7565 /// This routine performs all of the type-checking required for a 7566 /// variable declaration once it has been built. It is used both to 7567 /// check variables after they have been parsed and their declarators 7568 /// have been translated into a declaration, and to check variables 7569 /// that have been instantiated from a template. 7570 /// 7571 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7572 /// 7573 /// Returns true if the variable declaration is a redeclaration. 7574 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7575 CheckVariableDeclarationType(NewVD); 7576 7577 // If the decl is already known invalid, don't check it. 7578 if (NewVD->isInvalidDecl()) 7579 return false; 7580 7581 // If we did not find anything by this name, look for a non-visible 7582 // extern "C" declaration with the same name. 7583 if (Previous.empty() && 7584 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7585 Previous.setShadowed(); 7586 7587 if (!Previous.empty()) { 7588 MergeVarDecl(NewVD, Previous); 7589 return true; 7590 } 7591 return false; 7592 } 7593 7594 namespace { 7595 struct FindOverriddenMethod { 7596 Sema *S; 7597 CXXMethodDecl *Method; 7598 7599 /// Member lookup function that determines whether a given C++ 7600 /// method overrides a method in a base class, to be used with 7601 /// CXXRecordDecl::lookupInBases(). 7602 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7603 RecordDecl *BaseRecord = 7604 Specifier->getType()->getAs<RecordType>()->getDecl(); 7605 7606 DeclarationName Name = Method->getDeclName(); 7607 7608 // FIXME: Do we care about other names here too? 7609 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7610 // We really want to find the base class destructor here. 7611 QualType T = S->Context.getTypeDeclType(BaseRecord); 7612 CanQualType CT = S->Context.getCanonicalType(T); 7613 7614 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7615 } 7616 7617 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7618 Path.Decls = Path.Decls.slice(1)) { 7619 NamedDecl *D = Path.Decls.front(); 7620 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7621 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7622 return true; 7623 } 7624 } 7625 7626 return false; 7627 } 7628 }; 7629 7630 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7631 } // end anonymous namespace 7632 7633 /// Report an error regarding overriding, along with any relevant 7634 /// overridden methods. 7635 /// 7636 /// \param DiagID the primary error to report. 7637 /// \param MD the overriding method. 7638 /// \param OEK which overrides to include as notes. 7639 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7640 OverrideErrorKind OEK = OEK_All) { 7641 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7642 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7643 // This check (& the OEK parameter) could be replaced by a predicate, but 7644 // without lambdas that would be overkill. This is still nicer than writing 7645 // out the diag loop 3 times. 7646 if ((OEK == OEK_All) || 7647 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7648 (OEK == OEK_Deleted && O->isDeleted())) 7649 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7650 } 7651 } 7652 7653 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7654 /// and if so, check that it's a valid override and remember it. 7655 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7656 // Look for methods in base classes that this method might override. 7657 CXXBasePaths Paths; 7658 FindOverriddenMethod FOM; 7659 FOM.Method = MD; 7660 FOM.S = this; 7661 bool hasDeletedOverridenMethods = false; 7662 bool hasNonDeletedOverridenMethods = false; 7663 bool AddedAny = false; 7664 if (DC->lookupInBases(FOM, Paths)) { 7665 for (auto *I : Paths.found_decls()) { 7666 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7667 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7668 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7669 !CheckOverridingFunctionAttributes(MD, OldMD) && 7670 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7671 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7672 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7673 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7674 AddedAny = true; 7675 } 7676 } 7677 } 7678 } 7679 7680 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7681 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7682 } 7683 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7684 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7685 } 7686 7687 return AddedAny; 7688 } 7689 7690 namespace { 7691 // Struct for holding all of the extra arguments needed by 7692 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7693 struct ActOnFDArgs { 7694 Scope *S; 7695 Declarator &D; 7696 MultiTemplateParamsArg TemplateParamLists; 7697 bool AddToScope; 7698 }; 7699 } // end anonymous namespace 7700 7701 namespace { 7702 7703 // Callback to only accept typo corrections that have a non-zero edit distance. 7704 // Also only accept corrections that have the same parent decl. 7705 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 7706 public: 7707 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7708 CXXRecordDecl *Parent) 7709 : Context(Context), OriginalFD(TypoFD), 7710 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7711 7712 bool ValidateCandidate(const TypoCorrection &candidate) override { 7713 if (candidate.getEditDistance() == 0) 7714 return false; 7715 7716 SmallVector<unsigned, 1> MismatchedParams; 7717 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7718 CDeclEnd = candidate.end(); 7719 CDecl != CDeclEnd; ++CDecl) { 7720 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7721 7722 if (FD && !FD->hasBody() && 7723 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7724 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7725 CXXRecordDecl *Parent = MD->getParent(); 7726 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7727 return true; 7728 } else if (!ExpectedParent) { 7729 return true; 7730 } 7731 } 7732 } 7733 7734 return false; 7735 } 7736 7737 std::unique_ptr<CorrectionCandidateCallback> clone() override { 7738 return llvm::make_unique<DifferentNameValidatorCCC>(*this); 7739 } 7740 7741 private: 7742 ASTContext &Context; 7743 FunctionDecl *OriginalFD; 7744 CXXRecordDecl *ExpectedParent; 7745 }; 7746 7747 } // end anonymous namespace 7748 7749 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7750 TypoCorrectedFunctionDefinitions.insert(F); 7751 } 7752 7753 /// Generate diagnostics for an invalid function redeclaration. 7754 /// 7755 /// This routine handles generating the diagnostic messages for an invalid 7756 /// function redeclaration, including finding possible similar declarations 7757 /// or performing typo correction if there are no previous declarations with 7758 /// the same name. 7759 /// 7760 /// Returns a NamedDecl iff typo correction was performed and substituting in 7761 /// the new declaration name does not cause new errors. 7762 static NamedDecl *DiagnoseInvalidRedeclaration( 7763 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7764 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7765 DeclarationName Name = NewFD->getDeclName(); 7766 DeclContext *NewDC = NewFD->getDeclContext(); 7767 SmallVector<unsigned, 1> MismatchedParams; 7768 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7769 TypoCorrection Correction; 7770 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7771 unsigned DiagMsg = 7772 IsLocalFriend ? diag::err_no_matching_local_friend : 7773 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 7774 diag::err_member_decl_does_not_match; 7775 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7776 IsLocalFriend ? Sema::LookupLocalFriendName 7777 : Sema::LookupOrdinaryName, 7778 Sema::ForVisibleRedeclaration); 7779 7780 NewFD->setInvalidDecl(); 7781 if (IsLocalFriend) 7782 SemaRef.LookupName(Prev, S); 7783 else 7784 SemaRef.LookupQualifiedName(Prev, NewDC); 7785 assert(!Prev.isAmbiguous() && 7786 "Cannot have an ambiguity in previous-declaration lookup"); 7787 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7788 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 7789 MD ? MD->getParent() : nullptr); 7790 if (!Prev.empty()) { 7791 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7792 Func != FuncEnd; ++Func) { 7793 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7794 if (FD && 7795 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7796 // Add 1 to the index so that 0 can mean the mismatch didn't 7797 // involve a parameter 7798 unsigned ParamNum = 7799 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7800 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7801 } 7802 } 7803 // If the qualified name lookup yielded nothing, try typo correction 7804 } else if ((Correction = SemaRef.CorrectTypo( 7805 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7806 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 7807 IsLocalFriend ? nullptr : NewDC))) { 7808 // Set up everything for the call to ActOnFunctionDeclarator 7809 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7810 ExtraArgs.D.getIdentifierLoc()); 7811 Previous.clear(); 7812 Previous.setLookupName(Correction.getCorrection()); 7813 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7814 CDeclEnd = Correction.end(); 7815 CDecl != CDeclEnd; ++CDecl) { 7816 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7817 if (FD && !FD->hasBody() && 7818 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7819 Previous.addDecl(FD); 7820 } 7821 } 7822 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7823 7824 NamedDecl *Result; 7825 // Retry building the function declaration with the new previous 7826 // declarations, and with errors suppressed. 7827 { 7828 // Trap errors. 7829 Sema::SFINAETrap Trap(SemaRef); 7830 7831 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7832 // pieces need to verify the typo-corrected C++ declaration and hopefully 7833 // eliminate the need for the parameter pack ExtraArgs. 7834 Result = SemaRef.ActOnFunctionDeclarator( 7835 ExtraArgs.S, ExtraArgs.D, 7836 Correction.getCorrectionDecl()->getDeclContext(), 7837 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7838 ExtraArgs.AddToScope); 7839 7840 if (Trap.hasErrorOccurred()) 7841 Result = nullptr; 7842 } 7843 7844 if (Result) { 7845 // Determine which correction we picked. 7846 Decl *Canonical = Result->getCanonicalDecl(); 7847 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7848 I != E; ++I) 7849 if ((*I)->getCanonicalDecl() == Canonical) 7850 Correction.setCorrectionDecl(*I); 7851 7852 // Let Sema know about the correction. 7853 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7854 SemaRef.diagnoseTypo( 7855 Correction, 7856 SemaRef.PDiag(IsLocalFriend 7857 ? diag::err_no_matching_local_friend_suggest 7858 : diag::err_member_decl_does_not_match_suggest) 7859 << Name << NewDC << IsDefinition); 7860 return Result; 7861 } 7862 7863 // Pretend the typo correction never occurred 7864 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7865 ExtraArgs.D.getIdentifierLoc()); 7866 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7867 Previous.clear(); 7868 Previous.setLookupName(Name); 7869 } 7870 7871 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7872 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7873 7874 bool NewFDisConst = false; 7875 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7876 NewFDisConst = NewMD->isConst(); 7877 7878 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7879 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7880 NearMatch != NearMatchEnd; ++NearMatch) { 7881 FunctionDecl *FD = NearMatch->first; 7882 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7883 bool FDisConst = MD && MD->isConst(); 7884 bool IsMember = MD || !IsLocalFriend; 7885 7886 // FIXME: These notes are poorly worded for the local friend case. 7887 if (unsigned Idx = NearMatch->second) { 7888 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7889 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7890 if (Loc.isInvalid()) Loc = FD->getLocation(); 7891 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7892 : diag::note_local_decl_close_param_match) 7893 << Idx << FDParam->getType() 7894 << NewFD->getParamDecl(Idx - 1)->getType(); 7895 } else if (FDisConst != NewFDisConst) { 7896 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7897 << NewFDisConst << FD->getSourceRange().getEnd(); 7898 } else 7899 SemaRef.Diag(FD->getLocation(), 7900 IsMember ? diag::note_member_def_close_match 7901 : diag::note_local_decl_close_match); 7902 } 7903 return nullptr; 7904 } 7905 7906 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7907 switch (D.getDeclSpec().getStorageClassSpec()) { 7908 default: llvm_unreachable("Unknown storage class!"); 7909 case DeclSpec::SCS_auto: 7910 case DeclSpec::SCS_register: 7911 case DeclSpec::SCS_mutable: 7912 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7913 diag::err_typecheck_sclass_func); 7914 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7915 D.setInvalidType(); 7916 break; 7917 case DeclSpec::SCS_unspecified: break; 7918 case DeclSpec::SCS_extern: 7919 if (D.getDeclSpec().isExternInLinkageSpec()) 7920 return SC_None; 7921 return SC_Extern; 7922 case DeclSpec::SCS_static: { 7923 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7924 // C99 6.7.1p5: 7925 // The declaration of an identifier for a function that has 7926 // block scope shall have no explicit storage-class specifier 7927 // other than extern 7928 // See also (C++ [dcl.stc]p4). 7929 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7930 diag::err_static_block_func); 7931 break; 7932 } else 7933 return SC_Static; 7934 } 7935 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7936 } 7937 7938 // No explicit storage class has already been returned 7939 return SC_None; 7940 } 7941 7942 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7943 DeclContext *DC, QualType &R, 7944 TypeSourceInfo *TInfo, 7945 StorageClass SC, 7946 bool &IsVirtualOkay) { 7947 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7948 DeclarationName Name = NameInfo.getName(); 7949 7950 FunctionDecl *NewFD = nullptr; 7951 bool isInline = D.getDeclSpec().isInlineSpecified(); 7952 7953 if (!SemaRef.getLangOpts().CPlusPlus) { 7954 // Determine whether the function was written with a 7955 // prototype. This true when: 7956 // - there is a prototype in the declarator, or 7957 // - the type R of the function is some kind of typedef or other non- 7958 // attributed reference to a type name (which eventually refers to a 7959 // function type). 7960 bool HasPrototype = 7961 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7962 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7963 7964 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 7965 R, TInfo, SC, isInline, HasPrototype, false); 7966 if (D.isInvalidType()) 7967 NewFD->setInvalidDecl(); 7968 7969 return NewFD; 7970 } 7971 7972 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7973 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7974 7975 // Check that the return type is not an abstract class type. 7976 // For record types, this is done by the AbstractClassUsageDiagnoser once 7977 // the class has been completely parsed. 7978 if (!DC->isRecord() && 7979 SemaRef.RequireNonAbstractType( 7980 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7981 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7982 D.setInvalidType(); 7983 7984 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7985 // This is a C++ constructor declaration. 7986 assert(DC->isRecord() && 7987 "Constructors can only be declared in a member context"); 7988 7989 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7990 return CXXConstructorDecl::Create( 7991 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 7992 TInfo, isExplicit, isInline, 7993 /*isImplicitlyDeclared=*/false, isConstexpr); 7994 7995 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7996 // This is a C++ destructor declaration. 7997 if (DC->isRecord()) { 7998 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7999 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8000 CXXDestructorDecl *NewDD = 8001 CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(), 8002 NameInfo, R, TInfo, isInline, 8003 /*isImplicitlyDeclared=*/false); 8004 8005 // If the destructor needs an implicit exception specification, set it 8006 // now. FIXME: It'd be nice to be able to create the right type to start 8007 // with, but the type needs to reference the destructor declaration. 8008 if (SemaRef.getLangOpts().CPlusPlus11) 8009 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8010 8011 IsVirtualOkay = true; 8012 return NewDD; 8013 8014 } else { 8015 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8016 D.setInvalidType(); 8017 8018 // Create a FunctionDecl to satisfy the function definition parsing 8019 // code path. 8020 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8021 D.getIdentifierLoc(), Name, R, TInfo, SC, 8022 isInline, 8023 /*hasPrototype=*/true, isConstexpr); 8024 } 8025 8026 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8027 if (!DC->isRecord()) { 8028 SemaRef.Diag(D.getIdentifierLoc(), 8029 diag::err_conv_function_not_member); 8030 return nullptr; 8031 } 8032 8033 SemaRef.CheckConversionDeclarator(D, R, SC); 8034 IsVirtualOkay = true; 8035 return CXXConversionDecl::Create( 8036 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8037 TInfo, isInline, isExplicit, isConstexpr, SourceLocation()); 8038 8039 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8040 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8041 8042 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8043 isExplicit, NameInfo, R, TInfo, 8044 D.getEndLoc()); 8045 } else if (DC->isRecord()) { 8046 // If the name of the function is the same as the name of the record, 8047 // then this must be an invalid constructor that has a return type. 8048 // (The parser checks for a return type and makes the declarator a 8049 // constructor if it has no return type). 8050 if (Name.getAsIdentifierInfo() && 8051 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8052 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8053 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8054 << SourceRange(D.getIdentifierLoc()); 8055 return nullptr; 8056 } 8057 8058 // This is a C++ method declaration. 8059 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8060 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8061 TInfo, SC, isInline, isConstexpr, SourceLocation()); 8062 IsVirtualOkay = !Ret->isStatic(); 8063 return Ret; 8064 } else { 8065 bool isFriend = 8066 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8067 if (!isFriend && SemaRef.CurContext->isRecord()) 8068 return nullptr; 8069 8070 // Determine whether the function was written with a 8071 // prototype. This true when: 8072 // - we're in C++ (where every function has a prototype), 8073 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8074 R, TInfo, SC, isInline, true /*HasPrototype*/, 8075 isConstexpr); 8076 } 8077 } 8078 8079 enum OpenCLParamType { 8080 ValidKernelParam, 8081 PtrPtrKernelParam, 8082 PtrKernelParam, 8083 InvalidAddrSpacePtrKernelParam, 8084 InvalidKernelParam, 8085 RecordKernelParam 8086 }; 8087 8088 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8089 // Size dependent types are just typedefs to normal integer types 8090 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8091 // integers other than by their names. 8092 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8093 8094 // Remove typedefs one by one until we reach a typedef 8095 // for a size dependent type. 8096 QualType DesugaredTy = Ty; 8097 do { 8098 ArrayRef<StringRef> Names(SizeTypeNames); 8099 auto Match = llvm::find(Names, DesugaredTy.getAsString()); 8100 if (Names.end() != Match) 8101 return true; 8102 8103 Ty = DesugaredTy; 8104 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8105 } while (DesugaredTy != Ty); 8106 8107 return false; 8108 } 8109 8110 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8111 if (PT->isPointerType()) { 8112 QualType PointeeType = PT->getPointeeType(); 8113 if (PointeeType->isPointerType()) 8114 return PtrPtrKernelParam; 8115 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8116 PointeeType.getAddressSpace() == LangAS::opencl_private || 8117 PointeeType.getAddressSpace() == LangAS::Default) 8118 return InvalidAddrSpacePtrKernelParam; 8119 return PtrKernelParam; 8120 } 8121 8122 // OpenCL v1.2 s6.9.k: 8123 // Arguments to kernel functions in a program cannot be declared with the 8124 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8125 // uintptr_t or a struct and/or union that contain fields declared to be one 8126 // of these built-in scalar types. 8127 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8128 return InvalidKernelParam; 8129 8130 if (PT->isImageType()) 8131 return PtrKernelParam; 8132 8133 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8134 return InvalidKernelParam; 8135 8136 // OpenCL extension spec v1.2 s9.5: 8137 // This extension adds support for half scalar and vector types as built-in 8138 // types that can be used for arithmetic operations, conversions etc. 8139 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8140 return InvalidKernelParam; 8141 8142 if (PT->isRecordType()) 8143 return RecordKernelParam; 8144 8145 // Look into an array argument to check if it has a forbidden type. 8146 if (PT->isArrayType()) { 8147 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8148 // Call ourself to check an underlying type of an array. Since the 8149 // getPointeeOrArrayElementType returns an innermost type which is not an 8150 // array, this recursive call only happens once. 8151 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8152 } 8153 8154 return ValidKernelParam; 8155 } 8156 8157 static void checkIsValidOpenCLKernelParameter( 8158 Sema &S, 8159 Declarator &D, 8160 ParmVarDecl *Param, 8161 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8162 QualType PT = Param->getType(); 8163 8164 // Cache the valid types we encounter to avoid rechecking structs that are 8165 // used again 8166 if (ValidTypes.count(PT.getTypePtr())) 8167 return; 8168 8169 switch (getOpenCLKernelParameterType(S, PT)) { 8170 case PtrPtrKernelParam: 8171 // OpenCL v1.2 s6.9.a: 8172 // A kernel function argument cannot be declared as a 8173 // pointer to a pointer type. 8174 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8175 D.setInvalidType(); 8176 return; 8177 8178 case InvalidAddrSpacePtrKernelParam: 8179 // OpenCL v1.0 s6.5: 8180 // __kernel function arguments declared to be a pointer of a type can point 8181 // to one of the following address spaces only : __global, __local or 8182 // __constant. 8183 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8184 D.setInvalidType(); 8185 return; 8186 8187 // OpenCL v1.2 s6.9.k: 8188 // Arguments to kernel functions in a program cannot be declared with the 8189 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8190 // uintptr_t or a struct and/or union that contain fields declared to be 8191 // one of these built-in scalar types. 8192 8193 case InvalidKernelParam: 8194 // OpenCL v1.2 s6.8 n: 8195 // A kernel function argument cannot be declared 8196 // of event_t type. 8197 // Do not diagnose half type since it is diagnosed as invalid argument 8198 // type for any function elsewhere. 8199 if (!PT->isHalfType()) { 8200 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8201 8202 // Explain what typedefs are involved. 8203 const TypedefType *Typedef = nullptr; 8204 while ((Typedef = PT->getAs<TypedefType>())) { 8205 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8206 // SourceLocation may be invalid for a built-in type. 8207 if (Loc.isValid()) 8208 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8209 PT = Typedef->desugar(); 8210 } 8211 } 8212 8213 D.setInvalidType(); 8214 return; 8215 8216 case PtrKernelParam: 8217 case ValidKernelParam: 8218 ValidTypes.insert(PT.getTypePtr()); 8219 return; 8220 8221 case RecordKernelParam: 8222 break; 8223 } 8224 8225 // Track nested structs we will inspect 8226 SmallVector<const Decl *, 4> VisitStack; 8227 8228 // Track where we are in the nested structs. Items will migrate from 8229 // VisitStack to HistoryStack as we do the DFS for bad field. 8230 SmallVector<const FieldDecl *, 4> HistoryStack; 8231 HistoryStack.push_back(nullptr); 8232 8233 // At this point we already handled everything except of a RecordType or 8234 // an ArrayType of a RecordType. 8235 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8236 const RecordType *RecTy = 8237 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8238 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8239 8240 VisitStack.push_back(RecTy->getDecl()); 8241 assert(VisitStack.back() && "First decl null?"); 8242 8243 do { 8244 const Decl *Next = VisitStack.pop_back_val(); 8245 if (!Next) { 8246 assert(!HistoryStack.empty()); 8247 // Found a marker, we have gone up a level 8248 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8249 ValidTypes.insert(Hist->getType().getTypePtr()); 8250 8251 continue; 8252 } 8253 8254 // Adds everything except the original parameter declaration (which is not a 8255 // field itself) to the history stack. 8256 const RecordDecl *RD; 8257 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8258 HistoryStack.push_back(Field); 8259 8260 QualType FieldTy = Field->getType(); 8261 // Other field types (known to be valid or invalid) are handled while we 8262 // walk around RecordDecl::fields(). 8263 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8264 "Unexpected type."); 8265 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8266 8267 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8268 } else { 8269 RD = cast<RecordDecl>(Next); 8270 } 8271 8272 // Add a null marker so we know when we've gone back up a level 8273 VisitStack.push_back(nullptr); 8274 8275 for (const auto *FD : RD->fields()) { 8276 QualType QT = FD->getType(); 8277 8278 if (ValidTypes.count(QT.getTypePtr())) 8279 continue; 8280 8281 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8282 if (ParamType == ValidKernelParam) 8283 continue; 8284 8285 if (ParamType == RecordKernelParam) { 8286 VisitStack.push_back(FD); 8287 continue; 8288 } 8289 8290 // OpenCL v1.2 s6.9.p: 8291 // Arguments to kernel functions that are declared to be a struct or union 8292 // do not allow OpenCL objects to be passed as elements of the struct or 8293 // union. 8294 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8295 ParamType == InvalidAddrSpacePtrKernelParam) { 8296 S.Diag(Param->getLocation(), 8297 diag::err_record_with_pointers_kernel_param) 8298 << PT->isUnionType() 8299 << PT; 8300 } else { 8301 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8302 } 8303 8304 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8305 << OrigRecDecl->getDeclName(); 8306 8307 // We have an error, now let's go back up through history and show where 8308 // the offending field came from 8309 for (ArrayRef<const FieldDecl *>::const_iterator 8310 I = HistoryStack.begin() + 1, 8311 E = HistoryStack.end(); 8312 I != E; ++I) { 8313 const FieldDecl *OuterField = *I; 8314 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8315 << OuterField->getType(); 8316 } 8317 8318 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8319 << QT->isPointerType() 8320 << QT; 8321 D.setInvalidType(); 8322 return; 8323 } 8324 } while (!VisitStack.empty()); 8325 } 8326 8327 /// Find the DeclContext in which a tag is implicitly declared if we see an 8328 /// elaborated type specifier in the specified context, and lookup finds 8329 /// nothing. 8330 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8331 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8332 DC = DC->getParent(); 8333 return DC; 8334 } 8335 8336 /// Find the Scope in which a tag is implicitly declared if we see an 8337 /// elaborated type specifier in the specified context, and lookup finds 8338 /// nothing. 8339 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8340 while (S->isClassScope() || 8341 (LangOpts.CPlusPlus && 8342 S->isFunctionPrototypeScope()) || 8343 ((S->getFlags() & Scope::DeclScope) == 0) || 8344 (S->getEntity() && S->getEntity()->isTransparentContext())) 8345 S = S->getParent(); 8346 return S; 8347 } 8348 8349 NamedDecl* 8350 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8351 TypeSourceInfo *TInfo, LookupResult &Previous, 8352 MultiTemplateParamsArg TemplateParamLists, 8353 bool &AddToScope) { 8354 QualType R = TInfo->getType(); 8355 8356 assert(R->isFunctionType()); 8357 8358 // TODO: consider using NameInfo for diagnostic. 8359 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8360 DeclarationName Name = NameInfo.getName(); 8361 StorageClass SC = getFunctionStorageClass(*this, D); 8362 8363 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8364 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8365 diag::err_invalid_thread) 8366 << DeclSpec::getSpecifierName(TSCS); 8367 8368 if (D.isFirstDeclarationOfMember()) 8369 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8370 D.getIdentifierLoc()); 8371 8372 bool isFriend = false; 8373 FunctionTemplateDecl *FunctionTemplate = nullptr; 8374 bool isMemberSpecialization = false; 8375 bool isFunctionTemplateSpecialization = false; 8376 8377 bool isDependentClassScopeExplicitSpecialization = false; 8378 bool HasExplicitTemplateArgs = false; 8379 TemplateArgumentListInfo TemplateArgs; 8380 8381 bool isVirtualOkay = false; 8382 8383 DeclContext *OriginalDC = DC; 8384 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8385 8386 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8387 isVirtualOkay); 8388 if (!NewFD) return nullptr; 8389 8390 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8391 NewFD->setTopLevelDeclInObjCContainer(); 8392 8393 // Set the lexical context. If this is a function-scope declaration, or has a 8394 // C++ scope specifier, or is the object of a friend declaration, the lexical 8395 // context will be different from the semantic context. 8396 NewFD->setLexicalDeclContext(CurContext); 8397 8398 if (IsLocalExternDecl) 8399 NewFD->setLocalExternDecl(); 8400 8401 if (getLangOpts().CPlusPlus) { 8402 bool isInline = D.getDeclSpec().isInlineSpecified(); 8403 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8404 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8405 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8406 isFriend = D.getDeclSpec().isFriendSpecified(); 8407 if (isFriend && !isInline && D.isFunctionDefinition()) { 8408 // C++ [class.friend]p5 8409 // A function can be defined in a friend declaration of a 8410 // class . . . . Such a function is implicitly inline. 8411 NewFD->setImplicitlyInline(); 8412 } 8413 8414 // If this is a method defined in an __interface, and is not a constructor 8415 // or an overloaded operator, then set the pure flag (isVirtual will already 8416 // return true). 8417 if (const CXXRecordDecl *Parent = 8418 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8419 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8420 NewFD->setPure(true); 8421 8422 // C++ [class.union]p2 8423 // A union can have member functions, but not virtual functions. 8424 if (isVirtual && Parent->isUnion()) 8425 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8426 } 8427 8428 SetNestedNameSpecifier(*this, NewFD, D); 8429 isMemberSpecialization = false; 8430 isFunctionTemplateSpecialization = false; 8431 if (D.isInvalidType()) 8432 NewFD->setInvalidDecl(); 8433 8434 // Match up the template parameter lists with the scope specifier, then 8435 // determine whether we have a template or a template specialization. 8436 bool Invalid = false; 8437 if (TemplateParameterList *TemplateParams = 8438 MatchTemplateParametersToScopeSpecifier( 8439 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8440 D.getCXXScopeSpec(), 8441 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8442 ? D.getName().TemplateId 8443 : nullptr, 8444 TemplateParamLists, isFriend, isMemberSpecialization, 8445 Invalid)) { 8446 if (TemplateParams->size() > 0) { 8447 // This is a function template 8448 8449 // Check that we can declare a template here. 8450 if (CheckTemplateDeclScope(S, TemplateParams)) 8451 NewFD->setInvalidDecl(); 8452 8453 // A destructor cannot be a template. 8454 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8455 Diag(NewFD->getLocation(), diag::err_destructor_template); 8456 NewFD->setInvalidDecl(); 8457 } 8458 8459 // If we're adding a template to a dependent context, we may need to 8460 // rebuilding some of the types used within the template parameter list, 8461 // now that we know what the current instantiation is. 8462 if (DC->isDependentContext()) { 8463 ContextRAII SavedContext(*this, DC); 8464 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8465 Invalid = true; 8466 } 8467 8468 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8469 NewFD->getLocation(), 8470 Name, TemplateParams, 8471 NewFD); 8472 FunctionTemplate->setLexicalDeclContext(CurContext); 8473 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8474 8475 // For source fidelity, store the other template param lists. 8476 if (TemplateParamLists.size() > 1) { 8477 NewFD->setTemplateParameterListsInfo(Context, 8478 TemplateParamLists.drop_back(1)); 8479 } 8480 } else { 8481 // This is a function template specialization. 8482 isFunctionTemplateSpecialization = true; 8483 // For source fidelity, store all the template param lists. 8484 if (TemplateParamLists.size() > 0) 8485 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8486 8487 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8488 if (isFriend) { 8489 // We want to remove the "template<>", found here. 8490 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8491 8492 // If we remove the template<> and the name is not a 8493 // template-id, we're actually silently creating a problem: 8494 // the friend declaration will refer to an untemplated decl, 8495 // and clearly the user wants a template specialization. So 8496 // we need to insert '<>' after the name. 8497 SourceLocation InsertLoc; 8498 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8499 InsertLoc = D.getName().getSourceRange().getEnd(); 8500 InsertLoc = getLocForEndOfToken(InsertLoc); 8501 } 8502 8503 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8504 << Name << RemoveRange 8505 << FixItHint::CreateRemoval(RemoveRange) 8506 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8507 } 8508 } 8509 } else { 8510 // All template param lists were matched against the scope specifier: 8511 // this is NOT (an explicit specialization of) a template. 8512 if (TemplateParamLists.size() > 0) 8513 // For source fidelity, store all the template param lists. 8514 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8515 } 8516 8517 if (Invalid) { 8518 NewFD->setInvalidDecl(); 8519 if (FunctionTemplate) 8520 FunctionTemplate->setInvalidDecl(); 8521 } 8522 8523 // C++ [dcl.fct.spec]p5: 8524 // The virtual specifier shall only be used in declarations of 8525 // nonstatic class member functions that appear within a 8526 // member-specification of a class declaration; see 10.3. 8527 // 8528 if (isVirtual && !NewFD->isInvalidDecl()) { 8529 if (!isVirtualOkay) { 8530 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8531 diag::err_virtual_non_function); 8532 } else if (!CurContext->isRecord()) { 8533 // 'virtual' was specified outside of the class. 8534 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8535 diag::err_virtual_out_of_class) 8536 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8537 } else if (NewFD->getDescribedFunctionTemplate()) { 8538 // C++ [temp.mem]p3: 8539 // A member function template shall not be virtual. 8540 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8541 diag::err_virtual_member_function_template) 8542 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8543 } else { 8544 // Okay: Add virtual to the method. 8545 NewFD->setVirtualAsWritten(true); 8546 } 8547 8548 if (getLangOpts().CPlusPlus14 && 8549 NewFD->getReturnType()->isUndeducedType()) 8550 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8551 } 8552 8553 if (getLangOpts().CPlusPlus14 && 8554 (NewFD->isDependentContext() || 8555 (isFriend && CurContext->isDependentContext())) && 8556 NewFD->getReturnType()->isUndeducedType()) { 8557 // If the function template is referenced directly (for instance, as a 8558 // member of the current instantiation), pretend it has a dependent type. 8559 // This is not really justified by the standard, but is the only sane 8560 // thing to do. 8561 // FIXME: For a friend function, we have not marked the function as being 8562 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8563 const FunctionProtoType *FPT = 8564 NewFD->getType()->castAs<FunctionProtoType>(); 8565 QualType Result = 8566 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8567 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8568 FPT->getExtProtoInfo())); 8569 } 8570 8571 // C++ [dcl.fct.spec]p3: 8572 // The inline specifier shall not appear on a block scope function 8573 // declaration. 8574 if (isInline && !NewFD->isInvalidDecl()) { 8575 if (CurContext->isFunctionOrMethod()) { 8576 // 'inline' is not allowed on block scope function declaration. 8577 Diag(D.getDeclSpec().getInlineSpecLoc(), 8578 diag::err_inline_declaration_block_scope) << Name 8579 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8580 } 8581 } 8582 8583 // C++ [dcl.fct.spec]p6: 8584 // The explicit specifier shall be used only in the declaration of a 8585 // constructor or conversion function within its class definition; 8586 // see 12.3.1 and 12.3.2. 8587 if (isExplicit && !NewFD->isInvalidDecl() && 8588 !isa<CXXDeductionGuideDecl>(NewFD)) { 8589 if (!CurContext->isRecord()) { 8590 // 'explicit' was specified outside of the class. 8591 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8592 diag::err_explicit_out_of_class) 8593 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8594 } else if (!isa<CXXConstructorDecl>(NewFD) && 8595 !isa<CXXConversionDecl>(NewFD)) { 8596 // 'explicit' was specified on a function that wasn't a constructor 8597 // or conversion function. 8598 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8599 diag::err_explicit_non_ctor_or_conv_function) 8600 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8601 } 8602 } 8603 8604 if (isConstexpr) { 8605 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8606 // are implicitly inline. 8607 NewFD->setImplicitlyInline(); 8608 8609 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8610 // be either constructors or to return a literal type. Therefore, 8611 // destructors cannot be declared constexpr. 8612 if (isa<CXXDestructorDecl>(NewFD)) 8613 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8614 } 8615 8616 // If __module_private__ was specified, mark the function accordingly. 8617 if (D.getDeclSpec().isModulePrivateSpecified()) { 8618 if (isFunctionTemplateSpecialization) { 8619 SourceLocation ModulePrivateLoc 8620 = D.getDeclSpec().getModulePrivateSpecLoc(); 8621 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8622 << 0 8623 << FixItHint::CreateRemoval(ModulePrivateLoc); 8624 } else { 8625 NewFD->setModulePrivate(); 8626 if (FunctionTemplate) 8627 FunctionTemplate->setModulePrivate(); 8628 } 8629 } 8630 8631 if (isFriend) { 8632 if (FunctionTemplate) { 8633 FunctionTemplate->setObjectOfFriendDecl(); 8634 FunctionTemplate->setAccess(AS_public); 8635 } 8636 NewFD->setObjectOfFriendDecl(); 8637 NewFD->setAccess(AS_public); 8638 } 8639 8640 // If a function is defined as defaulted or deleted, mark it as such now. 8641 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8642 // definition kind to FDK_Definition. 8643 switch (D.getFunctionDefinitionKind()) { 8644 case FDK_Declaration: 8645 case FDK_Definition: 8646 break; 8647 8648 case FDK_Defaulted: 8649 NewFD->setDefaulted(); 8650 break; 8651 8652 case FDK_Deleted: 8653 NewFD->setDeletedAsWritten(); 8654 break; 8655 } 8656 8657 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8658 D.isFunctionDefinition()) { 8659 // C++ [class.mfct]p2: 8660 // A member function may be defined (8.4) in its class definition, in 8661 // which case it is an inline member function (7.1.2) 8662 NewFD->setImplicitlyInline(); 8663 } 8664 8665 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8666 !CurContext->isRecord()) { 8667 // C++ [class.static]p1: 8668 // A data or function member of a class may be declared static 8669 // in a class definition, in which case it is a static member of 8670 // the class. 8671 8672 // Complain about the 'static' specifier if it's on an out-of-line 8673 // member function definition. 8674 8675 // MSVC permits the use of a 'static' storage specifier on an out-of-line 8676 // member function template declaration, warn about this. 8677 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8678 NewFD->getDescribedFunctionTemplate() && getLangOpts().MSVCCompat 8679 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 8680 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8681 } 8682 8683 // C++11 [except.spec]p15: 8684 // A deallocation function with no exception-specification is treated 8685 // as if it were specified with noexcept(true). 8686 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8687 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8688 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8689 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8690 NewFD->setType(Context.getFunctionType( 8691 FPT->getReturnType(), FPT->getParamTypes(), 8692 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8693 } 8694 8695 // Filter out previous declarations that don't match the scope. 8696 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8697 D.getCXXScopeSpec().isNotEmpty() || 8698 isMemberSpecialization || 8699 isFunctionTemplateSpecialization); 8700 8701 // Handle GNU asm-label extension (encoded as an attribute). 8702 if (Expr *E = (Expr*) D.getAsmLabel()) { 8703 // The parser guarantees this is a string. 8704 StringLiteral *SE = cast<StringLiteral>(E); 8705 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8706 SE->getString(), 0)); 8707 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8708 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8709 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8710 if (I != ExtnameUndeclaredIdentifiers.end()) { 8711 if (isDeclExternC(NewFD)) { 8712 NewFD->addAttr(I->second); 8713 ExtnameUndeclaredIdentifiers.erase(I); 8714 } else 8715 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8716 << /*Variable*/0 << NewFD; 8717 } 8718 } 8719 8720 // Copy the parameter declarations from the declarator D to the function 8721 // declaration NewFD, if they are available. First scavenge them into Params. 8722 SmallVector<ParmVarDecl*, 16> Params; 8723 unsigned FTIIdx; 8724 if (D.isFunctionDeclarator(FTIIdx)) { 8725 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8726 8727 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8728 // function that takes no arguments, not a function that takes a 8729 // single void argument. 8730 // We let through "const void" here because Sema::GetTypeForDeclarator 8731 // already checks for that case. 8732 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8733 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8734 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8735 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8736 Param->setDeclContext(NewFD); 8737 Params.push_back(Param); 8738 8739 if (Param->isInvalidDecl()) 8740 NewFD->setInvalidDecl(); 8741 } 8742 } 8743 8744 if (!getLangOpts().CPlusPlus) { 8745 // In C, find all the tag declarations from the prototype and move them 8746 // into the function DeclContext. Remove them from the surrounding tag 8747 // injection context of the function, which is typically but not always 8748 // the TU. 8749 DeclContext *PrototypeTagContext = 8750 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8751 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8752 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8753 8754 // We don't want to reparent enumerators. Look at their parent enum 8755 // instead. 8756 if (!TD) { 8757 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8758 TD = cast<EnumDecl>(ECD->getDeclContext()); 8759 } 8760 if (!TD) 8761 continue; 8762 DeclContext *TagDC = TD->getLexicalDeclContext(); 8763 if (!TagDC->containsDecl(TD)) 8764 continue; 8765 TagDC->removeDecl(TD); 8766 TD->setDeclContext(NewFD); 8767 NewFD->addDecl(TD); 8768 8769 // Preserve the lexical DeclContext if it is not the surrounding tag 8770 // injection context of the FD. In this example, the semantic context of 8771 // E will be f and the lexical context will be S, while both the 8772 // semantic and lexical contexts of S will be f: 8773 // void f(struct S { enum E { a } f; } s); 8774 if (TagDC != PrototypeTagContext) 8775 TD->setLexicalDeclContext(TagDC); 8776 } 8777 } 8778 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8779 // When we're declaring a function with a typedef, typeof, etc as in the 8780 // following example, we'll need to synthesize (unnamed) 8781 // parameters for use in the declaration. 8782 // 8783 // @code 8784 // typedef void fn(int); 8785 // fn f; 8786 // @endcode 8787 8788 // Synthesize a parameter for each argument type. 8789 for (const auto &AI : FT->param_types()) { 8790 ParmVarDecl *Param = 8791 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8792 Param->setScopeInfo(0, Params.size()); 8793 Params.push_back(Param); 8794 } 8795 } else { 8796 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8797 "Should not need args for typedef of non-prototype fn"); 8798 } 8799 8800 // Finally, we know we have the right number of parameters, install them. 8801 NewFD->setParams(Params); 8802 8803 if (D.getDeclSpec().isNoreturnSpecified()) 8804 NewFD->addAttr( 8805 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8806 Context, 0)); 8807 8808 // Functions returning a variably modified type violate C99 6.7.5.2p2 8809 // because all functions have linkage. 8810 if (!NewFD->isInvalidDecl() && 8811 NewFD->getReturnType()->isVariablyModifiedType()) { 8812 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8813 NewFD->setInvalidDecl(); 8814 } 8815 8816 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8817 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8818 !NewFD->hasAttr<SectionAttr>()) { 8819 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8820 PragmaClangTextSection.SectionName, 8821 PragmaClangTextSection.PragmaLocation)); 8822 } 8823 8824 // Apply an implicit SectionAttr if #pragma code_seg is active. 8825 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8826 !NewFD->hasAttr<SectionAttr>()) { 8827 NewFD->addAttr( 8828 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8829 CodeSegStack.CurrentValue->getString(), 8830 CodeSegStack.CurrentPragmaLocation)); 8831 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8832 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8833 ASTContext::PSF_Read, 8834 NewFD)) 8835 NewFD->dropAttr<SectionAttr>(); 8836 } 8837 8838 // Apply an implicit CodeSegAttr from class declspec or 8839 // apply an implicit SectionAttr from #pragma code_seg if active. 8840 if (!NewFD->hasAttr<CodeSegAttr>()) { 8841 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 8842 D.isFunctionDefinition())) { 8843 NewFD->addAttr(SAttr); 8844 } 8845 } 8846 8847 // Handle attributes. 8848 ProcessDeclAttributes(S, NewFD, D); 8849 8850 if (getLangOpts().OpenCL) { 8851 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8852 // type declaration will generate a compilation error. 8853 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8854 if (AddressSpace != LangAS::Default) { 8855 Diag(NewFD->getLocation(), 8856 diag::err_opencl_return_value_with_address_space); 8857 NewFD->setInvalidDecl(); 8858 } 8859 } 8860 8861 if (!getLangOpts().CPlusPlus) { 8862 // Perform semantic checking on the function declaration. 8863 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8864 CheckMain(NewFD, D.getDeclSpec()); 8865 8866 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8867 CheckMSVCRTEntryPoint(NewFD); 8868 8869 if (!NewFD->isInvalidDecl()) 8870 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8871 isMemberSpecialization)); 8872 else if (!Previous.empty()) 8873 // Recover gracefully from an invalid redeclaration. 8874 D.setRedeclaration(true); 8875 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8876 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8877 "previous declaration set still overloaded"); 8878 8879 // Diagnose no-prototype function declarations with calling conventions that 8880 // don't support variadic calls. Only do this in C and do it after merging 8881 // possibly prototyped redeclarations. 8882 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8883 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8884 CallingConv CC = FT->getExtInfo().getCC(); 8885 if (!supportsVariadicCall(CC)) { 8886 // Windows system headers sometimes accidentally use stdcall without 8887 // (void) parameters, so we relax this to a warning. 8888 int DiagID = 8889 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8890 Diag(NewFD->getLocation(), DiagID) 8891 << FunctionType::getNameForCallConv(CC); 8892 } 8893 } 8894 } else { 8895 // C++11 [replacement.functions]p3: 8896 // The program's definitions shall not be specified as inline. 8897 // 8898 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8899 // 8900 // Suppress the diagnostic if the function is __attribute__((used)), since 8901 // that forces an external definition to be emitted. 8902 if (D.getDeclSpec().isInlineSpecified() && 8903 NewFD->isReplaceableGlobalAllocationFunction() && 8904 !NewFD->hasAttr<UsedAttr>()) 8905 Diag(D.getDeclSpec().getInlineSpecLoc(), 8906 diag::ext_operator_new_delete_declared_inline) 8907 << NewFD->getDeclName(); 8908 8909 // If the declarator is a template-id, translate the parser's template 8910 // argument list into our AST format. 8911 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8912 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8913 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8914 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8915 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8916 TemplateId->NumArgs); 8917 translateTemplateArguments(TemplateArgsPtr, 8918 TemplateArgs); 8919 8920 HasExplicitTemplateArgs = true; 8921 8922 if (NewFD->isInvalidDecl()) { 8923 HasExplicitTemplateArgs = false; 8924 } else if (FunctionTemplate) { 8925 // Function template with explicit template arguments. 8926 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8927 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8928 8929 HasExplicitTemplateArgs = false; 8930 } else { 8931 assert((isFunctionTemplateSpecialization || 8932 D.getDeclSpec().isFriendSpecified()) && 8933 "should have a 'template<>' for this decl"); 8934 // "friend void foo<>(int);" is an implicit specialization decl. 8935 isFunctionTemplateSpecialization = true; 8936 } 8937 } else if (isFriend && isFunctionTemplateSpecialization) { 8938 // This combination is only possible in a recovery case; the user 8939 // wrote something like: 8940 // template <> friend void foo(int); 8941 // which we're recovering from as if the user had written: 8942 // friend void foo<>(int); 8943 // Go ahead and fake up a template id. 8944 HasExplicitTemplateArgs = true; 8945 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8946 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8947 } 8948 8949 // We do not add HD attributes to specializations here because 8950 // they may have different constexpr-ness compared to their 8951 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8952 // may end up with different effective targets. Instead, a 8953 // specialization inherits its target attributes from its template 8954 // in the CheckFunctionTemplateSpecialization() call below. 8955 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8956 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8957 8958 // If it's a friend (and only if it's a friend), it's possible 8959 // that either the specialized function type or the specialized 8960 // template is dependent, and therefore matching will fail. In 8961 // this case, don't check the specialization yet. 8962 bool InstantiationDependent = false; 8963 if (isFunctionTemplateSpecialization && isFriend && 8964 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8965 TemplateSpecializationType::anyDependentTemplateArguments( 8966 TemplateArgs, 8967 InstantiationDependent))) { 8968 assert(HasExplicitTemplateArgs && 8969 "friend function specialization without template args"); 8970 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8971 Previous)) 8972 NewFD->setInvalidDecl(); 8973 } else if (isFunctionTemplateSpecialization) { 8974 if (CurContext->isDependentContext() && CurContext->isRecord() 8975 && !isFriend) { 8976 isDependentClassScopeExplicitSpecialization = true; 8977 } else if (!NewFD->isInvalidDecl() && 8978 CheckFunctionTemplateSpecialization( 8979 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8980 Previous)) 8981 NewFD->setInvalidDecl(); 8982 8983 // C++ [dcl.stc]p1: 8984 // A storage-class-specifier shall not be specified in an explicit 8985 // specialization (14.7.3) 8986 FunctionTemplateSpecializationInfo *Info = 8987 NewFD->getTemplateSpecializationInfo(); 8988 if (Info && SC != SC_None) { 8989 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8990 Diag(NewFD->getLocation(), 8991 diag::err_explicit_specialization_inconsistent_storage_class) 8992 << SC 8993 << FixItHint::CreateRemoval( 8994 D.getDeclSpec().getStorageClassSpecLoc()); 8995 8996 else 8997 Diag(NewFD->getLocation(), 8998 diag::ext_explicit_specialization_storage_class) 8999 << FixItHint::CreateRemoval( 9000 D.getDeclSpec().getStorageClassSpecLoc()); 9001 } 9002 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9003 if (CheckMemberSpecialization(NewFD, Previous)) 9004 NewFD->setInvalidDecl(); 9005 } 9006 9007 // Perform semantic checking on the function declaration. 9008 if (!isDependentClassScopeExplicitSpecialization) { 9009 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9010 CheckMain(NewFD, D.getDeclSpec()); 9011 9012 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9013 CheckMSVCRTEntryPoint(NewFD); 9014 9015 if (!NewFD->isInvalidDecl()) 9016 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9017 isMemberSpecialization)); 9018 else if (!Previous.empty()) 9019 // Recover gracefully from an invalid redeclaration. 9020 D.setRedeclaration(true); 9021 } 9022 9023 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9024 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9025 "previous declaration set still overloaded"); 9026 9027 NamedDecl *PrincipalDecl = (FunctionTemplate 9028 ? cast<NamedDecl>(FunctionTemplate) 9029 : NewFD); 9030 9031 if (isFriend && NewFD->getPreviousDecl()) { 9032 AccessSpecifier Access = AS_public; 9033 if (!NewFD->isInvalidDecl()) 9034 Access = NewFD->getPreviousDecl()->getAccess(); 9035 9036 NewFD->setAccess(Access); 9037 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9038 } 9039 9040 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9041 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9042 PrincipalDecl->setNonMemberOperator(); 9043 9044 // If we have a function template, check the template parameter 9045 // list. This will check and merge default template arguments. 9046 if (FunctionTemplate) { 9047 FunctionTemplateDecl *PrevTemplate = 9048 FunctionTemplate->getPreviousDecl(); 9049 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9050 PrevTemplate ? PrevTemplate->getTemplateParameters() 9051 : nullptr, 9052 D.getDeclSpec().isFriendSpecified() 9053 ? (D.isFunctionDefinition() 9054 ? TPC_FriendFunctionTemplateDefinition 9055 : TPC_FriendFunctionTemplate) 9056 : (D.getCXXScopeSpec().isSet() && 9057 DC && DC->isRecord() && 9058 DC->isDependentContext()) 9059 ? TPC_ClassTemplateMember 9060 : TPC_FunctionTemplate); 9061 } 9062 9063 if (NewFD->isInvalidDecl()) { 9064 // Ignore all the rest of this. 9065 } else if (!D.isRedeclaration()) { 9066 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9067 AddToScope }; 9068 // Fake up an access specifier if it's supposed to be a class member. 9069 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9070 NewFD->setAccess(AS_public); 9071 9072 // Qualified decls generally require a previous declaration. 9073 if (D.getCXXScopeSpec().isSet()) { 9074 // ...with the major exception of templated-scope or 9075 // dependent-scope friend declarations. 9076 9077 // TODO: we currently also suppress this check in dependent 9078 // contexts because (1) the parameter depth will be off when 9079 // matching friend templates and (2) we might actually be 9080 // selecting a friend based on a dependent factor. But there 9081 // are situations where these conditions don't apply and we 9082 // can actually do this check immediately. 9083 // 9084 // Unless the scope is dependent, it's always an error if qualified 9085 // redeclaration lookup found nothing at all. Diagnose that now; 9086 // nothing will diagnose that error later. 9087 if (isFriend && 9088 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9089 (!Previous.empty() && (TemplateParamLists.size() || 9090 CurContext->isDependentContext())))) { 9091 // ignore these 9092 } else { 9093 // The user tried to provide an out-of-line definition for a 9094 // function that is a member of a class or namespace, but there 9095 // was no such member function declared (C++ [class.mfct]p2, 9096 // C++ [namespace.memdef]p2). For example: 9097 // 9098 // class X { 9099 // void f() const; 9100 // }; 9101 // 9102 // void X::f() { } // ill-formed 9103 // 9104 // Complain about this problem, and attempt to suggest close 9105 // matches (e.g., those that differ only in cv-qualifiers and 9106 // whether the parameter types are references). 9107 9108 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9109 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9110 AddToScope = ExtraArgs.AddToScope; 9111 return Result; 9112 } 9113 } 9114 9115 // Unqualified local friend declarations are required to resolve 9116 // to something. 9117 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9118 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9119 *this, Previous, NewFD, ExtraArgs, true, S)) { 9120 AddToScope = ExtraArgs.AddToScope; 9121 return Result; 9122 } 9123 } 9124 } else if (!D.isFunctionDefinition() && 9125 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9126 !isFriend && !isFunctionTemplateSpecialization && 9127 !isMemberSpecialization) { 9128 // An out-of-line member function declaration must also be a 9129 // definition (C++ [class.mfct]p2). 9130 // Note that this is not the case for explicit specializations of 9131 // function templates or member functions of class templates, per 9132 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9133 // extension for compatibility with old SWIG code which likes to 9134 // generate them. 9135 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9136 << D.getCXXScopeSpec().getRange(); 9137 } 9138 } 9139 9140 ProcessPragmaWeak(S, NewFD); 9141 checkAttributesAfterMerging(*this, *NewFD); 9142 9143 AddKnownFunctionAttributes(NewFD); 9144 9145 if (NewFD->hasAttr<OverloadableAttr>() && 9146 !NewFD->getType()->getAs<FunctionProtoType>()) { 9147 Diag(NewFD->getLocation(), 9148 diag::err_attribute_overloadable_no_prototype) 9149 << NewFD; 9150 9151 // Turn this into a variadic function with no parameters. 9152 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9153 FunctionProtoType::ExtProtoInfo EPI( 9154 Context.getDefaultCallingConvention(true, false)); 9155 EPI.Variadic = true; 9156 EPI.ExtInfo = FT->getExtInfo(); 9157 9158 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9159 NewFD->setType(R); 9160 } 9161 9162 // If there's a #pragma GCC visibility in scope, and this isn't a class 9163 // member, set the visibility of this function. 9164 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9165 AddPushedVisibilityAttribute(NewFD); 9166 9167 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9168 // marking the function. 9169 AddCFAuditedAttribute(NewFD); 9170 9171 // If this is a function definition, check if we have to apply optnone due to 9172 // a pragma. 9173 if(D.isFunctionDefinition()) 9174 AddRangeBasedOptnone(NewFD); 9175 9176 // If this is the first declaration of an extern C variable, update 9177 // the map of such variables. 9178 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9179 isIncompleteDeclExternC(*this, NewFD)) 9180 RegisterLocallyScopedExternCDecl(NewFD, S); 9181 9182 // Set this FunctionDecl's range up to the right paren. 9183 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9184 9185 if (D.isRedeclaration() && !Previous.empty()) { 9186 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9187 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9188 isMemberSpecialization || 9189 isFunctionTemplateSpecialization, 9190 D.isFunctionDefinition()); 9191 } 9192 9193 if (getLangOpts().CUDA) { 9194 IdentifierInfo *II = NewFD->getIdentifier(); 9195 if (II && II->isStr(getCudaConfigureFuncName()) && 9196 !NewFD->isInvalidDecl() && 9197 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9198 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9199 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9200 << getCudaConfigureFuncName(); 9201 Context.setcudaConfigureCallDecl(NewFD); 9202 } 9203 9204 // Variadic functions, other than a *declaration* of printf, are not allowed 9205 // in device-side CUDA code, unless someone passed 9206 // -fcuda-allow-variadic-functions. 9207 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9208 (NewFD->hasAttr<CUDADeviceAttr>() || 9209 NewFD->hasAttr<CUDAGlobalAttr>()) && 9210 !(II && II->isStr("printf") && NewFD->isExternC() && 9211 !D.isFunctionDefinition())) { 9212 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9213 } 9214 } 9215 9216 MarkUnusedFileScopedDecl(NewFD); 9217 9218 if (getLangOpts().CPlusPlus) { 9219 if (FunctionTemplate) { 9220 if (NewFD->isInvalidDecl()) 9221 FunctionTemplate->setInvalidDecl(); 9222 return FunctionTemplate; 9223 } 9224 9225 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9226 CompleteMemberSpecialization(NewFD, Previous); 9227 } 9228 9229 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9230 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9231 if ((getLangOpts().OpenCLVersion >= 120) 9232 && (SC == SC_Static)) { 9233 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9234 D.setInvalidType(); 9235 } 9236 9237 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9238 if (!NewFD->getReturnType()->isVoidType()) { 9239 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9240 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9241 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9242 : FixItHint()); 9243 D.setInvalidType(); 9244 } 9245 9246 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9247 for (auto Param : NewFD->parameters()) 9248 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9249 } 9250 for (const ParmVarDecl *Param : NewFD->parameters()) { 9251 QualType PT = Param->getType(); 9252 9253 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9254 // types. 9255 if (getLangOpts().OpenCLVersion >= 200) { 9256 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9257 QualType ElemTy = PipeTy->getElementType(); 9258 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9259 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9260 D.setInvalidType(); 9261 } 9262 } 9263 } 9264 } 9265 9266 // Here we have an function template explicit specialization at class scope. 9267 // The actual specialization will be postponed to template instatiation 9268 // time via the ClassScopeFunctionSpecializationDecl node. 9269 if (isDependentClassScopeExplicitSpecialization) { 9270 ClassScopeFunctionSpecializationDecl *NewSpec = 9271 ClassScopeFunctionSpecializationDecl::Create( 9272 Context, CurContext, NewFD->getLocation(), 9273 cast<CXXMethodDecl>(NewFD), 9274 HasExplicitTemplateArgs, TemplateArgs); 9275 CurContext->addDecl(NewSpec); 9276 AddToScope = false; 9277 } 9278 9279 // Diagnose availability attributes. Availability cannot be used on functions 9280 // that are run during load/unload. 9281 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9282 if (NewFD->hasAttr<ConstructorAttr>()) { 9283 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9284 << 1; 9285 NewFD->dropAttr<AvailabilityAttr>(); 9286 } 9287 if (NewFD->hasAttr<DestructorAttr>()) { 9288 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9289 << 2; 9290 NewFD->dropAttr<AvailabilityAttr>(); 9291 } 9292 } 9293 9294 return NewFD; 9295 } 9296 9297 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9298 /// when __declspec(code_seg) "is applied to a class, all member functions of 9299 /// the class and nested classes -- this includes compiler-generated special 9300 /// member functions -- are put in the specified segment." 9301 /// The actual behavior is a little more complicated. The Microsoft compiler 9302 /// won't check outer classes if there is an active value from #pragma code_seg. 9303 /// The CodeSeg is always applied from the direct parent but only from outer 9304 /// classes when the #pragma code_seg stack is empty. See: 9305 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9306 /// available since MS has removed the page. 9307 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9308 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9309 if (!Method) 9310 return nullptr; 9311 const CXXRecordDecl *Parent = Method->getParent(); 9312 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9313 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9314 NewAttr->setImplicit(true); 9315 return NewAttr; 9316 } 9317 9318 // The Microsoft compiler won't check outer classes for the CodeSeg 9319 // when the #pragma code_seg stack is active. 9320 if (S.CodeSegStack.CurrentValue) 9321 return nullptr; 9322 9323 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9324 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9325 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9326 NewAttr->setImplicit(true); 9327 return NewAttr; 9328 } 9329 } 9330 return nullptr; 9331 } 9332 9333 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9334 /// containing class. Otherwise it will return implicit SectionAttr if the 9335 /// function is a definition and there is an active value on CodeSegStack 9336 /// (from the current #pragma code-seg value). 9337 /// 9338 /// \param FD Function being declared. 9339 /// \param IsDefinition Whether it is a definition or just a declarartion. 9340 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9341 /// nullptr if no attribute should be added. 9342 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9343 bool IsDefinition) { 9344 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9345 return A; 9346 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9347 CodeSegStack.CurrentValue) { 9348 return SectionAttr::CreateImplicit(getASTContext(), 9349 SectionAttr::Declspec_allocate, 9350 CodeSegStack.CurrentValue->getString(), 9351 CodeSegStack.CurrentPragmaLocation); 9352 } 9353 return nullptr; 9354 } 9355 9356 /// Determines if we can perform a correct type check for \p D as a 9357 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9358 /// best-effort check. 9359 /// 9360 /// \param NewD The new declaration. 9361 /// \param OldD The old declaration. 9362 /// \param NewT The portion of the type of the new declaration to check. 9363 /// \param OldT The portion of the type of the old declaration to check. 9364 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9365 QualType NewT, QualType OldT) { 9366 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9367 return true; 9368 9369 // For dependently-typed local extern declarations and friends, we can't 9370 // perform a correct type check in general until instantiation: 9371 // 9372 // int f(); 9373 // template<typename T> void g() { T f(); } 9374 // 9375 // (valid if g() is only instantiated with T = int). 9376 if (NewT->isDependentType() && 9377 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9378 return false; 9379 9380 // Similarly, if the previous declaration was a dependent local extern 9381 // declaration, we don't really know its type yet. 9382 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9383 return false; 9384 9385 return true; 9386 } 9387 9388 /// Checks if the new declaration declared in dependent context must be 9389 /// put in the same redeclaration chain as the specified declaration. 9390 /// 9391 /// \param D Declaration that is checked. 9392 /// \param PrevDecl Previous declaration found with proper lookup method for the 9393 /// same declaration name. 9394 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9395 /// belongs to. 9396 /// 9397 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9398 if (!D->getLexicalDeclContext()->isDependentContext()) 9399 return true; 9400 9401 // Don't chain dependent friend function definitions until instantiation, to 9402 // permit cases like 9403 // 9404 // void func(); 9405 // template<typename T> class C1 { friend void func() {} }; 9406 // template<typename T> class C2 { friend void func() {} }; 9407 // 9408 // ... which is valid if only one of C1 and C2 is ever instantiated. 9409 // 9410 // FIXME: This need only apply to function definitions. For now, we proxy 9411 // this by checking for a file-scope function. We do not want this to apply 9412 // to friend declarations nominating member functions, because that gets in 9413 // the way of access checks. 9414 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9415 return false; 9416 9417 auto *VD = dyn_cast<ValueDecl>(D); 9418 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9419 return !VD || !PrevVD || 9420 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9421 PrevVD->getType()); 9422 } 9423 9424 /// Check the target attribute of the function for MultiVersion 9425 /// validity. 9426 /// 9427 /// Returns true if there was an error, false otherwise. 9428 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9429 const auto *TA = FD->getAttr<TargetAttr>(); 9430 assert(TA && "MultiVersion Candidate requires a target attribute"); 9431 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9432 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9433 enum ErrType { Feature = 0, Architecture = 1 }; 9434 9435 if (!ParseInfo.Architecture.empty() && 9436 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9437 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9438 << Architecture << ParseInfo.Architecture; 9439 return true; 9440 } 9441 9442 for (const auto &Feat : ParseInfo.Features) { 9443 auto BareFeat = StringRef{Feat}.substr(1); 9444 if (Feat[0] == '-') { 9445 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9446 << Feature << ("no-" + BareFeat).str(); 9447 return true; 9448 } 9449 9450 if (!TargetInfo.validateCpuSupports(BareFeat) || 9451 !TargetInfo.isValidFeatureName(BareFeat)) { 9452 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9453 << Feature << BareFeat; 9454 return true; 9455 } 9456 } 9457 return false; 9458 } 9459 9460 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9461 MultiVersionKind MVType) { 9462 for (const Attr *A : FD->attrs()) { 9463 switch (A->getKind()) { 9464 case attr::CPUDispatch: 9465 case attr::CPUSpecific: 9466 if (MVType != MultiVersionKind::CPUDispatch && 9467 MVType != MultiVersionKind::CPUSpecific) 9468 return true; 9469 break; 9470 case attr::Target: 9471 if (MVType != MultiVersionKind::Target) 9472 return true; 9473 break; 9474 default: 9475 return true; 9476 } 9477 } 9478 return false; 9479 } 9480 9481 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9482 const FunctionDecl *NewFD, 9483 bool CausesMV, 9484 MultiVersionKind MVType) { 9485 enum DoesntSupport { 9486 FuncTemplates = 0, 9487 VirtFuncs = 1, 9488 DeducedReturn = 2, 9489 Constructors = 3, 9490 Destructors = 4, 9491 DeletedFuncs = 5, 9492 DefaultedFuncs = 6, 9493 ConstexprFuncs = 7, 9494 }; 9495 enum Different { 9496 CallingConv = 0, 9497 ReturnType = 1, 9498 ConstexprSpec = 2, 9499 InlineSpec = 3, 9500 StorageClass = 4, 9501 Linkage = 5 9502 }; 9503 9504 bool IsCPUSpecificCPUDispatchMVType = 9505 MVType == MultiVersionKind::CPUDispatch || 9506 MVType == MultiVersionKind::CPUSpecific; 9507 9508 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { 9509 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9510 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9511 return true; 9512 } 9513 9514 if (!NewFD->getType()->getAs<FunctionProtoType>()) 9515 return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9516 9517 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9518 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9519 if (OldFD) 9520 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9521 return true; 9522 } 9523 9524 // For now, disallow all other attributes. These should be opt-in, but 9525 // an analysis of all of them is a future FIXME. 9526 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 9527 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 9528 << IsCPUSpecificCPUDispatchMVType; 9529 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9530 return true; 9531 } 9532 9533 if (HasNonMultiVersionAttributes(NewFD, MVType)) 9534 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 9535 << IsCPUSpecificCPUDispatchMVType; 9536 9537 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9538 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9539 << IsCPUSpecificCPUDispatchMVType << FuncTemplates; 9540 9541 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9542 if (NewCXXFD->isVirtual()) 9543 return S.Diag(NewCXXFD->getLocation(), 9544 diag::err_multiversion_doesnt_support) 9545 << IsCPUSpecificCPUDispatchMVType << VirtFuncs; 9546 9547 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9548 return S.Diag(NewCXXCtor->getLocation(), 9549 diag::err_multiversion_doesnt_support) 9550 << IsCPUSpecificCPUDispatchMVType << Constructors; 9551 9552 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9553 return S.Diag(NewCXXDtor->getLocation(), 9554 diag::err_multiversion_doesnt_support) 9555 << IsCPUSpecificCPUDispatchMVType << Destructors; 9556 } 9557 9558 if (NewFD->isDeleted()) 9559 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9560 << IsCPUSpecificCPUDispatchMVType << DeletedFuncs; 9561 9562 if (NewFD->isDefaulted()) 9563 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9564 << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs; 9565 9566 if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch || 9567 MVType == MultiVersionKind::CPUSpecific)) 9568 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9569 << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs; 9570 9571 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9572 const auto *NewType = cast<FunctionType>(NewQType); 9573 QualType NewReturnType = NewType->getReturnType(); 9574 9575 if (NewReturnType->isUndeducedType()) 9576 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9577 << IsCPUSpecificCPUDispatchMVType << DeducedReturn; 9578 9579 // Only allow transition to MultiVersion if it hasn't been used. 9580 if (OldFD && CausesMV && OldFD->isUsed(false)) 9581 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9582 9583 // Ensure the return type is identical. 9584 if (OldFD) { 9585 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9586 const auto *OldType = cast<FunctionType>(OldQType); 9587 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9588 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9589 9590 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9591 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9592 << CallingConv; 9593 9594 QualType OldReturnType = OldType->getReturnType(); 9595 9596 if (OldReturnType != NewReturnType) 9597 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9598 << ReturnType; 9599 9600 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9601 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9602 << ConstexprSpec; 9603 9604 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9605 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9606 << InlineSpec; 9607 9608 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9609 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9610 << StorageClass; 9611 9612 if (OldFD->isExternC() != NewFD->isExternC()) 9613 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9614 << Linkage; 9615 9616 if (S.CheckEquivalentExceptionSpec( 9617 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9618 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9619 return true; 9620 } 9621 return false; 9622 } 9623 9624 /// Check the validity of a multiversion function declaration that is the 9625 /// first of its kind. Also sets the multiversion'ness' of the function itself. 9626 /// 9627 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9628 /// 9629 /// Returns true if there was an error, false otherwise. 9630 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 9631 MultiVersionKind MVType, 9632 const TargetAttr *TA) { 9633 assert(MVType != MultiVersionKind::None && 9634 "Function lacks multiversion attribute"); 9635 9636 // Target only causes MV if it is default, otherwise this is a normal 9637 // function. 9638 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 9639 return false; 9640 9641 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 9642 FD->setInvalidDecl(); 9643 return true; 9644 } 9645 9646 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 9647 FD->setInvalidDecl(); 9648 return true; 9649 } 9650 9651 FD->setIsMultiVersion(); 9652 return false; 9653 } 9654 9655 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 9656 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 9657 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 9658 return true; 9659 } 9660 9661 return false; 9662 } 9663 9664 static bool CheckTargetCausesMultiVersioning( 9665 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 9666 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9667 LookupResult &Previous) { 9668 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9669 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9670 // Sort order doesn't matter, it just needs to be consistent. 9671 llvm::sort(NewParsed.Features); 9672 9673 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9674 // to change, this is a simple redeclaration. 9675 if (!NewTA->isDefaultVersion() && 9676 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 9677 return false; 9678 9679 // Otherwise, this decl causes MultiVersioning. 9680 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9681 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9682 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9683 NewFD->setInvalidDecl(); 9684 return true; 9685 } 9686 9687 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 9688 MultiVersionKind::Target)) { 9689 NewFD->setInvalidDecl(); 9690 return true; 9691 } 9692 9693 if (CheckMultiVersionValue(S, NewFD)) { 9694 NewFD->setInvalidDecl(); 9695 return true; 9696 } 9697 9698 // If this is 'default', permit the forward declaration. 9699 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 9700 Redeclaration = true; 9701 OldDecl = OldFD; 9702 OldFD->setIsMultiVersion(); 9703 NewFD->setIsMultiVersion(); 9704 return false; 9705 } 9706 9707 if (CheckMultiVersionValue(S, OldFD)) { 9708 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9709 NewFD->setInvalidDecl(); 9710 return true; 9711 } 9712 9713 TargetAttr::ParsedTargetAttr OldParsed = 9714 OldTA->parse(std::less<std::string>()); 9715 9716 if (OldParsed == NewParsed) { 9717 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9718 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9719 NewFD->setInvalidDecl(); 9720 return true; 9721 } 9722 9723 for (const auto *FD : OldFD->redecls()) { 9724 const auto *CurTA = FD->getAttr<TargetAttr>(); 9725 // We allow forward declarations before ANY multiversioning attributes, but 9726 // nothing after the fact. 9727 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 9728 (!CurTA || CurTA->isInherited())) { 9729 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 9730 << 0; 9731 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9732 NewFD->setInvalidDecl(); 9733 return true; 9734 } 9735 } 9736 9737 OldFD->setIsMultiVersion(); 9738 NewFD->setIsMultiVersion(); 9739 Redeclaration = false; 9740 MergeTypeWithPrevious = false; 9741 OldDecl = nullptr; 9742 Previous.clear(); 9743 return false; 9744 } 9745 9746 /// Check the validity of a new function declaration being added to an existing 9747 /// multiversioned declaration collection. 9748 static bool CheckMultiVersionAdditionalDecl( 9749 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 9750 MultiVersionKind NewMVType, const TargetAttr *NewTA, 9751 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 9752 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9753 LookupResult &Previous) { 9754 9755 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 9756 // Disallow mixing of multiversioning types. 9757 if ((OldMVType == MultiVersionKind::Target && 9758 NewMVType != MultiVersionKind::Target) || 9759 (NewMVType == MultiVersionKind::Target && 9760 OldMVType != MultiVersionKind::Target)) { 9761 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9762 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9763 NewFD->setInvalidDecl(); 9764 return true; 9765 } 9766 9767 TargetAttr::ParsedTargetAttr NewParsed; 9768 if (NewTA) { 9769 NewParsed = NewTA->parse(); 9770 llvm::sort(NewParsed.Features); 9771 } 9772 9773 bool UseMemberUsingDeclRules = 9774 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9775 9776 // Next, check ALL non-overloads to see if this is a redeclaration of a 9777 // previous member of the MultiVersion set. 9778 for (NamedDecl *ND : Previous) { 9779 FunctionDecl *CurFD = ND->getAsFunction(); 9780 if (!CurFD) 9781 continue; 9782 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9783 continue; 9784 9785 if (NewMVType == MultiVersionKind::Target) { 9786 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9787 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9788 NewFD->setIsMultiVersion(); 9789 Redeclaration = true; 9790 OldDecl = ND; 9791 return false; 9792 } 9793 9794 TargetAttr::ParsedTargetAttr CurParsed = 9795 CurTA->parse(std::less<std::string>()); 9796 if (CurParsed == NewParsed) { 9797 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9798 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9799 NewFD->setInvalidDecl(); 9800 return true; 9801 } 9802 } else { 9803 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 9804 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 9805 // Handle CPUDispatch/CPUSpecific versions. 9806 // Only 1 CPUDispatch function is allowed, this will make it go through 9807 // the redeclaration errors. 9808 if (NewMVType == MultiVersionKind::CPUDispatch && 9809 CurFD->hasAttr<CPUDispatchAttr>()) { 9810 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 9811 std::equal( 9812 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 9813 NewCPUDisp->cpus_begin(), 9814 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9815 return Cur->getName() == New->getName(); 9816 })) { 9817 NewFD->setIsMultiVersion(); 9818 Redeclaration = true; 9819 OldDecl = ND; 9820 return false; 9821 } 9822 9823 // If the declarations don't match, this is an error condition. 9824 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 9825 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9826 NewFD->setInvalidDecl(); 9827 return true; 9828 } 9829 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 9830 9831 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 9832 std::equal( 9833 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 9834 NewCPUSpec->cpus_begin(), 9835 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9836 return Cur->getName() == New->getName(); 9837 })) { 9838 NewFD->setIsMultiVersion(); 9839 Redeclaration = true; 9840 OldDecl = ND; 9841 return false; 9842 } 9843 9844 // Only 1 version of CPUSpecific is allowed for each CPU. 9845 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 9846 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 9847 if (CurII == NewII) { 9848 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 9849 << NewII; 9850 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9851 NewFD->setInvalidDecl(); 9852 return true; 9853 } 9854 } 9855 } 9856 } 9857 // If the two decls aren't the same MVType, there is no possible error 9858 // condition. 9859 } 9860 } 9861 9862 // Else, this is simply a non-redecl case. Checking the 'value' is only 9863 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 9864 // handled in the attribute adding step. 9865 if (NewMVType == MultiVersionKind::Target && 9866 CheckMultiVersionValue(S, NewFD)) { 9867 NewFD->setInvalidDecl(); 9868 return true; 9869 } 9870 9871 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 9872 !OldFD->isMultiVersion(), NewMVType)) { 9873 NewFD->setInvalidDecl(); 9874 return true; 9875 } 9876 9877 // Permit forward declarations in the case where these two are compatible. 9878 if (!OldFD->isMultiVersion()) { 9879 OldFD->setIsMultiVersion(); 9880 NewFD->setIsMultiVersion(); 9881 Redeclaration = true; 9882 OldDecl = OldFD; 9883 return false; 9884 } 9885 9886 NewFD->setIsMultiVersion(); 9887 Redeclaration = false; 9888 MergeTypeWithPrevious = false; 9889 OldDecl = nullptr; 9890 Previous.clear(); 9891 return false; 9892 } 9893 9894 9895 /// Check the validity of a mulitversion function declaration. 9896 /// Also sets the multiversion'ness' of the function itself. 9897 /// 9898 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9899 /// 9900 /// Returns true if there was an error, false otherwise. 9901 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9902 bool &Redeclaration, NamedDecl *&OldDecl, 9903 bool &MergeTypeWithPrevious, 9904 LookupResult &Previous) { 9905 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9906 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 9907 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 9908 9909 // Mixing Multiversioning types is prohibited. 9910 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 9911 (NewCPUDisp && NewCPUSpec)) { 9912 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9913 NewFD->setInvalidDecl(); 9914 return true; 9915 } 9916 9917 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 9918 9919 // Main isn't allowed to become a multiversion function, however it IS 9920 // permitted to have 'main' be marked with the 'target' optimization hint. 9921 if (NewFD->isMain()) { 9922 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 9923 MVType == MultiVersionKind::CPUDispatch || 9924 MVType == MultiVersionKind::CPUSpecific) { 9925 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9926 NewFD->setInvalidDecl(); 9927 return true; 9928 } 9929 return false; 9930 } 9931 9932 if (!OldDecl || !OldDecl->getAsFunction() || 9933 OldDecl->getDeclContext()->getRedeclContext() != 9934 NewFD->getDeclContext()->getRedeclContext()) { 9935 // If there's no previous declaration, AND this isn't attempting to cause 9936 // multiversioning, this isn't an error condition. 9937 if (MVType == MultiVersionKind::None) 9938 return false; 9939 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 9940 } 9941 9942 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9943 9944 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 9945 return false; 9946 9947 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 9948 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 9949 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 9950 NewFD->setInvalidDecl(); 9951 return true; 9952 } 9953 9954 // Handle the target potentially causes multiversioning case. 9955 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 9956 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 9957 Redeclaration, OldDecl, 9958 MergeTypeWithPrevious, Previous); 9959 9960 // At this point, we have a multiversion function decl (in OldFD) AND an 9961 // appropriate attribute in the current function decl. Resolve that these are 9962 // still compatible with previous declarations. 9963 return CheckMultiVersionAdditionalDecl( 9964 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 9965 OldDecl, MergeTypeWithPrevious, Previous); 9966 } 9967 9968 /// Perform semantic checking of a new function declaration. 9969 /// 9970 /// Performs semantic analysis of the new function declaration 9971 /// NewFD. This routine performs all semantic checking that does not 9972 /// require the actual declarator involved in the declaration, and is 9973 /// used both for the declaration of functions as they are parsed 9974 /// (called via ActOnDeclarator) and for the declaration of functions 9975 /// that have been instantiated via C++ template instantiation (called 9976 /// via InstantiateDecl). 9977 /// 9978 /// \param IsMemberSpecialization whether this new function declaration is 9979 /// a member specialization (that replaces any definition provided by the 9980 /// previous declaration). 9981 /// 9982 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9983 /// 9984 /// \returns true if the function declaration is a redeclaration. 9985 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9986 LookupResult &Previous, 9987 bool IsMemberSpecialization) { 9988 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9989 "Variably modified return types are not handled here"); 9990 9991 // Determine whether the type of this function should be merged with 9992 // a previous visible declaration. This never happens for functions in C++, 9993 // and always happens in C if the previous declaration was visible. 9994 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9995 !Previous.isShadowed(); 9996 9997 bool Redeclaration = false; 9998 NamedDecl *OldDecl = nullptr; 9999 bool MayNeedOverloadableChecks = false; 10000 10001 // Merge or overload the declaration with an existing declaration of 10002 // the same name, if appropriate. 10003 if (!Previous.empty()) { 10004 // Determine whether NewFD is an overload of PrevDecl or 10005 // a declaration that requires merging. If it's an overload, 10006 // there's no more work to do here; we'll just add the new 10007 // function to the scope. 10008 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10009 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10010 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10011 Redeclaration = true; 10012 OldDecl = Candidate; 10013 } 10014 } else { 10015 MayNeedOverloadableChecks = true; 10016 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10017 /*NewIsUsingDecl*/ false)) { 10018 case Ovl_Match: 10019 Redeclaration = true; 10020 break; 10021 10022 case Ovl_NonFunction: 10023 Redeclaration = true; 10024 break; 10025 10026 case Ovl_Overload: 10027 Redeclaration = false; 10028 break; 10029 } 10030 } 10031 } 10032 10033 // Check for a previous extern "C" declaration with this name. 10034 if (!Redeclaration && 10035 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10036 if (!Previous.empty()) { 10037 // This is an extern "C" declaration with the same name as a previous 10038 // declaration, and thus redeclares that entity... 10039 Redeclaration = true; 10040 OldDecl = Previous.getFoundDecl(); 10041 MergeTypeWithPrevious = false; 10042 10043 // ... except in the presence of __attribute__((overloadable)). 10044 if (OldDecl->hasAttr<OverloadableAttr>() || 10045 NewFD->hasAttr<OverloadableAttr>()) { 10046 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10047 MayNeedOverloadableChecks = true; 10048 Redeclaration = false; 10049 OldDecl = nullptr; 10050 } 10051 } 10052 } 10053 } 10054 10055 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10056 MergeTypeWithPrevious, Previous)) 10057 return Redeclaration; 10058 10059 // C++11 [dcl.constexpr]p8: 10060 // A constexpr specifier for a non-static member function that is not 10061 // a constructor declares that member function to be const. 10062 // 10063 // This needs to be delayed until we know whether this is an out-of-line 10064 // definition of a static member function. 10065 // 10066 // This rule is not present in C++1y, so we produce a backwards 10067 // compatibility warning whenever it happens in C++11. 10068 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10069 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10070 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10071 !MD->getMethodQualifiers().hasConst()) { 10072 CXXMethodDecl *OldMD = nullptr; 10073 if (OldDecl) 10074 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10075 if (!OldMD || !OldMD->isStatic()) { 10076 const FunctionProtoType *FPT = 10077 MD->getType()->castAs<FunctionProtoType>(); 10078 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10079 EPI.TypeQuals.addConst(); 10080 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10081 FPT->getParamTypes(), EPI)); 10082 10083 // Warn that we did this, if we're not performing template instantiation. 10084 // In that case, we'll have warned already when the template was defined. 10085 if (!inTemplateInstantiation()) { 10086 SourceLocation AddConstLoc; 10087 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10088 .IgnoreParens().getAs<FunctionTypeLoc>()) 10089 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10090 10091 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10092 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10093 } 10094 } 10095 } 10096 10097 if (Redeclaration) { 10098 // NewFD and OldDecl represent declarations that need to be 10099 // merged. 10100 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10101 NewFD->setInvalidDecl(); 10102 return Redeclaration; 10103 } 10104 10105 Previous.clear(); 10106 Previous.addDecl(OldDecl); 10107 10108 if (FunctionTemplateDecl *OldTemplateDecl = 10109 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10110 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10111 FunctionTemplateDecl *NewTemplateDecl 10112 = NewFD->getDescribedFunctionTemplate(); 10113 assert(NewTemplateDecl && "Template/non-template mismatch"); 10114 10115 // The call to MergeFunctionDecl above may have created some state in 10116 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10117 // can add it as a redeclaration. 10118 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10119 10120 NewFD->setPreviousDeclaration(OldFD); 10121 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10122 if (NewFD->isCXXClassMember()) { 10123 NewFD->setAccess(OldTemplateDecl->getAccess()); 10124 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10125 } 10126 10127 // If this is an explicit specialization of a member that is a function 10128 // template, mark it as a member specialization. 10129 if (IsMemberSpecialization && 10130 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10131 NewTemplateDecl->setMemberSpecialization(); 10132 assert(OldTemplateDecl->isMemberSpecialization()); 10133 // Explicit specializations of a member template do not inherit deleted 10134 // status from the parent member template that they are specializing. 10135 if (OldFD->isDeleted()) { 10136 // FIXME: This assert will not hold in the presence of modules. 10137 assert(OldFD->getCanonicalDecl() == OldFD); 10138 // FIXME: We need an update record for this AST mutation. 10139 OldFD->setDeletedAsWritten(false); 10140 } 10141 } 10142 10143 } else { 10144 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10145 auto *OldFD = cast<FunctionDecl>(OldDecl); 10146 // This needs to happen first so that 'inline' propagates. 10147 NewFD->setPreviousDeclaration(OldFD); 10148 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10149 if (NewFD->isCXXClassMember()) 10150 NewFD->setAccess(OldFD->getAccess()); 10151 } 10152 } 10153 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10154 !NewFD->getAttr<OverloadableAttr>()) { 10155 assert((Previous.empty() || 10156 llvm::any_of(Previous, 10157 [](const NamedDecl *ND) { 10158 return ND->hasAttr<OverloadableAttr>(); 10159 })) && 10160 "Non-redecls shouldn't happen without overloadable present"); 10161 10162 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10163 const auto *FD = dyn_cast<FunctionDecl>(ND); 10164 return FD && !FD->hasAttr<OverloadableAttr>(); 10165 }); 10166 10167 if (OtherUnmarkedIter != Previous.end()) { 10168 Diag(NewFD->getLocation(), 10169 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10170 Diag((*OtherUnmarkedIter)->getLocation(), 10171 diag::note_attribute_overloadable_prev_overload) 10172 << false; 10173 10174 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10175 } 10176 } 10177 10178 // Semantic checking for this function declaration (in isolation). 10179 10180 if (getLangOpts().CPlusPlus) { 10181 // C++-specific checks. 10182 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10183 CheckConstructor(Constructor); 10184 } else if (CXXDestructorDecl *Destructor = 10185 dyn_cast<CXXDestructorDecl>(NewFD)) { 10186 CXXRecordDecl *Record = Destructor->getParent(); 10187 QualType ClassType = Context.getTypeDeclType(Record); 10188 10189 // FIXME: Shouldn't we be able to perform this check even when the class 10190 // type is dependent? Both gcc and edg can handle that. 10191 if (!ClassType->isDependentType()) { 10192 DeclarationName Name 10193 = Context.DeclarationNames.getCXXDestructorName( 10194 Context.getCanonicalType(ClassType)); 10195 if (NewFD->getDeclName() != Name) { 10196 Diag(NewFD->getLocation(), diag::err_destructor_name); 10197 NewFD->setInvalidDecl(); 10198 return Redeclaration; 10199 } 10200 } 10201 } else if (CXXConversionDecl *Conversion 10202 = dyn_cast<CXXConversionDecl>(NewFD)) { 10203 ActOnConversionDeclarator(Conversion); 10204 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10205 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10206 CheckDeductionGuideTemplate(TD); 10207 10208 // A deduction guide is not on the list of entities that can be 10209 // explicitly specialized. 10210 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10211 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10212 << /*explicit specialization*/ 1; 10213 } 10214 10215 // Find any virtual functions that this function overrides. 10216 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10217 if (!Method->isFunctionTemplateSpecialization() && 10218 !Method->getDescribedFunctionTemplate() && 10219 Method->isCanonicalDecl()) { 10220 if (AddOverriddenMethods(Method->getParent(), Method)) { 10221 // If the function was marked as "static", we have a problem. 10222 if (NewFD->getStorageClass() == SC_Static) { 10223 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10224 } 10225 } 10226 } 10227 10228 if (Method->isStatic()) 10229 checkThisInStaticMemberFunctionType(Method); 10230 } 10231 10232 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10233 if (NewFD->isOverloadedOperator() && 10234 CheckOverloadedOperatorDeclaration(NewFD)) { 10235 NewFD->setInvalidDecl(); 10236 return Redeclaration; 10237 } 10238 10239 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10240 if (NewFD->getLiteralIdentifier() && 10241 CheckLiteralOperatorDeclaration(NewFD)) { 10242 NewFD->setInvalidDecl(); 10243 return Redeclaration; 10244 } 10245 10246 // In C++, check default arguments now that we have merged decls. Unless 10247 // the lexical context is the class, because in this case this is done 10248 // during delayed parsing anyway. 10249 if (!CurContext->isRecord()) 10250 CheckCXXDefaultArguments(NewFD); 10251 10252 // If this function declares a builtin function, check the type of this 10253 // declaration against the expected type for the builtin. 10254 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10255 ASTContext::GetBuiltinTypeError Error; 10256 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10257 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10258 // If the type of the builtin differs only in its exception 10259 // specification, that's OK. 10260 // FIXME: If the types do differ in this way, it would be better to 10261 // retain the 'noexcept' form of the type. 10262 if (!T.isNull() && 10263 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10264 NewFD->getType())) 10265 // The type of this function differs from the type of the builtin, 10266 // so forget about the builtin entirely. 10267 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10268 } 10269 10270 // If this function is declared as being extern "C", then check to see if 10271 // the function returns a UDT (class, struct, or union type) that is not C 10272 // compatible, and if it does, warn the user. 10273 // But, issue any diagnostic on the first declaration only. 10274 if (Previous.empty() && NewFD->isExternC()) { 10275 QualType R = NewFD->getReturnType(); 10276 if (R->isIncompleteType() && !R->isVoidType()) 10277 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10278 << NewFD << R; 10279 else if (!R.isPODType(Context) && !R->isVoidType() && 10280 !R->isObjCObjectPointerType()) 10281 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10282 } 10283 10284 // C++1z [dcl.fct]p6: 10285 // [...] whether the function has a non-throwing exception-specification 10286 // [is] part of the function type 10287 // 10288 // This results in an ABI break between C++14 and C++17 for functions whose 10289 // declared type includes an exception-specification in a parameter or 10290 // return type. (Exception specifications on the function itself are OK in 10291 // most cases, and exception specifications are not permitted in most other 10292 // contexts where they could make it into a mangling.) 10293 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10294 auto HasNoexcept = [&](QualType T) -> bool { 10295 // Strip off declarator chunks that could be between us and a function 10296 // type. We don't need to look far, exception specifications are very 10297 // restricted prior to C++17. 10298 if (auto *RT = T->getAs<ReferenceType>()) 10299 T = RT->getPointeeType(); 10300 else if (T->isAnyPointerType()) 10301 T = T->getPointeeType(); 10302 else if (auto *MPT = T->getAs<MemberPointerType>()) 10303 T = MPT->getPointeeType(); 10304 if (auto *FPT = T->getAs<FunctionProtoType>()) 10305 if (FPT->isNothrow()) 10306 return true; 10307 return false; 10308 }; 10309 10310 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10311 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10312 for (QualType T : FPT->param_types()) 10313 AnyNoexcept |= HasNoexcept(T); 10314 if (AnyNoexcept) 10315 Diag(NewFD->getLocation(), 10316 diag::warn_cxx17_compat_exception_spec_in_signature) 10317 << NewFD; 10318 } 10319 10320 if (!Redeclaration && LangOpts.CUDA) 10321 checkCUDATargetOverload(NewFD, Previous); 10322 } 10323 return Redeclaration; 10324 } 10325 10326 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10327 // C++11 [basic.start.main]p3: 10328 // A program that [...] declares main to be inline, static or 10329 // constexpr is ill-formed. 10330 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10331 // appear in a declaration of main. 10332 // static main is not an error under C99, but we should warn about it. 10333 // We accept _Noreturn main as an extension. 10334 if (FD->getStorageClass() == SC_Static) 10335 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10336 ? diag::err_static_main : diag::warn_static_main) 10337 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10338 if (FD->isInlineSpecified()) 10339 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10340 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10341 if (DS.isNoreturnSpecified()) { 10342 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10343 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10344 Diag(NoreturnLoc, diag::ext_noreturn_main); 10345 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10346 << FixItHint::CreateRemoval(NoreturnRange); 10347 } 10348 if (FD->isConstexpr()) { 10349 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10350 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10351 FD->setConstexpr(false); 10352 } 10353 10354 if (getLangOpts().OpenCL) { 10355 Diag(FD->getLocation(), diag::err_opencl_no_main) 10356 << FD->hasAttr<OpenCLKernelAttr>(); 10357 FD->setInvalidDecl(); 10358 return; 10359 } 10360 10361 QualType T = FD->getType(); 10362 assert(T->isFunctionType() && "function decl is not of function type"); 10363 const FunctionType* FT = T->castAs<FunctionType>(); 10364 10365 // Set default calling convention for main() 10366 if (FT->getCallConv() != CC_C) { 10367 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10368 FD->setType(QualType(FT, 0)); 10369 T = Context.getCanonicalType(FD->getType()); 10370 } 10371 10372 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10373 // In C with GNU extensions we allow main() to have non-integer return 10374 // type, but we should warn about the extension, and we disable the 10375 // implicit-return-zero rule. 10376 10377 // GCC in C mode accepts qualified 'int'. 10378 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10379 FD->setHasImplicitReturnZero(true); 10380 else { 10381 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10382 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10383 if (RTRange.isValid()) 10384 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10385 << FixItHint::CreateReplacement(RTRange, "int"); 10386 } 10387 } else { 10388 // In C and C++, main magically returns 0 if you fall off the end; 10389 // set the flag which tells us that. 10390 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10391 10392 // All the standards say that main() should return 'int'. 10393 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10394 FD->setHasImplicitReturnZero(true); 10395 else { 10396 // Otherwise, this is just a flat-out error. 10397 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10398 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10399 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10400 : FixItHint()); 10401 FD->setInvalidDecl(true); 10402 } 10403 } 10404 10405 // Treat protoless main() as nullary. 10406 if (isa<FunctionNoProtoType>(FT)) return; 10407 10408 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10409 unsigned nparams = FTP->getNumParams(); 10410 assert(FD->getNumParams() == nparams); 10411 10412 bool HasExtraParameters = (nparams > 3); 10413 10414 if (FTP->isVariadic()) { 10415 Diag(FD->getLocation(), diag::ext_variadic_main); 10416 // FIXME: if we had information about the location of the ellipsis, we 10417 // could add a FixIt hint to remove it as a parameter. 10418 } 10419 10420 // Darwin passes an undocumented fourth argument of type char**. If 10421 // other platforms start sprouting these, the logic below will start 10422 // getting shifty. 10423 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10424 HasExtraParameters = false; 10425 10426 if (HasExtraParameters) { 10427 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10428 FD->setInvalidDecl(true); 10429 nparams = 3; 10430 } 10431 10432 // FIXME: a lot of the following diagnostics would be improved 10433 // if we had some location information about types. 10434 10435 QualType CharPP = 10436 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10437 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10438 10439 for (unsigned i = 0; i < nparams; ++i) { 10440 QualType AT = FTP->getParamType(i); 10441 10442 bool mismatch = true; 10443 10444 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10445 mismatch = false; 10446 else if (Expected[i] == CharPP) { 10447 // As an extension, the following forms are okay: 10448 // char const ** 10449 // char const * const * 10450 // char * const * 10451 10452 QualifierCollector qs; 10453 const PointerType* PT; 10454 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10455 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10456 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10457 Context.CharTy)) { 10458 qs.removeConst(); 10459 mismatch = !qs.empty(); 10460 } 10461 } 10462 10463 if (mismatch) { 10464 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10465 // TODO: suggest replacing given type with expected type 10466 FD->setInvalidDecl(true); 10467 } 10468 } 10469 10470 if (nparams == 1 && !FD->isInvalidDecl()) { 10471 Diag(FD->getLocation(), diag::warn_main_one_arg); 10472 } 10473 10474 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10475 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10476 FD->setInvalidDecl(); 10477 } 10478 } 10479 10480 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10481 QualType T = FD->getType(); 10482 assert(T->isFunctionType() && "function decl is not of function type"); 10483 const FunctionType *FT = T->castAs<FunctionType>(); 10484 10485 // Set an implicit return of 'zero' if the function can return some integral, 10486 // enumeration, pointer or nullptr type. 10487 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10488 FT->getReturnType()->isAnyPointerType() || 10489 FT->getReturnType()->isNullPtrType()) 10490 // DllMain is exempt because a return value of zero means it failed. 10491 if (FD->getName() != "DllMain") 10492 FD->setHasImplicitReturnZero(true); 10493 10494 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10495 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10496 FD->setInvalidDecl(); 10497 } 10498 } 10499 10500 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10501 // FIXME: Need strict checking. In C89, we need to check for 10502 // any assignment, increment, decrement, function-calls, or 10503 // commas outside of a sizeof. In C99, it's the same list, 10504 // except that the aforementioned are allowed in unevaluated 10505 // expressions. Everything else falls under the 10506 // "may accept other forms of constant expressions" exception. 10507 // (We never end up here for C++, so the constant expression 10508 // rules there don't matter.) 10509 const Expr *Culprit; 10510 if (Init->isConstantInitializer(Context, false, &Culprit)) 10511 return false; 10512 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10513 << Culprit->getSourceRange(); 10514 return true; 10515 } 10516 10517 namespace { 10518 // Visits an initialization expression to see if OrigDecl is evaluated in 10519 // its own initialization and throws a warning if it does. 10520 class SelfReferenceChecker 10521 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10522 Sema &S; 10523 Decl *OrigDecl; 10524 bool isRecordType; 10525 bool isPODType; 10526 bool isReferenceType; 10527 10528 bool isInitList; 10529 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10530 10531 public: 10532 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10533 10534 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10535 S(S), OrigDecl(OrigDecl) { 10536 isPODType = false; 10537 isRecordType = false; 10538 isReferenceType = false; 10539 isInitList = false; 10540 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10541 isPODType = VD->getType().isPODType(S.Context); 10542 isRecordType = VD->getType()->isRecordType(); 10543 isReferenceType = VD->getType()->isReferenceType(); 10544 } 10545 } 10546 10547 // For most expressions, just call the visitor. For initializer lists, 10548 // track the index of the field being initialized since fields are 10549 // initialized in order allowing use of previously initialized fields. 10550 void CheckExpr(Expr *E) { 10551 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10552 if (!InitList) { 10553 Visit(E); 10554 return; 10555 } 10556 10557 // Track and increment the index here. 10558 isInitList = true; 10559 InitFieldIndex.push_back(0); 10560 for (auto Child : InitList->children()) { 10561 CheckExpr(cast<Expr>(Child)); 10562 ++InitFieldIndex.back(); 10563 } 10564 InitFieldIndex.pop_back(); 10565 } 10566 10567 // Returns true if MemberExpr is checked and no further checking is needed. 10568 // Returns false if additional checking is required. 10569 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10570 llvm::SmallVector<FieldDecl*, 4> Fields; 10571 Expr *Base = E; 10572 bool ReferenceField = false; 10573 10574 // Get the field members used. 10575 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10576 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10577 if (!FD) 10578 return false; 10579 Fields.push_back(FD); 10580 if (FD->getType()->isReferenceType()) 10581 ReferenceField = true; 10582 Base = ME->getBase()->IgnoreParenImpCasts(); 10583 } 10584 10585 // Keep checking only if the base Decl is the same. 10586 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10587 if (!DRE || DRE->getDecl() != OrigDecl) 10588 return false; 10589 10590 // A reference field can be bound to an unininitialized field. 10591 if (CheckReference && !ReferenceField) 10592 return true; 10593 10594 // Convert FieldDecls to their index number. 10595 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10596 for (const FieldDecl *I : llvm::reverse(Fields)) 10597 UsedFieldIndex.push_back(I->getFieldIndex()); 10598 10599 // See if a warning is needed by checking the first difference in index 10600 // numbers. If field being used has index less than the field being 10601 // initialized, then the use is safe. 10602 for (auto UsedIter = UsedFieldIndex.begin(), 10603 UsedEnd = UsedFieldIndex.end(), 10604 OrigIter = InitFieldIndex.begin(), 10605 OrigEnd = InitFieldIndex.end(); 10606 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10607 if (*UsedIter < *OrigIter) 10608 return true; 10609 if (*UsedIter > *OrigIter) 10610 break; 10611 } 10612 10613 // TODO: Add a different warning which will print the field names. 10614 HandleDeclRefExpr(DRE); 10615 return true; 10616 } 10617 10618 // For most expressions, the cast is directly above the DeclRefExpr. 10619 // For conditional operators, the cast can be outside the conditional 10620 // operator if both expressions are DeclRefExpr's. 10621 void HandleValue(Expr *E) { 10622 E = E->IgnoreParens(); 10623 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10624 HandleDeclRefExpr(DRE); 10625 return; 10626 } 10627 10628 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10629 Visit(CO->getCond()); 10630 HandleValue(CO->getTrueExpr()); 10631 HandleValue(CO->getFalseExpr()); 10632 return; 10633 } 10634 10635 if (BinaryConditionalOperator *BCO = 10636 dyn_cast<BinaryConditionalOperator>(E)) { 10637 Visit(BCO->getCond()); 10638 HandleValue(BCO->getFalseExpr()); 10639 return; 10640 } 10641 10642 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10643 HandleValue(OVE->getSourceExpr()); 10644 return; 10645 } 10646 10647 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10648 if (BO->getOpcode() == BO_Comma) { 10649 Visit(BO->getLHS()); 10650 HandleValue(BO->getRHS()); 10651 return; 10652 } 10653 } 10654 10655 if (isa<MemberExpr>(E)) { 10656 if (isInitList) { 10657 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10658 false /*CheckReference*/)) 10659 return; 10660 } 10661 10662 Expr *Base = E->IgnoreParenImpCasts(); 10663 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10664 // Check for static member variables and don't warn on them. 10665 if (!isa<FieldDecl>(ME->getMemberDecl())) 10666 return; 10667 Base = ME->getBase()->IgnoreParenImpCasts(); 10668 } 10669 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10670 HandleDeclRefExpr(DRE); 10671 return; 10672 } 10673 10674 Visit(E); 10675 } 10676 10677 // Reference types not handled in HandleValue are handled here since all 10678 // uses of references are bad, not just r-value uses. 10679 void VisitDeclRefExpr(DeclRefExpr *E) { 10680 if (isReferenceType) 10681 HandleDeclRefExpr(E); 10682 } 10683 10684 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10685 if (E->getCastKind() == CK_LValueToRValue) { 10686 HandleValue(E->getSubExpr()); 10687 return; 10688 } 10689 10690 Inherited::VisitImplicitCastExpr(E); 10691 } 10692 10693 void VisitMemberExpr(MemberExpr *E) { 10694 if (isInitList) { 10695 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10696 return; 10697 } 10698 10699 // Don't warn on arrays since they can be treated as pointers. 10700 if (E->getType()->canDecayToPointerType()) return; 10701 10702 // Warn when a non-static method call is followed by non-static member 10703 // field accesses, which is followed by a DeclRefExpr. 10704 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10705 bool Warn = (MD && !MD->isStatic()); 10706 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10707 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10708 if (!isa<FieldDecl>(ME->getMemberDecl())) 10709 Warn = false; 10710 Base = ME->getBase()->IgnoreParenImpCasts(); 10711 } 10712 10713 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10714 if (Warn) 10715 HandleDeclRefExpr(DRE); 10716 return; 10717 } 10718 10719 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10720 // Visit that expression. 10721 Visit(Base); 10722 } 10723 10724 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10725 Expr *Callee = E->getCallee(); 10726 10727 if (isa<UnresolvedLookupExpr>(Callee)) 10728 return Inherited::VisitCXXOperatorCallExpr(E); 10729 10730 Visit(Callee); 10731 for (auto Arg: E->arguments()) 10732 HandleValue(Arg->IgnoreParenImpCasts()); 10733 } 10734 10735 void VisitUnaryOperator(UnaryOperator *E) { 10736 // For POD record types, addresses of its own members are well-defined. 10737 if (E->getOpcode() == UO_AddrOf && isRecordType && 10738 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10739 if (!isPODType) 10740 HandleValue(E->getSubExpr()); 10741 return; 10742 } 10743 10744 if (E->isIncrementDecrementOp()) { 10745 HandleValue(E->getSubExpr()); 10746 return; 10747 } 10748 10749 Inherited::VisitUnaryOperator(E); 10750 } 10751 10752 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10753 10754 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10755 if (E->getConstructor()->isCopyConstructor()) { 10756 Expr *ArgExpr = E->getArg(0); 10757 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10758 if (ILE->getNumInits() == 1) 10759 ArgExpr = ILE->getInit(0); 10760 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10761 if (ICE->getCastKind() == CK_NoOp) 10762 ArgExpr = ICE->getSubExpr(); 10763 HandleValue(ArgExpr); 10764 return; 10765 } 10766 Inherited::VisitCXXConstructExpr(E); 10767 } 10768 10769 void VisitCallExpr(CallExpr *E) { 10770 // Treat std::move as a use. 10771 if (E->isCallToStdMove()) { 10772 HandleValue(E->getArg(0)); 10773 return; 10774 } 10775 10776 Inherited::VisitCallExpr(E); 10777 } 10778 10779 void VisitBinaryOperator(BinaryOperator *E) { 10780 if (E->isCompoundAssignmentOp()) { 10781 HandleValue(E->getLHS()); 10782 Visit(E->getRHS()); 10783 return; 10784 } 10785 10786 Inherited::VisitBinaryOperator(E); 10787 } 10788 10789 // A custom visitor for BinaryConditionalOperator is needed because the 10790 // regular visitor would check the condition and true expression separately 10791 // but both point to the same place giving duplicate diagnostics. 10792 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10793 Visit(E->getCond()); 10794 Visit(E->getFalseExpr()); 10795 } 10796 10797 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10798 Decl* ReferenceDecl = DRE->getDecl(); 10799 if (OrigDecl != ReferenceDecl) return; 10800 unsigned diag; 10801 if (isReferenceType) { 10802 diag = diag::warn_uninit_self_reference_in_reference_init; 10803 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10804 diag = diag::warn_static_self_reference_in_init; 10805 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10806 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10807 DRE->getDecl()->getType()->isRecordType()) { 10808 diag = diag::warn_uninit_self_reference_in_init; 10809 } else { 10810 // Local variables will be handled by the CFG analysis. 10811 return; 10812 } 10813 10814 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 10815 S.PDiag(diag) 10816 << DRE->getDecl() << OrigDecl->getLocation() 10817 << DRE->getSourceRange()); 10818 } 10819 }; 10820 10821 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10822 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10823 bool DirectInit) { 10824 // Parameters arguments are occassionially constructed with itself, 10825 // for instance, in recursive functions. Skip them. 10826 if (isa<ParmVarDecl>(OrigDecl)) 10827 return; 10828 10829 E = E->IgnoreParens(); 10830 10831 // Skip checking T a = a where T is not a record or reference type. 10832 // Doing so is a way to silence uninitialized warnings. 10833 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10834 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10835 if (ICE->getCastKind() == CK_LValueToRValue) 10836 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10837 if (DRE->getDecl() == OrigDecl) 10838 return; 10839 10840 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10841 } 10842 } // end anonymous namespace 10843 10844 namespace { 10845 // Simple wrapper to add the name of a variable or (if no variable is 10846 // available) a DeclarationName into a diagnostic. 10847 struct VarDeclOrName { 10848 VarDecl *VDecl; 10849 DeclarationName Name; 10850 10851 friend const Sema::SemaDiagnosticBuilder & 10852 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10853 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10854 } 10855 }; 10856 } // end anonymous namespace 10857 10858 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10859 DeclarationName Name, QualType Type, 10860 TypeSourceInfo *TSI, 10861 SourceRange Range, bool DirectInit, 10862 Expr *Init) { 10863 bool IsInitCapture = !VDecl; 10864 assert((!VDecl || !VDecl->isInitCapture()) && 10865 "init captures are expected to be deduced prior to initialization"); 10866 10867 VarDeclOrName VN{VDecl, Name}; 10868 10869 DeducedType *Deduced = Type->getContainedDeducedType(); 10870 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10871 10872 // C++11 [dcl.spec.auto]p3 10873 if (!Init) { 10874 assert(VDecl && "no init for init capture deduction?"); 10875 10876 // Except for class argument deduction, and then for an initializing 10877 // declaration only, i.e. no static at class scope or extern. 10878 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10879 VDecl->hasExternalStorage() || 10880 VDecl->isStaticDataMember()) { 10881 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10882 << VDecl->getDeclName() << Type; 10883 return QualType(); 10884 } 10885 } 10886 10887 ArrayRef<Expr*> DeduceInits; 10888 if (Init) 10889 DeduceInits = Init; 10890 10891 if (DirectInit) { 10892 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10893 DeduceInits = PL->exprs(); 10894 } 10895 10896 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10897 assert(VDecl && "non-auto type for init capture deduction?"); 10898 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10899 InitializationKind Kind = InitializationKind::CreateForInit( 10900 VDecl->getLocation(), DirectInit, Init); 10901 // FIXME: Initialization should not be taking a mutable list of inits. 10902 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10903 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10904 InitsCopy); 10905 } 10906 10907 if (DirectInit) { 10908 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10909 DeduceInits = IL->inits(); 10910 } 10911 10912 // Deduction only works if we have exactly one source expression. 10913 if (DeduceInits.empty()) { 10914 // It isn't possible to write this directly, but it is possible to 10915 // end up in this situation with "auto x(some_pack...);" 10916 Diag(Init->getBeginLoc(), IsInitCapture 10917 ? diag::err_init_capture_no_expression 10918 : diag::err_auto_var_init_no_expression) 10919 << VN << Type << Range; 10920 return QualType(); 10921 } 10922 10923 if (DeduceInits.size() > 1) { 10924 Diag(DeduceInits[1]->getBeginLoc(), 10925 IsInitCapture ? diag::err_init_capture_multiple_expressions 10926 : diag::err_auto_var_init_multiple_expressions) 10927 << VN << Type << Range; 10928 return QualType(); 10929 } 10930 10931 Expr *DeduceInit = DeduceInits[0]; 10932 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10933 Diag(Init->getBeginLoc(), IsInitCapture 10934 ? diag::err_init_capture_paren_braces 10935 : diag::err_auto_var_init_paren_braces) 10936 << isa<InitListExpr>(Init) << VN << Type << Range; 10937 return QualType(); 10938 } 10939 10940 // Expressions default to 'id' when we're in a debugger. 10941 bool DefaultedAnyToId = false; 10942 if (getLangOpts().DebuggerCastResultToId && 10943 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10944 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10945 if (Result.isInvalid()) { 10946 return QualType(); 10947 } 10948 Init = Result.get(); 10949 DefaultedAnyToId = true; 10950 } 10951 10952 // C++ [dcl.decomp]p1: 10953 // If the assignment-expression [...] has array type A and no ref-qualifier 10954 // is present, e has type cv A 10955 if (VDecl && isa<DecompositionDecl>(VDecl) && 10956 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10957 DeduceInit->getType()->isConstantArrayType()) 10958 return Context.getQualifiedType(DeduceInit->getType(), 10959 Type.getQualifiers()); 10960 10961 QualType DeducedType; 10962 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10963 if (!IsInitCapture) 10964 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10965 else if (isa<InitListExpr>(Init)) 10966 Diag(Range.getBegin(), 10967 diag::err_init_capture_deduction_failure_from_init_list) 10968 << VN 10969 << (DeduceInit->getType().isNull() ? TSI->getType() 10970 : DeduceInit->getType()) 10971 << DeduceInit->getSourceRange(); 10972 else 10973 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10974 << VN << TSI->getType() 10975 << (DeduceInit->getType().isNull() ? TSI->getType() 10976 : DeduceInit->getType()) 10977 << DeduceInit->getSourceRange(); 10978 } 10979 10980 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10981 // 'id' instead of a specific object type prevents most of our usual 10982 // checks. 10983 // We only want to warn outside of template instantiations, though: 10984 // inside a template, the 'id' could have come from a parameter. 10985 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10986 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10987 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10988 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10989 } 10990 10991 return DeducedType; 10992 } 10993 10994 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10995 Expr *Init) { 10996 QualType DeducedType = deduceVarTypeFromInitializer( 10997 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10998 VDecl->getSourceRange(), DirectInit, Init); 10999 if (DeducedType.isNull()) { 11000 VDecl->setInvalidDecl(); 11001 return true; 11002 } 11003 11004 VDecl->setType(DeducedType); 11005 assert(VDecl->isLinkageValid()); 11006 11007 // In ARC, infer lifetime. 11008 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11009 VDecl->setInvalidDecl(); 11010 11011 // If this is a redeclaration, check that the type we just deduced matches 11012 // the previously declared type. 11013 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11014 // We never need to merge the type, because we cannot form an incomplete 11015 // array of auto, nor deduce such a type. 11016 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11017 } 11018 11019 // Check the deduced type is valid for a variable declaration. 11020 CheckVariableDeclarationType(VDecl); 11021 return VDecl->isInvalidDecl(); 11022 } 11023 11024 /// AddInitializerToDecl - Adds the initializer Init to the 11025 /// declaration dcl. If DirectInit is true, this is C++ direct 11026 /// initialization rather than copy initialization. 11027 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11028 // If there is no declaration, there was an error parsing it. Just ignore 11029 // the initializer. 11030 if (!RealDecl || RealDecl->isInvalidDecl()) { 11031 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11032 return; 11033 } 11034 11035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11036 // Pure-specifiers are handled in ActOnPureSpecifier. 11037 Diag(Method->getLocation(), diag::err_member_function_initialization) 11038 << Method->getDeclName() << Init->getSourceRange(); 11039 Method->setInvalidDecl(); 11040 return; 11041 } 11042 11043 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11044 if (!VDecl) { 11045 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11046 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11047 RealDecl->setInvalidDecl(); 11048 return; 11049 } 11050 11051 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11052 if (VDecl->getType()->isUndeducedType()) { 11053 // Attempt typo correction early so that the type of the init expression can 11054 // be deduced based on the chosen correction if the original init contains a 11055 // TypoExpr. 11056 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11057 if (!Res.isUsable()) { 11058 RealDecl->setInvalidDecl(); 11059 return; 11060 } 11061 Init = Res.get(); 11062 11063 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11064 return; 11065 } 11066 11067 // dllimport cannot be used on variable definitions. 11068 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11069 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11070 VDecl->setInvalidDecl(); 11071 return; 11072 } 11073 11074 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11075 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11076 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11077 VDecl->setInvalidDecl(); 11078 return; 11079 } 11080 11081 if (!VDecl->getType()->isDependentType()) { 11082 // A definition must end up with a complete type, which means it must be 11083 // complete with the restriction that an array type might be completed by 11084 // the initializer; note that later code assumes this restriction. 11085 QualType BaseDeclType = VDecl->getType(); 11086 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11087 BaseDeclType = Array->getElementType(); 11088 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11089 diag::err_typecheck_decl_incomplete_type)) { 11090 RealDecl->setInvalidDecl(); 11091 return; 11092 } 11093 11094 // The variable can not have an abstract class type. 11095 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11096 diag::err_abstract_type_in_decl, 11097 AbstractVariableType)) 11098 VDecl->setInvalidDecl(); 11099 } 11100 11101 // If adding the initializer will turn this declaration into a definition, 11102 // and we already have a definition for this variable, diagnose or otherwise 11103 // handle the situation. 11104 VarDecl *Def; 11105 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11106 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11107 !VDecl->isThisDeclarationADemotedDefinition() && 11108 checkVarDeclRedefinition(Def, VDecl)) 11109 return; 11110 11111 if (getLangOpts().CPlusPlus) { 11112 // C++ [class.static.data]p4 11113 // If a static data member is of const integral or const 11114 // enumeration type, its declaration in the class definition can 11115 // specify a constant-initializer which shall be an integral 11116 // constant expression (5.19). In that case, the member can appear 11117 // in integral constant expressions. The member shall still be 11118 // defined in a namespace scope if it is used in the program and the 11119 // namespace scope definition shall not contain an initializer. 11120 // 11121 // We already performed a redefinition check above, but for static 11122 // data members we also need to check whether there was an in-class 11123 // declaration with an initializer. 11124 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11125 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11126 << VDecl->getDeclName(); 11127 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11128 diag::note_previous_initializer) 11129 << 0; 11130 return; 11131 } 11132 11133 if (VDecl->hasLocalStorage()) 11134 setFunctionHasBranchProtectedScope(); 11135 11136 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11137 VDecl->setInvalidDecl(); 11138 return; 11139 } 11140 } 11141 11142 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11143 // a kernel function cannot be initialized." 11144 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11145 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11146 VDecl->setInvalidDecl(); 11147 return; 11148 } 11149 11150 // Get the decls type and save a reference for later, since 11151 // CheckInitializerTypes may change it. 11152 QualType DclT = VDecl->getType(), SavT = DclT; 11153 11154 // Expressions default to 'id' when we're in a debugger 11155 // and we are assigning it to a variable of Objective-C pointer type. 11156 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11157 Init->getType() == Context.UnknownAnyTy) { 11158 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11159 if (Result.isInvalid()) { 11160 VDecl->setInvalidDecl(); 11161 return; 11162 } 11163 Init = Result.get(); 11164 } 11165 11166 // Perform the initialization. 11167 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11168 if (!VDecl->isInvalidDecl()) { 11169 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11170 InitializationKind Kind = InitializationKind::CreateForInit( 11171 VDecl->getLocation(), DirectInit, Init); 11172 11173 MultiExprArg Args = Init; 11174 if (CXXDirectInit) 11175 Args = MultiExprArg(CXXDirectInit->getExprs(), 11176 CXXDirectInit->getNumExprs()); 11177 11178 // Try to correct any TypoExprs in the initialization arguments. 11179 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11180 ExprResult Res = CorrectDelayedTyposInExpr( 11181 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11182 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11183 return Init.Failed() ? ExprError() : E; 11184 }); 11185 if (Res.isInvalid()) { 11186 VDecl->setInvalidDecl(); 11187 } else if (Res.get() != Args[Idx]) { 11188 Args[Idx] = Res.get(); 11189 } 11190 } 11191 if (VDecl->isInvalidDecl()) 11192 return; 11193 11194 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11195 /*TopLevelOfInitList=*/false, 11196 /*TreatUnavailableAsInvalid=*/false); 11197 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11198 if (Result.isInvalid()) { 11199 VDecl->setInvalidDecl(); 11200 return; 11201 } 11202 11203 Init = Result.getAs<Expr>(); 11204 } 11205 11206 // Check for self-references within variable initializers. 11207 // Variables declared within a function/method body (except for references) 11208 // are handled by a dataflow analysis. 11209 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11210 VDecl->getType()->isReferenceType()) { 11211 CheckSelfReference(*this, RealDecl, Init, DirectInit); 11212 } 11213 11214 // If the type changed, it means we had an incomplete type that was 11215 // completed by the initializer. For example: 11216 // int ary[] = { 1, 3, 5 }; 11217 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 11218 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 11219 VDecl->setType(DclT); 11220 11221 if (!VDecl->isInvalidDecl()) { 11222 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 11223 11224 if (VDecl->hasAttr<BlocksAttr>()) 11225 checkRetainCycles(VDecl, Init); 11226 11227 // It is safe to assign a weak reference into a strong variable. 11228 // Although this code can still have problems: 11229 // id x = self.weakProp; 11230 // id y = self.weakProp; 11231 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11232 // paths through the function. This should be revisited if 11233 // -Wrepeated-use-of-weak is made flow-sensitive. 11234 if (FunctionScopeInfo *FSI = getCurFunction()) 11235 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 11236 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 11237 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11238 Init->getBeginLoc())) 11239 FSI->markSafeWeakUse(Init); 11240 } 11241 11242 // The initialization is usually a full-expression. 11243 // 11244 // FIXME: If this is a braced initialization of an aggregate, it is not 11245 // an expression, and each individual field initializer is a separate 11246 // full-expression. For instance, in: 11247 // 11248 // struct Temp { ~Temp(); }; 11249 // struct S { S(Temp); }; 11250 // struct T { S a, b; } t = { Temp(), Temp() } 11251 // 11252 // we should destroy the first Temp before constructing the second. 11253 ExprResult Result = 11254 ActOnFinishFullExpr(Init, VDecl->getLocation(), 11255 /*DiscardedValue*/ false, VDecl->isConstexpr()); 11256 if (Result.isInvalid()) { 11257 VDecl->setInvalidDecl(); 11258 return; 11259 } 11260 Init = Result.get(); 11261 11262 // Attach the initializer to the decl. 11263 VDecl->setInit(Init); 11264 11265 if (VDecl->isLocalVarDecl()) { 11266 // Don't check the initializer if the declaration is malformed. 11267 if (VDecl->isInvalidDecl()) { 11268 // do nothing 11269 11270 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 11271 // This is true even in OpenCL C++. 11272 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 11273 CheckForConstantInitializer(Init, DclT); 11274 11275 // Otherwise, C++ does not restrict the initializer. 11276 } else if (getLangOpts().CPlusPlus) { 11277 // do nothing 11278 11279 // C99 6.7.8p4: All the expressions in an initializer for an object that has 11280 // static storage duration shall be constant expressions or string literals. 11281 } else if (VDecl->getStorageClass() == SC_Static) { 11282 CheckForConstantInitializer(Init, DclT); 11283 11284 // C89 is stricter than C99 for aggregate initializers. 11285 // C89 6.5.7p3: All the expressions [...] in an initializer list 11286 // for an object that has aggregate or union type shall be 11287 // constant expressions. 11288 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 11289 isa<InitListExpr>(Init)) { 11290 const Expr *Culprit; 11291 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 11292 Diag(Culprit->getExprLoc(), 11293 diag::ext_aggregate_init_not_constant) 11294 << Culprit->getSourceRange(); 11295 } 11296 } 11297 11298 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 11299 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 11300 if (VDecl->hasLocalStorage()) 11301 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 11302 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 11303 VDecl->getLexicalDeclContext()->isRecord()) { 11304 // This is an in-class initialization for a static data member, e.g., 11305 // 11306 // struct S { 11307 // static const int value = 17; 11308 // }; 11309 11310 // C++ [class.mem]p4: 11311 // A member-declarator can contain a constant-initializer only 11312 // if it declares a static member (9.4) of const integral or 11313 // const enumeration type, see 9.4.2. 11314 // 11315 // C++11 [class.static.data]p3: 11316 // If a non-volatile non-inline const static data member is of integral 11317 // or enumeration type, its declaration in the class definition can 11318 // specify a brace-or-equal-initializer in which every initializer-clause 11319 // that is an assignment-expression is a constant expression. A static 11320 // data member of literal type can be declared in the class definition 11321 // with the constexpr specifier; if so, its declaration shall specify a 11322 // brace-or-equal-initializer in which every initializer-clause that is 11323 // an assignment-expression is a constant expression. 11324 11325 // Do nothing on dependent types. 11326 if (DclT->isDependentType()) { 11327 11328 // Allow any 'static constexpr' members, whether or not they are of literal 11329 // type. We separately check that every constexpr variable is of literal 11330 // type. 11331 } else if (VDecl->isConstexpr()) { 11332 11333 // Require constness. 11334 } else if (!DclT.isConstQualified()) { 11335 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 11336 << Init->getSourceRange(); 11337 VDecl->setInvalidDecl(); 11338 11339 // We allow integer constant expressions in all cases. 11340 } else if (DclT->isIntegralOrEnumerationType()) { 11341 // Check whether the expression is a constant expression. 11342 SourceLocation Loc; 11343 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 11344 // In C++11, a non-constexpr const static data member with an 11345 // in-class initializer cannot be volatile. 11346 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 11347 else if (Init->isValueDependent()) 11348 ; // Nothing to check. 11349 else if (Init->isIntegerConstantExpr(Context, &Loc)) 11350 ; // Ok, it's an ICE! 11351 else if (Init->getType()->isScopedEnumeralType() && 11352 Init->isCXX11ConstantExpr(Context)) 11353 ; // Ok, it is a scoped-enum constant expression. 11354 else if (Init->isEvaluatable(Context)) { 11355 // If we can constant fold the initializer through heroics, accept it, 11356 // but report this as a use of an extension for -pedantic. 11357 Diag(Loc, diag::ext_in_class_initializer_non_constant) 11358 << Init->getSourceRange(); 11359 } else { 11360 // Otherwise, this is some crazy unknown case. Report the issue at the 11361 // location provided by the isIntegerConstantExpr failed check. 11362 Diag(Loc, diag::err_in_class_initializer_non_constant) 11363 << Init->getSourceRange(); 11364 VDecl->setInvalidDecl(); 11365 } 11366 11367 // We allow foldable floating-point constants as an extension. 11368 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 11369 // In C++98, this is a GNU extension. In C++11, it is not, but we support 11370 // it anyway and provide a fixit to add the 'constexpr'. 11371 if (getLangOpts().CPlusPlus11) { 11372 Diag(VDecl->getLocation(), 11373 diag::ext_in_class_initializer_float_type_cxx11) 11374 << DclT << Init->getSourceRange(); 11375 Diag(VDecl->getBeginLoc(), 11376 diag::note_in_class_initializer_float_type_cxx11) 11377 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11378 } else { 11379 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 11380 << DclT << Init->getSourceRange(); 11381 11382 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 11383 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 11384 << Init->getSourceRange(); 11385 VDecl->setInvalidDecl(); 11386 } 11387 } 11388 11389 // Suggest adding 'constexpr' in C++11 for literal types. 11390 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 11391 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 11392 << DclT << Init->getSourceRange() 11393 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11394 VDecl->setConstexpr(true); 11395 11396 } else { 11397 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 11398 << DclT << Init->getSourceRange(); 11399 VDecl->setInvalidDecl(); 11400 } 11401 } else if (VDecl->isFileVarDecl()) { 11402 // In C, extern is typically used to avoid tentative definitions when 11403 // declaring variables in headers, but adding an intializer makes it a 11404 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 11405 // In C++, extern is often used to give implictly static const variables 11406 // external linkage, so don't warn in that case. If selectany is present, 11407 // this might be header code intended for C and C++ inclusion, so apply the 11408 // C++ rules. 11409 if (VDecl->getStorageClass() == SC_Extern && 11410 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 11411 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 11412 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 11413 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 11414 Diag(VDecl->getLocation(), diag::warn_extern_init); 11415 11416 // In Microsoft C++ mode, a const variable defined in namespace scope has 11417 // external linkage by default if the variable is declared with 11418 // __declspec(dllexport). 11419 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 11420 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 11421 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 11422 VDecl->setStorageClass(SC_Extern); 11423 11424 // C99 6.7.8p4. All file scoped initializers need to be constant. 11425 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 11426 CheckForConstantInitializer(Init, DclT); 11427 } 11428 11429 // We will represent direct-initialization similarly to copy-initialization: 11430 // int x(1); -as-> int x = 1; 11431 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 11432 // 11433 // Clients that want to distinguish between the two forms, can check for 11434 // direct initializer using VarDecl::getInitStyle(). 11435 // A major benefit is that clients that don't particularly care about which 11436 // exactly form was it (like the CodeGen) can handle both cases without 11437 // special case code. 11438 11439 // C++ 8.5p11: 11440 // The form of initialization (using parentheses or '=') is generally 11441 // insignificant, but does matter when the entity being initialized has a 11442 // class type. 11443 if (CXXDirectInit) { 11444 assert(DirectInit && "Call-style initializer must be direct init."); 11445 VDecl->setInitStyle(VarDecl::CallInit); 11446 } else if (DirectInit) { 11447 // This must be list-initialization. No other way is direct-initialization. 11448 VDecl->setInitStyle(VarDecl::ListInit); 11449 } 11450 11451 CheckCompleteVariableDeclaration(VDecl); 11452 } 11453 11454 /// ActOnInitializerError - Given that there was an error parsing an 11455 /// initializer for the given declaration, try to return to some form 11456 /// of sanity. 11457 void Sema::ActOnInitializerError(Decl *D) { 11458 // Our main concern here is re-establishing invariants like "a 11459 // variable's type is either dependent or complete". 11460 if (!D || D->isInvalidDecl()) return; 11461 11462 VarDecl *VD = dyn_cast<VarDecl>(D); 11463 if (!VD) return; 11464 11465 // Bindings are not usable if we can't make sense of the initializer. 11466 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11467 for (auto *BD : DD->bindings()) 11468 BD->setInvalidDecl(); 11469 11470 // Auto types are meaningless if we can't make sense of the initializer. 11471 if (ParsingInitForAutoVars.count(D)) { 11472 D->setInvalidDecl(); 11473 return; 11474 } 11475 11476 QualType Ty = VD->getType(); 11477 if (Ty->isDependentType()) return; 11478 11479 // Require a complete type. 11480 if (RequireCompleteType(VD->getLocation(), 11481 Context.getBaseElementType(Ty), 11482 diag::err_typecheck_decl_incomplete_type)) { 11483 VD->setInvalidDecl(); 11484 return; 11485 } 11486 11487 // Require a non-abstract type. 11488 if (RequireNonAbstractType(VD->getLocation(), Ty, 11489 diag::err_abstract_type_in_decl, 11490 AbstractVariableType)) { 11491 VD->setInvalidDecl(); 11492 return; 11493 } 11494 11495 // Don't bother complaining about constructors or destructors, 11496 // though. 11497 } 11498 11499 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11500 // If there is no declaration, there was an error parsing it. Just ignore it. 11501 if (!RealDecl) 11502 return; 11503 11504 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11505 QualType Type = Var->getType(); 11506 11507 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11508 if (isa<DecompositionDecl>(RealDecl)) { 11509 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11510 Var->setInvalidDecl(); 11511 return; 11512 } 11513 11514 if (Type->isUndeducedType() && 11515 DeduceVariableDeclarationType(Var, false, nullptr)) 11516 return; 11517 11518 // C++11 [class.static.data]p3: A static data member can be declared with 11519 // the constexpr specifier; if so, its declaration shall specify 11520 // a brace-or-equal-initializer. 11521 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11522 // the definition of a variable [...] or the declaration of a static data 11523 // member. 11524 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11525 !Var->isThisDeclarationADemotedDefinition()) { 11526 if (Var->isStaticDataMember()) { 11527 // C++1z removes the relevant rule; the in-class declaration is always 11528 // a definition there. 11529 if (!getLangOpts().CPlusPlus17) { 11530 Diag(Var->getLocation(), 11531 diag::err_constexpr_static_mem_var_requires_init) 11532 << Var->getDeclName(); 11533 Var->setInvalidDecl(); 11534 return; 11535 } 11536 } else { 11537 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11538 Var->setInvalidDecl(); 11539 return; 11540 } 11541 } 11542 11543 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11544 // be initialized. 11545 if (!Var->isInvalidDecl() && 11546 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11547 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11548 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11549 Var->setInvalidDecl(); 11550 return; 11551 } 11552 11553 switch (Var->isThisDeclarationADefinition()) { 11554 case VarDecl::Definition: 11555 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11556 break; 11557 11558 // We have an out-of-line definition of a static data member 11559 // that has an in-class initializer, so we type-check this like 11560 // a declaration. 11561 // 11562 LLVM_FALLTHROUGH; 11563 11564 case VarDecl::DeclarationOnly: 11565 // It's only a declaration. 11566 11567 // Block scope. C99 6.7p7: If an identifier for an object is 11568 // declared with no linkage (C99 6.2.2p6), the type for the 11569 // object shall be complete. 11570 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11571 !Var->hasLinkage() && !Var->isInvalidDecl() && 11572 RequireCompleteType(Var->getLocation(), Type, 11573 diag::err_typecheck_decl_incomplete_type)) 11574 Var->setInvalidDecl(); 11575 11576 // Make sure that the type is not abstract. 11577 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11578 RequireNonAbstractType(Var->getLocation(), Type, 11579 diag::err_abstract_type_in_decl, 11580 AbstractVariableType)) 11581 Var->setInvalidDecl(); 11582 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11583 Var->getStorageClass() == SC_PrivateExtern) { 11584 Diag(Var->getLocation(), diag::warn_private_extern); 11585 Diag(Var->getLocation(), diag::note_private_extern); 11586 } 11587 11588 return; 11589 11590 case VarDecl::TentativeDefinition: 11591 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11592 // object that has file scope without an initializer, and without a 11593 // storage-class specifier or with the storage-class specifier "static", 11594 // constitutes a tentative definition. Note: A tentative definition with 11595 // external linkage is valid (C99 6.2.2p5). 11596 if (!Var->isInvalidDecl()) { 11597 if (const IncompleteArrayType *ArrayT 11598 = Context.getAsIncompleteArrayType(Type)) { 11599 if (RequireCompleteType(Var->getLocation(), 11600 ArrayT->getElementType(), 11601 diag::err_illegal_decl_array_incomplete_type)) 11602 Var->setInvalidDecl(); 11603 } else if (Var->getStorageClass() == SC_Static) { 11604 // C99 6.9.2p3: If the declaration of an identifier for an object is 11605 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11606 // declared type shall not be an incomplete type. 11607 // NOTE: code such as the following 11608 // static struct s; 11609 // struct s { int a; }; 11610 // is accepted by gcc. Hence here we issue a warning instead of 11611 // an error and we do not invalidate the static declaration. 11612 // NOTE: to avoid multiple warnings, only check the first declaration. 11613 if (Var->isFirstDecl()) 11614 RequireCompleteType(Var->getLocation(), Type, 11615 diag::ext_typecheck_decl_incomplete_type); 11616 } 11617 } 11618 11619 // Record the tentative definition; we're done. 11620 if (!Var->isInvalidDecl()) 11621 TentativeDefinitions.push_back(Var); 11622 return; 11623 } 11624 11625 // Provide a specific diagnostic for uninitialized variable 11626 // definitions with incomplete array type. 11627 if (Type->isIncompleteArrayType()) { 11628 Diag(Var->getLocation(), 11629 diag::err_typecheck_incomplete_array_needs_initializer); 11630 Var->setInvalidDecl(); 11631 return; 11632 } 11633 11634 // Provide a specific diagnostic for uninitialized variable 11635 // definitions with reference type. 11636 if (Type->isReferenceType()) { 11637 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11638 << Var->getDeclName() 11639 << SourceRange(Var->getLocation(), Var->getLocation()); 11640 Var->setInvalidDecl(); 11641 return; 11642 } 11643 11644 // Do not attempt to type-check the default initializer for a 11645 // variable with dependent type. 11646 if (Type->isDependentType()) 11647 return; 11648 11649 if (Var->isInvalidDecl()) 11650 return; 11651 11652 if (!Var->hasAttr<AliasAttr>()) { 11653 if (RequireCompleteType(Var->getLocation(), 11654 Context.getBaseElementType(Type), 11655 diag::err_typecheck_decl_incomplete_type)) { 11656 Var->setInvalidDecl(); 11657 return; 11658 } 11659 } else { 11660 return; 11661 } 11662 11663 // The variable can not have an abstract class type. 11664 if (RequireNonAbstractType(Var->getLocation(), Type, 11665 diag::err_abstract_type_in_decl, 11666 AbstractVariableType)) { 11667 Var->setInvalidDecl(); 11668 return; 11669 } 11670 11671 // Check for jumps past the implicit initializer. C++0x 11672 // clarifies that this applies to a "variable with automatic 11673 // storage duration", not a "local variable". 11674 // C++11 [stmt.dcl]p3 11675 // A program that jumps from a point where a variable with automatic 11676 // storage duration is not in scope to a point where it is in scope is 11677 // ill-formed unless the variable has scalar type, class type with a 11678 // trivial default constructor and a trivial destructor, a cv-qualified 11679 // version of one of these types, or an array of one of the preceding 11680 // types and is declared without an initializer. 11681 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11682 if (const RecordType *Record 11683 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11684 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11685 // Mark the function (if we're in one) for further checking even if the 11686 // looser rules of C++11 do not require such checks, so that we can 11687 // diagnose incompatibilities with C++98. 11688 if (!CXXRecord->isPOD()) 11689 setFunctionHasBranchProtectedScope(); 11690 } 11691 } 11692 // In OpenCL, we can't initialize objects in the __local address space, 11693 // even implicitly, so don't synthesize an implicit initializer. 11694 if (getLangOpts().OpenCL && 11695 Var->getType().getAddressSpace() == LangAS::opencl_local) 11696 return; 11697 // C++03 [dcl.init]p9: 11698 // If no initializer is specified for an object, and the 11699 // object is of (possibly cv-qualified) non-POD class type (or 11700 // array thereof), the object shall be default-initialized; if 11701 // the object is of const-qualified type, the underlying class 11702 // type shall have a user-declared default 11703 // constructor. Otherwise, if no initializer is specified for 11704 // a non- static object, the object and its subobjects, if 11705 // any, have an indeterminate initial value); if the object 11706 // or any of its subobjects are of const-qualified type, the 11707 // program is ill-formed. 11708 // C++0x [dcl.init]p11: 11709 // If no initializer is specified for an object, the object is 11710 // default-initialized; [...]. 11711 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11712 InitializationKind Kind 11713 = InitializationKind::CreateDefault(Var->getLocation()); 11714 11715 InitializationSequence InitSeq(*this, Entity, Kind, None); 11716 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11717 if (Init.isInvalid()) 11718 Var->setInvalidDecl(); 11719 else if (Init.get()) { 11720 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11721 // This is important for template substitution. 11722 Var->setInitStyle(VarDecl::CallInit); 11723 } 11724 11725 CheckCompleteVariableDeclaration(Var); 11726 } 11727 } 11728 11729 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11730 // If there is no declaration, there was an error parsing it. Ignore it. 11731 if (!D) 11732 return; 11733 11734 VarDecl *VD = dyn_cast<VarDecl>(D); 11735 if (!VD) { 11736 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11737 D->setInvalidDecl(); 11738 return; 11739 } 11740 11741 VD->setCXXForRangeDecl(true); 11742 11743 // for-range-declaration cannot be given a storage class specifier. 11744 int Error = -1; 11745 switch (VD->getStorageClass()) { 11746 case SC_None: 11747 break; 11748 case SC_Extern: 11749 Error = 0; 11750 break; 11751 case SC_Static: 11752 Error = 1; 11753 break; 11754 case SC_PrivateExtern: 11755 Error = 2; 11756 break; 11757 case SC_Auto: 11758 Error = 3; 11759 break; 11760 case SC_Register: 11761 Error = 4; 11762 break; 11763 } 11764 if (Error != -1) { 11765 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11766 << VD->getDeclName() << Error; 11767 D->setInvalidDecl(); 11768 } 11769 } 11770 11771 StmtResult 11772 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11773 IdentifierInfo *Ident, 11774 ParsedAttributes &Attrs, 11775 SourceLocation AttrEnd) { 11776 // C++1y [stmt.iter]p1: 11777 // A range-based for statement of the form 11778 // for ( for-range-identifier : for-range-initializer ) statement 11779 // is equivalent to 11780 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11781 DeclSpec DS(Attrs.getPool().getFactory()); 11782 11783 const char *PrevSpec; 11784 unsigned DiagID; 11785 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11786 getPrintingPolicy()); 11787 11788 Declarator D(DS, DeclaratorContext::ForContext); 11789 D.SetIdentifier(Ident, IdentLoc); 11790 D.takeAttributes(Attrs, AttrEnd); 11791 11792 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 11793 IdentLoc); 11794 Decl *Var = ActOnDeclarator(S, D); 11795 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11796 FinalizeDeclaration(Var); 11797 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11798 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11799 } 11800 11801 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11802 if (var->isInvalidDecl()) return; 11803 11804 if (getLangOpts().OpenCL) { 11805 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11806 // initialiser 11807 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11808 !var->hasInit()) { 11809 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11810 << 1 /*Init*/; 11811 var->setInvalidDecl(); 11812 return; 11813 } 11814 } 11815 11816 // In Objective-C, don't allow jumps past the implicit initialization of a 11817 // local retaining variable. 11818 if (getLangOpts().ObjC && 11819 var->hasLocalStorage()) { 11820 switch (var->getType().getObjCLifetime()) { 11821 case Qualifiers::OCL_None: 11822 case Qualifiers::OCL_ExplicitNone: 11823 case Qualifiers::OCL_Autoreleasing: 11824 break; 11825 11826 case Qualifiers::OCL_Weak: 11827 case Qualifiers::OCL_Strong: 11828 setFunctionHasBranchProtectedScope(); 11829 break; 11830 } 11831 } 11832 11833 if (var->hasLocalStorage() && 11834 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11835 setFunctionHasBranchProtectedScope(); 11836 11837 // Warn about externally-visible variables being defined without a 11838 // prior declaration. We only want to do this for global 11839 // declarations, but we also specifically need to avoid doing it for 11840 // class members because the linkage of an anonymous class can 11841 // change if it's later given a typedef name. 11842 if (var->isThisDeclarationADefinition() && 11843 var->getDeclContext()->getRedeclContext()->isFileContext() && 11844 var->isExternallyVisible() && var->hasLinkage() && 11845 !var->isInline() && !var->getDescribedVarTemplate() && 11846 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11847 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11848 var->getLocation())) { 11849 // Find a previous declaration that's not a definition. 11850 VarDecl *prev = var->getPreviousDecl(); 11851 while (prev && prev->isThisDeclarationADefinition()) 11852 prev = prev->getPreviousDecl(); 11853 11854 if (!prev) 11855 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11856 } 11857 11858 // Cache the result of checking for constant initialization. 11859 Optional<bool> CacheHasConstInit; 11860 const Expr *CacheCulprit; 11861 auto checkConstInit = [&]() mutable { 11862 if (!CacheHasConstInit) 11863 CacheHasConstInit = var->getInit()->isConstantInitializer( 11864 Context, var->getType()->isReferenceType(), &CacheCulprit); 11865 return *CacheHasConstInit; 11866 }; 11867 11868 if (var->getTLSKind() == VarDecl::TLS_Static) { 11869 if (var->getType().isDestructedType()) { 11870 // GNU C++98 edits for __thread, [basic.start.term]p3: 11871 // The type of an object with thread storage duration shall not 11872 // have a non-trivial destructor. 11873 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11874 if (getLangOpts().CPlusPlus11) 11875 Diag(var->getLocation(), diag::note_use_thread_local); 11876 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11877 if (!checkConstInit()) { 11878 // GNU C++98 edits for __thread, [basic.start.init]p4: 11879 // An object of thread storage duration shall not require dynamic 11880 // initialization. 11881 // FIXME: Need strict checking here. 11882 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11883 << CacheCulprit->getSourceRange(); 11884 if (getLangOpts().CPlusPlus11) 11885 Diag(var->getLocation(), diag::note_use_thread_local); 11886 } 11887 } 11888 } 11889 11890 // Apply section attributes and pragmas to global variables. 11891 bool GlobalStorage = var->hasGlobalStorage(); 11892 if (GlobalStorage && var->isThisDeclarationADefinition() && 11893 !inTemplateInstantiation()) { 11894 PragmaStack<StringLiteral *> *Stack = nullptr; 11895 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11896 if (var->getType().isConstQualified()) 11897 Stack = &ConstSegStack; 11898 else if (!var->getInit()) { 11899 Stack = &BSSSegStack; 11900 SectionFlags |= ASTContext::PSF_Write; 11901 } else { 11902 Stack = &DataSegStack; 11903 SectionFlags |= ASTContext::PSF_Write; 11904 } 11905 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11906 var->addAttr(SectionAttr::CreateImplicit( 11907 Context, SectionAttr::Declspec_allocate, 11908 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11909 } 11910 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11911 if (UnifySection(SA->getName(), SectionFlags, var)) 11912 var->dropAttr<SectionAttr>(); 11913 11914 // Apply the init_seg attribute if this has an initializer. If the 11915 // initializer turns out to not be dynamic, we'll end up ignoring this 11916 // attribute. 11917 if (CurInitSeg && var->getInit()) 11918 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11919 CurInitSegLoc)); 11920 } 11921 11922 // All the following checks are C++ only. 11923 if (!getLangOpts().CPlusPlus) { 11924 // If this variable must be emitted, add it as an initializer for the 11925 // current module. 11926 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11927 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11928 return; 11929 } 11930 11931 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11932 CheckCompleteDecompositionDeclaration(DD); 11933 11934 QualType type = var->getType(); 11935 if (type->isDependentType()) return; 11936 11937 if (var->hasAttr<BlocksAttr>()) 11938 getCurFunction()->addByrefBlockVar(var); 11939 11940 Expr *Init = var->getInit(); 11941 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11942 QualType baseType = Context.getBaseElementType(type); 11943 11944 if (Init && !Init->isValueDependent()) { 11945 if (var->isConstexpr()) { 11946 SmallVector<PartialDiagnosticAt, 8> Notes; 11947 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11948 SourceLocation DiagLoc = var->getLocation(); 11949 // If the note doesn't add any useful information other than a source 11950 // location, fold it into the primary diagnostic. 11951 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11952 diag::note_invalid_subexpr_in_const_expr) { 11953 DiagLoc = Notes[0].first; 11954 Notes.clear(); 11955 } 11956 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11957 << var << Init->getSourceRange(); 11958 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11959 Diag(Notes[I].first, Notes[I].second); 11960 } 11961 } else if (var->isUsableInConstantExpressions(Context)) { 11962 // Check whether the initializer of a const variable of integral or 11963 // enumeration type is an ICE now, since we can't tell whether it was 11964 // initialized by a constant expression if we check later. 11965 var->checkInitIsICE(); 11966 } 11967 11968 // Don't emit further diagnostics about constexpr globals since they 11969 // were just diagnosed. 11970 if (!var->isConstexpr() && GlobalStorage && 11971 var->hasAttr<RequireConstantInitAttr>()) { 11972 // FIXME: Need strict checking in C++03 here. 11973 bool DiagErr = getLangOpts().CPlusPlus11 11974 ? !var->checkInitIsICE() : !checkConstInit(); 11975 if (DiagErr) { 11976 auto attr = var->getAttr<RequireConstantInitAttr>(); 11977 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11978 << Init->getSourceRange(); 11979 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11980 << attr->getRange(); 11981 if (getLangOpts().CPlusPlus11) { 11982 APValue Value; 11983 SmallVector<PartialDiagnosticAt, 8> Notes; 11984 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11985 for (auto &it : Notes) 11986 Diag(it.first, it.second); 11987 } else { 11988 Diag(CacheCulprit->getExprLoc(), 11989 diag::note_invalid_subexpr_in_const_expr) 11990 << CacheCulprit->getSourceRange(); 11991 } 11992 } 11993 } 11994 else if (!var->isConstexpr() && IsGlobal && 11995 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11996 var->getLocation())) { 11997 // Warn about globals which don't have a constant initializer. Don't 11998 // warn about globals with a non-trivial destructor because we already 11999 // warned about them. 12000 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12001 if (!(RD && !RD->hasTrivialDestructor())) { 12002 if (!checkConstInit()) 12003 Diag(var->getLocation(), diag::warn_global_constructor) 12004 << Init->getSourceRange(); 12005 } 12006 } 12007 } 12008 12009 // Require the destructor. 12010 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12011 FinalizeVarWithDestructor(var, recordType); 12012 12013 // If this variable must be emitted, add it as an initializer for the current 12014 // module. 12015 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12016 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12017 } 12018 12019 /// Determines if a variable's alignment is dependent. 12020 static bool hasDependentAlignment(VarDecl *VD) { 12021 if (VD->getType()->isDependentType()) 12022 return true; 12023 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12024 if (I->isAlignmentDependent()) 12025 return true; 12026 return false; 12027 } 12028 12029 /// Check if VD needs to be dllexport/dllimport due to being in a 12030 /// dllexport/import function. 12031 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12032 assert(VD->isStaticLocal()); 12033 12034 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12035 12036 // Find outermost function when VD is in lambda function. 12037 while (FD && !getDLLAttr(FD) && 12038 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12039 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12040 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12041 } 12042 12043 if (!FD) 12044 return; 12045 12046 // Static locals inherit dll attributes from their function. 12047 if (Attr *A = getDLLAttr(FD)) { 12048 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12049 NewAttr->setInherited(true); 12050 VD->addAttr(NewAttr); 12051 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12052 auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(), 12053 getASTContext(), 12054 A->getSpellingListIndex()); 12055 NewAttr->setInherited(true); 12056 VD->addAttr(NewAttr); 12057 12058 // Export this function to enforce exporting this static variable even 12059 // if it is not used in this compilation unit. 12060 if (!FD->hasAttr<DLLExportAttr>()) 12061 FD->addAttr(NewAttr); 12062 12063 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12064 auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(), 12065 getASTContext(), 12066 A->getSpellingListIndex()); 12067 NewAttr->setInherited(true); 12068 VD->addAttr(NewAttr); 12069 } 12070 } 12071 12072 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12073 /// any semantic actions necessary after any initializer has been attached. 12074 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12075 // Note that we are no longer parsing the initializer for this declaration. 12076 ParsingInitForAutoVars.erase(ThisDecl); 12077 12078 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12079 if (!VD) 12080 return; 12081 12082 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12083 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12084 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12085 if (PragmaClangBSSSection.Valid) 12086 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 12087 PragmaClangBSSSection.SectionName, 12088 PragmaClangBSSSection.PragmaLocation)); 12089 if (PragmaClangDataSection.Valid) 12090 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 12091 PragmaClangDataSection.SectionName, 12092 PragmaClangDataSection.PragmaLocation)); 12093 if (PragmaClangRodataSection.Valid) 12094 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 12095 PragmaClangRodataSection.SectionName, 12096 PragmaClangRodataSection.PragmaLocation)); 12097 } 12098 12099 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12100 for (auto *BD : DD->bindings()) { 12101 FinalizeDeclaration(BD); 12102 } 12103 } 12104 12105 checkAttributesAfterMerging(*this, *VD); 12106 12107 // Perform TLS alignment check here after attributes attached to the variable 12108 // which may affect the alignment have been processed. Only perform the check 12109 // if the target has a maximum TLS alignment (zero means no constraints). 12110 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12111 // Protect the check so that it's not performed on dependent types and 12112 // dependent alignments (we can't determine the alignment in that case). 12113 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12114 !VD->isInvalidDecl()) { 12115 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12116 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12117 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12118 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12119 << (unsigned)MaxAlignChars.getQuantity(); 12120 } 12121 } 12122 } 12123 12124 if (VD->isStaticLocal()) { 12125 CheckStaticLocalForDllExport(VD); 12126 12127 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12128 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12129 // function, only __shared__ variables or variables without any device 12130 // memory qualifiers may be declared with static storage class. 12131 // Note: It is unclear how a function-scope non-const static variable 12132 // without device memory qualifier is implemented, therefore only static 12133 // const variable without device memory qualifier is allowed. 12134 [&]() { 12135 if (!getLangOpts().CUDA) 12136 return; 12137 if (VD->hasAttr<CUDASharedAttr>()) 12138 return; 12139 if (VD->getType().isConstQualified() && 12140 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12141 return; 12142 if (CUDADiagIfDeviceCode(VD->getLocation(), 12143 diag::err_device_static_local_var) 12144 << CurrentCUDATarget()) 12145 VD->setInvalidDecl(); 12146 }(); 12147 } 12148 } 12149 12150 // Perform check for initializers of device-side global variables. 12151 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12152 // 7.5). We must also apply the same checks to all __shared__ 12153 // variables whether they are local or not. CUDA also allows 12154 // constant initializers for __constant__ and __device__ variables. 12155 if (getLangOpts().CUDA) 12156 checkAllowedCUDAInitializer(VD); 12157 12158 // Grab the dllimport or dllexport attribute off of the VarDecl. 12159 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12160 12161 // Imported static data members cannot be defined out-of-line. 12162 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12163 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12164 VD->isThisDeclarationADefinition()) { 12165 // We allow definitions of dllimport class template static data members 12166 // with a warning. 12167 CXXRecordDecl *Context = 12168 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12169 bool IsClassTemplateMember = 12170 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12171 Context->getDescribedClassTemplate(); 12172 12173 Diag(VD->getLocation(), 12174 IsClassTemplateMember 12175 ? diag::warn_attribute_dllimport_static_field_definition 12176 : diag::err_attribute_dllimport_static_field_definition); 12177 Diag(IA->getLocation(), diag::note_attribute); 12178 if (!IsClassTemplateMember) 12179 VD->setInvalidDecl(); 12180 } 12181 } 12182 12183 // dllimport/dllexport variables cannot be thread local, their TLS index 12184 // isn't exported with the variable. 12185 if (DLLAttr && VD->getTLSKind()) { 12186 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12187 if (F && getDLLAttr(F)) { 12188 assert(VD->isStaticLocal()); 12189 // But if this is a static local in a dlimport/dllexport function, the 12190 // function will never be inlined, which means the var would never be 12191 // imported, so having it marked import/export is safe. 12192 } else { 12193 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 12194 << DLLAttr; 12195 VD->setInvalidDecl(); 12196 } 12197 } 12198 12199 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 12200 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 12201 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 12202 VD->dropAttr<UsedAttr>(); 12203 } 12204 } 12205 12206 const DeclContext *DC = VD->getDeclContext(); 12207 // If there's a #pragma GCC visibility in scope, and this isn't a class 12208 // member, set the visibility of this variable. 12209 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 12210 AddPushedVisibilityAttribute(VD); 12211 12212 // FIXME: Warn on unused var template partial specializations. 12213 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 12214 MarkUnusedFileScopedDecl(VD); 12215 12216 // Now we have parsed the initializer and can update the table of magic 12217 // tag values. 12218 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 12219 !VD->getType()->isIntegralOrEnumerationType()) 12220 return; 12221 12222 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 12223 const Expr *MagicValueExpr = VD->getInit(); 12224 if (!MagicValueExpr) { 12225 continue; 12226 } 12227 llvm::APSInt MagicValueInt; 12228 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 12229 Diag(I->getRange().getBegin(), 12230 diag::err_type_tag_for_datatype_not_ice) 12231 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12232 continue; 12233 } 12234 if (MagicValueInt.getActiveBits() > 64) { 12235 Diag(I->getRange().getBegin(), 12236 diag::err_type_tag_for_datatype_too_large) 12237 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12238 continue; 12239 } 12240 uint64_t MagicValue = MagicValueInt.getZExtValue(); 12241 RegisterTypeTagForDatatype(I->getArgumentKind(), 12242 MagicValue, 12243 I->getMatchingCType(), 12244 I->getLayoutCompatible(), 12245 I->getMustBeNull()); 12246 } 12247 } 12248 12249 static bool hasDeducedAuto(DeclaratorDecl *DD) { 12250 auto *VD = dyn_cast<VarDecl>(DD); 12251 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 12252 } 12253 12254 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 12255 ArrayRef<Decl *> Group) { 12256 SmallVector<Decl*, 8> Decls; 12257 12258 if (DS.isTypeSpecOwned()) 12259 Decls.push_back(DS.getRepAsDecl()); 12260 12261 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 12262 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 12263 bool DiagnosedMultipleDecomps = false; 12264 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 12265 bool DiagnosedNonDeducedAuto = false; 12266 12267 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12268 if (Decl *D = Group[i]) { 12269 // For declarators, there are some additional syntactic-ish checks we need 12270 // to perform. 12271 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 12272 if (!FirstDeclaratorInGroup) 12273 FirstDeclaratorInGroup = DD; 12274 if (!FirstDecompDeclaratorInGroup) 12275 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 12276 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 12277 !hasDeducedAuto(DD)) 12278 FirstNonDeducedAutoInGroup = DD; 12279 12280 if (FirstDeclaratorInGroup != DD) { 12281 // A decomposition declaration cannot be combined with any other 12282 // declaration in the same group. 12283 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 12284 Diag(FirstDecompDeclaratorInGroup->getLocation(), 12285 diag::err_decomp_decl_not_alone) 12286 << FirstDeclaratorInGroup->getSourceRange() 12287 << DD->getSourceRange(); 12288 DiagnosedMultipleDecomps = true; 12289 } 12290 12291 // A declarator that uses 'auto' in any way other than to declare a 12292 // variable with a deduced type cannot be combined with any other 12293 // declarator in the same group. 12294 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 12295 Diag(FirstNonDeducedAutoInGroup->getLocation(), 12296 diag::err_auto_non_deduced_not_alone) 12297 << FirstNonDeducedAutoInGroup->getType() 12298 ->hasAutoForTrailingReturnType() 12299 << FirstDeclaratorInGroup->getSourceRange() 12300 << DD->getSourceRange(); 12301 DiagnosedNonDeducedAuto = true; 12302 } 12303 } 12304 } 12305 12306 Decls.push_back(D); 12307 } 12308 } 12309 12310 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 12311 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 12312 handleTagNumbering(Tag, S); 12313 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 12314 getLangOpts().CPlusPlus) 12315 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 12316 } 12317 } 12318 12319 return BuildDeclaratorGroup(Decls); 12320 } 12321 12322 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 12323 /// group, performing any necessary semantic checking. 12324 Sema::DeclGroupPtrTy 12325 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 12326 // C++14 [dcl.spec.auto]p7: (DR1347) 12327 // If the type that replaces the placeholder type is not the same in each 12328 // deduction, the program is ill-formed. 12329 if (Group.size() > 1) { 12330 QualType Deduced; 12331 VarDecl *DeducedDecl = nullptr; 12332 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12333 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 12334 if (!D || D->isInvalidDecl()) 12335 break; 12336 DeducedType *DT = D->getType()->getContainedDeducedType(); 12337 if (!DT || DT->getDeducedType().isNull()) 12338 continue; 12339 if (Deduced.isNull()) { 12340 Deduced = DT->getDeducedType(); 12341 DeducedDecl = D; 12342 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 12343 auto *AT = dyn_cast<AutoType>(DT); 12344 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 12345 diag::err_auto_different_deductions) 12346 << (AT ? (unsigned)AT->getKeyword() : 3) 12347 << Deduced << DeducedDecl->getDeclName() 12348 << DT->getDeducedType() << D->getDeclName() 12349 << DeducedDecl->getInit()->getSourceRange() 12350 << D->getInit()->getSourceRange(); 12351 D->setInvalidDecl(); 12352 break; 12353 } 12354 } 12355 } 12356 12357 ActOnDocumentableDecls(Group); 12358 12359 return DeclGroupPtrTy::make( 12360 DeclGroupRef::Create(Context, Group.data(), Group.size())); 12361 } 12362 12363 void Sema::ActOnDocumentableDecl(Decl *D) { 12364 ActOnDocumentableDecls(D); 12365 } 12366 12367 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 12368 // Don't parse the comment if Doxygen diagnostics are ignored. 12369 if (Group.empty() || !Group[0]) 12370 return; 12371 12372 if (Diags.isIgnored(diag::warn_doc_param_not_found, 12373 Group[0]->getLocation()) && 12374 Diags.isIgnored(diag::warn_unknown_comment_command_name, 12375 Group[0]->getLocation())) 12376 return; 12377 12378 if (Group.size() >= 2) { 12379 // This is a decl group. Normally it will contain only declarations 12380 // produced from declarator list. But in case we have any definitions or 12381 // additional declaration references: 12382 // 'typedef struct S {} S;' 12383 // 'typedef struct S *S;' 12384 // 'struct S *pS;' 12385 // FinalizeDeclaratorGroup adds these as separate declarations. 12386 Decl *MaybeTagDecl = Group[0]; 12387 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 12388 Group = Group.slice(1); 12389 } 12390 } 12391 12392 // See if there are any new comments that are not attached to a decl. 12393 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 12394 if (!Comments.empty() && 12395 !Comments.back()->isAttached()) { 12396 // There is at least one comment that not attached to a decl. 12397 // Maybe it should be attached to one of these decls? 12398 // 12399 // Note that this way we pick up not only comments that precede the 12400 // declaration, but also comments that *follow* the declaration -- thanks to 12401 // the lookahead in the lexer: we've consumed the semicolon and looked 12402 // ahead through comments. 12403 for (unsigned i = 0, e = Group.size(); i != e; ++i) 12404 Context.getCommentForDecl(Group[i], &PP); 12405 } 12406 } 12407 12408 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 12409 /// to introduce parameters into function prototype scope. 12410 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 12411 const DeclSpec &DS = D.getDeclSpec(); 12412 12413 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 12414 12415 // C++03 [dcl.stc]p2 also permits 'auto'. 12416 StorageClass SC = SC_None; 12417 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 12418 SC = SC_Register; 12419 // In C++11, the 'register' storage class specifier is deprecated. 12420 // In C++17, it is not allowed, but we tolerate it as an extension. 12421 if (getLangOpts().CPlusPlus11) { 12422 Diag(DS.getStorageClassSpecLoc(), 12423 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 12424 : diag::warn_deprecated_register) 12425 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12426 } 12427 } else if (getLangOpts().CPlusPlus && 12428 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 12429 SC = SC_Auto; 12430 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 12431 Diag(DS.getStorageClassSpecLoc(), 12432 diag::err_invalid_storage_class_in_func_decl); 12433 D.getMutableDeclSpec().ClearStorageClassSpecs(); 12434 } 12435 12436 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12437 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12438 << DeclSpec::getSpecifierName(TSCS); 12439 if (DS.isInlineSpecified()) 12440 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12441 << getLangOpts().CPlusPlus17; 12442 if (DS.isConstexprSpecified()) 12443 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12444 << 0; 12445 12446 DiagnoseFunctionSpecifiers(DS); 12447 12448 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12449 QualType parmDeclType = TInfo->getType(); 12450 12451 if (getLangOpts().CPlusPlus) { 12452 // Check that there are no default arguments inside the type of this 12453 // parameter. 12454 CheckExtraCXXDefaultArguments(D); 12455 12456 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12457 if (D.getCXXScopeSpec().isSet()) { 12458 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12459 << D.getCXXScopeSpec().getRange(); 12460 D.getCXXScopeSpec().clear(); 12461 } 12462 } 12463 12464 // Ensure we have a valid name 12465 IdentifierInfo *II = nullptr; 12466 if (D.hasName()) { 12467 II = D.getIdentifier(); 12468 if (!II) { 12469 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12470 << GetNameForDeclarator(D).getName(); 12471 D.setInvalidType(true); 12472 } 12473 } 12474 12475 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12476 if (II) { 12477 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12478 ForVisibleRedeclaration); 12479 LookupName(R, S); 12480 if (R.isSingleResult()) { 12481 NamedDecl *PrevDecl = R.getFoundDecl(); 12482 if (PrevDecl->isTemplateParameter()) { 12483 // Maybe we will complain about the shadowed template parameter. 12484 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12485 // Just pretend that we didn't see the previous declaration. 12486 PrevDecl = nullptr; 12487 } else if (S->isDeclScope(PrevDecl)) { 12488 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12489 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12490 12491 // Recover by removing the name 12492 II = nullptr; 12493 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12494 D.setInvalidType(true); 12495 } 12496 } 12497 } 12498 12499 // Temporarily put parameter variables in the translation unit, not 12500 // the enclosing context. This prevents them from accidentally 12501 // looking like class members in C++. 12502 ParmVarDecl *New = 12503 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 12504 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 12505 12506 if (D.isInvalidType()) 12507 New->setInvalidDecl(); 12508 12509 assert(S->isFunctionPrototypeScope()); 12510 assert(S->getFunctionPrototypeDepth() >= 1); 12511 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12512 S->getNextFunctionPrototypeIndex()); 12513 12514 // Add the parameter declaration into this scope. 12515 S->AddDecl(New); 12516 if (II) 12517 IdResolver.AddDecl(New); 12518 12519 ProcessDeclAttributes(S, New, D); 12520 12521 if (D.getDeclSpec().isModulePrivateSpecified()) 12522 Diag(New->getLocation(), diag::err_module_private_local) 12523 << 1 << New->getDeclName() 12524 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12525 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12526 12527 if (New->hasAttr<BlocksAttr>()) { 12528 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12529 } 12530 return New; 12531 } 12532 12533 /// Synthesizes a variable for a parameter arising from a 12534 /// typedef. 12535 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12536 SourceLocation Loc, 12537 QualType T) { 12538 /* FIXME: setting StartLoc == Loc. 12539 Would it be worth to modify callers so as to provide proper source 12540 location for the unnamed parameters, embedding the parameter's type? */ 12541 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12542 T, Context.getTrivialTypeSourceInfo(T, Loc), 12543 SC_None, nullptr); 12544 Param->setImplicit(); 12545 return Param; 12546 } 12547 12548 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12549 // Don't diagnose unused-parameter errors in template instantiations; we 12550 // will already have done so in the template itself. 12551 if (inTemplateInstantiation()) 12552 return; 12553 12554 for (const ParmVarDecl *Parameter : Parameters) { 12555 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12556 !Parameter->hasAttr<UnusedAttr>()) { 12557 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12558 << Parameter->getDeclName(); 12559 } 12560 } 12561 } 12562 12563 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12564 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12565 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12566 return; 12567 12568 // Warn if the return value is pass-by-value and larger than the specified 12569 // threshold. 12570 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12571 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12572 if (Size > LangOpts.NumLargeByValueCopy) 12573 Diag(D->getLocation(), diag::warn_return_value_size) 12574 << D->getDeclName() << Size; 12575 } 12576 12577 // Warn if any parameter is pass-by-value and larger than the specified 12578 // threshold. 12579 for (const ParmVarDecl *Parameter : Parameters) { 12580 QualType T = Parameter->getType(); 12581 if (T->isDependentType() || !T.isPODType(Context)) 12582 continue; 12583 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12584 if (Size > LangOpts.NumLargeByValueCopy) 12585 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12586 << Parameter->getDeclName() << Size; 12587 } 12588 } 12589 12590 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12591 SourceLocation NameLoc, IdentifierInfo *Name, 12592 QualType T, TypeSourceInfo *TSInfo, 12593 StorageClass SC) { 12594 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12595 if (getLangOpts().ObjCAutoRefCount && 12596 T.getObjCLifetime() == Qualifiers::OCL_None && 12597 T->isObjCLifetimeType()) { 12598 12599 Qualifiers::ObjCLifetime lifetime; 12600 12601 // Special cases for arrays: 12602 // - if it's const, use __unsafe_unretained 12603 // - otherwise, it's an error 12604 if (T->isArrayType()) { 12605 if (!T.isConstQualified()) { 12606 if (DelayedDiagnostics.shouldDelayDiagnostics()) 12607 DelayedDiagnostics.add( 12608 sema::DelayedDiagnostic::makeForbiddenType( 12609 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12610 else 12611 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 12612 << TSInfo->getTypeLoc().getSourceRange(); 12613 } 12614 lifetime = Qualifiers::OCL_ExplicitNone; 12615 } else { 12616 lifetime = T->getObjCARCImplicitLifetime(); 12617 } 12618 T = Context.getLifetimeQualifiedType(T, lifetime); 12619 } 12620 12621 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12622 Context.getAdjustedParameterType(T), 12623 TSInfo, SC, nullptr); 12624 12625 // Parameters can not be abstract class types. 12626 // For record types, this is done by the AbstractClassUsageDiagnoser once 12627 // the class has been completely parsed. 12628 if (!CurContext->isRecord() && 12629 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12630 AbstractParamType)) 12631 New->setInvalidDecl(); 12632 12633 // Parameter declarators cannot be interface types. All ObjC objects are 12634 // passed by reference. 12635 if (T->isObjCObjectType()) { 12636 SourceLocation TypeEndLoc = 12637 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 12638 Diag(NameLoc, 12639 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12640 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12641 T = Context.getObjCObjectPointerType(T); 12642 New->setType(T); 12643 } 12644 12645 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12646 // duration shall not be qualified by an address-space qualifier." 12647 // Since all parameters have automatic store duration, they can not have 12648 // an address space. 12649 if (T.getAddressSpace() != LangAS::Default && 12650 // OpenCL allows function arguments declared to be an array of a type 12651 // to be qualified with an address space. 12652 !(getLangOpts().OpenCL && 12653 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12654 Diag(NameLoc, diag::err_arg_with_address_space); 12655 New->setInvalidDecl(); 12656 } 12657 12658 return New; 12659 } 12660 12661 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12662 SourceLocation LocAfterDecls) { 12663 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12664 12665 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12666 // for a K&R function. 12667 if (!FTI.hasPrototype) { 12668 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12669 --i; 12670 if (FTI.Params[i].Param == nullptr) { 12671 SmallString<256> Code; 12672 llvm::raw_svector_ostream(Code) 12673 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12674 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12675 << FTI.Params[i].Ident 12676 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12677 12678 // Implicitly declare the argument as type 'int' for lack of a better 12679 // type. 12680 AttributeFactory attrs; 12681 DeclSpec DS(attrs); 12682 const char* PrevSpec; // unused 12683 unsigned DiagID; // unused 12684 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12685 DiagID, Context.getPrintingPolicy()); 12686 // Use the identifier location for the type source range. 12687 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12688 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12689 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12690 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12691 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12692 } 12693 } 12694 } 12695 } 12696 12697 Decl * 12698 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12699 MultiTemplateParamsArg TemplateParameterLists, 12700 SkipBodyInfo *SkipBody) { 12701 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12702 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12703 Scope *ParentScope = FnBodyScope->getParent(); 12704 12705 D.setFunctionDefinitionKind(FDK_Definition); 12706 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12707 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12708 } 12709 12710 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12711 Consumer.HandleInlineFunctionDefinition(D); 12712 } 12713 12714 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12715 const FunctionDecl*& PossibleZeroParamPrototype) { 12716 // Don't warn about invalid declarations. 12717 if (FD->isInvalidDecl()) 12718 return false; 12719 12720 // Or declarations that aren't global. 12721 if (!FD->isGlobal()) 12722 return false; 12723 12724 // Don't warn about C++ member functions. 12725 if (isa<CXXMethodDecl>(FD)) 12726 return false; 12727 12728 // Don't warn about 'main'. 12729 if (FD->isMain()) 12730 return false; 12731 12732 // Don't warn about inline functions. 12733 if (FD->isInlined()) 12734 return false; 12735 12736 // Don't warn about function templates. 12737 if (FD->getDescribedFunctionTemplate()) 12738 return false; 12739 12740 // Don't warn about function template specializations. 12741 if (FD->isFunctionTemplateSpecialization()) 12742 return false; 12743 12744 // Don't warn for OpenCL kernels. 12745 if (FD->hasAttr<OpenCLKernelAttr>()) 12746 return false; 12747 12748 // Don't warn on explicitly deleted functions. 12749 if (FD->isDeleted()) 12750 return false; 12751 12752 bool MissingPrototype = true; 12753 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12754 Prev; Prev = Prev->getPreviousDecl()) { 12755 // Ignore any declarations that occur in function or method 12756 // scope, because they aren't visible from the header. 12757 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12758 continue; 12759 12760 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12761 if (FD->getNumParams() == 0) 12762 PossibleZeroParamPrototype = Prev; 12763 break; 12764 } 12765 12766 return MissingPrototype; 12767 } 12768 12769 void 12770 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12771 const FunctionDecl *EffectiveDefinition, 12772 SkipBodyInfo *SkipBody) { 12773 const FunctionDecl *Definition = EffectiveDefinition; 12774 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12775 // If this is a friend function defined in a class template, it does not 12776 // have a body until it is used, nevertheless it is a definition, see 12777 // [temp.inst]p2: 12778 // 12779 // ... for the purpose of determining whether an instantiated redeclaration 12780 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12781 // corresponds to a definition in the template is considered to be a 12782 // definition. 12783 // 12784 // The following code must produce redefinition error: 12785 // 12786 // template<typename T> struct C20 { friend void func_20() {} }; 12787 // C20<int> c20i; 12788 // void func_20() {} 12789 // 12790 for (auto I : FD->redecls()) { 12791 if (I != FD && !I->isInvalidDecl() && 12792 I->getFriendObjectKind() != Decl::FOK_None) { 12793 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12794 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12795 // A merged copy of the same function, instantiated as a member of 12796 // the same class, is OK. 12797 if (declaresSameEntity(OrigFD, Original) && 12798 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12799 cast<Decl>(FD->getLexicalDeclContext()))) 12800 continue; 12801 } 12802 12803 if (Original->isThisDeclarationADefinition()) { 12804 Definition = I; 12805 break; 12806 } 12807 } 12808 } 12809 } 12810 } 12811 12812 if (!Definition) 12813 // Similar to friend functions a friend function template may be a 12814 // definition and do not have a body if it is instantiated in a class 12815 // template. 12816 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 12817 for (auto I : FTD->redecls()) { 12818 auto D = cast<FunctionTemplateDecl>(I); 12819 if (D != FTD) { 12820 assert(!D->isThisDeclarationADefinition() && 12821 "More than one definition in redeclaration chain"); 12822 if (D->getFriendObjectKind() != Decl::FOK_None) 12823 if (FunctionTemplateDecl *FT = 12824 D->getInstantiatedFromMemberTemplate()) { 12825 if (FT->isThisDeclarationADefinition()) { 12826 Definition = D->getTemplatedDecl(); 12827 break; 12828 } 12829 } 12830 } 12831 } 12832 } 12833 12834 if (!Definition) 12835 return; 12836 12837 if (canRedefineFunction(Definition, getLangOpts())) 12838 return; 12839 12840 // Don't emit an error when this is redefinition of a typo-corrected 12841 // definition. 12842 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12843 return; 12844 12845 // If we don't have a visible definition of the function, and it's inline or 12846 // a template, skip the new definition. 12847 if (SkipBody && !hasVisibleDefinition(Definition) && 12848 (Definition->getFormalLinkage() == InternalLinkage || 12849 Definition->isInlined() || 12850 Definition->getDescribedFunctionTemplate() || 12851 Definition->getNumTemplateParameterLists())) { 12852 SkipBody->ShouldSkip = true; 12853 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 12854 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12855 makeMergedDefinitionVisible(TD); 12856 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12857 return; 12858 } 12859 12860 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12861 Definition->getStorageClass() == SC_Extern) 12862 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12863 << FD->getDeclName() << getLangOpts().CPlusPlus; 12864 else 12865 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12866 12867 Diag(Definition->getLocation(), diag::note_previous_definition); 12868 FD->setInvalidDecl(); 12869 } 12870 12871 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12872 Sema &S) { 12873 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12874 12875 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12876 LSI->CallOperator = CallOperator; 12877 LSI->Lambda = LambdaClass; 12878 LSI->ReturnType = CallOperator->getReturnType(); 12879 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12880 12881 if (LCD == LCD_None) 12882 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12883 else if (LCD == LCD_ByCopy) 12884 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12885 else if (LCD == LCD_ByRef) 12886 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12887 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12888 12889 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12890 LSI->Mutable = !CallOperator->isConst(); 12891 12892 // Add the captures to the LSI so they can be noted as already 12893 // captured within tryCaptureVar. 12894 auto I = LambdaClass->field_begin(); 12895 for (const auto &C : LambdaClass->captures()) { 12896 if (C.capturesVariable()) { 12897 VarDecl *VD = C.getCapturedVar(); 12898 if (VD->isInitCapture()) 12899 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12900 QualType CaptureType = VD->getType(); 12901 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12902 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12903 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12904 /*EllipsisLoc*/C.isPackExpansion() 12905 ? C.getEllipsisLoc() : SourceLocation(), 12906 CaptureType, /*Expr*/ nullptr); 12907 12908 } else if (C.capturesThis()) { 12909 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12910 /*Expr*/ nullptr, 12911 C.getCaptureKind() == LCK_StarThis); 12912 } else { 12913 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12914 } 12915 ++I; 12916 } 12917 } 12918 12919 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12920 SkipBodyInfo *SkipBody) { 12921 if (!D) { 12922 // Parsing the function declaration failed in some way. Push on a fake scope 12923 // anyway so we can try to parse the function body. 12924 PushFunctionScope(); 12925 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12926 return D; 12927 } 12928 12929 FunctionDecl *FD = nullptr; 12930 12931 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12932 FD = FunTmpl->getTemplatedDecl(); 12933 else 12934 FD = cast<FunctionDecl>(D); 12935 12936 // Do not push if it is a lambda because one is already pushed when building 12937 // the lambda in ActOnStartOfLambdaDefinition(). 12938 if (!isLambdaCallOperator(FD)) 12939 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12940 12941 // Check for defining attributes before the check for redefinition. 12942 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12943 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12944 FD->dropAttr<AliasAttr>(); 12945 FD->setInvalidDecl(); 12946 } 12947 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12948 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12949 FD->dropAttr<IFuncAttr>(); 12950 FD->setInvalidDecl(); 12951 } 12952 12953 // See if this is a redefinition. If 'will have body' is already set, then 12954 // these checks were already performed when it was set. 12955 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12956 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12957 12958 // If we're skipping the body, we're done. Don't enter the scope. 12959 if (SkipBody && SkipBody->ShouldSkip) 12960 return D; 12961 } 12962 12963 // Mark this function as "will have a body eventually". This lets users to 12964 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12965 // this function. 12966 FD->setWillHaveBody(); 12967 12968 // If we are instantiating a generic lambda call operator, push 12969 // a LambdaScopeInfo onto the function stack. But use the information 12970 // that's already been calculated (ActOnLambdaExpr) to prime the current 12971 // LambdaScopeInfo. 12972 // When the template operator is being specialized, the LambdaScopeInfo, 12973 // has to be properly restored so that tryCaptureVariable doesn't try 12974 // and capture any new variables. In addition when calculating potential 12975 // captures during transformation of nested lambdas, it is necessary to 12976 // have the LSI properly restored. 12977 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12978 assert(inTemplateInstantiation() && 12979 "There should be an active template instantiation on the stack " 12980 "when instantiating a generic lambda!"); 12981 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12982 } else { 12983 // Enter a new function scope 12984 PushFunctionScope(); 12985 } 12986 12987 // Builtin functions cannot be defined. 12988 if (unsigned BuiltinID = FD->getBuiltinID()) { 12989 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12990 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12991 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12992 FD->setInvalidDecl(); 12993 } 12994 } 12995 12996 // The return type of a function definition must be complete 12997 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12998 QualType ResultType = FD->getReturnType(); 12999 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13000 !FD->isInvalidDecl() && 13001 RequireCompleteType(FD->getLocation(), ResultType, 13002 diag::err_func_def_incomplete_result)) 13003 FD->setInvalidDecl(); 13004 13005 if (FnBodyScope) 13006 PushDeclContext(FnBodyScope, FD); 13007 13008 // Check the validity of our function parameters 13009 CheckParmsForFunctionDef(FD->parameters(), 13010 /*CheckParameterNames=*/true); 13011 13012 // Add non-parameter declarations already in the function to the current 13013 // scope. 13014 if (FnBodyScope) { 13015 for (Decl *NPD : FD->decls()) { 13016 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13017 if (!NonParmDecl) 13018 continue; 13019 assert(!isa<ParmVarDecl>(NonParmDecl) && 13020 "parameters should not be in newly created FD yet"); 13021 13022 // If the decl has a name, make it accessible in the current scope. 13023 if (NonParmDecl->getDeclName()) 13024 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13025 13026 // Similarly, dive into enums and fish their constants out, making them 13027 // accessible in this scope. 13028 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13029 for (auto *EI : ED->enumerators()) 13030 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13031 } 13032 } 13033 } 13034 13035 // Introduce our parameters into the function scope 13036 for (auto Param : FD->parameters()) { 13037 Param->setOwningFunction(FD); 13038 13039 // If this has an identifier, add it to the scope stack. 13040 if (Param->getIdentifier() && FnBodyScope) { 13041 CheckShadow(FnBodyScope, Param); 13042 13043 PushOnScopeChains(Param, FnBodyScope); 13044 } 13045 } 13046 13047 // Ensure that the function's exception specification is instantiated. 13048 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13049 ResolveExceptionSpec(D->getLocation(), FPT); 13050 13051 // dllimport cannot be applied to non-inline function definitions. 13052 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13053 !FD->isTemplateInstantiation()) { 13054 assert(!FD->hasAttr<DLLExportAttr>()); 13055 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13056 FD->setInvalidDecl(); 13057 return D; 13058 } 13059 // We want to attach documentation to original Decl (which might be 13060 // a function template). 13061 ActOnDocumentableDecl(D); 13062 if (getCurLexicalContext()->isObjCContainer() && 13063 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13064 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13065 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13066 13067 return D; 13068 } 13069 13070 /// Given the set of return statements within a function body, 13071 /// compute the variables that are subject to the named return value 13072 /// optimization. 13073 /// 13074 /// Each of the variables that is subject to the named return value 13075 /// optimization will be marked as NRVO variables in the AST, and any 13076 /// return statement that has a marked NRVO variable as its NRVO candidate can 13077 /// use the named return value optimization. 13078 /// 13079 /// This function applies a very simplistic algorithm for NRVO: if every return 13080 /// statement in the scope of a variable has the same NRVO candidate, that 13081 /// candidate is an NRVO variable. 13082 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13083 ReturnStmt **Returns = Scope->Returns.data(); 13084 13085 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13086 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13087 if (!NRVOCandidate->isNRVOVariable()) 13088 Returns[I]->setNRVOCandidate(nullptr); 13089 } 13090 } 13091 } 13092 13093 bool Sema::canDelayFunctionBody(const Declarator &D) { 13094 // We can't delay parsing the body of a constexpr function template (yet). 13095 if (D.getDeclSpec().isConstexprSpecified()) 13096 return false; 13097 13098 // We can't delay parsing the body of a function template with a deduced 13099 // return type (yet). 13100 if (D.getDeclSpec().hasAutoTypeSpec()) { 13101 // If the placeholder introduces a non-deduced trailing return type, 13102 // we can still delay parsing it. 13103 if (D.getNumTypeObjects()) { 13104 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13105 if (Outer.Kind == DeclaratorChunk::Function && 13106 Outer.Fun.hasTrailingReturnType()) { 13107 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13108 return Ty.isNull() || !Ty->isUndeducedType(); 13109 } 13110 } 13111 return false; 13112 } 13113 13114 return true; 13115 } 13116 13117 bool Sema::canSkipFunctionBody(Decl *D) { 13118 // We cannot skip the body of a function (or function template) which is 13119 // constexpr, since we may need to evaluate its body in order to parse the 13120 // rest of the file. 13121 // We cannot skip the body of a function with an undeduced return type, 13122 // because any callers of that function need to know the type. 13123 if (const FunctionDecl *FD = D->getAsFunction()) { 13124 if (FD->isConstexpr()) 13125 return false; 13126 // We can't simply call Type::isUndeducedType here, because inside template 13127 // auto can be deduced to a dependent type, which is not considered 13128 // "undeduced". 13129 if (FD->getReturnType()->getContainedDeducedType()) 13130 return false; 13131 } 13132 return Consumer.shouldSkipFunctionBody(D); 13133 } 13134 13135 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13136 if (!Decl) 13137 return nullptr; 13138 if (FunctionDecl *FD = Decl->getAsFunction()) 13139 FD->setHasSkippedBody(); 13140 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13141 MD->setHasSkippedBody(); 13142 return Decl; 13143 } 13144 13145 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13146 return ActOnFinishFunctionBody(D, BodyArg, false); 13147 } 13148 13149 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13150 /// body. 13151 class ExitFunctionBodyRAII { 13152 public: 13153 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13154 ~ExitFunctionBodyRAII() { 13155 if (!IsLambda) 13156 S.PopExpressionEvaluationContext(); 13157 } 13158 13159 private: 13160 Sema &S; 13161 bool IsLambda = false; 13162 }; 13163 13164 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 13165 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 13166 13167 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 13168 if (EscapeInfo.count(BD)) 13169 return EscapeInfo[BD]; 13170 13171 bool R = false; 13172 const BlockDecl *CurBD = BD; 13173 13174 do { 13175 R = !CurBD->doesNotEscape(); 13176 if (R) 13177 break; 13178 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 13179 } while (CurBD); 13180 13181 return EscapeInfo[BD] = R; 13182 }; 13183 13184 // If the location where 'self' is implicitly retained is inside a escaping 13185 // block, emit a diagnostic. 13186 for (const std::pair<SourceLocation, const BlockDecl *> &P : 13187 S.ImplicitlyRetainedSelfLocs) 13188 if (IsOrNestedInEscapingBlock(P.second)) 13189 S.Diag(P.first, diag::warn_implicitly_retains_self) 13190 << FixItHint::CreateInsertion(P.first, "self->"); 13191 } 13192 13193 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 13194 bool IsInstantiation) { 13195 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 13196 13197 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13198 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 13199 13200 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 13201 CheckCompletedCoroutineBody(FD, Body); 13202 13203 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 13204 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 13205 // meant to pop the context added in ActOnStartOfFunctionDef(). 13206 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 13207 13208 if (FD) { 13209 FD->setBody(Body); 13210 FD->setWillHaveBody(false); 13211 13212 if (getLangOpts().CPlusPlus14) { 13213 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 13214 FD->getReturnType()->isUndeducedType()) { 13215 // If the function has a deduced result type but contains no 'return' 13216 // statements, the result type as written must be exactly 'auto', and 13217 // the deduced result type is 'void'. 13218 if (!FD->getReturnType()->getAs<AutoType>()) { 13219 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 13220 << FD->getReturnType(); 13221 FD->setInvalidDecl(); 13222 } else { 13223 // Substitute 'void' for the 'auto' in the type. 13224 TypeLoc ResultType = getReturnTypeLoc(FD); 13225 Context.adjustDeducedFunctionResultType( 13226 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 13227 } 13228 } 13229 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 13230 // In C++11, we don't use 'auto' deduction rules for lambda call 13231 // operators because we don't support return type deduction. 13232 auto *LSI = getCurLambda(); 13233 if (LSI->HasImplicitReturnType) { 13234 deduceClosureReturnType(*LSI); 13235 13236 // C++11 [expr.prim.lambda]p4: 13237 // [...] if there are no return statements in the compound-statement 13238 // [the deduced type is] the type void 13239 QualType RetType = 13240 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 13241 13242 // Update the return type to the deduced type. 13243 const FunctionProtoType *Proto = 13244 FD->getType()->getAs<FunctionProtoType>(); 13245 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 13246 Proto->getExtProtoInfo())); 13247 } 13248 } 13249 13250 // If the function implicitly returns zero (like 'main') or is naked, 13251 // don't complain about missing return statements. 13252 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 13253 WP.disableCheckFallThrough(); 13254 13255 // MSVC permits the use of pure specifier (=0) on function definition, 13256 // defined at class scope, warn about this non-standard construct. 13257 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 13258 Diag(FD->getLocation(), diag::ext_pure_function_definition); 13259 13260 if (!FD->isInvalidDecl()) { 13261 // Don't diagnose unused parameters of defaulted or deleted functions. 13262 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 13263 DiagnoseUnusedParameters(FD->parameters()); 13264 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 13265 FD->getReturnType(), FD); 13266 13267 // If this is a structor, we need a vtable. 13268 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 13269 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 13270 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 13271 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 13272 13273 // Try to apply the named return value optimization. We have to check 13274 // if we can do this here because lambdas keep return statements around 13275 // to deduce an implicit return type. 13276 if (FD->getReturnType()->isRecordType() && 13277 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 13278 computeNRVO(Body, getCurFunction()); 13279 } 13280 13281 // GNU warning -Wmissing-prototypes: 13282 // Warn if a global function is defined without a previous 13283 // prototype declaration. This warning is issued even if the 13284 // definition itself provides a prototype. The aim is to detect 13285 // global functions that fail to be declared in header files. 13286 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 13287 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 13288 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 13289 13290 if (PossibleZeroParamPrototype) { 13291 // We found a declaration that is not a prototype, 13292 // but that could be a zero-parameter prototype 13293 if (TypeSourceInfo *TI = 13294 PossibleZeroParamPrototype->getTypeSourceInfo()) { 13295 TypeLoc TL = TI->getTypeLoc(); 13296 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 13297 Diag(PossibleZeroParamPrototype->getLocation(), 13298 diag::note_declaration_not_a_prototype) 13299 << PossibleZeroParamPrototype 13300 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 13301 } 13302 } 13303 13304 // GNU warning -Wstrict-prototypes 13305 // Warn if K&R function is defined without a previous declaration. 13306 // This warning is issued only if the definition itself does not provide 13307 // a prototype. Only K&R definitions do not provide a prototype. 13308 // An empty list in a function declarator that is part of a definition 13309 // of that function specifies that the function has no parameters 13310 // (C99 6.7.5.3p14) 13311 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 13312 !LangOpts.CPlusPlus) { 13313 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 13314 TypeLoc TL = TI->getTypeLoc(); 13315 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 13316 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 13317 } 13318 } 13319 13320 // Warn on CPUDispatch with an actual body. 13321 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 13322 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 13323 if (!CmpndBody->body_empty()) 13324 Diag(CmpndBody->body_front()->getBeginLoc(), 13325 diag::warn_dispatch_body_ignored); 13326 13327 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 13328 const CXXMethodDecl *KeyFunction; 13329 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 13330 MD->isVirtual() && 13331 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 13332 MD == KeyFunction->getCanonicalDecl()) { 13333 // Update the key-function state if necessary for this ABI. 13334 if (FD->isInlined() && 13335 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 13336 Context.setNonKeyFunction(MD); 13337 13338 // If the newly-chosen key function is already defined, then we 13339 // need to mark the vtable as used retroactively. 13340 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 13341 const FunctionDecl *Definition; 13342 if (KeyFunction && KeyFunction->isDefined(Definition)) 13343 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 13344 } else { 13345 // We just defined they key function; mark the vtable as used. 13346 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 13347 } 13348 } 13349 } 13350 13351 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 13352 "Function parsing confused"); 13353 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 13354 assert(MD == getCurMethodDecl() && "Method parsing confused"); 13355 MD->setBody(Body); 13356 if (!MD->isInvalidDecl()) { 13357 if (!MD->hasSkippedBody()) 13358 DiagnoseUnusedParameters(MD->parameters()); 13359 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 13360 MD->getReturnType(), MD); 13361 13362 if (Body) 13363 computeNRVO(Body, getCurFunction()); 13364 } 13365 if (getCurFunction()->ObjCShouldCallSuper) { 13366 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 13367 << MD->getSelector().getAsString(); 13368 getCurFunction()->ObjCShouldCallSuper = false; 13369 } 13370 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 13371 const ObjCMethodDecl *InitMethod = nullptr; 13372 bool isDesignated = 13373 MD->isDesignatedInitializerForTheInterface(&InitMethod); 13374 assert(isDesignated && InitMethod); 13375 (void)isDesignated; 13376 13377 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 13378 auto IFace = MD->getClassInterface(); 13379 if (!IFace) 13380 return false; 13381 auto SuperD = IFace->getSuperClass(); 13382 if (!SuperD) 13383 return false; 13384 return SuperD->getIdentifier() == 13385 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 13386 }; 13387 // Don't issue this warning for unavailable inits or direct subclasses 13388 // of NSObject. 13389 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 13390 Diag(MD->getLocation(), 13391 diag::warn_objc_designated_init_missing_super_call); 13392 Diag(InitMethod->getLocation(), 13393 diag::note_objc_designated_init_marked_here); 13394 } 13395 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 13396 } 13397 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 13398 // Don't issue this warning for unavaialable inits. 13399 if (!MD->isUnavailable()) 13400 Diag(MD->getLocation(), 13401 diag::warn_objc_secondary_init_missing_init_call); 13402 getCurFunction()->ObjCWarnForNoInitDelegation = false; 13403 } 13404 13405 diagnoseImplicitlyRetainedSelf(*this); 13406 } else { 13407 // Parsing the function declaration failed in some way. Pop the fake scope 13408 // we pushed on. 13409 PopFunctionScopeInfo(ActivePolicy, dcl); 13410 return nullptr; 13411 } 13412 13413 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13414 DiagnoseUnguardedAvailabilityViolations(dcl); 13415 13416 assert(!getCurFunction()->ObjCShouldCallSuper && 13417 "This should only be set for ObjC methods, which should have been " 13418 "handled in the block above."); 13419 13420 // Verify and clean out per-function state. 13421 if (Body && (!FD || !FD->isDefaulted())) { 13422 // C++ constructors that have function-try-blocks can't have return 13423 // statements in the handlers of that block. (C++ [except.handle]p14) 13424 // Verify this. 13425 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 13426 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 13427 13428 // Verify that gotos and switch cases don't jump into scopes illegally. 13429 if (getCurFunction()->NeedsScopeChecking() && 13430 !PP.isCodeCompletionEnabled()) 13431 DiagnoseInvalidJumps(Body); 13432 13433 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 13434 if (!Destructor->getParent()->isDependentType()) 13435 CheckDestructor(Destructor); 13436 13437 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13438 Destructor->getParent()); 13439 } 13440 13441 // If any errors have occurred, clear out any temporaries that may have 13442 // been leftover. This ensures that these temporaries won't be picked up for 13443 // deletion in some later function. 13444 if (getDiagnostics().hasErrorOccurred() || 13445 getDiagnostics().getSuppressAllDiagnostics()) { 13446 DiscardCleanupsInEvaluationContext(); 13447 } 13448 if (!getDiagnostics().hasUncompilableErrorOccurred() && 13449 !isa<FunctionTemplateDecl>(dcl)) { 13450 // Since the body is valid, issue any analysis-based warnings that are 13451 // enabled. 13452 ActivePolicy = &WP; 13453 } 13454 13455 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 13456 (!CheckConstexprFunctionDecl(FD) || 13457 !CheckConstexprFunctionBody(FD, Body))) 13458 FD->setInvalidDecl(); 13459 13460 if (FD && FD->hasAttr<NakedAttr>()) { 13461 for (const Stmt *S : Body->children()) { 13462 // Allow local register variables without initializer as they don't 13463 // require prologue. 13464 bool RegisterVariables = false; 13465 if (auto *DS = dyn_cast<DeclStmt>(S)) { 13466 for (const auto *Decl : DS->decls()) { 13467 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 13468 RegisterVariables = 13469 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 13470 if (!RegisterVariables) 13471 break; 13472 } 13473 } 13474 } 13475 if (RegisterVariables) 13476 continue; 13477 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 13478 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 13479 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 13480 FD->setInvalidDecl(); 13481 break; 13482 } 13483 } 13484 } 13485 13486 assert(ExprCleanupObjects.size() == 13487 ExprEvalContexts.back().NumCleanupObjects && 13488 "Leftover temporaries in function"); 13489 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 13490 assert(MaybeODRUseExprs.empty() && 13491 "Leftover expressions for odr-use checking"); 13492 } 13493 13494 if (!IsInstantiation) 13495 PopDeclContext(); 13496 13497 PopFunctionScopeInfo(ActivePolicy, dcl); 13498 // If any errors have occurred, clear out any temporaries that may have 13499 // been leftover. This ensures that these temporaries won't be picked up for 13500 // deletion in some later function. 13501 if (getDiagnostics().hasErrorOccurred()) { 13502 DiscardCleanupsInEvaluationContext(); 13503 } 13504 13505 return dcl; 13506 } 13507 13508 /// When we finish delayed parsing of an attribute, we must attach it to the 13509 /// relevant Decl. 13510 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 13511 ParsedAttributes &Attrs) { 13512 // Always attach attributes to the underlying decl. 13513 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 13514 D = TD->getTemplatedDecl(); 13515 ProcessDeclAttributeList(S, D, Attrs); 13516 13517 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 13518 if (Method->isStatic()) 13519 checkThisInStaticMemberFunctionAttributes(Method); 13520 } 13521 13522 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 13523 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 13524 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 13525 IdentifierInfo &II, Scope *S) { 13526 // Find the scope in which the identifier is injected and the corresponding 13527 // DeclContext. 13528 // FIXME: C89 does not say what happens if there is no enclosing block scope. 13529 // In that case, we inject the declaration into the translation unit scope 13530 // instead. 13531 Scope *BlockScope = S; 13532 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 13533 BlockScope = BlockScope->getParent(); 13534 13535 Scope *ContextScope = BlockScope; 13536 while (!ContextScope->getEntity()) 13537 ContextScope = ContextScope->getParent(); 13538 ContextRAII SavedContext(*this, ContextScope->getEntity()); 13539 13540 // Before we produce a declaration for an implicitly defined 13541 // function, see whether there was a locally-scoped declaration of 13542 // this name as a function or variable. If so, use that 13543 // (non-visible) declaration, and complain about it. 13544 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 13545 if (ExternCPrev) { 13546 // We still need to inject the function into the enclosing block scope so 13547 // that later (non-call) uses can see it. 13548 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13549 13550 // C89 footnote 38: 13551 // If in fact it is not defined as having type "function returning int", 13552 // the behavior is undefined. 13553 if (!isa<FunctionDecl>(ExternCPrev) || 13554 !Context.typesAreCompatible( 13555 cast<FunctionDecl>(ExternCPrev)->getType(), 13556 Context.getFunctionNoProtoType(Context.IntTy))) { 13557 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13558 << ExternCPrev << !getLangOpts().C99; 13559 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13560 return ExternCPrev; 13561 } 13562 } 13563 13564 // Extension in C99. Legal in C90, but warn about it. 13565 unsigned diag_id; 13566 if (II.getName().startswith("__builtin_")) 13567 diag_id = diag::warn_builtin_unknown; 13568 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13569 else if (getLangOpts().OpenCL) 13570 diag_id = diag::err_opencl_implicit_function_decl; 13571 else if (getLangOpts().C99) 13572 diag_id = diag::ext_implicit_function_decl; 13573 else 13574 diag_id = diag::warn_implicit_function_decl; 13575 Diag(Loc, diag_id) << &II; 13576 13577 // If we found a prior declaration of this function, don't bother building 13578 // another one. We've already pushed that one into scope, so there's nothing 13579 // more to do. 13580 if (ExternCPrev) 13581 return ExternCPrev; 13582 13583 // Because typo correction is expensive, only do it if the implicit 13584 // function declaration is going to be treated as an error. 13585 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13586 TypoCorrection Corrected; 13587 DeclFilterCCC<FunctionDecl> CCC{}; 13588 if (S && (Corrected = 13589 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 13590 S, nullptr, CCC, CTK_NonError))) 13591 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13592 /*ErrorRecovery*/false); 13593 } 13594 13595 // Set a Declarator for the implicit definition: int foo(); 13596 const char *Dummy; 13597 AttributeFactory attrFactory; 13598 DeclSpec DS(attrFactory); 13599 unsigned DiagID; 13600 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13601 Context.getPrintingPolicy()); 13602 (void)Error; // Silence warning. 13603 assert(!Error && "Error setting up implicit decl!"); 13604 SourceLocation NoLoc; 13605 Declarator D(DS, DeclaratorContext::BlockContext); 13606 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13607 /*IsAmbiguous=*/false, 13608 /*LParenLoc=*/NoLoc, 13609 /*Params=*/nullptr, 13610 /*NumParams=*/0, 13611 /*EllipsisLoc=*/NoLoc, 13612 /*RParenLoc=*/NoLoc, 13613 /*RefQualifierIsLvalueRef=*/true, 13614 /*RefQualifierLoc=*/NoLoc, 13615 /*MutableLoc=*/NoLoc, EST_None, 13616 /*ESpecRange=*/SourceRange(), 13617 /*Exceptions=*/nullptr, 13618 /*ExceptionRanges=*/nullptr, 13619 /*NumExceptions=*/0, 13620 /*NoexceptExpr=*/nullptr, 13621 /*ExceptionSpecTokens=*/nullptr, 13622 /*DeclsInPrototype=*/None, Loc, 13623 Loc, D), 13624 std::move(DS.getAttributes()), SourceLocation()); 13625 D.SetIdentifier(&II, Loc); 13626 13627 // Insert this function into the enclosing block scope. 13628 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13629 FD->setImplicit(); 13630 13631 AddKnownFunctionAttributes(FD); 13632 13633 return FD; 13634 } 13635 13636 /// Adds any function attributes that we know a priori based on 13637 /// the declaration of this function. 13638 /// 13639 /// These attributes can apply both to implicitly-declared builtins 13640 /// (like __builtin___printf_chk) or to library-declared functions 13641 /// like NSLog or printf. 13642 /// 13643 /// We need to check for duplicate attributes both here and where user-written 13644 /// attributes are applied to declarations. 13645 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13646 if (FD->isInvalidDecl()) 13647 return; 13648 13649 // If this is a built-in function, map its builtin attributes to 13650 // actual attributes. 13651 if (unsigned BuiltinID = FD->getBuiltinID()) { 13652 // Handle printf-formatting attributes. 13653 unsigned FormatIdx; 13654 bool HasVAListArg; 13655 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13656 if (!FD->hasAttr<FormatAttr>()) { 13657 const char *fmt = "printf"; 13658 unsigned int NumParams = FD->getNumParams(); 13659 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13660 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13661 fmt = "NSString"; 13662 FD->addAttr(FormatAttr::CreateImplicit(Context, 13663 &Context.Idents.get(fmt), 13664 FormatIdx+1, 13665 HasVAListArg ? 0 : FormatIdx+2, 13666 FD->getLocation())); 13667 } 13668 } 13669 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13670 HasVAListArg)) { 13671 if (!FD->hasAttr<FormatAttr>()) 13672 FD->addAttr(FormatAttr::CreateImplicit(Context, 13673 &Context.Idents.get("scanf"), 13674 FormatIdx+1, 13675 HasVAListArg ? 0 : FormatIdx+2, 13676 FD->getLocation())); 13677 } 13678 13679 // Handle automatically recognized callbacks. 13680 SmallVector<int, 4> Encoding; 13681 if (!FD->hasAttr<CallbackAttr>() && 13682 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 13683 FD->addAttr(CallbackAttr::CreateImplicit( 13684 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 13685 13686 // Mark const if we don't care about errno and that is the only thing 13687 // preventing the function from being const. This allows IRgen to use LLVM 13688 // intrinsics for such functions. 13689 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13690 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13691 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13692 13693 // We make "fma" on some platforms const because we know it does not set 13694 // errno in those environments even though it could set errno based on the 13695 // C standard. 13696 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13697 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13698 !FD->hasAttr<ConstAttr>()) { 13699 switch (BuiltinID) { 13700 case Builtin::BI__builtin_fma: 13701 case Builtin::BI__builtin_fmaf: 13702 case Builtin::BI__builtin_fmal: 13703 case Builtin::BIfma: 13704 case Builtin::BIfmaf: 13705 case Builtin::BIfmal: 13706 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13707 break; 13708 default: 13709 break; 13710 } 13711 } 13712 13713 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13714 !FD->hasAttr<ReturnsTwiceAttr>()) 13715 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13716 FD->getLocation())); 13717 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13718 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13719 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13720 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13721 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13722 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13723 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13724 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13725 // Add the appropriate attribute, depending on the CUDA compilation mode 13726 // and which target the builtin belongs to. For example, during host 13727 // compilation, aux builtins are __device__, while the rest are __host__. 13728 if (getLangOpts().CUDAIsDevice != 13729 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13730 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13731 else 13732 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13733 } 13734 } 13735 13736 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13737 // throw, add an implicit nothrow attribute to any extern "C" function we come 13738 // across. 13739 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13740 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13741 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13742 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13743 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13744 } 13745 13746 IdentifierInfo *Name = FD->getIdentifier(); 13747 if (!Name) 13748 return; 13749 if ((!getLangOpts().CPlusPlus && 13750 FD->getDeclContext()->isTranslationUnit()) || 13751 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13752 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13753 LinkageSpecDecl::lang_c)) { 13754 // Okay: this could be a libc/libm/Objective-C function we know 13755 // about. 13756 } else 13757 return; 13758 13759 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13760 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13761 // target-specific builtins, perhaps? 13762 if (!FD->hasAttr<FormatAttr>()) 13763 FD->addAttr(FormatAttr::CreateImplicit(Context, 13764 &Context.Idents.get("printf"), 2, 13765 Name->isStr("vasprintf") ? 0 : 3, 13766 FD->getLocation())); 13767 } 13768 13769 if (Name->isStr("__CFStringMakeConstantString")) { 13770 // We already have a __builtin___CFStringMakeConstantString, 13771 // but builds that use -fno-constant-cfstrings don't go through that. 13772 if (!FD->hasAttr<FormatArgAttr>()) 13773 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13774 FD->getLocation())); 13775 } 13776 } 13777 13778 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13779 TypeSourceInfo *TInfo) { 13780 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13781 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13782 13783 if (!TInfo) { 13784 assert(D.isInvalidType() && "no declarator info for valid type"); 13785 TInfo = Context.getTrivialTypeSourceInfo(T); 13786 } 13787 13788 // Scope manipulation handled by caller. 13789 TypedefDecl *NewTD = 13790 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 13791 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 13792 13793 // Bail out immediately if we have an invalid declaration. 13794 if (D.isInvalidType()) { 13795 NewTD->setInvalidDecl(); 13796 return NewTD; 13797 } 13798 13799 if (D.getDeclSpec().isModulePrivateSpecified()) { 13800 if (CurContext->isFunctionOrMethod()) 13801 Diag(NewTD->getLocation(), diag::err_module_private_local) 13802 << 2 << NewTD->getDeclName() 13803 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13804 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13805 else 13806 NewTD->setModulePrivate(); 13807 } 13808 13809 // C++ [dcl.typedef]p8: 13810 // If the typedef declaration defines an unnamed class (or 13811 // enum), the first typedef-name declared by the declaration 13812 // to be that class type (or enum type) is used to denote the 13813 // class type (or enum type) for linkage purposes only. 13814 // We need to check whether the type was declared in the declaration. 13815 switch (D.getDeclSpec().getTypeSpecType()) { 13816 case TST_enum: 13817 case TST_struct: 13818 case TST_interface: 13819 case TST_union: 13820 case TST_class: { 13821 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13822 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13823 break; 13824 } 13825 13826 default: 13827 break; 13828 } 13829 13830 return NewTD; 13831 } 13832 13833 /// Check that this is a valid underlying type for an enum declaration. 13834 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13835 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13836 QualType T = TI->getType(); 13837 13838 if (T->isDependentType()) 13839 return false; 13840 13841 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13842 if (BT->isInteger()) 13843 return false; 13844 13845 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13846 return true; 13847 } 13848 13849 /// Check whether this is a valid redeclaration of a previous enumeration. 13850 /// \return true if the redeclaration was invalid. 13851 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13852 QualType EnumUnderlyingTy, bool IsFixed, 13853 const EnumDecl *Prev) { 13854 if (IsScoped != Prev->isScoped()) { 13855 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13856 << Prev->isScoped(); 13857 Diag(Prev->getLocation(), diag::note_previous_declaration); 13858 return true; 13859 } 13860 13861 if (IsFixed && Prev->isFixed()) { 13862 if (!EnumUnderlyingTy->isDependentType() && 13863 !Prev->getIntegerType()->isDependentType() && 13864 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13865 Prev->getIntegerType())) { 13866 // TODO: Highlight the underlying type of the redeclaration. 13867 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13868 << EnumUnderlyingTy << Prev->getIntegerType(); 13869 Diag(Prev->getLocation(), diag::note_previous_declaration) 13870 << Prev->getIntegerTypeRange(); 13871 return true; 13872 } 13873 } else if (IsFixed != Prev->isFixed()) { 13874 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13875 << Prev->isFixed(); 13876 Diag(Prev->getLocation(), diag::note_previous_declaration); 13877 return true; 13878 } 13879 13880 return false; 13881 } 13882 13883 /// Get diagnostic %select index for tag kind for 13884 /// redeclaration diagnostic message. 13885 /// WARNING: Indexes apply to particular diagnostics only! 13886 /// 13887 /// \returns diagnostic %select index. 13888 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13889 switch (Tag) { 13890 case TTK_Struct: return 0; 13891 case TTK_Interface: return 1; 13892 case TTK_Class: return 2; 13893 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13894 } 13895 } 13896 13897 /// Determine if tag kind is a class-key compatible with 13898 /// class for redeclaration (class, struct, or __interface). 13899 /// 13900 /// \returns true iff the tag kind is compatible. 13901 static bool isClassCompatTagKind(TagTypeKind Tag) 13902 { 13903 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13904 } 13905 13906 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13907 TagTypeKind TTK) { 13908 if (isa<TypedefDecl>(PrevDecl)) 13909 return NTK_Typedef; 13910 else if (isa<TypeAliasDecl>(PrevDecl)) 13911 return NTK_TypeAlias; 13912 else if (isa<ClassTemplateDecl>(PrevDecl)) 13913 return NTK_Template; 13914 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13915 return NTK_TypeAliasTemplate; 13916 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13917 return NTK_TemplateTemplateArgument; 13918 switch (TTK) { 13919 case TTK_Struct: 13920 case TTK_Interface: 13921 case TTK_Class: 13922 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13923 case TTK_Union: 13924 return NTK_NonUnion; 13925 case TTK_Enum: 13926 return NTK_NonEnum; 13927 } 13928 llvm_unreachable("invalid TTK"); 13929 } 13930 13931 /// Determine whether a tag with a given kind is acceptable 13932 /// as a redeclaration of the given tag declaration. 13933 /// 13934 /// \returns true if the new tag kind is acceptable, false otherwise. 13935 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13936 TagTypeKind NewTag, bool isDefinition, 13937 SourceLocation NewTagLoc, 13938 const IdentifierInfo *Name) { 13939 // C++ [dcl.type.elab]p3: 13940 // The class-key or enum keyword present in the 13941 // elaborated-type-specifier shall agree in kind with the 13942 // declaration to which the name in the elaborated-type-specifier 13943 // refers. This rule also applies to the form of 13944 // elaborated-type-specifier that declares a class-name or 13945 // friend class since it can be construed as referring to the 13946 // definition of the class. Thus, in any 13947 // elaborated-type-specifier, the enum keyword shall be used to 13948 // refer to an enumeration (7.2), the union class-key shall be 13949 // used to refer to a union (clause 9), and either the class or 13950 // struct class-key shall be used to refer to a class (clause 9) 13951 // declared using the class or struct class-key. 13952 TagTypeKind OldTag = Previous->getTagKind(); 13953 if (OldTag != NewTag && 13954 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 13955 return false; 13956 13957 // Tags are compatible, but we might still want to warn on mismatched tags. 13958 // Non-class tags can't be mismatched at this point. 13959 if (!isClassCompatTagKind(NewTag)) 13960 return true; 13961 13962 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 13963 // by our warning analysis. We don't want to warn about mismatches with (eg) 13964 // declarations in system headers that are designed to be specialized, but if 13965 // a user asks us to warn, we should warn if their code contains mismatched 13966 // declarations. 13967 auto IsIgnoredLoc = [&](SourceLocation Loc) { 13968 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 13969 Loc); 13970 }; 13971 if (IsIgnoredLoc(NewTagLoc)) 13972 return true; 13973 13974 auto IsIgnored = [&](const TagDecl *Tag) { 13975 return IsIgnoredLoc(Tag->getLocation()); 13976 }; 13977 while (IsIgnored(Previous)) { 13978 Previous = Previous->getPreviousDecl(); 13979 if (!Previous) 13980 return true; 13981 OldTag = Previous->getTagKind(); 13982 } 13983 13984 bool isTemplate = false; 13985 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13986 isTemplate = Record->getDescribedClassTemplate(); 13987 13988 if (inTemplateInstantiation()) { 13989 if (OldTag != NewTag) { 13990 // In a template instantiation, do not offer fix-its for tag mismatches 13991 // since they usually mess up the template instead of fixing the problem. 13992 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13993 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13994 << getRedeclDiagFromTagKind(OldTag); 13995 // FIXME: Note previous location? 13996 } 13997 return true; 13998 } 13999 14000 if (isDefinition) { 14001 // On definitions, check all previous tags and issue a fix-it for each 14002 // one that doesn't match the current tag. 14003 if (Previous->getDefinition()) { 14004 // Don't suggest fix-its for redefinitions. 14005 return true; 14006 } 14007 14008 bool previousMismatch = false; 14009 for (const TagDecl *I : Previous->redecls()) { 14010 if (I->getTagKind() != NewTag) { 14011 // Ignore previous declarations for which the warning was disabled. 14012 if (IsIgnored(I)) 14013 continue; 14014 14015 if (!previousMismatch) { 14016 previousMismatch = true; 14017 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 14018 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14019 << getRedeclDiagFromTagKind(I->getTagKind()); 14020 } 14021 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 14022 << getRedeclDiagFromTagKind(NewTag) 14023 << FixItHint::CreateReplacement(I->getInnerLocStart(), 14024 TypeWithKeyword::getTagTypeKindName(NewTag)); 14025 } 14026 } 14027 return true; 14028 } 14029 14030 // Identify the prevailing tag kind: this is the kind of the definition (if 14031 // there is a non-ignored definition), or otherwise the kind of the prior 14032 // (non-ignored) declaration. 14033 const TagDecl *PrevDef = Previous->getDefinition(); 14034 if (PrevDef && IsIgnored(PrevDef)) 14035 PrevDef = nullptr; 14036 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 14037 if (Redecl->getTagKind() != NewTag) { 14038 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14039 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14040 << getRedeclDiagFromTagKind(OldTag); 14041 Diag(Redecl->getLocation(), diag::note_previous_use); 14042 14043 // If there is a previous definition, suggest a fix-it. 14044 if (PrevDef) { 14045 Diag(NewTagLoc, diag::note_struct_class_suggestion) 14046 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 14047 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 14048 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 14049 } 14050 } 14051 14052 return true; 14053 } 14054 14055 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 14056 /// from an outer enclosing namespace or file scope inside a friend declaration. 14057 /// This should provide the commented out code in the following snippet: 14058 /// namespace N { 14059 /// struct X; 14060 /// namespace M { 14061 /// struct Y { friend struct /*N::*/ X; }; 14062 /// } 14063 /// } 14064 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 14065 SourceLocation NameLoc) { 14066 // While the decl is in a namespace, do repeated lookup of that name and see 14067 // if we get the same namespace back. If we do not, continue until 14068 // translation unit scope, at which point we have a fully qualified NNS. 14069 SmallVector<IdentifierInfo *, 4> Namespaces; 14070 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14071 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 14072 // This tag should be declared in a namespace, which can only be enclosed by 14073 // other namespaces. Bail if there's an anonymous namespace in the chain. 14074 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 14075 if (!Namespace || Namespace->isAnonymousNamespace()) 14076 return FixItHint(); 14077 IdentifierInfo *II = Namespace->getIdentifier(); 14078 Namespaces.push_back(II); 14079 NamedDecl *Lookup = SemaRef.LookupSingleName( 14080 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 14081 if (Lookup == Namespace) 14082 break; 14083 } 14084 14085 // Once we have all the namespaces, reverse them to go outermost first, and 14086 // build an NNS. 14087 SmallString<64> Insertion; 14088 llvm::raw_svector_ostream OS(Insertion); 14089 if (DC->isTranslationUnit()) 14090 OS << "::"; 14091 std::reverse(Namespaces.begin(), Namespaces.end()); 14092 for (auto *II : Namespaces) 14093 OS << II->getName() << "::"; 14094 return FixItHint::CreateInsertion(NameLoc, Insertion); 14095 } 14096 14097 /// Determine whether a tag originally declared in context \p OldDC can 14098 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 14099 /// found a declaration in \p OldDC as a previous decl, perhaps through a 14100 /// using-declaration). 14101 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 14102 DeclContext *NewDC) { 14103 OldDC = OldDC->getRedeclContext(); 14104 NewDC = NewDC->getRedeclContext(); 14105 14106 if (OldDC->Equals(NewDC)) 14107 return true; 14108 14109 // In MSVC mode, we allow a redeclaration if the contexts are related (either 14110 // encloses the other). 14111 if (S.getLangOpts().MSVCCompat && 14112 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 14113 return true; 14114 14115 return false; 14116 } 14117 14118 /// This is invoked when we see 'struct foo' or 'struct {'. In the 14119 /// former case, Name will be non-null. In the later case, Name will be null. 14120 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 14121 /// reference/declaration/definition of a tag. 14122 /// 14123 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 14124 /// trailing-type-specifier) other than one in an alias-declaration. 14125 /// 14126 /// \param SkipBody If non-null, will be set to indicate if the caller should 14127 /// skip the definition of this tag and treat it as if it were a declaration. 14128 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 14129 SourceLocation KWLoc, CXXScopeSpec &SS, 14130 IdentifierInfo *Name, SourceLocation NameLoc, 14131 const ParsedAttributesView &Attrs, AccessSpecifier AS, 14132 SourceLocation ModulePrivateLoc, 14133 MultiTemplateParamsArg TemplateParameterLists, 14134 bool &OwnedDecl, bool &IsDependent, 14135 SourceLocation ScopedEnumKWLoc, 14136 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 14137 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 14138 SkipBodyInfo *SkipBody) { 14139 // If this is not a definition, it must have a name. 14140 IdentifierInfo *OrigName = Name; 14141 assert((Name != nullptr || TUK == TUK_Definition) && 14142 "Nameless record must be a definition!"); 14143 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 14144 14145 OwnedDecl = false; 14146 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14147 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 14148 14149 // FIXME: Check member specializations more carefully. 14150 bool isMemberSpecialization = false; 14151 bool Invalid = false; 14152 14153 // We only need to do this matching if we have template parameters 14154 // or a scope specifier, which also conveniently avoids this work 14155 // for non-C++ cases. 14156 if (TemplateParameterLists.size() > 0 || 14157 (SS.isNotEmpty() && TUK != TUK_Reference)) { 14158 if (TemplateParameterList *TemplateParams = 14159 MatchTemplateParametersToScopeSpecifier( 14160 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 14161 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 14162 if (Kind == TTK_Enum) { 14163 Diag(KWLoc, diag::err_enum_template); 14164 return nullptr; 14165 } 14166 14167 if (TemplateParams->size() > 0) { 14168 // This is a declaration or definition of a class template (which may 14169 // be a member of another template). 14170 14171 if (Invalid) 14172 return nullptr; 14173 14174 OwnedDecl = false; 14175 DeclResult Result = CheckClassTemplate( 14176 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 14177 AS, ModulePrivateLoc, 14178 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 14179 TemplateParameterLists.data(), SkipBody); 14180 return Result.get(); 14181 } else { 14182 // The "template<>" header is extraneous. 14183 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14184 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14185 isMemberSpecialization = true; 14186 } 14187 } 14188 } 14189 14190 // Figure out the underlying type if this a enum declaration. We need to do 14191 // this early, because it's needed to detect if this is an incompatible 14192 // redeclaration. 14193 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 14194 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 14195 14196 if (Kind == TTK_Enum) { 14197 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 14198 // No underlying type explicitly specified, or we failed to parse the 14199 // type, default to int. 14200 EnumUnderlying = Context.IntTy.getTypePtr(); 14201 } else if (UnderlyingType.get()) { 14202 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 14203 // integral type; any cv-qualification is ignored. 14204 TypeSourceInfo *TI = nullptr; 14205 GetTypeFromParser(UnderlyingType.get(), &TI); 14206 EnumUnderlying = TI; 14207 14208 if (CheckEnumUnderlyingType(TI)) 14209 // Recover by falling back to int. 14210 EnumUnderlying = Context.IntTy.getTypePtr(); 14211 14212 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 14213 UPPC_FixedUnderlyingType)) 14214 EnumUnderlying = Context.IntTy.getTypePtr(); 14215 14216 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14217 // For MSVC ABI compatibility, unfixed enums must use an underlying type 14218 // of 'int'. However, if this is an unfixed forward declaration, don't set 14219 // the underlying type unless the user enables -fms-compatibility. This 14220 // makes unfixed forward declared enums incomplete and is more conforming. 14221 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 14222 EnumUnderlying = Context.IntTy.getTypePtr(); 14223 } 14224 } 14225 14226 DeclContext *SearchDC = CurContext; 14227 DeclContext *DC = CurContext; 14228 bool isStdBadAlloc = false; 14229 bool isStdAlignValT = false; 14230 14231 RedeclarationKind Redecl = forRedeclarationInCurContext(); 14232 if (TUK == TUK_Friend || TUK == TUK_Reference) 14233 Redecl = NotForRedeclaration; 14234 14235 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 14236 /// implemented asks for structural equivalence checking, the returned decl 14237 /// here is passed back to the parser, allowing the tag body to be parsed. 14238 auto createTagFromNewDecl = [&]() -> TagDecl * { 14239 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 14240 // If there is an identifier, use the location of the identifier as the 14241 // location of the decl, otherwise use the location of the struct/union 14242 // keyword. 14243 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14244 TagDecl *New = nullptr; 14245 14246 if (Kind == TTK_Enum) { 14247 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 14248 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 14249 // If this is an undefined enum, bail. 14250 if (TUK != TUK_Definition && !Invalid) 14251 return nullptr; 14252 if (EnumUnderlying) { 14253 EnumDecl *ED = cast<EnumDecl>(New); 14254 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 14255 ED->setIntegerTypeSourceInfo(TI); 14256 else 14257 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 14258 ED->setPromotionType(ED->getIntegerType()); 14259 } 14260 } else { // struct/union 14261 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14262 nullptr); 14263 } 14264 14265 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14266 // Add alignment attributes if necessary; these attributes are checked 14267 // when the ASTContext lays out the structure. 14268 // 14269 // It is important for implementing the correct semantics that this 14270 // happen here (in ActOnTag). The #pragma pack stack is 14271 // maintained as a result of parser callbacks which can occur at 14272 // many points during the parsing of a struct declaration (because 14273 // the #pragma tokens are effectively skipped over during the 14274 // parsing of the struct). 14275 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14276 AddAlignmentAttributesForRecord(RD); 14277 AddMsStructLayoutForRecord(RD); 14278 } 14279 } 14280 New->setLexicalDeclContext(CurContext); 14281 return New; 14282 }; 14283 14284 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 14285 if (Name && SS.isNotEmpty()) { 14286 // We have a nested-name tag ('struct foo::bar'). 14287 14288 // Check for invalid 'foo::'. 14289 if (SS.isInvalid()) { 14290 Name = nullptr; 14291 goto CreateNewDecl; 14292 } 14293 14294 // If this is a friend or a reference to a class in a dependent 14295 // context, don't try to make a decl for it. 14296 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14297 DC = computeDeclContext(SS, false); 14298 if (!DC) { 14299 IsDependent = true; 14300 return nullptr; 14301 } 14302 } else { 14303 DC = computeDeclContext(SS, true); 14304 if (!DC) { 14305 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 14306 << SS.getRange(); 14307 return nullptr; 14308 } 14309 } 14310 14311 if (RequireCompleteDeclContext(SS, DC)) 14312 return nullptr; 14313 14314 SearchDC = DC; 14315 // Look-up name inside 'foo::'. 14316 LookupQualifiedName(Previous, DC); 14317 14318 if (Previous.isAmbiguous()) 14319 return nullptr; 14320 14321 if (Previous.empty()) { 14322 // Name lookup did not find anything. However, if the 14323 // nested-name-specifier refers to the current instantiation, 14324 // and that current instantiation has any dependent base 14325 // classes, we might find something at instantiation time: treat 14326 // this as a dependent elaborated-type-specifier. 14327 // But this only makes any sense for reference-like lookups. 14328 if (Previous.wasNotFoundInCurrentInstantiation() && 14329 (TUK == TUK_Reference || TUK == TUK_Friend)) { 14330 IsDependent = true; 14331 return nullptr; 14332 } 14333 14334 // A tag 'foo::bar' must already exist. 14335 Diag(NameLoc, diag::err_not_tag_in_scope) 14336 << Kind << Name << DC << SS.getRange(); 14337 Name = nullptr; 14338 Invalid = true; 14339 goto CreateNewDecl; 14340 } 14341 } else if (Name) { 14342 // C++14 [class.mem]p14: 14343 // If T is the name of a class, then each of the following shall have a 14344 // name different from T: 14345 // -- every member of class T that is itself a type 14346 if (TUK != TUK_Reference && TUK != TUK_Friend && 14347 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 14348 return nullptr; 14349 14350 // If this is a named struct, check to see if there was a previous forward 14351 // declaration or definition. 14352 // FIXME: We're looking into outer scopes here, even when we 14353 // shouldn't be. Doing so can result in ambiguities that we 14354 // shouldn't be diagnosing. 14355 LookupName(Previous, S); 14356 14357 // When declaring or defining a tag, ignore ambiguities introduced 14358 // by types using'ed into this scope. 14359 if (Previous.isAmbiguous() && 14360 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 14361 LookupResult::Filter F = Previous.makeFilter(); 14362 while (F.hasNext()) { 14363 NamedDecl *ND = F.next(); 14364 if (!ND->getDeclContext()->getRedeclContext()->Equals( 14365 SearchDC->getRedeclContext())) 14366 F.erase(); 14367 } 14368 F.done(); 14369 } 14370 14371 // C++11 [namespace.memdef]p3: 14372 // If the name in a friend declaration is neither qualified nor 14373 // a template-id and the declaration is a function or an 14374 // elaborated-type-specifier, the lookup to determine whether 14375 // the entity has been previously declared shall not consider 14376 // any scopes outside the innermost enclosing namespace. 14377 // 14378 // MSVC doesn't implement the above rule for types, so a friend tag 14379 // declaration may be a redeclaration of a type declared in an enclosing 14380 // scope. They do implement this rule for friend functions. 14381 // 14382 // Does it matter that this should be by scope instead of by 14383 // semantic context? 14384 if (!Previous.empty() && TUK == TUK_Friend) { 14385 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 14386 LookupResult::Filter F = Previous.makeFilter(); 14387 bool FriendSawTagOutsideEnclosingNamespace = false; 14388 while (F.hasNext()) { 14389 NamedDecl *ND = F.next(); 14390 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14391 if (DC->isFileContext() && 14392 !EnclosingNS->Encloses(ND->getDeclContext())) { 14393 if (getLangOpts().MSVCCompat) 14394 FriendSawTagOutsideEnclosingNamespace = true; 14395 else 14396 F.erase(); 14397 } 14398 } 14399 F.done(); 14400 14401 // Diagnose this MSVC extension in the easy case where lookup would have 14402 // unambiguously found something outside the enclosing namespace. 14403 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 14404 NamedDecl *ND = Previous.getFoundDecl(); 14405 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 14406 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 14407 } 14408 } 14409 14410 // Note: there used to be some attempt at recovery here. 14411 if (Previous.isAmbiguous()) 14412 return nullptr; 14413 14414 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 14415 // FIXME: This makes sure that we ignore the contexts associated 14416 // with C structs, unions, and enums when looking for a matching 14417 // tag declaration or definition. See the similar lookup tweak 14418 // in Sema::LookupName; is there a better way to deal with this? 14419 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 14420 SearchDC = SearchDC->getParent(); 14421 } 14422 } 14423 14424 if (Previous.isSingleResult() && 14425 Previous.getFoundDecl()->isTemplateParameter()) { 14426 // Maybe we will complain about the shadowed template parameter. 14427 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 14428 // Just pretend that we didn't see the previous declaration. 14429 Previous.clear(); 14430 } 14431 14432 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 14433 DC->Equals(getStdNamespace())) { 14434 if (Name->isStr("bad_alloc")) { 14435 // This is a declaration of or a reference to "std::bad_alloc". 14436 isStdBadAlloc = true; 14437 14438 // If std::bad_alloc has been implicitly declared (but made invisible to 14439 // name lookup), fill in this implicit declaration as the previous 14440 // declaration, so that the declarations get chained appropriately. 14441 if (Previous.empty() && StdBadAlloc) 14442 Previous.addDecl(getStdBadAlloc()); 14443 } else if (Name->isStr("align_val_t")) { 14444 isStdAlignValT = true; 14445 if (Previous.empty() && StdAlignValT) 14446 Previous.addDecl(getStdAlignValT()); 14447 } 14448 } 14449 14450 // If we didn't find a previous declaration, and this is a reference 14451 // (or friend reference), move to the correct scope. In C++, we 14452 // also need to do a redeclaration lookup there, just in case 14453 // there's a shadow friend decl. 14454 if (Name && Previous.empty() && 14455 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 14456 if (Invalid) goto CreateNewDecl; 14457 assert(SS.isEmpty()); 14458 14459 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 14460 // C++ [basic.scope.pdecl]p5: 14461 // -- for an elaborated-type-specifier of the form 14462 // 14463 // class-key identifier 14464 // 14465 // if the elaborated-type-specifier is used in the 14466 // decl-specifier-seq or parameter-declaration-clause of a 14467 // function defined in namespace scope, the identifier is 14468 // declared as a class-name in the namespace that contains 14469 // the declaration; otherwise, except as a friend 14470 // declaration, the identifier is declared in the smallest 14471 // non-class, non-function-prototype scope that contains the 14472 // declaration. 14473 // 14474 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 14475 // C structs and unions. 14476 // 14477 // It is an error in C++ to declare (rather than define) an enum 14478 // type, including via an elaborated type specifier. We'll 14479 // diagnose that later; for now, declare the enum in the same 14480 // scope as we would have picked for any other tag type. 14481 // 14482 // GNU C also supports this behavior as part of its incomplete 14483 // enum types extension, while GNU C++ does not. 14484 // 14485 // Find the context where we'll be declaring the tag. 14486 // FIXME: We would like to maintain the current DeclContext as the 14487 // lexical context, 14488 SearchDC = getTagInjectionContext(SearchDC); 14489 14490 // Find the scope where we'll be declaring the tag. 14491 S = getTagInjectionScope(S, getLangOpts()); 14492 } else { 14493 assert(TUK == TUK_Friend); 14494 // C++ [namespace.memdef]p3: 14495 // If a friend declaration in a non-local class first declares a 14496 // class or function, the friend class or function is a member of 14497 // the innermost enclosing namespace. 14498 SearchDC = SearchDC->getEnclosingNamespaceContext(); 14499 } 14500 14501 // In C++, we need to do a redeclaration lookup to properly 14502 // diagnose some problems. 14503 // FIXME: redeclaration lookup is also used (with and without C++) to find a 14504 // hidden declaration so that we don't get ambiguity errors when using a 14505 // type declared by an elaborated-type-specifier. In C that is not correct 14506 // and we should instead merge compatible types found by lookup. 14507 if (getLangOpts().CPlusPlus) { 14508 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14509 LookupQualifiedName(Previous, SearchDC); 14510 } else { 14511 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14512 LookupName(Previous, S); 14513 } 14514 } 14515 14516 // If we have a known previous declaration to use, then use it. 14517 if (Previous.empty() && SkipBody && SkipBody->Previous) 14518 Previous.addDecl(SkipBody->Previous); 14519 14520 if (!Previous.empty()) { 14521 NamedDecl *PrevDecl = Previous.getFoundDecl(); 14522 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 14523 14524 // It's okay to have a tag decl in the same scope as a typedef 14525 // which hides a tag decl in the same scope. Finding this 14526 // insanity with a redeclaration lookup can only actually happen 14527 // in C++. 14528 // 14529 // This is also okay for elaborated-type-specifiers, which is 14530 // technically forbidden by the current standard but which is 14531 // okay according to the likely resolution of an open issue; 14532 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 14533 if (getLangOpts().CPlusPlus) { 14534 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14535 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 14536 TagDecl *Tag = TT->getDecl(); 14537 if (Tag->getDeclName() == Name && 14538 Tag->getDeclContext()->getRedeclContext() 14539 ->Equals(TD->getDeclContext()->getRedeclContext())) { 14540 PrevDecl = Tag; 14541 Previous.clear(); 14542 Previous.addDecl(Tag); 14543 Previous.resolveKind(); 14544 } 14545 } 14546 } 14547 } 14548 14549 // If this is a redeclaration of a using shadow declaration, it must 14550 // declare a tag in the same context. In MSVC mode, we allow a 14551 // redefinition if either context is within the other. 14552 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 14553 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 14554 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 14555 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 14556 !(OldTag && isAcceptableTagRedeclContext( 14557 *this, OldTag->getDeclContext(), SearchDC))) { 14558 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 14559 Diag(Shadow->getTargetDecl()->getLocation(), 14560 diag::note_using_decl_target); 14561 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 14562 << 0; 14563 // Recover by ignoring the old declaration. 14564 Previous.clear(); 14565 goto CreateNewDecl; 14566 } 14567 } 14568 14569 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 14570 // If this is a use of a previous tag, or if the tag is already declared 14571 // in the same scope (so that the definition/declaration completes or 14572 // rementions the tag), reuse the decl. 14573 if (TUK == TUK_Reference || TUK == TUK_Friend || 14574 isDeclInScope(DirectPrevDecl, SearchDC, S, 14575 SS.isNotEmpty() || isMemberSpecialization)) { 14576 // Make sure that this wasn't declared as an enum and now used as a 14577 // struct or something similar. 14578 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14579 TUK == TUK_Definition, KWLoc, 14580 Name)) { 14581 bool SafeToContinue 14582 = (PrevTagDecl->getTagKind() != TTK_Enum && 14583 Kind != TTK_Enum); 14584 if (SafeToContinue) 14585 Diag(KWLoc, diag::err_use_with_wrong_tag) 14586 << Name 14587 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14588 PrevTagDecl->getKindName()); 14589 else 14590 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14591 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14592 14593 if (SafeToContinue) 14594 Kind = PrevTagDecl->getTagKind(); 14595 else { 14596 // Recover by making this an anonymous redefinition. 14597 Name = nullptr; 14598 Previous.clear(); 14599 Invalid = true; 14600 } 14601 } 14602 14603 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14604 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14605 14606 // If this is an elaborated-type-specifier for a scoped enumeration, 14607 // the 'class' keyword is not necessary and not permitted. 14608 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14609 if (ScopedEnum) 14610 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14611 << PrevEnum->isScoped() 14612 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14613 return PrevTagDecl; 14614 } 14615 14616 QualType EnumUnderlyingTy; 14617 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14618 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14619 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14620 EnumUnderlyingTy = QualType(T, 0); 14621 14622 // All conflicts with previous declarations are recovered by 14623 // returning the previous declaration, unless this is a definition, 14624 // in which case we want the caller to bail out. 14625 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14626 ScopedEnum, EnumUnderlyingTy, 14627 IsFixed, PrevEnum)) 14628 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14629 } 14630 14631 // C++11 [class.mem]p1: 14632 // A member shall not be declared twice in the member-specification, 14633 // except that a nested class or member class template can be declared 14634 // and then later defined. 14635 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14636 S->isDeclScope(PrevDecl)) { 14637 Diag(NameLoc, diag::ext_member_redeclared); 14638 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14639 } 14640 14641 if (!Invalid) { 14642 // If this is a use, just return the declaration we found, unless 14643 // we have attributes. 14644 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14645 if (!Attrs.empty()) { 14646 // FIXME: Diagnose these attributes. For now, we create a new 14647 // declaration to hold them. 14648 } else if (TUK == TUK_Reference && 14649 (PrevTagDecl->getFriendObjectKind() == 14650 Decl::FOK_Undeclared || 14651 PrevDecl->getOwningModule() != getCurrentModule()) && 14652 SS.isEmpty()) { 14653 // This declaration is a reference to an existing entity, but 14654 // has different visibility from that entity: it either makes 14655 // a friend visible or it makes a type visible in a new module. 14656 // In either case, create a new declaration. We only do this if 14657 // the declaration would have meant the same thing if no prior 14658 // declaration were found, that is, if it was found in the same 14659 // scope where we would have injected a declaration. 14660 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14661 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14662 return PrevTagDecl; 14663 // This is in the injected scope, create a new declaration in 14664 // that scope. 14665 S = getTagInjectionScope(S, getLangOpts()); 14666 } else { 14667 return PrevTagDecl; 14668 } 14669 } 14670 14671 // Diagnose attempts to redefine a tag. 14672 if (TUK == TUK_Definition) { 14673 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14674 // If we're defining a specialization and the previous definition 14675 // is from an implicit instantiation, don't emit an error 14676 // here; we'll catch this in the general case below. 14677 bool IsExplicitSpecializationAfterInstantiation = false; 14678 if (isMemberSpecialization) { 14679 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14680 IsExplicitSpecializationAfterInstantiation = 14681 RD->getTemplateSpecializationKind() != 14682 TSK_ExplicitSpecialization; 14683 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14684 IsExplicitSpecializationAfterInstantiation = 14685 ED->getTemplateSpecializationKind() != 14686 TSK_ExplicitSpecialization; 14687 } 14688 14689 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14690 // not keep more that one definition around (merge them). However, 14691 // ensure the decl passes the structural compatibility check in 14692 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14693 NamedDecl *Hidden = nullptr; 14694 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14695 // There is a definition of this tag, but it is not visible. We 14696 // explicitly make use of C++'s one definition rule here, and 14697 // assume that this definition is identical to the hidden one 14698 // we already have. Make the existing definition visible and 14699 // use it in place of this one. 14700 if (!getLangOpts().CPlusPlus) { 14701 // Postpone making the old definition visible until after we 14702 // complete parsing the new one and do the structural 14703 // comparison. 14704 SkipBody->CheckSameAsPrevious = true; 14705 SkipBody->New = createTagFromNewDecl(); 14706 SkipBody->Previous = Def; 14707 return Def; 14708 } else { 14709 SkipBody->ShouldSkip = true; 14710 SkipBody->Previous = Def; 14711 makeMergedDefinitionVisible(Hidden); 14712 // Carry on and handle it like a normal definition. We'll 14713 // skip starting the definitiion later. 14714 } 14715 } else if (!IsExplicitSpecializationAfterInstantiation) { 14716 // A redeclaration in function prototype scope in C isn't 14717 // visible elsewhere, so merely issue a warning. 14718 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14719 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14720 else 14721 Diag(NameLoc, diag::err_redefinition) << Name; 14722 notePreviousDefinition(Def, 14723 NameLoc.isValid() ? NameLoc : KWLoc); 14724 // If this is a redefinition, recover by making this 14725 // struct be anonymous, which will make any later 14726 // references get the previous definition. 14727 Name = nullptr; 14728 Previous.clear(); 14729 Invalid = true; 14730 } 14731 } else { 14732 // If the type is currently being defined, complain 14733 // about a nested redefinition. 14734 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14735 if (TD->isBeingDefined()) { 14736 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14737 Diag(PrevTagDecl->getLocation(), 14738 diag::note_previous_definition); 14739 Name = nullptr; 14740 Previous.clear(); 14741 Invalid = true; 14742 } 14743 } 14744 14745 // Okay, this is definition of a previously declared or referenced 14746 // tag. We're going to create a new Decl for it. 14747 } 14748 14749 // Okay, we're going to make a redeclaration. If this is some kind 14750 // of reference, make sure we build the redeclaration in the same DC 14751 // as the original, and ignore the current access specifier. 14752 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14753 SearchDC = PrevTagDecl->getDeclContext(); 14754 AS = AS_none; 14755 } 14756 } 14757 // If we get here we have (another) forward declaration or we 14758 // have a definition. Just create a new decl. 14759 14760 } else { 14761 // If we get here, this is a definition of a new tag type in a nested 14762 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14763 // new decl/type. We set PrevDecl to NULL so that the entities 14764 // have distinct types. 14765 Previous.clear(); 14766 } 14767 // If we get here, we're going to create a new Decl. If PrevDecl 14768 // is non-NULL, it's a definition of the tag declared by 14769 // PrevDecl. If it's NULL, we have a new definition. 14770 14771 // Otherwise, PrevDecl is not a tag, but was found with tag 14772 // lookup. This is only actually possible in C++, where a few 14773 // things like templates still live in the tag namespace. 14774 } else { 14775 // Use a better diagnostic if an elaborated-type-specifier 14776 // found the wrong kind of type on the first 14777 // (non-redeclaration) lookup. 14778 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14779 !Previous.isForRedeclaration()) { 14780 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14781 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14782 << Kind; 14783 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14784 Invalid = true; 14785 14786 // Otherwise, only diagnose if the declaration is in scope. 14787 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14788 SS.isNotEmpty() || isMemberSpecialization)) { 14789 // do nothing 14790 14791 // Diagnose implicit declarations introduced by elaborated types. 14792 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14793 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14794 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14795 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14796 Invalid = true; 14797 14798 // Otherwise it's a declaration. Call out a particularly common 14799 // case here. 14800 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14801 unsigned Kind = 0; 14802 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14803 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14804 << Name << Kind << TND->getUnderlyingType(); 14805 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14806 Invalid = true; 14807 14808 // Otherwise, diagnose. 14809 } else { 14810 // The tag name clashes with something else in the target scope, 14811 // issue an error and recover by making this tag be anonymous. 14812 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14813 notePreviousDefinition(PrevDecl, NameLoc); 14814 Name = nullptr; 14815 Invalid = true; 14816 } 14817 14818 // The existing declaration isn't relevant to us; we're in a 14819 // new scope, so clear out the previous declaration. 14820 Previous.clear(); 14821 } 14822 } 14823 14824 CreateNewDecl: 14825 14826 TagDecl *PrevDecl = nullptr; 14827 if (Previous.isSingleResult()) 14828 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14829 14830 // If there is an identifier, use the location of the identifier as the 14831 // location of the decl, otherwise use the location of the struct/union 14832 // keyword. 14833 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14834 14835 // Otherwise, create a new declaration. If there is a previous 14836 // declaration of the same entity, the two will be linked via 14837 // PrevDecl. 14838 TagDecl *New; 14839 14840 if (Kind == TTK_Enum) { 14841 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14842 // enum X { A, B, C } D; D should chain to X. 14843 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14844 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14845 ScopedEnumUsesClassTag, IsFixed); 14846 14847 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14848 StdAlignValT = cast<EnumDecl>(New); 14849 14850 // If this is an undefined enum, warn. 14851 if (TUK != TUK_Definition && !Invalid) { 14852 TagDecl *Def; 14853 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 14854 // C++0x: 7.2p2: opaque-enum-declaration. 14855 // Conflicts are diagnosed above. Do nothing. 14856 } 14857 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14858 Diag(Loc, diag::ext_forward_ref_enum_def) 14859 << New; 14860 Diag(Def->getLocation(), diag::note_previous_definition); 14861 } else { 14862 unsigned DiagID = diag::ext_forward_ref_enum; 14863 if (getLangOpts().MSVCCompat) 14864 DiagID = diag::ext_ms_forward_ref_enum; 14865 else if (getLangOpts().CPlusPlus) 14866 DiagID = diag::err_forward_ref_enum; 14867 Diag(Loc, DiagID); 14868 } 14869 } 14870 14871 if (EnumUnderlying) { 14872 EnumDecl *ED = cast<EnumDecl>(New); 14873 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14874 ED->setIntegerTypeSourceInfo(TI); 14875 else 14876 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14877 ED->setPromotionType(ED->getIntegerType()); 14878 assert(ED->isComplete() && "enum with type should be complete"); 14879 } 14880 } else { 14881 // struct/union/class 14882 14883 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14884 // struct X { int A; } D; D should chain to X. 14885 if (getLangOpts().CPlusPlus) { 14886 // FIXME: Look for a way to use RecordDecl for simple structs. 14887 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14888 cast_or_null<CXXRecordDecl>(PrevDecl)); 14889 14890 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14891 StdBadAlloc = cast<CXXRecordDecl>(New); 14892 } else 14893 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14894 cast_or_null<RecordDecl>(PrevDecl)); 14895 } 14896 14897 // C++11 [dcl.type]p3: 14898 // A type-specifier-seq shall not define a class or enumeration [...]. 14899 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14900 TUK == TUK_Definition) { 14901 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14902 << Context.getTagDeclType(New); 14903 Invalid = true; 14904 } 14905 14906 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14907 DC->getDeclKind() == Decl::Enum) { 14908 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14909 << Context.getTagDeclType(New); 14910 Invalid = true; 14911 } 14912 14913 // Maybe add qualifier info. 14914 if (SS.isNotEmpty()) { 14915 if (SS.isSet()) { 14916 // If this is either a declaration or a definition, check the 14917 // nested-name-specifier against the current context. 14918 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14919 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14920 isMemberSpecialization)) 14921 Invalid = true; 14922 14923 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14924 if (TemplateParameterLists.size() > 0) { 14925 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14926 } 14927 } 14928 else 14929 Invalid = true; 14930 } 14931 14932 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14933 // Add alignment attributes if necessary; these attributes are checked when 14934 // the ASTContext lays out the structure. 14935 // 14936 // It is important for implementing the correct semantics that this 14937 // happen here (in ActOnTag). The #pragma pack stack is 14938 // maintained as a result of parser callbacks which can occur at 14939 // many points during the parsing of a struct declaration (because 14940 // the #pragma tokens are effectively skipped over during the 14941 // parsing of the struct). 14942 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14943 AddAlignmentAttributesForRecord(RD); 14944 AddMsStructLayoutForRecord(RD); 14945 } 14946 } 14947 14948 if (ModulePrivateLoc.isValid()) { 14949 if (isMemberSpecialization) 14950 Diag(New->getLocation(), diag::err_module_private_specialization) 14951 << 2 14952 << FixItHint::CreateRemoval(ModulePrivateLoc); 14953 // __module_private__ does not apply to local classes. However, we only 14954 // diagnose this as an error when the declaration specifiers are 14955 // freestanding. Here, we just ignore the __module_private__. 14956 else if (!SearchDC->isFunctionOrMethod()) 14957 New->setModulePrivate(); 14958 } 14959 14960 // If this is a specialization of a member class (of a class template), 14961 // check the specialization. 14962 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14963 Invalid = true; 14964 14965 // If we're declaring or defining a tag in function prototype scope in C, 14966 // note that this type can only be used within the function and add it to 14967 // the list of decls to inject into the function definition scope. 14968 if ((Name || Kind == TTK_Enum) && 14969 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14970 if (getLangOpts().CPlusPlus) { 14971 // C++ [dcl.fct]p6: 14972 // Types shall not be defined in return or parameter types. 14973 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14974 Diag(Loc, diag::err_type_defined_in_param_type) 14975 << Name; 14976 Invalid = true; 14977 } 14978 } else if (!PrevDecl) { 14979 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14980 } 14981 } 14982 14983 if (Invalid) 14984 New->setInvalidDecl(); 14985 14986 // Set the lexical context. If the tag has a C++ scope specifier, the 14987 // lexical context will be different from the semantic context. 14988 New->setLexicalDeclContext(CurContext); 14989 14990 // Mark this as a friend decl if applicable. 14991 // In Microsoft mode, a friend declaration also acts as a forward 14992 // declaration so we always pass true to setObjectOfFriendDecl to make 14993 // the tag name visible. 14994 if (TUK == TUK_Friend) 14995 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14996 14997 // Set the access specifier. 14998 if (!Invalid && SearchDC->isRecord()) 14999 SetMemberAccessSpecifier(New, PrevDecl, AS); 15000 15001 if (PrevDecl) 15002 CheckRedeclarationModuleOwnership(New, PrevDecl); 15003 15004 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 15005 New->startDefinition(); 15006 15007 ProcessDeclAttributeList(S, New, Attrs); 15008 AddPragmaAttributes(S, New); 15009 15010 // If this has an identifier, add it to the scope stack. 15011 if (TUK == TUK_Friend) { 15012 // We might be replacing an existing declaration in the lookup tables; 15013 // if so, borrow its access specifier. 15014 if (PrevDecl) 15015 New->setAccess(PrevDecl->getAccess()); 15016 15017 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 15018 DC->makeDeclVisibleInContext(New); 15019 if (Name) // can be null along some error paths 15020 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15021 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 15022 } else if (Name) { 15023 S = getNonFieldDeclScope(S); 15024 PushOnScopeChains(New, S, true); 15025 } else { 15026 CurContext->addDecl(New); 15027 } 15028 15029 // If this is the C FILE type, notify the AST context. 15030 if (IdentifierInfo *II = New->getIdentifier()) 15031 if (!New->isInvalidDecl() && 15032 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 15033 II->isStr("FILE")) 15034 Context.setFILEDecl(New); 15035 15036 if (PrevDecl) 15037 mergeDeclAttributes(New, PrevDecl); 15038 15039 // If there's a #pragma GCC visibility in scope, set the visibility of this 15040 // record. 15041 AddPushedVisibilityAttribute(New); 15042 15043 if (isMemberSpecialization && !New->isInvalidDecl()) 15044 CompleteMemberSpecialization(New, Previous); 15045 15046 OwnedDecl = true; 15047 // In C++, don't return an invalid declaration. We can't recover well from 15048 // the cases where we make the type anonymous. 15049 if (Invalid && getLangOpts().CPlusPlus) { 15050 if (New->isBeingDefined()) 15051 if (auto RD = dyn_cast<RecordDecl>(New)) 15052 RD->completeDefinition(); 15053 return nullptr; 15054 } else if (SkipBody && SkipBody->ShouldSkip) { 15055 return SkipBody->Previous; 15056 } else { 15057 return New; 15058 } 15059 } 15060 15061 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 15062 AdjustDeclIfTemplate(TagD); 15063 TagDecl *Tag = cast<TagDecl>(TagD); 15064 15065 // Enter the tag context. 15066 PushDeclContext(S, Tag); 15067 15068 ActOnDocumentableDecl(TagD); 15069 15070 // If there's a #pragma GCC visibility in scope, set the visibility of this 15071 // record. 15072 AddPushedVisibilityAttribute(Tag); 15073 } 15074 15075 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 15076 SkipBodyInfo &SkipBody) { 15077 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 15078 return false; 15079 15080 // Make the previous decl visible. 15081 makeMergedDefinitionVisible(SkipBody.Previous); 15082 return true; 15083 } 15084 15085 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 15086 assert(isa<ObjCContainerDecl>(IDecl) && 15087 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 15088 DeclContext *OCD = cast<DeclContext>(IDecl); 15089 assert(getContainingDC(OCD) == CurContext && 15090 "The next DeclContext should be lexically contained in the current one."); 15091 CurContext = OCD; 15092 return IDecl; 15093 } 15094 15095 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 15096 SourceLocation FinalLoc, 15097 bool IsFinalSpelledSealed, 15098 SourceLocation LBraceLoc) { 15099 AdjustDeclIfTemplate(TagD); 15100 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 15101 15102 FieldCollector->StartClass(); 15103 15104 if (!Record->getIdentifier()) 15105 return; 15106 15107 if (FinalLoc.isValid()) 15108 Record->addAttr(new (Context) 15109 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 15110 15111 // C++ [class]p2: 15112 // [...] The class-name is also inserted into the scope of the 15113 // class itself; this is known as the injected-class-name. For 15114 // purposes of access checking, the injected-class-name is treated 15115 // as if it were a public member name. 15116 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 15117 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 15118 Record->getLocation(), Record->getIdentifier(), 15119 /*PrevDecl=*/nullptr, 15120 /*DelayTypeCreation=*/true); 15121 Context.getTypeDeclType(InjectedClassName, Record); 15122 InjectedClassName->setImplicit(); 15123 InjectedClassName->setAccess(AS_public); 15124 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 15125 InjectedClassName->setDescribedClassTemplate(Template); 15126 PushOnScopeChains(InjectedClassName, S); 15127 assert(InjectedClassName->isInjectedClassName() && 15128 "Broken injected-class-name"); 15129 } 15130 15131 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 15132 SourceRange BraceRange) { 15133 AdjustDeclIfTemplate(TagD); 15134 TagDecl *Tag = cast<TagDecl>(TagD); 15135 Tag->setBraceRange(BraceRange); 15136 15137 // Make sure we "complete" the definition even it is invalid. 15138 if (Tag->isBeingDefined()) { 15139 assert(Tag->isInvalidDecl() && "We should already have completed it"); 15140 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15141 RD->completeDefinition(); 15142 } 15143 15144 if (isa<CXXRecordDecl>(Tag)) { 15145 FieldCollector->FinishClass(); 15146 } 15147 15148 // Exit this scope of this tag's definition. 15149 PopDeclContext(); 15150 15151 if (getCurLexicalContext()->isObjCContainer() && 15152 Tag->getDeclContext()->isFileContext()) 15153 Tag->setTopLevelDeclInObjCContainer(); 15154 15155 // Notify the consumer that we've defined a tag. 15156 if (!Tag->isInvalidDecl()) 15157 Consumer.HandleTagDeclDefinition(Tag); 15158 } 15159 15160 void Sema::ActOnObjCContainerFinishDefinition() { 15161 // Exit this scope of this interface definition. 15162 PopDeclContext(); 15163 } 15164 15165 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 15166 assert(DC == CurContext && "Mismatch of container contexts"); 15167 OriginalLexicalContext = DC; 15168 ActOnObjCContainerFinishDefinition(); 15169 } 15170 15171 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 15172 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 15173 OriginalLexicalContext = nullptr; 15174 } 15175 15176 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 15177 AdjustDeclIfTemplate(TagD); 15178 TagDecl *Tag = cast<TagDecl>(TagD); 15179 Tag->setInvalidDecl(); 15180 15181 // Make sure we "complete" the definition even it is invalid. 15182 if (Tag->isBeingDefined()) { 15183 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15184 RD->completeDefinition(); 15185 } 15186 15187 // We're undoing ActOnTagStartDefinition here, not 15188 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 15189 // the FieldCollector. 15190 15191 PopDeclContext(); 15192 } 15193 15194 // Note that FieldName may be null for anonymous bitfields. 15195 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 15196 IdentifierInfo *FieldName, 15197 QualType FieldTy, bool IsMsStruct, 15198 Expr *BitWidth, bool *ZeroWidth) { 15199 // Default to true; that shouldn't confuse checks for emptiness 15200 if (ZeroWidth) 15201 *ZeroWidth = true; 15202 15203 // C99 6.7.2.1p4 - verify the field type. 15204 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 15205 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 15206 // Handle incomplete types with specific error. 15207 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 15208 return ExprError(); 15209 if (FieldName) 15210 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 15211 << FieldName << FieldTy << BitWidth->getSourceRange(); 15212 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 15213 << FieldTy << BitWidth->getSourceRange(); 15214 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 15215 UPPC_BitFieldWidth)) 15216 return ExprError(); 15217 15218 // If the bit-width is type- or value-dependent, don't try to check 15219 // it now. 15220 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 15221 return BitWidth; 15222 15223 llvm::APSInt Value; 15224 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 15225 if (ICE.isInvalid()) 15226 return ICE; 15227 BitWidth = ICE.get(); 15228 15229 if (Value != 0 && ZeroWidth) 15230 *ZeroWidth = false; 15231 15232 // Zero-width bitfield is ok for anonymous field. 15233 if (Value == 0 && FieldName) 15234 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 15235 15236 if (Value.isSigned() && Value.isNegative()) { 15237 if (FieldName) 15238 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 15239 << FieldName << Value.toString(10); 15240 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 15241 << Value.toString(10); 15242 } 15243 15244 if (!FieldTy->isDependentType()) { 15245 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 15246 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 15247 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 15248 15249 // Over-wide bitfields are an error in C or when using the MSVC bitfield 15250 // ABI. 15251 bool CStdConstraintViolation = 15252 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 15253 bool MSBitfieldViolation = 15254 Value.ugt(TypeStorageSize) && 15255 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 15256 if (CStdConstraintViolation || MSBitfieldViolation) { 15257 unsigned DiagWidth = 15258 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 15259 if (FieldName) 15260 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 15261 << FieldName << (unsigned)Value.getZExtValue() 15262 << !CStdConstraintViolation << DiagWidth; 15263 15264 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 15265 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 15266 << DiagWidth; 15267 } 15268 15269 // Warn on types where the user might conceivably expect to get all 15270 // specified bits as value bits: that's all integral types other than 15271 // 'bool'. 15272 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 15273 if (FieldName) 15274 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 15275 << FieldName << (unsigned)Value.getZExtValue() 15276 << (unsigned)TypeWidth; 15277 else 15278 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 15279 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 15280 } 15281 } 15282 15283 return BitWidth; 15284 } 15285 15286 /// ActOnField - Each field of a C struct/union is passed into this in order 15287 /// to create a FieldDecl object for it. 15288 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 15289 Declarator &D, Expr *BitfieldWidth) { 15290 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 15291 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 15292 /*InitStyle=*/ICIS_NoInit, AS_public); 15293 return Res; 15294 } 15295 15296 /// HandleField - Analyze a field of a C struct or a C++ data member. 15297 /// 15298 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 15299 SourceLocation DeclStart, 15300 Declarator &D, Expr *BitWidth, 15301 InClassInitStyle InitStyle, 15302 AccessSpecifier AS) { 15303 if (D.isDecompositionDeclarator()) { 15304 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 15305 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 15306 << Decomp.getSourceRange(); 15307 return nullptr; 15308 } 15309 15310 IdentifierInfo *II = D.getIdentifier(); 15311 SourceLocation Loc = DeclStart; 15312 if (II) Loc = D.getIdentifierLoc(); 15313 15314 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15315 QualType T = TInfo->getType(); 15316 if (getLangOpts().CPlusPlus) { 15317 CheckExtraCXXDefaultArguments(D); 15318 15319 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15320 UPPC_DataMemberType)) { 15321 D.setInvalidType(); 15322 T = Context.IntTy; 15323 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15324 } 15325 } 15326 15327 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15328 15329 if (D.getDeclSpec().isInlineSpecified()) 15330 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15331 << getLangOpts().CPlusPlus17; 15332 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15333 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15334 diag::err_invalid_thread) 15335 << DeclSpec::getSpecifierName(TSCS); 15336 15337 // Check to see if this name was declared as a member previously 15338 NamedDecl *PrevDecl = nullptr; 15339 LookupResult Previous(*this, II, Loc, LookupMemberName, 15340 ForVisibleRedeclaration); 15341 LookupName(Previous, S); 15342 switch (Previous.getResultKind()) { 15343 case LookupResult::Found: 15344 case LookupResult::FoundUnresolvedValue: 15345 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15346 break; 15347 15348 case LookupResult::FoundOverloaded: 15349 PrevDecl = Previous.getRepresentativeDecl(); 15350 break; 15351 15352 case LookupResult::NotFound: 15353 case LookupResult::NotFoundInCurrentInstantiation: 15354 case LookupResult::Ambiguous: 15355 break; 15356 } 15357 Previous.suppressDiagnostics(); 15358 15359 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15360 // Maybe we will complain about the shadowed template parameter. 15361 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15362 // Just pretend that we didn't see the previous declaration. 15363 PrevDecl = nullptr; 15364 } 15365 15366 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15367 PrevDecl = nullptr; 15368 15369 bool Mutable 15370 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 15371 SourceLocation TSSL = D.getBeginLoc(); 15372 FieldDecl *NewFD 15373 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 15374 TSSL, AS, PrevDecl, &D); 15375 15376 if (NewFD->isInvalidDecl()) 15377 Record->setInvalidDecl(); 15378 15379 if (D.getDeclSpec().isModulePrivateSpecified()) 15380 NewFD->setModulePrivate(); 15381 15382 if (NewFD->isInvalidDecl() && PrevDecl) { 15383 // Don't introduce NewFD into scope; there's already something 15384 // with the same name in the same scope. 15385 } else if (II) { 15386 PushOnScopeChains(NewFD, S); 15387 } else 15388 Record->addDecl(NewFD); 15389 15390 return NewFD; 15391 } 15392 15393 /// Build a new FieldDecl and check its well-formedness. 15394 /// 15395 /// This routine builds a new FieldDecl given the fields name, type, 15396 /// record, etc. \p PrevDecl should refer to any previous declaration 15397 /// with the same name and in the same scope as the field to be 15398 /// created. 15399 /// 15400 /// \returns a new FieldDecl. 15401 /// 15402 /// \todo The Declarator argument is a hack. It will be removed once 15403 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 15404 TypeSourceInfo *TInfo, 15405 RecordDecl *Record, SourceLocation Loc, 15406 bool Mutable, Expr *BitWidth, 15407 InClassInitStyle InitStyle, 15408 SourceLocation TSSL, 15409 AccessSpecifier AS, NamedDecl *PrevDecl, 15410 Declarator *D) { 15411 IdentifierInfo *II = Name.getAsIdentifierInfo(); 15412 bool InvalidDecl = false; 15413 if (D) InvalidDecl = D->isInvalidType(); 15414 15415 // If we receive a broken type, recover by assuming 'int' and 15416 // marking this declaration as invalid. 15417 if (T.isNull()) { 15418 InvalidDecl = true; 15419 T = Context.IntTy; 15420 } 15421 15422 QualType EltTy = Context.getBaseElementType(T); 15423 if (!EltTy->isDependentType()) { 15424 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 15425 // Fields of incomplete type force their record to be invalid. 15426 Record->setInvalidDecl(); 15427 InvalidDecl = true; 15428 } else { 15429 NamedDecl *Def; 15430 EltTy->isIncompleteType(&Def); 15431 if (Def && Def->isInvalidDecl()) { 15432 Record->setInvalidDecl(); 15433 InvalidDecl = true; 15434 } 15435 } 15436 } 15437 15438 // TR 18037 does not allow fields to be declared with address space 15439 if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || 15440 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 15441 Diag(Loc, diag::err_field_with_address_space); 15442 Record->setInvalidDecl(); 15443 InvalidDecl = true; 15444 } 15445 15446 if (LangOpts.OpenCL) { 15447 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 15448 // used as structure or union field: image, sampler, event or block types. 15449 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 15450 T->isBlockPointerType()) { 15451 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 15452 Record->setInvalidDecl(); 15453 InvalidDecl = true; 15454 } 15455 // OpenCL v1.2 s6.9.c: bitfields are not supported. 15456 if (BitWidth) { 15457 Diag(Loc, diag::err_opencl_bitfields); 15458 InvalidDecl = true; 15459 } 15460 } 15461 15462 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 15463 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 15464 T.hasQualifiers()) { 15465 InvalidDecl = true; 15466 Diag(Loc, diag::err_anon_bitfield_qualifiers); 15467 } 15468 15469 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15470 // than a variably modified type. 15471 if (!InvalidDecl && T->isVariablyModifiedType()) { 15472 bool SizeIsNegative; 15473 llvm::APSInt Oversized; 15474 15475 TypeSourceInfo *FixedTInfo = 15476 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 15477 SizeIsNegative, 15478 Oversized); 15479 if (FixedTInfo) { 15480 Diag(Loc, diag::warn_illegal_constant_array_size); 15481 TInfo = FixedTInfo; 15482 T = FixedTInfo->getType(); 15483 } else { 15484 if (SizeIsNegative) 15485 Diag(Loc, diag::err_typecheck_negative_array_size); 15486 else if (Oversized.getBoolValue()) 15487 Diag(Loc, diag::err_array_too_large) 15488 << Oversized.toString(10); 15489 else 15490 Diag(Loc, diag::err_typecheck_field_variable_size); 15491 InvalidDecl = true; 15492 } 15493 } 15494 15495 // Fields can not have abstract class types 15496 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 15497 diag::err_abstract_type_in_decl, 15498 AbstractFieldType)) 15499 InvalidDecl = true; 15500 15501 bool ZeroWidth = false; 15502 if (InvalidDecl) 15503 BitWidth = nullptr; 15504 // If this is declared as a bit-field, check the bit-field. 15505 if (BitWidth) { 15506 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 15507 &ZeroWidth).get(); 15508 if (!BitWidth) { 15509 InvalidDecl = true; 15510 BitWidth = nullptr; 15511 ZeroWidth = false; 15512 } 15513 } 15514 15515 // Check that 'mutable' is consistent with the type of the declaration. 15516 if (!InvalidDecl && Mutable) { 15517 unsigned DiagID = 0; 15518 if (T->isReferenceType()) 15519 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 15520 : diag::err_mutable_reference; 15521 else if (T.isConstQualified()) 15522 DiagID = diag::err_mutable_const; 15523 15524 if (DiagID) { 15525 SourceLocation ErrLoc = Loc; 15526 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 15527 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 15528 Diag(ErrLoc, DiagID); 15529 if (DiagID != diag::ext_mutable_reference) { 15530 Mutable = false; 15531 InvalidDecl = true; 15532 } 15533 } 15534 } 15535 15536 // C++11 [class.union]p8 (DR1460): 15537 // At most one variant member of a union may have a 15538 // brace-or-equal-initializer. 15539 if (InitStyle != ICIS_NoInit) 15540 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 15541 15542 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 15543 BitWidth, Mutable, InitStyle); 15544 if (InvalidDecl) 15545 NewFD->setInvalidDecl(); 15546 15547 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 15548 Diag(Loc, diag::err_duplicate_member) << II; 15549 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15550 NewFD->setInvalidDecl(); 15551 } 15552 15553 if (!InvalidDecl && getLangOpts().CPlusPlus) { 15554 if (Record->isUnion()) { 15555 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15556 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15557 if (RDecl->getDefinition()) { 15558 // C++ [class.union]p1: An object of a class with a non-trivial 15559 // constructor, a non-trivial copy constructor, a non-trivial 15560 // destructor, or a non-trivial copy assignment operator 15561 // cannot be a member of a union, nor can an array of such 15562 // objects. 15563 if (CheckNontrivialField(NewFD)) 15564 NewFD->setInvalidDecl(); 15565 } 15566 } 15567 15568 // C++ [class.union]p1: If a union contains a member of reference type, 15569 // the program is ill-formed, except when compiling with MSVC extensions 15570 // enabled. 15571 if (EltTy->isReferenceType()) { 15572 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15573 diag::ext_union_member_of_reference_type : 15574 diag::err_union_member_of_reference_type) 15575 << NewFD->getDeclName() << EltTy; 15576 if (!getLangOpts().MicrosoftExt) 15577 NewFD->setInvalidDecl(); 15578 } 15579 } 15580 } 15581 15582 // FIXME: We need to pass in the attributes given an AST 15583 // representation, not a parser representation. 15584 if (D) { 15585 // FIXME: The current scope is almost... but not entirely... correct here. 15586 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15587 15588 if (NewFD->hasAttrs()) 15589 CheckAlignasUnderalignment(NewFD); 15590 } 15591 15592 // In auto-retain/release, infer strong retension for fields of 15593 // retainable type. 15594 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15595 NewFD->setInvalidDecl(); 15596 15597 if (T.isObjCGCWeak()) 15598 Diag(Loc, diag::warn_attribute_weak_on_field); 15599 15600 NewFD->setAccess(AS); 15601 return NewFD; 15602 } 15603 15604 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15605 assert(FD); 15606 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15607 15608 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15609 return false; 15610 15611 QualType EltTy = Context.getBaseElementType(FD->getType()); 15612 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15613 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15614 if (RDecl->getDefinition()) { 15615 // We check for copy constructors before constructors 15616 // because otherwise we'll never get complaints about 15617 // copy constructors. 15618 15619 CXXSpecialMember member = CXXInvalid; 15620 // We're required to check for any non-trivial constructors. Since the 15621 // implicit default constructor is suppressed if there are any 15622 // user-declared constructors, we just need to check that there is a 15623 // trivial default constructor and a trivial copy constructor. (We don't 15624 // worry about move constructors here, since this is a C++98 check.) 15625 if (RDecl->hasNonTrivialCopyConstructor()) 15626 member = CXXCopyConstructor; 15627 else if (!RDecl->hasTrivialDefaultConstructor()) 15628 member = CXXDefaultConstructor; 15629 else if (RDecl->hasNonTrivialCopyAssignment()) 15630 member = CXXCopyAssignment; 15631 else if (RDecl->hasNonTrivialDestructor()) 15632 member = CXXDestructor; 15633 15634 if (member != CXXInvalid) { 15635 if (!getLangOpts().CPlusPlus11 && 15636 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15637 // Objective-C++ ARC: it is an error to have a non-trivial field of 15638 // a union. However, system headers in Objective-C programs 15639 // occasionally have Objective-C lifetime objects within unions, 15640 // and rather than cause the program to fail, we make those 15641 // members unavailable. 15642 SourceLocation Loc = FD->getLocation(); 15643 if (getSourceManager().isInSystemHeader(Loc)) { 15644 if (!FD->hasAttr<UnavailableAttr>()) 15645 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15646 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15647 return false; 15648 } 15649 } 15650 15651 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15652 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15653 diag::err_illegal_union_or_anon_struct_member) 15654 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15655 DiagnoseNontrivial(RDecl, member); 15656 return !getLangOpts().CPlusPlus11; 15657 } 15658 } 15659 } 15660 15661 return false; 15662 } 15663 15664 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15665 /// AST enum value. 15666 static ObjCIvarDecl::AccessControl 15667 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15668 switch (ivarVisibility) { 15669 default: llvm_unreachable("Unknown visitibility kind"); 15670 case tok::objc_private: return ObjCIvarDecl::Private; 15671 case tok::objc_public: return ObjCIvarDecl::Public; 15672 case tok::objc_protected: return ObjCIvarDecl::Protected; 15673 case tok::objc_package: return ObjCIvarDecl::Package; 15674 } 15675 } 15676 15677 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15678 /// in order to create an IvarDecl object for it. 15679 Decl *Sema::ActOnIvar(Scope *S, 15680 SourceLocation DeclStart, 15681 Declarator &D, Expr *BitfieldWidth, 15682 tok::ObjCKeywordKind Visibility) { 15683 15684 IdentifierInfo *II = D.getIdentifier(); 15685 Expr *BitWidth = (Expr*)BitfieldWidth; 15686 SourceLocation Loc = DeclStart; 15687 if (II) Loc = D.getIdentifierLoc(); 15688 15689 // FIXME: Unnamed fields can be handled in various different ways, for 15690 // example, unnamed unions inject all members into the struct namespace! 15691 15692 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15693 QualType T = TInfo->getType(); 15694 15695 if (BitWidth) { 15696 // 6.7.2.1p3, 6.7.2.1p4 15697 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15698 if (!BitWidth) 15699 D.setInvalidType(); 15700 } else { 15701 // Not a bitfield. 15702 15703 // validate II. 15704 15705 } 15706 if (T->isReferenceType()) { 15707 Diag(Loc, diag::err_ivar_reference_type); 15708 D.setInvalidType(); 15709 } 15710 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15711 // than a variably modified type. 15712 else if (T->isVariablyModifiedType()) { 15713 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15714 D.setInvalidType(); 15715 } 15716 15717 // Get the visibility (access control) for this ivar. 15718 ObjCIvarDecl::AccessControl ac = 15719 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15720 : ObjCIvarDecl::None; 15721 // Must set ivar's DeclContext to its enclosing interface. 15722 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15723 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15724 return nullptr; 15725 ObjCContainerDecl *EnclosingContext; 15726 if (ObjCImplementationDecl *IMPDecl = 15727 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15728 if (LangOpts.ObjCRuntime.isFragile()) { 15729 // Case of ivar declared in an implementation. Context is that of its class. 15730 EnclosingContext = IMPDecl->getClassInterface(); 15731 assert(EnclosingContext && "Implementation has no class interface!"); 15732 } 15733 else 15734 EnclosingContext = EnclosingDecl; 15735 } else { 15736 if (ObjCCategoryDecl *CDecl = 15737 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15738 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15739 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15740 return nullptr; 15741 } 15742 } 15743 EnclosingContext = EnclosingDecl; 15744 } 15745 15746 // Construct the decl. 15747 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15748 DeclStart, Loc, II, T, 15749 TInfo, ac, (Expr *)BitfieldWidth); 15750 15751 if (II) { 15752 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15753 ForVisibleRedeclaration); 15754 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15755 && !isa<TagDecl>(PrevDecl)) { 15756 Diag(Loc, diag::err_duplicate_member) << II; 15757 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15758 NewID->setInvalidDecl(); 15759 } 15760 } 15761 15762 // Process attributes attached to the ivar. 15763 ProcessDeclAttributes(S, NewID, D); 15764 15765 if (D.isInvalidType()) 15766 NewID->setInvalidDecl(); 15767 15768 // In ARC, infer 'retaining' for ivars of retainable type. 15769 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15770 NewID->setInvalidDecl(); 15771 15772 if (D.getDeclSpec().isModulePrivateSpecified()) 15773 NewID->setModulePrivate(); 15774 15775 if (II) { 15776 // FIXME: When interfaces are DeclContexts, we'll need to add 15777 // these to the interface. 15778 S->AddDecl(NewID); 15779 IdResolver.AddDecl(NewID); 15780 } 15781 15782 if (LangOpts.ObjCRuntime.isNonFragile() && 15783 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15784 Diag(Loc, diag::warn_ivars_in_interface); 15785 15786 return NewID; 15787 } 15788 15789 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15790 /// class and class extensions. For every class \@interface and class 15791 /// extension \@interface, if the last ivar is a bitfield of any type, 15792 /// then add an implicit `char :0` ivar to the end of that interface. 15793 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15794 SmallVectorImpl<Decl *> &AllIvarDecls) { 15795 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15796 return; 15797 15798 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15799 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15800 15801 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15802 return; 15803 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15804 if (!ID) { 15805 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15806 if (!CD->IsClassExtension()) 15807 return; 15808 } 15809 // No need to add this to end of @implementation. 15810 else 15811 return; 15812 } 15813 // All conditions are met. Add a new bitfield to the tail end of ivars. 15814 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15815 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15816 15817 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15818 DeclLoc, DeclLoc, nullptr, 15819 Context.CharTy, 15820 Context.getTrivialTypeSourceInfo(Context.CharTy, 15821 DeclLoc), 15822 ObjCIvarDecl::Private, BW, 15823 true); 15824 AllIvarDecls.push_back(Ivar); 15825 } 15826 15827 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15828 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15829 SourceLocation RBrac, 15830 const ParsedAttributesView &Attrs) { 15831 assert(EnclosingDecl && "missing record or interface decl"); 15832 15833 // If this is an Objective-C @implementation or category and we have 15834 // new fields here we should reset the layout of the interface since 15835 // it will now change. 15836 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15837 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15838 switch (DC->getKind()) { 15839 default: break; 15840 case Decl::ObjCCategory: 15841 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15842 break; 15843 case Decl::ObjCImplementation: 15844 Context. 15845 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15846 break; 15847 } 15848 } 15849 15850 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15851 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 15852 15853 // Start counting up the number of named members; make sure to include 15854 // members of anonymous structs and unions in the total. 15855 unsigned NumNamedMembers = 0; 15856 if (Record) { 15857 for (const auto *I : Record->decls()) { 15858 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15859 if (IFD->getDeclName()) 15860 ++NumNamedMembers; 15861 } 15862 } 15863 15864 // Verify that all the fields are okay. 15865 SmallVector<FieldDecl*, 32> RecFields; 15866 15867 bool ObjCFieldLifetimeErrReported = false; 15868 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15869 i != end; ++i) { 15870 FieldDecl *FD = cast<FieldDecl>(*i); 15871 15872 // Get the type for the field. 15873 const Type *FDTy = FD->getType().getTypePtr(); 15874 15875 if (!FD->isAnonymousStructOrUnion()) { 15876 // Remember all fields written by the user. 15877 RecFields.push_back(FD); 15878 } 15879 15880 // If the field is already invalid for some reason, don't emit more 15881 // diagnostics about it. 15882 if (FD->isInvalidDecl()) { 15883 EnclosingDecl->setInvalidDecl(); 15884 continue; 15885 } 15886 15887 // C99 6.7.2.1p2: 15888 // A structure or union shall not contain a member with 15889 // incomplete or function type (hence, a structure shall not 15890 // contain an instance of itself, but may contain a pointer to 15891 // an instance of itself), except that the last member of a 15892 // structure with more than one named member may have incomplete 15893 // array type; such a structure (and any union containing, 15894 // possibly recursively, a member that is such a structure) 15895 // shall not be a member of a structure or an element of an 15896 // array. 15897 bool IsLastField = (i + 1 == Fields.end()); 15898 if (FDTy->isFunctionType()) { 15899 // Field declared as a function. 15900 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15901 << FD->getDeclName(); 15902 FD->setInvalidDecl(); 15903 EnclosingDecl->setInvalidDecl(); 15904 continue; 15905 } else if (FDTy->isIncompleteArrayType() && 15906 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15907 if (Record) { 15908 // Flexible array member. 15909 // Microsoft and g++ is more permissive regarding flexible array. 15910 // It will accept flexible array in union and also 15911 // as the sole element of a struct/class. 15912 unsigned DiagID = 0; 15913 if (!Record->isUnion() && !IsLastField) { 15914 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15915 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15916 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15917 FD->setInvalidDecl(); 15918 EnclosingDecl->setInvalidDecl(); 15919 continue; 15920 } else if (Record->isUnion()) 15921 DiagID = getLangOpts().MicrosoftExt 15922 ? diag::ext_flexible_array_union_ms 15923 : getLangOpts().CPlusPlus 15924 ? diag::ext_flexible_array_union_gnu 15925 : diag::err_flexible_array_union; 15926 else if (NumNamedMembers < 1) 15927 DiagID = getLangOpts().MicrosoftExt 15928 ? diag::ext_flexible_array_empty_aggregate_ms 15929 : getLangOpts().CPlusPlus 15930 ? diag::ext_flexible_array_empty_aggregate_gnu 15931 : diag::err_flexible_array_empty_aggregate; 15932 15933 if (DiagID) 15934 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15935 << Record->getTagKind(); 15936 // While the layout of types that contain virtual bases is not specified 15937 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15938 // virtual bases after the derived members. This would make a flexible 15939 // array member declared at the end of an object not adjacent to the end 15940 // of the type. 15941 if (CXXRecord && CXXRecord->getNumVBases() != 0) 15942 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15943 << FD->getDeclName() << Record->getTagKind(); 15944 if (!getLangOpts().C99) 15945 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15946 << FD->getDeclName() << Record->getTagKind(); 15947 15948 // If the element type has a non-trivial destructor, we would not 15949 // implicitly destroy the elements, so disallow it for now. 15950 // 15951 // FIXME: GCC allows this. We should probably either implicitly delete 15952 // the destructor of the containing class, or just allow this. 15953 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15954 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15955 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15956 << FD->getDeclName() << FD->getType(); 15957 FD->setInvalidDecl(); 15958 EnclosingDecl->setInvalidDecl(); 15959 continue; 15960 } 15961 // Okay, we have a legal flexible array member at the end of the struct. 15962 Record->setHasFlexibleArrayMember(true); 15963 } else { 15964 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15965 // unless they are followed by another ivar. That check is done 15966 // elsewhere, after synthesized ivars are known. 15967 } 15968 } else if (!FDTy->isDependentType() && 15969 RequireCompleteType(FD->getLocation(), FD->getType(), 15970 diag::err_field_incomplete)) { 15971 // Incomplete type 15972 FD->setInvalidDecl(); 15973 EnclosingDecl->setInvalidDecl(); 15974 continue; 15975 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15976 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15977 // A type which contains a flexible array member is considered to be a 15978 // flexible array member. 15979 Record->setHasFlexibleArrayMember(true); 15980 if (!Record->isUnion()) { 15981 // If this is a struct/class and this is not the last element, reject 15982 // it. Note that GCC supports variable sized arrays in the middle of 15983 // structures. 15984 if (!IsLastField) 15985 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15986 << FD->getDeclName() << FD->getType(); 15987 else { 15988 // We support flexible arrays at the end of structs in 15989 // other structs as an extension. 15990 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15991 << FD->getDeclName(); 15992 } 15993 } 15994 } 15995 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15996 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15997 diag::err_abstract_type_in_decl, 15998 AbstractIvarType)) { 15999 // Ivars can not have abstract class types 16000 FD->setInvalidDecl(); 16001 } 16002 if (Record && FDTTy->getDecl()->hasObjectMember()) 16003 Record->setHasObjectMember(true); 16004 if (Record && FDTTy->getDecl()->hasVolatileMember()) 16005 Record->setHasVolatileMember(true); 16006 if (Record && Record->isUnion() && 16007 FD->getType().isNonTrivialPrimitiveCType(Context)) 16008 Diag(FD->getLocation(), 16009 diag::err_nontrivial_primitive_type_in_union); 16010 } else if (FDTy->isObjCObjectType()) { 16011 /// A field cannot be an Objective-c object 16012 Diag(FD->getLocation(), diag::err_statically_allocated_object) 16013 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 16014 QualType T = Context.getObjCObjectPointerType(FD->getType()); 16015 FD->setType(T); 16016 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 16017 Record && !ObjCFieldLifetimeErrReported && Record->isUnion() && 16018 !getLangOpts().CPlusPlus) { 16019 // It's an error in ARC or Weak if a field has lifetime. 16020 // We don't want to report this in a system header, though, 16021 // so we just make the field unavailable. 16022 // FIXME: that's really not sufficient; we need to make the type 16023 // itself invalid to, say, initialize or copy. 16024 QualType T = FD->getType(); 16025 if (T.hasNonTrivialObjCLifetime()) { 16026 SourceLocation loc = FD->getLocation(); 16027 if (getSourceManager().isInSystemHeader(loc)) { 16028 if (!FD->hasAttr<UnavailableAttr>()) { 16029 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16030 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 16031 } 16032 } else { 16033 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 16034 << T->isBlockPointerType() << Record->getTagKind(); 16035 } 16036 ObjCFieldLifetimeErrReported = true; 16037 } 16038 } else if (getLangOpts().ObjC && 16039 getLangOpts().getGC() != LangOptions::NonGC && 16040 Record && !Record->hasObjectMember()) { 16041 if (FD->getType()->isObjCObjectPointerType() || 16042 FD->getType().isObjCGCStrong()) 16043 Record->setHasObjectMember(true); 16044 else if (Context.getAsArrayType(FD->getType())) { 16045 QualType BaseType = Context.getBaseElementType(FD->getType()); 16046 if (BaseType->isRecordType() && 16047 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 16048 Record->setHasObjectMember(true); 16049 else if (BaseType->isObjCObjectPointerType() || 16050 BaseType.isObjCGCStrong()) 16051 Record->setHasObjectMember(true); 16052 } 16053 } 16054 16055 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 16056 QualType FT = FD->getType(); 16057 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 16058 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 16059 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 16060 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 16061 Record->setNonTrivialToPrimitiveCopy(true); 16062 if (FT.isDestructedType()) { 16063 Record->setNonTrivialToPrimitiveDestroy(true); 16064 Record->setParamDestroyedInCallee(true); 16065 } 16066 16067 if (const auto *RT = FT->getAs<RecordType>()) { 16068 if (RT->getDecl()->getArgPassingRestrictions() == 16069 RecordDecl::APK_CanNeverPassInRegs) 16070 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16071 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 16072 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16073 } 16074 16075 if (Record && FD->getType().isVolatileQualified()) 16076 Record->setHasVolatileMember(true); 16077 // Keep track of the number of named members. 16078 if (FD->getIdentifier()) 16079 ++NumNamedMembers; 16080 } 16081 16082 // Okay, we successfully defined 'Record'. 16083 if (Record) { 16084 bool Completed = false; 16085 if (CXXRecord) { 16086 if (!CXXRecord->isInvalidDecl()) { 16087 // Set access bits correctly on the directly-declared conversions. 16088 for (CXXRecordDecl::conversion_iterator 16089 I = CXXRecord->conversion_begin(), 16090 E = CXXRecord->conversion_end(); I != E; ++I) 16091 I.setAccess((*I)->getAccess()); 16092 } 16093 16094 if (!CXXRecord->isDependentType()) { 16095 // Add any implicitly-declared members to this class. 16096 AddImplicitlyDeclaredMembersToClass(CXXRecord); 16097 16098 if (!CXXRecord->isInvalidDecl()) { 16099 // If we have virtual base classes, we may end up finding multiple 16100 // final overriders for a given virtual function. Check for this 16101 // problem now. 16102 if (CXXRecord->getNumVBases()) { 16103 CXXFinalOverriderMap FinalOverriders; 16104 CXXRecord->getFinalOverriders(FinalOverriders); 16105 16106 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 16107 MEnd = FinalOverriders.end(); 16108 M != MEnd; ++M) { 16109 for (OverridingMethods::iterator SO = M->second.begin(), 16110 SOEnd = M->second.end(); 16111 SO != SOEnd; ++SO) { 16112 assert(SO->second.size() > 0 && 16113 "Virtual function without overriding functions?"); 16114 if (SO->second.size() == 1) 16115 continue; 16116 16117 // C++ [class.virtual]p2: 16118 // In a derived class, if a virtual member function of a base 16119 // class subobject has more than one final overrider the 16120 // program is ill-formed. 16121 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 16122 << (const NamedDecl *)M->first << Record; 16123 Diag(M->first->getLocation(), 16124 diag::note_overridden_virtual_function); 16125 for (OverridingMethods::overriding_iterator 16126 OM = SO->second.begin(), 16127 OMEnd = SO->second.end(); 16128 OM != OMEnd; ++OM) 16129 Diag(OM->Method->getLocation(), diag::note_final_overrider) 16130 << (const NamedDecl *)M->first << OM->Method->getParent(); 16131 16132 Record->setInvalidDecl(); 16133 } 16134 } 16135 CXXRecord->completeDefinition(&FinalOverriders); 16136 Completed = true; 16137 } 16138 } 16139 } 16140 } 16141 16142 if (!Completed) 16143 Record->completeDefinition(); 16144 16145 // Handle attributes before checking the layout. 16146 ProcessDeclAttributeList(S, Record, Attrs); 16147 16148 // We may have deferred checking for a deleted destructor. Check now. 16149 if (CXXRecord) { 16150 auto *Dtor = CXXRecord->getDestructor(); 16151 if (Dtor && Dtor->isImplicit() && 16152 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 16153 CXXRecord->setImplicitDestructorIsDeleted(); 16154 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 16155 } 16156 } 16157 16158 if (Record->hasAttrs()) { 16159 CheckAlignasUnderalignment(Record); 16160 16161 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 16162 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 16163 IA->getRange(), IA->getBestCase(), 16164 IA->getSemanticSpelling()); 16165 } 16166 16167 // Check if the structure/union declaration is a type that can have zero 16168 // size in C. For C this is a language extension, for C++ it may cause 16169 // compatibility problems. 16170 bool CheckForZeroSize; 16171 if (!getLangOpts().CPlusPlus) { 16172 CheckForZeroSize = true; 16173 } else { 16174 // For C++ filter out types that cannot be referenced in C code. 16175 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 16176 CheckForZeroSize = 16177 CXXRecord->getLexicalDeclContext()->isExternCContext() && 16178 !CXXRecord->isDependentType() && 16179 CXXRecord->isCLike(); 16180 } 16181 if (CheckForZeroSize) { 16182 bool ZeroSize = true; 16183 bool IsEmpty = true; 16184 unsigned NonBitFields = 0; 16185 for (RecordDecl::field_iterator I = Record->field_begin(), 16186 E = Record->field_end(); 16187 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 16188 IsEmpty = false; 16189 if (I->isUnnamedBitfield()) { 16190 if (!I->isZeroLengthBitField(Context)) 16191 ZeroSize = false; 16192 } else { 16193 ++NonBitFields; 16194 QualType FieldType = I->getType(); 16195 if (FieldType->isIncompleteType() || 16196 !Context.getTypeSizeInChars(FieldType).isZero()) 16197 ZeroSize = false; 16198 } 16199 } 16200 16201 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 16202 // allowed in C++, but warn if its declaration is inside 16203 // extern "C" block. 16204 if (ZeroSize) { 16205 Diag(RecLoc, getLangOpts().CPlusPlus ? 16206 diag::warn_zero_size_struct_union_in_extern_c : 16207 diag::warn_zero_size_struct_union_compat) 16208 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 16209 } 16210 16211 // Structs without named members are extension in C (C99 6.7.2.1p7), 16212 // but are accepted by GCC. 16213 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 16214 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 16215 diag::ext_no_named_members_in_struct_union) 16216 << Record->isUnion(); 16217 } 16218 } 16219 } else { 16220 ObjCIvarDecl **ClsFields = 16221 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 16222 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 16223 ID->setEndOfDefinitionLoc(RBrac); 16224 // Add ivar's to class's DeclContext. 16225 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16226 ClsFields[i]->setLexicalDeclContext(ID); 16227 ID->addDecl(ClsFields[i]); 16228 } 16229 // Must enforce the rule that ivars in the base classes may not be 16230 // duplicates. 16231 if (ID->getSuperClass()) 16232 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 16233 } else if (ObjCImplementationDecl *IMPDecl = 16234 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16235 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 16236 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 16237 // Ivar declared in @implementation never belongs to the implementation. 16238 // Only it is in implementation's lexical context. 16239 ClsFields[I]->setLexicalDeclContext(IMPDecl); 16240 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 16241 IMPDecl->setIvarLBraceLoc(LBrac); 16242 IMPDecl->setIvarRBraceLoc(RBrac); 16243 } else if (ObjCCategoryDecl *CDecl = 16244 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16245 // case of ivars in class extension; all other cases have been 16246 // reported as errors elsewhere. 16247 // FIXME. Class extension does not have a LocEnd field. 16248 // CDecl->setLocEnd(RBrac); 16249 // Add ivar's to class extension's DeclContext. 16250 // Diagnose redeclaration of private ivars. 16251 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 16252 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16253 if (IDecl) { 16254 if (const ObjCIvarDecl *ClsIvar = 16255 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 16256 Diag(ClsFields[i]->getLocation(), 16257 diag::err_duplicate_ivar_declaration); 16258 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 16259 continue; 16260 } 16261 for (const auto *Ext : IDecl->known_extensions()) { 16262 if (const ObjCIvarDecl *ClsExtIvar 16263 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 16264 Diag(ClsFields[i]->getLocation(), 16265 diag::err_duplicate_ivar_declaration); 16266 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 16267 continue; 16268 } 16269 } 16270 } 16271 ClsFields[i]->setLexicalDeclContext(CDecl); 16272 CDecl->addDecl(ClsFields[i]); 16273 } 16274 CDecl->setIvarLBraceLoc(LBrac); 16275 CDecl->setIvarRBraceLoc(RBrac); 16276 } 16277 } 16278 } 16279 16280 /// Determine whether the given integral value is representable within 16281 /// the given type T. 16282 static bool isRepresentableIntegerValue(ASTContext &Context, 16283 llvm::APSInt &Value, 16284 QualType T) { 16285 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 16286 "Integral type required!"); 16287 unsigned BitWidth = Context.getIntWidth(T); 16288 16289 if (Value.isUnsigned() || Value.isNonNegative()) { 16290 if (T->isSignedIntegerOrEnumerationType()) 16291 --BitWidth; 16292 return Value.getActiveBits() <= BitWidth; 16293 } 16294 return Value.getMinSignedBits() <= BitWidth; 16295 } 16296 16297 // Given an integral type, return the next larger integral type 16298 // (or a NULL type of no such type exists). 16299 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 16300 // FIXME: Int128/UInt128 support, which also needs to be introduced into 16301 // enum checking below. 16302 assert((T->isIntegralType(Context) || 16303 T->isEnumeralType()) && "Integral type required!"); 16304 const unsigned NumTypes = 4; 16305 QualType SignedIntegralTypes[NumTypes] = { 16306 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 16307 }; 16308 QualType UnsignedIntegralTypes[NumTypes] = { 16309 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 16310 Context.UnsignedLongLongTy 16311 }; 16312 16313 unsigned BitWidth = Context.getTypeSize(T); 16314 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 16315 : UnsignedIntegralTypes; 16316 for (unsigned I = 0; I != NumTypes; ++I) 16317 if (Context.getTypeSize(Types[I]) > BitWidth) 16318 return Types[I]; 16319 16320 return QualType(); 16321 } 16322 16323 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 16324 EnumConstantDecl *LastEnumConst, 16325 SourceLocation IdLoc, 16326 IdentifierInfo *Id, 16327 Expr *Val) { 16328 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16329 llvm::APSInt EnumVal(IntWidth); 16330 QualType EltTy; 16331 16332 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 16333 Val = nullptr; 16334 16335 if (Val) 16336 Val = DefaultLvalueConversion(Val).get(); 16337 16338 if (Val) { 16339 if (Enum->isDependentType() || Val->isTypeDependent()) 16340 EltTy = Context.DependentTy; 16341 else { 16342 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 16343 !getLangOpts().MSVCCompat) { 16344 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 16345 // constant-expression in the enumerator-definition shall be a converted 16346 // constant expression of the underlying type. 16347 EltTy = Enum->getIntegerType(); 16348 ExprResult Converted = 16349 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 16350 CCEK_Enumerator); 16351 if (Converted.isInvalid()) 16352 Val = nullptr; 16353 else 16354 Val = Converted.get(); 16355 } else if (!Val->isValueDependent() && 16356 !(Val = VerifyIntegerConstantExpression(Val, 16357 &EnumVal).get())) { 16358 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 16359 } else { 16360 if (Enum->isComplete()) { 16361 EltTy = Enum->getIntegerType(); 16362 16363 // In Obj-C and Microsoft mode, require the enumeration value to be 16364 // representable in the underlying type of the enumeration. In C++11, 16365 // we perform a non-narrowing conversion as part of converted constant 16366 // expression checking. 16367 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16368 if (getLangOpts().MSVCCompat) { 16369 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 16370 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 16371 } else 16372 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 16373 } else 16374 Val = ImpCastExprToType(Val, EltTy, 16375 EltTy->isBooleanType() ? 16376 CK_IntegralToBoolean : CK_IntegralCast) 16377 .get(); 16378 } else if (getLangOpts().CPlusPlus) { 16379 // C++11 [dcl.enum]p5: 16380 // If the underlying type is not fixed, the type of each enumerator 16381 // is the type of its initializing value: 16382 // - If an initializer is specified for an enumerator, the 16383 // initializing value has the same type as the expression. 16384 EltTy = Val->getType(); 16385 } else { 16386 // C99 6.7.2.2p2: 16387 // The expression that defines the value of an enumeration constant 16388 // shall be an integer constant expression that has a value 16389 // representable as an int. 16390 16391 // Complain if the value is not representable in an int. 16392 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 16393 Diag(IdLoc, diag::ext_enum_value_not_int) 16394 << EnumVal.toString(10) << Val->getSourceRange() 16395 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 16396 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 16397 // Force the type of the expression to 'int'. 16398 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 16399 } 16400 EltTy = Val->getType(); 16401 } 16402 } 16403 } 16404 } 16405 16406 if (!Val) { 16407 if (Enum->isDependentType()) 16408 EltTy = Context.DependentTy; 16409 else if (!LastEnumConst) { 16410 // C++0x [dcl.enum]p5: 16411 // If the underlying type is not fixed, the type of each enumerator 16412 // is the type of its initializing value: 16413 // - If no initializer is specified for the first enumerator, the 16414 // initializing value has an unspecified integral type. 16415 // 16416 // GCC uses 'int' for its unspecified integral type, as does 16417 // C99 6.7.2.2p3. 16418 if (Enum->isFixed()) { 16419 EltTy = Enum->getIntegerType(); 16420 } 16421 else { 16422 EltTy = Context.IntTy; 16423 } 16424 } else { 16425 // Assign the last value + 1. 16426 EnumVal = LastEnumConst->getInitVal(); 16427 ++EnumVal; 16428 EltTy = LastEnumConst->getType(); 16429 16430 // Check for overflow on increment. 16431 if (EnumVal < LastEnumConst->getInitVal()) { 16432 // C++0x [dcl.enum]p5: 16433 // If the underlying type is not fixed, the type of each enumerator 16434 // is the type of its initializing value: 16435 // 16436 // - Otherwise the type of the initializing value is the same as 16437 // the type of the initializing value of the preceding enumerator 16438 // unless the incremented value is not representable in that type, 16439 // in which case the type is an unspecified integral type 16440 // sufficient to contain the incremented value. If no such type 16441 // exists, the program is ill-formed. 16442 QualType T = getNextLargerIntegralType(Context, EltTy); 16443 if (T.isNull() || Enum->isFixed()) { 16444 // There is no integral type larger enough to represent this 16445 // value. Complain, then allow the value to wrap around. 16446 EnumVal = LastEnumConst->getInitVal(); 16447 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 16448 ++EnumVal; 16449 if (Enum->isFixed()) 16450 // When the underlying type is fixed, this is ill-formed. 16451 Diag(IdLoc, diag::err_enumerator_wrapped) 16452 << EnumVal.toString(10) 16453 << EltTy; 16454 else 16455 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 16456 << EnumVal.toString(10); 16457 } else { 16458 EltTy = T; 16459 } 16460 16461 // Retrieve the last enumerator's value, extent that type to the 16462 // type that is supposed to be large enough to represent the incremented 16463 // value, then increment. 16464 EnumVal = LastEnumConst->getInitVal(); 16465 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16466 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 16467 ++EnumVal; 16468 16469 // If we're not in C++, diagnose the overflow of enumerator values, 16470 // which in C99 means that the enumerator value is not representable in 16471 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 16472 // permits enumerator values that are representable in some larger 16473 // integral type. 16474 if (!getLangOpts().CPlusPlus && !T.isNull()) 16475 Diag(IdLoc, diag::warn_enum_value_overflow); 16476 } else if (!getLangOpts().CPlusPlus && 16477 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16478 // Enforce C99 6.7.2.2p2 even when we compute the next value. 16479 Diag(IdLoc, diag::ext_enum_value_not_int) 16480 << EnumVal.toString(10) << 1; 16481 } 16482 } 16483 } 16484 16485 if (!EltTy->isDependentType()) { 16486 // Make the enumerator value match the signedness and size of the 16487 // enumerator's type. 16488 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 16489 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16490 } 16491 16492 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 16493 Val, EnumVal); 16494 } 16495 16496 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 16497 SourceLocation IILoc) { 16498 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 16499 !getLangOpts().CPlusPlus) 16500 return SkipBodyInfo(); 16501 16502 // We have an anonymous enum definition. Look up the first enumerator to 16503 // determine if we should merge the definition with an existing one and 16504 // skip the body. 16505 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 16506 forRedeclarationInCurContext()); 16507 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 16508 if (!PrevECD) 16509 return SkipBodyInfo(); 16510 16511 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 16512 NamedDecl *Hidden; 16513 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 16514 SkipBodyInfo Skip; 16515 Skip.Previous = Hidden; 16516 return Skip; 16517 } 16518 16519 return SkipBodyInfo(); 16520 } 16521 16522 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 16523 SourceLocation IdLoc, IdentifierInfo *Id, 16524 const ParsedAttributesView &Attrs, 16525 SourceLocation EqualLoc, Expr *Val) { 16526 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 16527 EnumConstantDecl *LastEnumConst = 16528 cast_or_null<EnumConstantDecl>(lastEnumConst); 16529 16530 // The scope passed in may not be a decl scope. Zip up the scope tree until 16531 // we find one that is. 16532 S = getNonFieldDeclScope(S); 16533 16534 // Verify that there isn't already something declared with this name in this 16535 // scope. 16536 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 16537 LookupName(R, S); 16538 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 16539 16540 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16541 // Maybe we will complain about the shadowed template parameter. 16542 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 16543 // Just pretend that we didn't see the previous declaration. 16544 PrevDecl = nullptr; 16545 } 16546 16547 // C++ [class.mem]p15: 16548 // If T is the name of a class, then each of the following shall have a name 16549 // different from T: 16550 // - every enumerator of every member of class T that is an unscoped 16551 // enumerated type 16552 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 16553 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 16554 DeclarationNameInfo(Id, IdLoc)); 16555 16556 EnumConstantDecl *New = 16557 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 16558 if (!New) 16559 return nullptr; 16560 16561 if (PrevDecl) { 16562 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 16563 // Check for other kinds of shadowing not already handled. 16564 CheckShadow(New, PrevDecl, R); 16565 } 16566 16567 // When in C++, we may get a TagDecl with the same name; in this case the 16568 // enum constant will 'hide' the tag. 16569 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 16570 "Received TagDecl when not in C++!"); 16571 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 16572 if (isa<EnumConstantDecl>(PrevDecl)) 16573 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 16574 else 16575 Diag(IdLoc, diag::err_redefinition) << Id; 16576 notePreviousDefinition(PrevDecl, IdLoc); 16577 return nullptr; 16578 } 16579 } 16580 16581 // Process attributes. 16582 ProcessDeclAttributeList(S, New, Attrs); 16583 AddPragmaAttributes(S, New); 16584 16585 // Register this decl in the current scope stack. 16586 New->setAccess(TheEnumDecl->getAccess()); 16587 PushOnScopeChains(New, S); 16588 16589 ActOnDocumentableDecl(New); 16590 16591 return New; 16592 } 16593 16594 // Returns true when the enum initial expression does not trigger the 16595 // duplicate enum warning. A few common cases are exempted as follows: 16596 // Element2 = Element1 16597 // Element2 = Element1 + 1 16598 // Element2 = Element1 - 1 16599 // Where Element2 and Element1 are from the same enum. 16600 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16601 Expr *InitExpr = ECD->getInitExpr(); 16602 if (!InitExpr) 16603 return true; 16604 InitExpr = InitExpr->IgnoreImpCasts(); 16605 16606 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16607 if (!BO->isAdditiveOp()) 16608 return true; 16609 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16610 if (!IL) 16611 return true; 16612 if (IL->getValue() != 1) 16613 return true; 16614 16615 InitExpr = BO->getLHS(); 16616 } 16617 16618 // This checks if the elements are from the same enum. 16619 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16620 if (!DRE) 16621 return true; 16622 16623 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16624 if (!EnumConstant) 16625 return true; 16626 16627 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16628 Enum) 16629 return true; 16630 16631 return false; 16632 } 16633 16634 // Emits a warning when an element is implicitly set a value that 16635 // a previous element has already been set to. 16636 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16637 EnumDecl *Enum, QualType EnumType) { 16638 // Avoid anonymous enums 16639 if (!Enum->getIdentifier()) 16640 return; 16641 16642 // Only check for small enums. 16643 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16644 return; 16645 16646 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16647 return; 16648 16649 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16650 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16651 16652 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16653 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 16654 16655 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16656 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16657 llvm::APSInt Val = D->getInitVal(); 16658 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16659 }; 16660 16661 DuplicatesVector DupVector; 16662 ValueToVectorMap EnumMap; 16663 16664 // Populate the EnumMap with all values represented by enum constants without 16665 // an initializer. 16666 for (auto *Element : Elements) { 16667 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16668 16669 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16670 // this constant. Skip this enum since it may be ill-formed. 16671 if (!ECD) { 16672 return; 16673 } 16674 16675 // Constants with initalizers are handled in the next loop. 16676 if (ECD->getInitExpr()) 16677 continue; 16678 16679 // Duplicate values are handled in the next loop. 16680 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16681 } 16682 16683 if (EnumMap.size() == 0) 16684 return; 16685 16686 // Create vectors for any values that has duplicates. 16687 for (auto *Element : Elements) { 16688 // The last loop returned if any constant was null. 16689 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16690 if (!ValidDuplicateEnum(ECD, Enum)) 16691 continue; 16692 16693 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16694 if (Iter == EnumMap.end()) 16695 continue; 16696 16697 DeclOrVector& Entry = Iter->second; 16698 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16699 // Ensure constants are different. 16700 if (D == ECD) 16701 continue; 16702 16703 // Create new vector and push values onto it. 16704 auto Vec = llvm::make_unique<ECDVector>(); 16705 Vec->push_back(D); 16706 Vec->push_back(ECD); 16707 16708 // Update entry to point to the duplicates vector. 16709 Entry = Vec.get(); 16710 16711 // Store the vector somewhere we can consult later for quick emission of 16712 // diagnostics. 16713 DupVector.emplace_back(std::move(Vec)); 16714 continue; 16715 } 16716 16717 ECDVector *Vec = Entry.get<ECDVector*>(); 16718 // Make sure constants are not added more than once. 16719 if (*Vec->begin() == ECD) 16720 continue; 16721 16722 Vec->push_back(ECD); 16723 } 16724 16725 // Emit diagnostics. 16726 for (const auto &Vec : DupVector) { 16727 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16728 16729 // Emit warning for one enum constant. 16730 auto *FirstECD = Vec->front(); 16731 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16732 << FirstECD << FirstECD->getInitVal().toString(10) 16733 << FirstECD->getSourceRange(); 16734 16735 // Emit one note for each of the remaining enum constants with 16736 // the same value. 16737 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16738 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16739 << ECD << ECD->getInitVal().toString(10) 16740 << ECD->getSourceRange(); 16741 } 16742 } 16743 16744 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16745 bool AllowMask) const { 16746 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16747 assert(ED->isCompleteDefinition() && "expected enum definition"); 16748 16749 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16750 llvm::APInt &FlagBits = R.first->second; 16751 16752 if (R.second) { 16753 for (auto *E : ED->enumerators()) { 16754 const auto &EVal = E->getInitVal(); 16755 // Only single-bit enumerators introduce new flag values. 16756 if (EVal.isPowerOf2()) 16757 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16758 } 16759 } 16760 16761 // A value is in a flag enum if either its bits are a subset of the enum's 16762 // flag bits (the first condition) or we are allowing masks and the same is 16763 // true of its complement (the second condition). When masks are allowed, we 16764 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16765 // 16766 // While it's true that any value could be used as a mask, the assumption is 16767 // that a mask will have all of the insignificant bits set. Anything else is 16768 // likely a logic error. 16769 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16770 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16771 } 16772 16773 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16774 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 16775 const ParsedAttributesView &Attrs) { 16776 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16777 QualType EnumType = Context.getTypeDeclType(Enum); 16778 16779 ProcessDeclAttributeList(S, Enum, Attrs); 16780 16781 if (Enum->isDependentType()) { 16782 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16783 EnumConstantDecl *ECD = 16784 cast_or_null<EnumConstantDecl>(Elements[i]); 16785 if (!ECD) continue; 16786 16787 ECD->setType(EnumType); 16788 } 16789 16790 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16791 return; 16792 } 16793 16794 // TODO: If the result value doesn't fit in an int, it must be a long or long 16795 // long value. ISO C does not support this, but GCC does as an extension, 16796 // emit a warning. 16797 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16798 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16799 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16800 16801 // Verify that all the values are okay, compute the size of the values, and 16802 // reverse the list. 16803 unsigned NumNegativeBits = 0; 16804 unsigned NumPositiveBits = 0; 16805 16806 // Keep track of whether all elements have type int. 16807 bool AllElementsInt = true; 16808 16809 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16810 EnumConstantDecl *ECD = 16811 cast_or_null<EnumConstantDecl>(Elements[i]); 16812 if (!ECD) continue; // Already issued a diagnostic. 16813 16814 const llvm::APSInt &InitVal = ECD->getInitVal(); 16815 16816 // Keep track of the size of positive and negative values. 16817 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16818 NumPositiveBits = std::max(NumPositiveBits, 16819 (unsigned)InitVal.getActiveBits()); 16820 else 16821 NumNegativeBits = std::max(NumNegativeBits, 16822 (unsigned)InitVal.getMinSignedBits()); 16823 16824 // Keep track of whether every enum element has type int (very common). 16825 if (AllElementsInt) 16826 AllElementsInt = ECD->getType() == Context.IntTy; 16827 } 16828 16829 // Figure out the type that should be used for this enum. 16830 QualType BestType; 16831 unsigned BestWidth; 16832 16833 // C++0x N3000 [conv.prom]p3: 16834 // An rvalue of an unscoped enumeration type whose underlying 16835 // type is not fixed can be converted to an rvalue of the first 16836 // of the following types that can represent all the values of 16837 // the enumeration: int, unsigned int, long int, unsigned long 16838 // int, long long int, or unsigned long long int. 16839 // C99 6.4.4.3p2: 16840 // An identifier declared as an enumeration constant has type int. 16841 // The C99 rule is modified by a gcc extension 16842 QualType BestPromotionType; 16843 16844 bool Packed = Enum->hasAttr<PackedAttr>(); 16845 // -fshort-enums is the equivalent to specifying the packed attribute on all 16846 // enum definitions. 16847 if (LangOpts.ShortEnums) 16848 Packed = true; 16849 16850 // If the enum already has a type because it is fixed or dictated by the 16851 // target, promote that type instead of analyzing the enumerators. 16852 if (Enum->isComplete()) { 16853 BestType = Enum->getIntegerType(); 16854 if (BestType->isPromotableIntegerType()) 16855 BestPromotionType = Context.getPromotedIntegerType(BestType); 16856 else 16857 BestPromotionType = BestType; 16858 16859 BestWidth = Context.getIntWidth(BestType); 16860 } 16861 else if (NumNegativeBits) { 16862 // If there is a negative value, figure out the smallest integer type (of 16863 // int/long/longlong) that fits. 16864 // If it's packed, check also if it fits a char or a short. 16865 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16866 BestType = Context.SignedCharTy; 16867 BestWidth = CharWidth; 16868 } else if (Packed && NumNegativeBits <= ShortWidth && 16869 NumPositiveBits < ShortWidth) { 16870 BestType = Context.ShortTy; 16871 BestWidth = ShortWidth; 16872 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16873 BestType = Context.IntTy; 16874 BestWidth = IntWidth; 16875 } else { 16876 BestWidth = Context.getTargetInfo().getLongWidth(); 16877 16878 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16879 BestType = Context.LongTy; 16880 } else { 16881 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16882 16883 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16884 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16885 BestType = Context.LongLongTy; 16886 } 16887 } 16888 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16889 } else { 16890 // If there is no negative value, figure out the smallest type that fits 16891 // all of the enumerator values. 16892 // If it's packed, check also if it fits a char or a short. 16893 if (Packed && NumPositiveBits <= CharWidth) { 16894 BestType = Context.UnsignedCharTy; 16895 BestPromotionType = Context.IntTy; 16896 BestWidth = CharWidth; 16897 } else if (Packed && NumPositiveBits <= ShortWidth) { 16898 BestType = Context.UnsignedShortTy; 16899 BestPromotionType = Context.IntTy; 16900 BestWidth = ShortWidth; 16901 } else if (NumPositiveBits <= IntWidth) { 16902 BestType = Context.UnsignedIntTy; 16903 BestWidth = IntWidth; 16904 BestPromotionType 16905 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16906 ? Context.UnsignedIntTy : Context.IntTy; 16907 } else if (NumPositiveBits <= 16908 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16909 BestType = Context.UnsignedLongTy; 16910 BestPromotionType 16911 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16912 ? Context.UnsignedLongTy : Context.LongTy; 16913 } else { 16914 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16915 assert(NumPositiveBits <= BestWidth && 16916 "How could an initializer get larger than ULL?"); 16917 BestType = Context.UnsignedLongLongTy; 16918 BestPromotionType 16919 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16920 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16921 } 16922 } 16923 16924 // Loop over all of the enumerator constants, changing their types to match 16925 // the type of the enum if needed. 16926 for (auto *D : Elements) { 16927 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16928 if (!ECD) continue; // Already issued a diagnostic. 16929 16930 // Standard C says the enumerators have int type, but we allow, as an 16931 // extension, the enumerators to be larger than int size. If each 16932 // enumerator value fits in an int, type it as an int, otherwise type it the 16933 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16934 // that X has type 'int', not 'unsigned'. 16935 16936 // Determine whether the value fits into an int. 16937 llvm::APSInt InitVal = ECD->getInitVal(); 16938 16939 // If it fits into an integer type, force it. Otherwise force it to match 16940 // the enum decl type. 16941 QualType NewTy; 16942 unsigned NewWidth; 16943 bool NewSign; 16944 if (!getLangOpts().CPlusPlus && 16945 !Enum->isFixed() && 16946 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16947 NewTy = Context.IntTy; 16948 NewWidth = IntWidth; 16949 NewSign = true; 16950 } else if (ECD->getType() == BestType) { 16951 // Already the right type! 16952 if (getLangOpts().CPlusPlus) 16953 // C++ [dcl.enum]p4: Following the closing brace of an 16954 // enum-specifier, each enumerator has the type of its 16955 // enumeration. 16956 ECD->setType(EnumType); 16957 continue; 16958 } else { 16959 NewTy = BestType; 16960 NewWidth = BestWidth; 16961 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16962 } 16963 16964 // Adjust the APSInt value. 16965 InitVal = InitVal.extOrTrunc(NewWidth); 16966 InitVal.setIsSigned(NewSign); 16967 ECD->setInitVal(InitVal); 16968 16969 // Adjust the Expr initializer and type. 16970 if (ECD->getInitExpr() && 16971 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16972 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16973 CK_IntegralCast, 16974 ECD->getInitExpr(), 16975 /*base paths*/ nullptr, 16976 VK_RValue)); 16977 if (getLangOpts().CPlusPlus) 16978 // C++ [dcl.enum]p4: Following the closing brace of an 16979 // enum-specifier, each enumerator has the type of its 16980 // enumeration. 16981 ECD->setType(EnumType); 16982 else 16983 ECD->setType(NewTy); 16984 } 16985 16986 Enum->completeDefinition(BestType, BestPromotionType, 16987 NumPositiveBits, NumNegativeBits); 16988 16989 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16990 16991 if (Enum->isClosedFlag()) { 16992 for (Decl *D : Elements) { 16993 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16994 if (!ECD) continue; // Already issued a diagnostic. 16995 16996 llvm::APSInt InitVal = ECD->getInitVal(); 16997 if (InitVal != 0 && !InitVal.isPowerOf2() && 16998 !IsValueInFlagEnum(Enum, InitVal, true)) 16999 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 17000 << ECD << Enum; 17001 } 17002 } 17003 17004 // Now that the enum type is defined, ensure it's not been underaligned. 17005 if (Enum->hasAttrs()) 17006 CheckAlignasUnderalignment(Enum); 17007 } 17008 17009 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 17010 SourceLocation StartLoc, 17011 SourceLocation EndLoc) { 17012 StringLiteral *AsmString = cast<StringLiteral>(expr); 17013 17014 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 17015 AsmString, StartLoc, 17016 EndLoc); 17017 CurContext->addDecl(New); 17018 return New; 17019 } 17020 17021 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17022 IdentifierInfo* AliasName, 17023 SourceLocation PragmaLoc, 17024 SourceLocation NameLoc, 17025 SourceLocation AliasNameLoc) { 17026 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17027 LookupOrdinaryName); 17028 AsmLabelAttr *Attr = 17029 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 17030 17031 // If a declaration that: 17032 // 1) declares a function or a variable 17033 // 2) has external linkage 17034 // already exists, add a label attribute to it. 17035 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17036 if (isDeclExternC(PrevDecl)) 17037 PrevDecl->addAttr(Attr); 17038 else 17039 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17040 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17041 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17042 } else 17043 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17044 } 17045 17046 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17047 SourceLocation PragmaLoc, 17048 SourceLocation NameLoc) { 17049 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17050 17051 if (PrevDecl) { 17052 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 17053 } else { 17054 (void)WeakUndeclaredIdentifiers.insert( 17055 std::pair<IdentifierInfo*,WeakInfo> 17056 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17057 } 17058 } 17059 17060 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17061 IdentifierInfo* AliasName, 17062 SourceLocation PragmaLoc, 17063 SourceLocation NameLoc, 17064 SourceLocation AliasNameLoc) { 17065 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17066 LookupOrdinaryName); 17067 WeakInfo W = WeakInfo(Name, NameLoc); 17068 17069 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17070 if (!PrevDecl->hasAttr<AliasAttr>()) 17071 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17072 DeclApplyPragmaWeak(TUScope, ND, W); 17073 } else { 17074 (void)WeakUndeclaredIdentifiers.insert( 17075 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 17076 } 17077 } 17078 17079 Decl *Sema::getObjCDeclContext() const { 17080 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 17081 } 17082