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/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw_wchar_t: 145 case tok::kw_bool: 146 case tok::kw___underlying_type: 147 case tok::kw___auto_type: 148 return true; 149 150 case tok::annot_typename: 151 case tok::kw_char16_t: 152 case tok::kw_char32_t: 153 case tok::kw_typeof: 154 case tok::annot_decltype: 155 case tok::kw_decltype: 156 return getLangOpts().CPlusPlus; 157 158 case tok::kw_char8_t: 159 return getLangOpts().Char8; 160 161 default: 162 break; 163 } 164 165 return false; 166 } 167 168 namespace { 169 enum class UnqualifiedTypeNameLookupResult { 170 NotFound, 171 FoundNonType, 172 FoundType 173 }; 174 } // end anonymous namespace 175 176 /// Tries to perform unqualified lookup of the type decls in bases for 177 /// dependent class. 178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 179 /// type decl, \a FoundType if only type decls are found. 180 static UnqualifiedTypeNameLookupResult 181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 182 SourceLocation NameLoc, 183 const CXXRecordDecl *RD) { 184 if (!RD->hasDefinition()) 185 return UnqualifiedTypeNameLookupResult::NotFound; 186 // Look for type decls in base classes. 187 UnqualifiedTypeNameLookupResult FoundTypeDecl = 188 UnqualifiedTypeNameLookupResult::NotFound; 189 for (const auto &Base : RD->bases()) { 190 const CXXRecordDecl *BaseRD = nullptr; 191 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 192 BaseRD = BaseTT->getAsCXXRecordDecl(); 193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 194 // Look for type decls in dependent base classes that have known primary 195 // templates. 196 if (!TST || !TST->isDependentType()) 197 continue; 198 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 199 if (!TD) 200 continue; 201 if (auto *BasePrimaryTemplate = 202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 204 BaseRD = BasePrimaryTemplate; 205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 206 if (const ClassTemplatePartialSpecializationDecl *PS = 207 CTD->findPartialSpecialization(Base.getType())) 208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 209 BaseRD = PS; 210 } 211 } 212 } 213 if (BaseRD) { 214 for (NamedDecl *ND : BaseRD->lookup(&II)) { 215 if (!isa<TypeDecl>(ND)) 216 return UnqualifiedTypeNameLookupResult::FoundNonType; 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 } 219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 221 case UnqualifiedTypeNameLookupResult::FoundNonType: 222 return UnqualifiedTypeNameLookupResult::FoundNonType; 223 case UnqualifiedTypeNameLookupResult::FoundType: 224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 225 break; 226 case UnqualifiedTypeNameLookupResult::NotFound: 227 break; 228 } 229 } 230 } 231 } 232 233 return FoundTypeDecl; 234 } 235 236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 237 const IdentifierInfo &II, 238 SourceLocation NameLoc) { 239 // Lookup in the parent class template context, if any. 240 const CXXRecordDecl *RD = nullptr; 241 UnqualifiedTypeNameLookupResult FoundTypeDecl = 242 UnqualifiedTypeNameLookupResult::NotFound; 243 for (DeclContext *DC = S.CurContext; 244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 245 DC = DC->getParent()) { 246 // Look for type decls in dependent base classes that have known primary 247 // templates. 248 RD = dyn_cast<CXXRecordDecl>(DC); 249 if (RD && RD->getDescribedClassTemplate()) 250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 251 } 252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 253 return nullptr; 254 255 // We found some types in dependent base classes. Recover as if the user 256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 257 // lookup during template instantiation. 258 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 259 260 ASTContext &Context = S.Context; 261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 262 cast<Type>(Context.getRecordType(RD))); 263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 264 265 CXXScopeSpec SS; 266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 267 268 TypeLocBuilder Builder; 269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 270 DepTL.setNameLoc(NameLoc); 271 DepTL.setElaboratedKeywordLoc(SourceLocation()); 272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 274 } 275 276 /// If the identifier refers to a type name within this scope, 277 /// return the declaration of that type. 278 /// 279 /// This routine performs ordinary name lookup of the identifier II 280 /// within the given scope, with optional C++ scope specifier SS, to 281 /// determine whether the name refers to a type. If so, returns an 282 /// opaque pointer (actually a QualType) corresponding to that 283 /// type. Otherwise, returns NULL. 284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 285 Scope *S, CXXScopeSpec *SS, 286 bool isClassName, bool HasTrailingDot, 287 ParsedType ObjectTypePtr, 288 bool IsCtorOrDtorName, 289 bool WantNontrivialTypeSourceInfo, 290 bool IsClassTemplateDeductionContext, 291 IdentifierInfo **CorrectedII) { 292 // FIXME: Consider allowing this outside C++1z mode as an extension. 293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 295 !isClassName && !HasTrailingDot; 296 297 // Determine where we will perform name lookup. 298 DeclContext *LookupCtx = nullptr; 299 if (ObjectTypePtr) { 300 QualType ObjectType = ObjectTypePtr.get(); 301 if (ObjectType->isRecordType()) 302 LookupCtx = computeDeclContext(ObjectType); 303 } else if (SS && SS->isNotEmpty()) { 304 LookupCtx = computeDeclContext(*SS, false); 305 306 if (!LookupCtx) { 307 if (isDependentScopeSpecifier(*SS)) { 308 // C++ [temp.res]p3: 309 // A qualified-id that refers to a type and in which the 310 // nested-name-specifier depends on a template-parameter (14.6.2) 311 // shall be prefixed by the keyword typename to indicate that the 312 // qualified-id denotes a type, forming an 313 // elaborated-type-specifier (7.1.5.3). 314 // 315 // We therefore do not perform any name lookup if the result would 316 // refer to a member of an unknown specialization. 317 if (!isClassName && !IsCtorOrDtorName) 318 return nullptr; 319 320 // We know from the grammar that this name refers to a type, 321 // so build a dependent node to describe the type. 322 if (WantNontrivialTypeSourceInfo) 323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 324 325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 327 II, NameLoc); 328 return ParsedType::make(T); 329 } 330 331 return nullptr; 332 } 333 334 if (!LookupCtx->isDependentContext() && 335 RequireCompleteDeclContext(*SS, LookupCtx)) 336 return nullptr; 337 } 338 339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 340 // lookup for class-names. 341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 342 LookupOrdinaryName; 343 LookupResult Result(*this, &II, NameLoc, Kind); 344 if (LookupCtx) { 345 // Perform "qualified" name lookup into the declaration context we 346 // computed, which is either the type of the base of a member access 347 // expression or the declaration context associated with a prior 348 // nested-name-specifier. 349 LookupQualifiedName(Result, LookupCtx); 350 351 if (ObjectTypePtr && Result.empty()) { 352 // C++ [basic.lookup.classref]p3: 353 // If the unqualified-id is ~type-name, the type-name is looked up 354 // in the context of the entire postfix-expression. If the type T of 355 // the object expression is of a class type C, the type-name is also 356 // looked up in the scope of class C. At least one of the lookups shall 357 // find a name that refers to (possibly cv-qualified) T. 358 LookupName(Result, S); 359 } 360 } else { 361 // Perform unqualified name lookup. 362 LookupName(Result, S); 363 364 // For unqualified lookup in a class template in MSVC mode, look into 365 // dependent base classes where the primary class template is known. 366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 367 if (ParsedType TypeInBase = 368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 369 return TypeInBase; 370 } 371 } 372 373 NamedDecl *IIDecl = nullptr; 374 switch (Result.getResultKind()) { 375 case LookupResult::NotFound: 376 case LookupResult::NotFoundInCurrentInstantiation: 377 if (CorrectedII) { 378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 379 AllowDeducedTemplate); 380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 381 S, SS, CCC, CTK_ErrorRecovery); 382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 383 TemplateTy Template; 384 bool MemberOfUnknownSpecialization; 385 UnqualifiedId TemplateName; 386 TemplateName.setIdentifier(NewII, NameLoc); 387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 388 CXXScopeSpec NewSS, *NewSSPtr = SS; 389 if (SS && NNS) { 390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 391 NewSSPtr = &NewSS; 392 } 393 if (Correction && (NNS || NewII != &II) && 394 // Ignore a correction to a template type as the to-be-corrected 395 // identifier is not a template (typo correction for template names 396 // is handled elsewhere). 397 !(getLangOpts().CPlusPlus && NewSSPtr && 398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 399 Template, MemberOfUnknownSpecialization))) { 400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 401 isClassName, HasTrailingDot, ObjectTypePtr, 402 IsCtorOrDtorName, 403 WantNontrivialTypeSourceInfo, 404 IsClassTemplateDeductionContext); 405 if (Ty) { 406 diagnoseTypo(Correction, 407 PDiag(diag::err_unknown_type_or_class_name_suggest) 408 << Result.getLookupName() << isClassName); 409 if (SS && NNS) 410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 411 *CorrectedII = NewII; 412 return Ty; 413 } 414 } 415 } 416 // If typo correction failed or was not performed, fall through 417 LLVM_FALLTHROUGH; 418 case LookupResult::FoundOverloaded: 419 case LookupResult::FoundUnresolvedValue: 420 Result.suppressDiagnostics(); 421 return nullptr; 422 423 case LookupResult::Ambiguous: 424 // Recover from type-hiding ambiguities by hiding the type. We'll 425 // do the lookup again when looking for an object, and we can 426 // diagnose the error then. If we don't do this, then the error 427 // about hiding the type will be immediately followed by an error 428 // that only makes sense if the identifier was treated like a type. 429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 430 Result.suppressDiagnostics(); 431 return nullptr; 432 } 433 434 // Look to see if we have a type anywhere in the list of results. 435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 436 Res != ResEnd; ++Res) { 437 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 439 if (!IIDecl || 440 (*Res)->getLocation().getRawEncoding() < 441 IIDecl->getLocation().getRawEncoding()) 442 IIDecl = *Res; 443 } 444 } 445 446 if (!IIDecl) { 447 // None of the entities we found is a type, so there is no way 448 // to even assume that the result is a type. In this case, don't 449 // complain about the ambiguity. The parser will either try to 450 // perform this lookup again (e.g., as an object name), which 451 // will produce the ambiguity, or will complain that it expected 452 // a type name. 453 Result.suppressDiagnostics(); 454 return nullptr; 455 } 456 457 // We found a type within the ambiguous lookup; diagnose the 458 // ambiguity and then return that type. This might be the right 459 // answer, or it might not be, but it suppresses any attempt to 460 // perform the name lookup again. 461 break; 462 463 case LookupResult::Found: 464 IIDecl = Result.getFoundDecl(); 465 break; 466 } 467 468 assert(IIDecl && "Didn't find decl"); 469 470 QualType T; 471 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 472 // C++ [class.qual]p2: A lookup that would find the injected-class-name 473 // instead names the constructors of the class, except when naming a class. 474 // This is ill-formed when we're not actually forming a ctor or dtor name. 475 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 476 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 477 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 478 FoundRD->isInjectedClassName() && 479 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 480 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 481 << &II << /*Type*/1; 482 483 DiagnoseUseOfDecl(IIDecl, NameLoc); 484 485 T = Context.getTypeDeclType(TD); 486 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 487 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 488 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 489 if (!HasTrailingDot) 490 T = Context.getObjCInterfaceType(IDecl); 491 } else if (AllowDeducedTemplate) { 492 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 493 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 494 QualType(), false); 495 } 496 497 if (T.isNull()) { 498 // If it's not plausibly a type, suppress diagnostics. 499 Result.suppressDiagnostics(); 500 return nullptr; 501 } 502 503 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 504 // constructor or destructor name (in such a case, the scope specifier 505 // will be attached to the enclosing Expr or Decl node). 506 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 507 !isa<ObjCInterfaceDecl>(IIDecl)) { 508 if (WantNontrivialTypeSourceInfo) { 509 // Construct a type with type-source information. 510 TypeLocBuilder Builder; 511 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 512 513 T = getElaboratedType(ETK_None, *SS, T); 514 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 515 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 516 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 517 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 518 } else { 519 T = getElaboratedType(ETK_None, *SS, T); 520 } 521 } 522 523 return ParsedType::make(T); 524 } 525 526 // Builds a fake NNS for the given decl context. 527 static NestedNameSpecifier * 528 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 529 for (;; DC = DC->getLookupParent()) { 530 DC = DC->getPrimaryContext(); 531 auto *ND = dyn_cast<NamespaceDecl>(DC); 532 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 533 return NestedNameSpecifier::Create(Context, nullptr, ND); 534 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 535 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 536 RD->getTypeForDecl()); 537 else if (isa<TranslationUnitDecl>(DC)) 538 return NestedNameSpecifier::GlobalSpecifier(Context); 539 } 540 llvm_unreachable("something isn't in TU scope?"); 541 } 542 543 /// Find the parent class with dependent bases of the innermost enclosing method 544 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 545 /// up allowing unqualified dependent type names at class-level, which MSVC 546 /// correctly rejects. 547 static const CXXRecordDecl * 548 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 549 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 550 DC = DC->getPrimaryContext(); 551 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 552 if (MD->getParent()->hasAnyDependentBases()) 553 return MD->getParent(); 554 } 555 return nullptr; 556 } 557 558 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 559 SourceLocation NameLoc, 560 bool IsTemplateTypeArg) { 561 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 562 563 NestedNameSpecifier *NNS = nullptr; 564 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 565 // If we weren't able to parse a default template argument, delay lookup 566 // until instantiation time by making a non-dependent DependentTypeName. We 567 // pretend we saw a NestedNameSpecifier referring to the current scope, and 568 // lookup is retried. 569 // FIXME: This hurts our diagnostic quality, since we get errors like "no 570 // type named 'Foo' in 'current_namespace'" when the user didn't write any 571 // name specifiers. 572 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 573 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 574 } else if (const CXXRecordDecl *RD = 575 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 576 // Build a DependentNameType that will perform lookup into RD at 577 // instantiation time. 578 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 579 RD->getTypeForDecl()); 580 581 // Diagnose that this identifier was undeclared, and retry the lookup during 582 // template instantiation. 583 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 584 << RD; 585 } else { 586 // This is not a situation that we should recover from. 587 return ParsedType(); 588 } 589 590 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 591 592 // Build type location information. We synthesized the qualifier, so we have 593 // to build a fake NestedNameSpecifierLoc. 594 NestedNameSpecifierLocBuilder NNSLocBuilder; 595 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 596 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 597 598 TypeLocBuilder Builder; 599 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 600 DepTL.setNameLoc(NameLoc); 601 DepTL.setElaboratedKeywordLoc(SourceLocation()); 602 DepTL.setQualifierLoc(QualifierLoc); 603 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 604 } 605 606 /// isTagName() - This method is called *for error recovery purposes only* 607 /// to determine if the specified name is a valid tag name ("struct foo"). If 608 /// so, this returns the TST for the tag corresponding to it (TST_enum, 609 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 610 /// cases in C where the user forgot to specify the tag. 611 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 612 // Do a tag name lookup in this scope. 613 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 614 LookupName(R, S, false); 615 R.suppressDiagnostics(); 616 if (R.getResultKind() == LookupResult::Found) 617 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 618 switch (TD->getTagKind()) { 619 case TTK_Struct: return DeclSpec::TST_struct; 620 case TTK_Interface: return DeclSpec::TST_interface; 621 case TTK_Union: return DeclSpec::TST_union; 622 case TTK_Class: return DeclSpec::TST_class; 623 case TTK_Enum: return DeclSpec::TST_enum; 624 } 625 } 626 627 return DeclSpec::TST_unspecified; 628 } 629 630 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 631 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 632 /// then downgrade the missing typename error to a warning. 633 /// This is needed for MSVC compatibility; Example: 634 /// @code 635 /// template<class T> class A { 636 /// public: 637 /// typedef int TYPE; 638 /// }; 639 /// template<class T> class B : public A<T> { 640 /// public: 641 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 642 /// }; 643 /// @endcode 644 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 645 if (CurContext->isRecord()) { 646 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 647 return true; 648 649 const Type *Ty = SS->getScopeRep()->getAsType(); 650 651 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 652 for (const auto &Base : RD->bases()) 653 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 654 return true; 655 return S->isFunctionPrototypeScope(); 656 } 657 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 658 } 659 660 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 661 SourceLocation IILoc, 662 Scope *S, 663 CXXScopeSpec *SS, 664 ParsedType &SuggestedType, 665 bool IsTemplateName) { 666 // Don't report typename errors for editor placeholders. 667 if (II->isEditorPlaceholder()) 668 return; 669 // We don't have anything to suggest (yet). 670 SuggestedType = nullptr; 671 672 // There may have been a typo in the name of the type. Look up typo 673 // results, in case we have something that we can suggest. 674 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 675 /*AllowTemplates=*/IsTemplateName, 676 /*AllowNonTemplates=*/!IsTemplateName); 677 if (TypoCorrection Corrected = 678 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 679 CCC, CTK_ErrorRecovery)) { 680 // FIXME: Support error recovery for the template-name case. 681 bool CanRecover = !IsTemplateName; 682 if (Corrected.isKeyword()) { 683 // We corrected to a keyword. 684 diagnoseTypo(Corrected, 685 PDiag(IsTemplateName ? diag::err_no_template_suggest 686 : diag::err_unknown_typename_suggest) 687 << II); 688 II = Corrected.getCorrectionAsIdentifierInfo(); 689 } else { 690 // We found a similarly-named type or interface; suggest that. 691 if (!SS || !SS->isSet()) { 692 diagnoseTypo(Corrected, 693 PDiag(IsTemplateName ? diag::err_no_template_suggest 694 : diag::err_unknown_typename_suggest) 695 << II, CanRecover); 696 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 697 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 698 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 699 II->getName().equals(CorrectedStr); 700 diagnoseTypo(Corrected, 701 PDiag(IsTemplateName 702 ? diag::err_no_member_template_suggest 703 : diag::err_unknown_nested_typename_suggest) 704 << II << DC << DroppedSpecifier << SS->getRange(), 705 CanRecover); 706 } else { 707 llvm_unreachable("could not have corrected a typo here"); 708 } 709 710 if (!CanRecover) 711 return; 712 713 CXXScopeSpec tmpSS; 714 if (Corrected.getCorrectionSpecifier()) 715 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 716 SourceRange(IILoc)); 717 // FIXME: Support class template argument deduction here. 718 SuggestedType = 719 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 720 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 721 /*IsCtorOrDtorName=*/false, 722 /*WantNontrivialTypeSourceInfo=*/true); 723 } 724 return; 725 } 726 727 if (getLangOpts().CPlusPlus && !IsTemplateName) { 728 // See if II is a class template that the user forgot to pass arguments to. 729 UnqualifiedId Name; 730 Name.setIdentifier(II, IILoc); 731 CXXScopeSpec EmptySS; 732 TemplateTy TemplateResult; 733 bool MemberOfUnknownSpecialization; 734 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 735 Name, nullptr, true, TemplateResult, 736 MemberOfUnknownSpecialization) == TNK_Type_template) { 737 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 738 return; 739 } 740 } 741 742 // FIXME: Should we move the logic that tries to recover from a missing tag 743 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 744 745 if (!SS || (!SS->isSet() && !SS->isInvalid())) 746 Diag(IILoc, IsTemplateName ? diag::err_no_template 747 : diag::err_unknown_typename) 748 << II; 749 else if (DeclContext *DC = computeDeclContext(*SS, false)) 750 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 751 : diag::err_typename_nested_not_found) 752 << II << DC << SS->getRange(); 753 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 754 SuggestedType = 755 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 756 } else if (isDependentScopeSpecifier(*SS)) { 757 unsigned DiagID = diag::err_typename_missing; 758 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 759 DiagID = diag::ext_typename_missing; 760 761 Diag(SS->getRange().getBegin(), DiagID) 762 << SS->getScopeRep() << II->getName() 763 << SourceRange(SS->getRange().getBegin(), IILoc) 764 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 765 SuggestedType = ActOnTypenameType(S, SourceLocation(), 766 *SS, *II, IILoc).get(); 767 } else { 768 assert(SS && SS->isInvalid() && 769 "Invalid scope specifier has already been diagnosed"); 770 } 771 } 772 773 /// Determine whether the given result set contains either a type name 774 /// or 775 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 776 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 777 NextToken.is(tok::less); 778 779 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 780 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 781 return true; 782 783 if (CheckTemplate && isa<TemplateDecl>(*I)) 784 return true; 785 } 786 787 return false; 788 } 789 790 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 791 Scope *S, CXXScopeSpec &SS, 792 IdentifierInfo *&Name, 793 SourceLocation NameLoc) { 794 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 795 SemaRef.LookupParsedName(R, S, &SS); 796 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 797 StringRef FixItTagName; 798 switch (Tag->getTagKind()) { 799 case TTK_Class: 800 FixItTagName = "class "; 801 break; 802 803 case TTK_Enum: 804 FixItTagName = "enum "; 805 break; 806 807 case TTK_Struct: 808 FixItTagName = "struct "; 809 break; 810 811 case TTK_Interface: 812 FixItTagName = "__interface "; 813 break; 814 815 case TTK_Union: 816 FixItTagName = "union "; 817 break; 818 } 819 820 StringRef TagName = FixItTagName.drop_back(); 821 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 822 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 823 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 824 825 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 826 I != IEnd; ++I) 827 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 828 << Name << TagName; 829 830 // Replace lookup results with just the tag decl. 831 Result.clear(Sema::LookupTagName); 832 SemaRef.LookupParsedName(Result, S, &SS); 833 return true; 834 } 835 836 return false; 837 } 838 839 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 840 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 841 QualType T, SourceLocation NameLoc) { 842 ASTContext &Context = S.Context; 843 844 TypeLocBuilder Builder; 845 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 846 847 T = S.getElaboratedType(ETK_None, SS, T); 848 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 849 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 850 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 851 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 852 } 853 854 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 855 IdentifierInfo *&Name, 856 SourceLocation NameLoc, 857 const Token &NextToken, 858 CorrectionCandidateCallback *CCC) { 859 DeclarationNameInfo NameInfo(Name, NameLoc); 860 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 861 862 assert(NextToken.isNot(tok::coloncolon) && 863 "parse nested name specifiers before calling ClassifyName"); 864 if (getLangOpts().CPlusPlus && SS.isSet() && 865 isCurrentClassName(*Name, S, &SS)) { 866 // Per [class.qual]p2, this names the constructors of SS, not the 867 // injected-class-name. We don't have a classification for that. 868 // There's not much point caching this result, since the parser 869 // will reject it later. 870 return NameClassification::Unknown(); 871 } 872 873 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 874 LookupParsedName(Result, S, &SS, !CurMethod); 875 876 if (SS.isInvalid()) 877 return NameClassification::Error(); 878 879 // For unqualified lookup in a class template in MSVC mode, look into 880 // dependent base classes where the primary class template is known. 881 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 882 if (ParsedType TypeInBase = 883 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 884 return TypeInBase; 885 } 886 887 // Perform lookup for Objective-C instance variables (including automatically 888 // synthesized instance variables), if we're in an Objective-C method. 889 // FIXME: This lookup really, really needs to be folded in to the normal 890 // unqualified lookup mechanism. 891 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 892 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 893 if (Ivar.isInvalid()) 894 return NameClassification::Error(); 895 if (Ivar.isUsable()) 896 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 897 898 // We defer builtin creation until after ivar lookup inside ObjC methods. 899 if (Result.empty()) 900 LookupBuiltin(Result); 901 } 902 903 bool SecondTry = false; 904 bool IsFilteredTemplateName = false; 905 906 Corrected: 907 switch (Result.getResultKind()) { 908 case LookupResult::NotFound: 909 // If an unqualified-id is followed by a '(', then we have a function 910 // call. 911 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 912 // In C++, this is an ADL-only call. 913 // FIXME: Reference? 914 if (getLangOpts().CPlusPlus) 915 return NameClassification::UndeclaredNonType(); 916 917 // C90 6.3.2.2: 918 // If the expression that precedes the parenthesized argument list in a 919 // function call consists solely of an identifier, and if no 920 // declaration is visible for this identifier, the identifier is 921 // implicitly declared exactly as if, in the innermost block containing 922 // the function call, the declaration 923 // 924 // extern int identifier (); 925 // 926 // appeared. 927 // 928 // We also allow this in C99 as an extension. 929 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 930 return NameClassification::NonType(D); 931 } 932 933 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 934 // In C++20 onwards, this could be an ADL-only call to a function 935 // template, and we're required to assume that this is a template name. 936 // 937 // FIXME: Find a way to still do typo correction in this case. 938 TemplateName Template = 939 Context.getAssumedTemplateName(NameInfo.getName()); 940 return NameClassification::UndeclaredTemplate(Template); 941 } 942 943 // In C, we first see whether there is a tag type by the same name, in 944 // which case it's likely that the user just forgot to write "enum", 945 // "struct", or "union". 946 if (!getLangOpts().CPlusPlus && !SecondTry && 947 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 948 break; 949 } 950 951 // Perform typo correction to determine if there is another name that is 952 // close to this name. 953 if (!SecondTry && CCC) { 954 SecondTry = true; 955 if (TypoCorrection Corrected = 956 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 957 &SS, *CCC, CTK_ErrorRecovery)) { 958 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 959 unsigned QualifiedDiag = diag::err_no_member_suggest; 960 961 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 962 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 963 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 964 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 965 UnqualifiedDiag = diag::err_no_template_suggest; 966 QualifiedDiag = diag::err_no_member_template_suggest; 967 } else if (UnderlyingFirstDecl && 968 (isa<TypeDecl>(UnderlyingFirstDecl) || 969 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 970 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 971 UnqualifiedDiag = diag::err_unknown_typename_suggest; 972 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 973 } 974 975 if (SS.isEmpty()) { 976 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 977 } else {// FIXME: is this even reachable? Test it. 978 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 979 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 980 Name->getName().equals(CorrectedStr); 981 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 982 << Name << computeDeclContext(SS, false) 983 << DroppedSpecifier << SS.getRange()); 984 } 985 986 // Update the name, so that the caller has the new name. 987 Name = Corrected.getCorrectionAsIdentifierInfo(); 988 989 // Typo correction corrected to a keyword. 990 if (Corrected.isKeyword()) 991 return Name; 992 993 // Also update the LookupResult... 994 // FIXME: This should probably go away at some point 995 Result.clear(); 996 Result.setLookupName(Corrected.getCorrection()); 997 if (FirstDecl) 998 Result.addDecl(FirstDecl); 999 1000 // If we found an Objective-C instance variable, let 1001 // LookupInObjCMethod build the appropriate expression to 1002 // reference the ivar. 1003 // FIXME: This is a gross hack. 1004 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1005 DeclResult R = 1006 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1007 if (R.isInvalid()) 1008 return NameClassification::Error(); 1009 if (R.isUsable()) 1010 return NameClassification::NonType(Ivar); 1011 } 1012 1013 goto Corrected; 1014 } 1015 } 1016 1017 // We failed to correct; just fall through and let the parser deal with it. 1018 Result.suppressDiagnostics(); 1019 return NameClassification::Unknown(); 1020 1021 case LookupResult::NotFoundInCurrentInstantiation: { 1022 // We performed name lookup into the current instantiation, and there were 1023 // dependent bases, so we treat this result the same way as any other 1024 // dependent nested-name-specifier. 1025 1026 // C++ [temp.res]p2: 1027 // A name used in a template declaration or definition and that is 1028 // dependent on a template-parameter is assumed not to name a type 1029 // unless the applicable name lookup finds a type name or the name is 1030 // qualified by the keyword typename. 1031 // 1032 // FIXME: If the next token is '<', we might want to ask the parser to 1033 // perform some heroics to see if we actually have a 1034 // template-argument-list, which would indicate a missing 'template' 1035 // keyword here. 1036 return NameClassification::DependentNonType(); 1037 } 1038 1039 case LookupResult::Found: 1040 case LookupResult::FoundOverloaded: 1041 case LookupResult::FoundUnresolvedValue: 1042 break; 1043 1044 case LookupResult::Ambiguous: 1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1046 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1047 /*AllowDependent=*/false)) { 1048 // C++ [temp.local]p3: 1049 // A lookup that finds an injected-class-name (10.2) can result in an 1050 // ambiguity in certain cases (for example, if it is found in more than 1051 // one base class). If all of the injected-class-names that are found 1052 // refer to specializations of the same class template, and if the name 1053 // is followed by a template-argument-list, the reference refers to the 1054 // class template itself and not a specialization thereof, and is not 1055 // ambiguous. 1056 // 1057 // This filtering can make an ambiguous result into an unambiguous one, 1058 // so try again after filtering out template names. 1059 FilterAcceptableTemplateNames(Result); 1060 if (!Result.isAmbiguous()) { 1061 IsFilteredTemplateName = true; 1062 break; 1063 } 1064 } 1065 1066 // Diagnose the ambiguity and return an error. 1067 return NameClassification::Error(); 1068 } 1069 1070 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1071 (IsFilteredTemplateName || 1072 hasAnyAcceptableTemplateNames( 1073 Result, /*AllowFunctionTemplates=*/true, 1074 /*AllowDependent=*/false, 1075 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1076 getLangOpts().CPlusPlus20))) { 1077 // C++ [temp.names]p3: 1078 // After name lookup (3.4) finds that a name is a template-name or that 1079 // an operator-function-id or a literal- operator-id refers to a set of 1080 // overloaded functions any member of which is a function template if 1081 // this is followed by a <, the < is always taken as the delimiter of a 1082 // template-argument-list and never as the less-than operator. 1083 // C++2a [temp.names]p2: 1084 // A name is also considered to refer to a template if it is an 1085 // unqualified-id followed by a < and name lookup finds either one 1086 // or more functions or finds nothing. 1087 if (!IsFilteredTemplateName) 1088 FilterAcceptableTemplateNames(Result); 1089 1090 bool IsFunctionTemplate; 1091 bool IsVarTemplate; 1092 TemplateName Template; 1093 if (Result.end() - Result.begin() > 1) { 1094 IsFunctionTemplate = true; 1095 Template = Context.getOverloadedTemplateName(Result.begin(), 1096 Result.end()); 1097 } else if (!Result.empty()) { 1098 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1099 *Result.begin(), /*AllowFunctionTemplates=*/true, 1100 /*AllowDependent=*/false)); 1101 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1102 IsVarTemplate = isa<VarTemplateDecl>(TD); 1103 1104 if (SS.isNotEmpty()) 1105 Template = 1106 Context.getQualifiedTemplateName(SS.getScopeRep(), 1107 /*TemplateKeyword=*/false, TD); 1108 else 1109 Template = TemplateName(TD); 1110 } else { 1111 // All results were non-template functions. This is a function template 1112 // name. 1113 IsFunctionTemplate = true; 1114 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1115 } 1116 1117 if (IsFunctionTemplate) { 1118 // Function templates always go through overload resolution, at which 1119 // point we'll perform the various checks (e.g., accessibility) we need 1120 // to based on which function we selected. 1121 Result.suppressDiagnostics(); 1122 1123 return NameClassification::FunctionTemplate(Template); 1124 } 1125 1126 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1127 : NameClassification::TypeTemplate(Template); 1128 } 1129 1130 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1131 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1132 DiagnoseUseOfDecl(Type, NameLoc); 1133 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1134 QualType T = Context.getTypeDeclType(Type); 1135 if (SS.isNotEmpty()) 1136 return buildNestedType(*this, SS, T, NameLoc); 1137 return ParsedType::make(T); 1138 } 1139 1140 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1141 if (!Class) { 1142 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1143 if (ObjCCompatibleAliasDecl *Alias = 1144 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1145 Class = Alias->getClassInterface(); 1146 } 1147 1148 if (Class) { 1149 DiagnoseUseOfDecl(Class, NameLoc); 1150 1151 if (NextToken.is(tok::period)) { 1152 // Interface. <something> is parsed as a property reference expression. 1153 // Just return "unknown" as a fall-through for now. 1154 Result.suppressDiagnostics(); 1155 return NameClassification::Unknown(); 1156 } 1157 1158 QualType T = Context.getObjCInterfaceType(Class); 1159 return ParsedType::make(T); 1160 } 1161 1162 if (isa<ConceptDecl>(FirstDecl)) 1163 return NameClassification::Concept( 1164 TemplateName(cast<TemplateDecl>(FirstDecl))); 1165 1166 // We can have a type template here if we're classifying a template argument. 1167 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1168 !isa<VarTemplateDecl>(FirstDecl)) 1169 return NameClassification::TypeTemplate( 1170 TemplateName(cast<TemplateDecl>(FirstDecl))); 1171 1172 // Check for a tag type hidden by a non-type decl in a few cases where it 1173 // seems likely a type is wanted instead of the non-type that was found. 1174 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1175 if ((NextToken.is(tok::identifier) || 1176 (NextIsOp && 1177 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1178 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1179 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1180 DiagnoseUseOfDecl(Type, NameLoc); 1181 QualType T = Context.getTypeDeclType(Type); 1182 if (SS.isNotEmpty()) 1183 return buildNestedType(*this, SS, T, NameLoc); 1184 return ParsedType::make(T); 1185 } 1186 1187 // If we already know which single declaration is referenced, just annotate 1188 // that declaration directly. Defer resolving even non-overloaded class 1189 // member accesses, as we need to defer certain access checks until we know 1190 // the context. 1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1192 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1193 return NameClassification::NonType(Result.getRepresentativeDecl()); 1194 1195 // Otherwise, this is an overload set that we will need to resolve later. 1196 Result.suppressDiagnostics(); 1197 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1198 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1199 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1200 Result.begin(), Result.end())); 1201 } 1202 1203 ExprResult 1204 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1205 SourceLocation NameLoc) { 1206 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1207 CXXScopeSpec SS; 1208 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1209 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1210 } 1211 1212 ExprResult 1213 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1214 IdentifierInfo *Name, 1215 SourceLocation NameLoc, 1216 bool IsAddressOfOperand) { 1217 DeclarationNameInfo NameInfo(Name, NameLoc); 1218 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1219 NameInfo, IsAddressOfOperand, 1220 /*TemplateArgs=*/nullptr); 1221 } 1222 1223 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1224 NamedDecl *Found, 1225 SourceLocation NameLoc, 1226 const Token &NextToken) { 1227 if (getCurMethodDecl() && SS.isEmpty()) 1228 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1229 return BuildIvarRefExpr(S, NameLoc, Ivar); 1230 1231 // Reconstruct the lookup result. 1232 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1233 Result.addDecl(Found); 1234 Result.resolveKind(); 1235 1236 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1237 return BuildDeclarationNameExpr(SS, Result, ADL); 1238 } 1239 1240 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1241 // For an implicit class member access, transform the result into a member 1242 // access expression if necessary. 1243 auto *ULE = cast<UnresolvedLookupExpr>(E); 1244 if ((*ULE->decls_begin())->isCXXClassMember()) { 1245 CXXScopeSpec SS; 1246 SS.Adopt(ULE->getQualifierLoc()); 1247 1248 // Reconstruct the lookup result. 1249 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1250 LookupOrdinaryName); 1251 Result.setNamingClass(ULE->getNamingClass()); 1252 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1253 Result.addDecl(*I, I.getAccess()); 1254 Result.resolveKind(); 1255 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1256 nullptr, S); 1257 } 1258 1259 // Otherwise, this is already in the form we needed, and no further checks 1260 // are necessary. 1261 return ULE; 1262 } 1263 1264 Sema::TemplateNameKindForDiagnostics 1265 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1266 auto *TD = Name.getAsTemplateDecl(); 1267 if (!TD) 1268 return TemplateNameKindForDiagnostics::DependentTemplate; 1269 if (isa<ClassTemplateDecl>(TD)) 1270 return TemplateNameKindForDiagnostics::ClassTemplate; 1271 if (isa<FunctionTemplateDecl>(TD)) 1272 return TemplateNameKindForDiagnostics::FunctionTemplate; 1273 if (isa<VarTemplateDecl>(TD)) 1274 return TemplateNameKindForDiagnostics::VarTemplate; 1275 if (isa<TypeAliasTemplateDecl>(TD)) 1276 return TemplateNameKindForDiagnostics::AliasTemplate; 1277 if (isa<TemplateTemplateParmDecl>(TD)) 1278 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1279 if (isa<ConceptDecl>(TD)) 1280 return TemplateNameKindForDiagnostics::Concept; 1281 return TemplateNameKindForDiagnostics::DependentTemplate; 1282 } 1283 1284 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1285 assert(DC->getLexicalParent() == CurContext && 1286 "The next DeclContext should be lexically contained in the current one."); 1287 CurContext = DC; 1288 S->setEntity(DC); 1289 } 1290 1291 void Sema::PopDeclContext() { 1292 assert(CurContext && "DeclContext imbalance!"); 1293 1294 CurContext = CurContext->getLexicalParent(); 1295 assert(CurContext && "Popped translation unit!"); 1296 } 1297 1298 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1299 Decl *D) { 1300 // Unlike PushDeclContext, the context to which we return is not necessarily 1301 // the containing DC of TD, because the new context will be some pre-existing 1302 // TagDecl definition instead of a fresh one. 1303 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1304 CurContext = cast<TagDecl>(D)->getDefinition(); 1305 assert(CurContext && "skipping definition of undefined tag"); 1306 // Start lookups from the parent of the current context; we don't want to look 1307 // into the pre-existing complete definition. 1308 S->setEntity(CurContext->getLookupParent()); 1309 return Result; 1310 } 1311 1312 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1313 CurContext = static_cast<decltype(CurContext)>(Context); 1314 } 1315 1316 /// EnterDeclaratorContext - Used when we must lookup names in the context 1317 /// of a declarator's nested name specifier. 1318 /// 1319 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1320 // C++0x [basic.lookup.unqual]p13: 1321 // A name used in the definition of a static data member of class 1322 // X (after the qualified-id of the static member) is looked up as 1323 // if the name was used in a member function of X. 1324 // C++0x [basic.lookup.unqual]p14: 1325 // If a variable member of a namespace is defined outside of the 1326 // scope of its namespace then any name used in the definition of 1327 // the variable member (after the declarator-id) is looked up as 1328 // if the definition of the variable member occurred in its 1329 // namespace. 1330 // Both of these imply that we should push a scope whose context 1331 // is the semantic context of the declaration. We can't use 1332 // PushDeclContext here because that context is not necessarily 1333 // lexically contained in the current context. Fortunately, 1334 // the containing scope should have the appropriate information. 1335 1336 assert(!S->getEntity() && "scope already has entity"); 1337 1338 #ifndef NDEBUG 1339 Scope *Ancestor = S->getParent(); 1340 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1341 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1342 #endif 1343 1344 CurContext = DC; 1345 S->setEntity(DC); 1346 1347 if (S->getParent()->isTemplateParamScope()) { 1348 // Also set the corresponding entities for all immediately-enclosing 1349 // template parameter scopes. 1350 EnterTemplatedContext(S->getParent(), DC); 1351 } 1352 } 1353 1354 void Sema::ExitDeclaratorContext(Scope *S) { 1355 assert(S->getEntity() == CurContext && "Context imbalance!"); 1356 1357 // Switch back to the lexical context. The safety of this is 1358 // enforced by an assert in EnterDeclaratorContext. 1359 Scope *Ancestor = S->getParent(); 1360 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1361 CurContext = Ancestor->getEntity(); 1362 1363 // We don't need to do anything with the scope, which is going to 1364 // disappear. 1365 } 1366 1367 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1368 assert(S->isTemplateParamScope() && 1369 "expected to be initializing a template parameter scope"); 1370 1371 // C++20 [temp.local]p7: 1372 // In the definition of a member of a class template that appears outside 1373 // of the class template definition, the name of a member of the class 1374 // template hides the name of a template-parameter of any enclosing class 1375 // templates (but not a template-parameter of the member if the member is a 1376 // class or function template). 1377 // C++20 [temp.local]p9: 1378 // In the definition of a class template or in the definition of a member 1379 // of such a template that appears outside of the template definition, for 1380 // each non-dependent base class (13.8.2.1), if the name of the base class 1381 // or the name of a member of the base class is the same as the name of a 1382 // template-parameter, the base class name or member name hides the 1383 // template-parameter name (6.4.10). 1384 // 1385 // This means that a template parameter scope should be searched immediately 1386 // after searching the DeclContext for which it is a template parameter 1387 // scope. For example, for 1388 // template<typename T> template<typename U> template<typename V> 1389 // void N::A<T>::B<U>::f(...) 1390 // we search V then B<U> (and base classes) then U then A<T> (and base 1391 // classes) then T then N then ::. 1392 unsigned ScopeDepth = getTemplateDepth(S); 1393 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1394 DeclContext *SearchDCAfterScope = DC; 1395 for (; DC; DC = DC->getLookupParent()) { 1396 if (const TemplateParameterList *TPL = 1397 cast<Decl>(DC)->getDescribedTemplateParams()) { 1398 unsigned DCDepth = TPL->getDepth() + 1; 1399 if (DCDepth > ScopeDepth) 1400 continue; 1401 if (ScopeDepth == DCDepth) 1402 SearchDCAfterScope = DC = DC->getLookupParent(); 1403 break; 1404 } 1405 } 1406 S->setLookupEntity(SearchDCAfterScope); 1407 } 1408 } 1409 1410 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1411 // We assume that the caller has already called 1412 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1413 FunctionDecl *FD = D->getAsFunction(); 1414 if (!FD) 1415 return; 1416 1417 // Same implementation as PushDeclContext, but enters the context 1418 // from the lexical parent, rather than the top-level class. 1419 assert(CurContext == FD->getLexicalParent() && 1420 "The next DeclContext should be lexically contained in the current one."); 1421 CurContext = FD; 1422 S->setEntity(CurContext); 1423 1424 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1425 ParmVarDecl *Param = FD->getParamDecl(P); 1426 // If the parameter has an identifier, then add it to the scope 1427 if (Param->getIdentifier()) { 1428 S->AddDecl(Param); 1429 IdResolver.AddDecl(Param); 1430 } 1431 } 1432 } 1433 1434 void Sema::ActOnExitFunctionContext() { 1435 // Same implementation as PopDeclContext, but returns to the lexical parent, 1436 // rather than the top-level class. 1437 assert(CurContext && "DeclContext imbalance!"); 1438 CurContext = CurContext->getLexicalParent(); 1439 assert(CurContext && "Popped translation unit!"); 1440 } 1441 1442 /// Determine whether we allow overloading of the function 1443 /// PrevDecl with another declaration. 1444 /// 1445 /// This routine determines whether overloading is possible, not 1446 /// whether some new function is actually an overload. It will return 1447 /// true in C++ (where we can always provide overloads) or, as an 1448 /// extension, in C when the previous function is already an 1449 /// overloaded function declaration or has the "overloadable" 1450 /// attribute. 1451 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1452 ASTContext &Context, 1453 const FunctionDecl *New) { 1454 if (Context.getLangOpts().CPlusPlus) 1455 return true; 1456 1457 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1458 return true; 1459 1460 return Previous.getResultKind() == LookupResult::Found && 1461 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1462 New->hasAttr<OverloadableAttr>()); 1463 } 1464 1465 /// Add this decl to the scope shadowed decl chains. 1466 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1467 // Move up the scope chain until we find the nearest enclosing 1468 // non-transparent context. The declaration will be introduced into this 1469 // scope. 1470 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1471 S = S->getParent(); 1472 1473 // Add scoped declarations into their context, so that they can be 1474 // found later. Declarations without a context won't be inserted 1475 // into any context. 1476 if (AddToContext) 1477 CurContext->addDecl(D); 1478 1479 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1480 // are function-local declarations. 1481 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1482 return; 1483 1484 // Template instantiations should also not be pushed into scope. 1485 if (isa<FunctionDecl>(D) && 1486 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1487 return; 1488 1489 // If this replaces anything in the current scope, 1490 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1491 IEnd = IdResolver.end(); 1492 for (; I != IEnd; ++I) { 1493 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1494 S->RemoveDecl(*I); 1495 IdResolver.RemoveDecl(*I); 1496 1497 // Should only need to replace one decl. 1498 break; 1499 } 1500 } 1501 1502 S->AddDecl(D); 1503 1504 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1505 // Implicitly-generated labels may end up getting generated in an order that 1506 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1507 // the label at the appropriate place in the identifier chain. 1508 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1509 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1510 if (IDC == CurContext) { 1511 if (!S->isDeclScope(*I)) 1512 continue; 1513 } else if (IDC->Encloses(CurContext)) 1514 break; 1515 } 1516 1517 IdResolver.InsertDeclAfter(I, D); 1518 } else { 1519 IdResolver.AddDecl(D); 1520 } 1521 } 1522 1523 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1524 bool AllowInlineNamespace) { 1525 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1526 } 1527 1528 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1529 DeclContext *TargetDC = DC->getPrimaryContext(); 1530 do { 1531 if (DeclContext *ScopeDC = S->getEntity()) 1532 if (ScopeDC->getPrimaryContext() == TargetDC) 1533 return S; 1534 } while ((S = S->getParent())); 1535 1536 return nullptr; 1537 } 1538 1539 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1540 DeclContext*, 1541 ASTContext&); 1542 1543 /// Filters out lookup results that don't fall within the given scope 1544 /// as determined by isDeclInScope. 1545 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1546 bool ConsiderLinkage, 1547 bool AllowInlineNamespace) { 1548 LookupResult::Filter F = R.makeFilter(); 1549 while (F.hasNext()) { 1550 NamedDecl *D = F.next(); 1551 1552 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1553 continue; 1554 1555 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1556 continue; 1557 1558 F.erase(); 1559 } 1560 1561 F.done(); 1562 } 1563 1564 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1565 /// have compatible owning modules. 1566 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1567 // FIXME: The Modules TS is not clear about how friend declarations are 1568 // to be treated. It's not meaningful to have different owning modules for 1569 // linkage in redeclarations of the same entity, so for now allow the 1570 // redeclaration and change the owning modules to match. 1571 if (New->getFriendObjectKind() && 1572 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1573 New->setLocalOwningModule(Old->getOwningModule()); 1574 makeMergedDefinitionVisible(New); 1575 return false; 1576 } 1577 1578 Module *NewM = New->getOwningModule(); 1579 Module *OldM = Old->getOwningModule(); 1580 1581 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1582 NewM = NewM->Parent; 1583 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1584 OldM = OldM->Parent; 1585 1586 if (NewM == OldM) 1587 return false; 1588 1589 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1590 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1591 if (NewIsModuleInterface || OldIsModuleInterface) { 1592 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1593 // if a declaration of D [...] appears in the purview of a module, all 1594 // other such declarations shall appear in the purview of the same module 1595 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1596 << New 1597 << NewIsModuleInterface 1598 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1599 << OldIsModuleInterface 1600 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1601 Diag(Old->getLocation(), diag::note_previous_declaration); 1602 New->setInvalidDecl(); 1603 return true; 1604 } 1605 1606 return false; 1607 } 1608 1609 static bool isUsingDecl(NamedDecl *D) { 1610 return isa<UsingShadowDecl>(D) || 1611 isa<UnresolvedUsingTypenameDecl>(D) || 1612 isa<UnresolvedUsingValueDecl>(D); 1613 } 1614 1615 /// Removes using shadow declarations from the lookup results. 1616 static void RemoveUsingDecls(LookupResult &R) { 1617 LookupResult::Filter F = R.makeFilter(); 1618 while (F.hasNext()) 1619 if (isUsingDecl(F.next())) 1620 F.erase(); 1621 1622 F.done(); 1623 } 1624 1625 /// Check for this common pattern: 1626 /// @code 1627 /// class S { 1628 /// S(const S&); // DO NOT IMPLEMENT 1629 /// void operator=(const S&); // DO NOT IMPLEMENT 1630 /// }; 1631 /// @endcode 1632 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1633 // FIXME: Should check for private access too but access is set after we get 1634 // the decl here. 1635 if (D->doesThisDeclarationHaveABody()) 1636 return false; 1637 1638 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1639 return CD->isCopyConstructor(); 1640 return D->isCopyAssignmentOperator(); 1641 } 1642 1643 // We need this to handle 1644 // 1645 // typedef struct { 1646 // void *foo() { return 0; } 1647 // } A; 1648 // 1649 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1650 // for example. If 'A', foo will have external linkage. If we have '*A', 1651 // foo will have no linkage. Since we can't know until we get to the end 1652 // of the typedef, this function finds out if D might have non-external linkage. 1653 // Callers should verify at the end of the TU if it D has external linkage or 1654 // not. 1655 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1656 const DeclContext *DC = D->getDeclContext(); 1657 while (!DC->isTranslationUnit()) { 1658 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1659 if (!RD->hasNameForLinkage()) 1660 return true; 1661 } 1662 DC = DC->getParent(); 1663 } 1664 1665 return !D->isExternallyVisible(); 1666 } 1667 1668 // FIXME: This needs to be refactored; some other isInMainFile users want 1669 // these semantics. 1670 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1671 if (S.TUKind != TU_Complete) 1672 return false; 1673 return S.SourceMgr.isInMainFile(Loc); 1674 } 1675 1676 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1677 assert(D); 1678 1679 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1680 return false; 1681 1682 // Ignore all entities declared within templates, and out-of-line definitions 1683 // of members of class templates. 1684 if (D->getDeclContext()->isDependentContext() || 1685 D->getLexicalDeclContext()->isDependentContext()) 1686 return false; 1687 1688 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1689 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1690 return false; 1691 // A non-out-of-line declaration of a member specialization was implicitly 1692 // instantiated; it's the out-of-line declaration that we're interested in. 1693 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1694 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1695 return false; 1696 1697 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1698 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1699 return false; 1700 } else { 1701 // 'static inline' functions are defined in headers; don't warn. 1702 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1703 return false; 1704 } 1705 1706 if (FD->doesThisDeclarationHaveABody() && 1707 Context.DeclMustBeEmitted(FD)) 1708 return false; 1709 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1710 // Constants and utility variables are defined in headers with internal 1711 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1712 // like "inline".) 1713 if (!isMainFileLoc(*this, VD->getLocation())) 1714 return false; 1715 1716 if (Context.DeclMustBeEmitted(VD)) 1717 return false; 1718 1719 if (VD->isStaticDataMember() && 1720 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1721 return false; 1722 if (VD->isStaticDataMember() && 1723 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1724 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1725 return false; 1726 1727 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1728 return false; 1729 } else { 1730 return false; 1731 } 1732 1733 // Only warn for unused decls internal to the translation unit. 1734 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1735 // for inline functions defined in the main source file, for instance. 1736 return mightHaveNonExternalLinkage(D); 1737 } 1738 1739 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1740 if (!D) 1741 return; 1742 1743 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1744 const FunctionDecl *First = FD->getFirstDecl(); 1745 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1746 return; // First should already be in the vector. 1747 } 1748 1749 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1750 const VarDecl *First = VD->getFirstDecl(); 1751 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1752 return; // First should already be in the vector. 1753 } 1754 1755 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1756 UnusedFileScopedDecls.push_back(D); 1757 } 1758 1759 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1760 if (D->isInvalidDecl()) 1761 return false; 1762 1763 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1764 // For a decomposition declaration, warn if none of the bindings are 1765 // referenced, instead of if the variable itself is referenced (which 1766 // it is, by the bindings' expressions). 1767 for (auto *BD : DD->bindings()) 1768 if (BD->isReferenced()) 1769 return false; 1770 } else if (!D->getDeclName()) { 1771 return false; 1772 } else if (D->isReferenced() || D->isUsed()) { 1773 return false; 1774 } 1775 1776 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1777 return false; 1778 1779 if (isa<LabelDecl>(D)) 1780 return true; 1781 1782 // Except for labels, we only care about unused decls that are local to 1783 // functions. 1784 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1785 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1786 // For dependent types, the diagnostic is deferred. 1787 WithinFunction = 1788 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1789 if (!WithinFunction) 1790 return false; 1791 1792 if (isa<TypedefNameDecl>(D)) 1793 return true; 1794 1795 // White-list anything that isn't a local variable. 1796 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1797 return false; 1798 1799 // Types of valid local variables should be complete, so this should succeed. 1800 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1801 1802 // White-list anything with an __attribute__((unused)) type. 1803 const auto *Ty = VD->getType().getTypePtr(); 1804 1805 // Only look at the outermost level of typedef. 1806 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1807 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1808 return false; 1809 } 1810 1811 // If we failed to complete the type for some reason, or if the type is 1812 // dependent, don't diagnose the variable. 1813 if (Ty->isIncompleteType() || Ty->isDependentType()) 1814 return false; 1815 1816 // Look at the element type to ensure that the warning behaviour is 1817 // consistent for both scalars and arrays. 1818 Ty = Ty->getBaseElementTypeUnsafe(); 1819 1820 if (const TagType *TT = Ty->getAs<TagType>()) { 1821 const TagDecl *Tag = TT->getDecl(); 1822 if (Tag->hasAttr<UnusedAttr>()) 1823 return false; 1824 1825 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1826 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1827 return false; 1828 1829 if (const Expr *Init = VD->getInit()) { 1830 if (const ExprWithCleanups *Cleanups = 1831 dyn_cast<ExprWithCleanups>(Init)) 1832 Init = Cleanups->getSubExpr(); 1833 const CXXConstructExpr *Construct = 1834 dyn_cast<CXXConstructExpr>(Init); 1835 if (Construct && !Construct->isElidable()) { 1836 CXXConstructorDecl *CD = Construct->getConstructor(); 1837 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1838 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1839 return false; 1840 } 1841 1842 // Suppress the warning if we don't know how this is constructed, and 1843 // it could possibly be non-trivial constructor. 1844 if (Init->isTypeDependent()) 1845 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1846 if (!Ctor->isTrivial()) 1847 return false; 1848 } 1849 } 1850 } 1851 1852 // TODO: __attribute__((unused)) templates? 1853 } 1854 1855 return true; 1856 } 1857 1858 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1859 FixItHint &Hint) { 1860 if (isa<LabelDecl>(D)) { 1861 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1862 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1863 true); 1864 if (AfterColon.isInvalid()) 1865 return; 1866 Hint = FixItHint::CreateRemoval( 1867 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1868 } 1869 } 1870 1871 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1872 if (D->getTypeForDecl()->isDependentType()) 1873 return; 1874 1875 for (auto *TmpD : D->decls()) { 1876 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1877 DiagnoseUnusedDecl(T); 1878 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1879 DiagnoseUnusedNestedTypedefs(R); 1880 } 1881 } 1882 1883 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1884 /// unless they are marked attr(unused). 1885 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1886 if (!ShouldDiagnoseUnusedDecl(D)) 1887 return; 1888 1889 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1890 // typedefs can be referenced later on, so the diagnostics are emitted 1891 // at end-of-translation-unit. 1892 UnusedLocalTypedefNameCandidates.insert(TD); 1893 return; 1894 } 1895 1896 FixItHint Hint; 1897 GenerateFixForUnusedDecl(D, Context, Hint); 1898 1899 unsigned DiagID; 1900 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1901 DiagID = diag::warn_unused_exception_param; 1902 else if (isa<LabelDecl>(D)) 1903 DiagID = diag::warn_unused_label; 1904 else 1905 DiagID = diag::warn_unused_variable; 1906 1907 Diag(D->getLocation(), DiagID) << D << Hint; 1908 } 1909 1910 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1911 // Verify that we have no forward references left. If so, there was a goto 1912 // or address of a label taken, but no definition of it. Label fwd 1913 // definitions are indicated with a null substmt which is also not a resolved 1914 // MS inline assembly label name. 1915 bool Diagnose = false; 1916 if (L->isMSAsmLabel()) 1917 Diagnose = !L->isResolvedMSAsmLabel(); 1918 else 1919 Diagnose = L->getStmt() == nullptr; 1920 if (Diagnose) 1921 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1922 } 1923 1924 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1925 S->mergeNRVOIntoParent(); 1926 1927 if (S->decl_empty()) return; 1928 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1929 "Scope shouldn't contain decls!"); 1930 1931 for (auto *TmpD : S->decls()) { 1932 assert(TmpD && "This decl didn't get pushed??"); 1933 1934 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1935 NamedDecl *D = cast<NamedDecl>(TmpD); 1936 1937 // Diagnose unused variables in this scope. 1938 if (!S->hasUnrecoverableErrorOccurred()) { 1939 DiagnoseUnusedDecl(D); 1940 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1941 DiagnoseUnusedNestedTypedefs(RD); 1942 } 1943 1944 if (!D->getDeclName()) continue; 1945 1946 // If this was a forward reference to a label, verify it was defined. 1947 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1948 CheckPoppedLabel(LD, *this); 1949 1950 // Remove this name from our lexical scope, and warn on it if we haven't 1951 // already. 1952 IdResolver.RemoveDecl(D); 1953 auto ShadowI = ShadowingDecls.find(D); 1954 if (ShadowI != ShadowingDecls.end()) { 1955 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1956 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1957 << D << FD << FD->getParent(); 1958 Diag(FD->getLocation(), diag::note_previous_declaration); 1959 } 1960 ShadowingDecls.erase(ShadowI); 1961 } 1962 } 1963 } 1964 1965 /// Look for an Objective-C class in the translation unit. 1966 /// 1967 /// \param Id The name of the Objective-C class we're looking for. If 1968 /// typo-correction fixes this name, the Id will be updated 1969 /// to the fixed name. 1970 /// 1971 /// \param IdLoc The location of the name in the translation unit. 1972 /// 1973 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1974 /// if there is no class with the given name. 1975 /// 1976 /// \returns The declaration of the named Objective-C class, or NULL if the 1977 /// class could not be found. 1978 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1979 SourceLocation IdLoc, 1980 bool DoTypoCorrection) { 1981 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1982 // creation from this context. 1983 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1984 1985 if (!IDecl && DoTypoCorrection) { 1986 // Perform typo correction at the given location, but only if we 1987 // find an Objective-C class name. 1988 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1989 if (TypoCorrection C = 1990 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1991 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1992 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1993 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1994 Id = IDecl->getIdentifier(); 1995 } 1996 } 1997 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1998 // This routine must always return a class definition, if any. 1999 if (Def && Def->getDefinition()) 2000 Def = Def->getDefinition(); 2001 return Def; 2002 } 2003 2004 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2005 /// from S, where a non-field would be declared. This routine copes 2006 /// with the difference between C and C++ scoping rules in structs and 2007 /// unions. For example, the following code is well-formed in C but 2008 /// ill-formed in C++: 2009 /// @code 2010 /// struct S6 { 2011 /// enum { BAR } e; 2012 /// }; 2013 /// 2014 /// void test_S6() { 2015 /// struct S6 a; 2016 /// a.e = BAR; 2017 /// } 2018 /// @endcode 2019 /// For the declaration of BAR, this routine will return a different 2020 /// scope. The scope S will be the scope of the unnamed enumeration 2021 /// within S6. In C++, this routine will return the scope associated 2022 /// with S6, because the enumeration's scope is a transparent 2023 /// context but structures can contain non-field names. In C, this 2024 /// routine will return the translation unit scope, since the 2025 /// enumeration's scope is a transparent context and structures cannot 2026 /// contain non-field names. 2027 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2028 while (((S->getFlags() & Scope::DeclScope) == 0) || 2029 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2030 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2031 S = S->getParent(); 2032 return S; 2033 } 2034 2035 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2036 ASTContext::GetBuiltinTypeError Error) { 2037 switch (Error) { 2038 case ASTContext::GE_None: 2039 return ""; 2040 case ASTContext::GE_Missing_type: 2041 return BuiltinInfo.getHeaderName(ID); 2042 case ASTContext::GE_Missing_stdio: 2043 return "stdio.h"; 2044 case ASTContext::GE_Missing_setjmp: 2045 return "setjmp.h"; 2046 case ASTContext::GE_Missing_ucontext: 2047 return "ucontext.h"; 2048 } 2049 llvm_unreachable("unhandled error kind"); 2050 } 2051 2052 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2053 unsigned ID, SourceLocation Loc) { 2054 DeclContext *Parent = Context.getTranslationUnitDecl(); 2055 2056 if (getLangOpts().CPlusPlus) { 2057 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2058 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2059 CLinkageDecl->setImplicit(); 2060 Parent->addDecl(CLinkageDecl); 2061 Parent = CLinkageDecl; 2062 } 2063 2064 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2065 /*TInfo=*/nullptr, SC_Extern, false, 2066 Type->isFunctionProtoType()); 2067 New->setImplicit(); 2068 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2069 2070 // Create Decl objects for each parameter, adding them to the 2071 // FunctionDecl. 2072 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2073 SmallVector<ParmVarDecl *, 16> Params; 2074 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2075 ParmVarDecl *parm = ParmVarDecl::Create( 2076 Context, New, SourceLocation(), SourceLocation(), nullptr, 2077 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2078 parm->setScopeInfo(0, i); 2079 Params.push_back(parm); 2080 } 2081 New->setParams(Params); 2082 } 2083 2084 AddKnownFunctionAttributes(New); 2085 return New; 2086 } 2087 2088 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2089 /// file scope. lazily create a decl for it. ForRedeclaration is true 2090 /// if we're creating this built-in in anticipation of redeclaring the 2091 /// built-in. 2092 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2093 Scope *S, bool ForRedeclaration, 2094 SourceLocation Loc) { 2095 LookupNecessaryTypesForBuiltin(S, ID); 2096 2097 ASTContext::GetBuiltinTypeError Error; 2098 QualType R = Context.GetBuiltinType(ID, Error); 2099 if (Error) { 2100 if (!ForRedeclaration) 2101 return nullptr; 2102 2103 // If we have a builtin without an associated type we should not emit a 2104 // warning when we were not able to find a type for it. 2105 if (Error == ASTContext::GE_Missing_type || 2106 Context.BuiltinInfo.allowTypeMismatch(ID)) 2107 return nullptr; 2108 2109 // If we could not find a type for setjmp it is because the jmp_buf type was 2110 // not defined prior to the setjmp declaration. 2111 if (Error == ASTContext::GE_Missing_setjmp) { 2112 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2113 << Context.BuiltinInfo.getName(ID); 2114 return nullptr; 2115 } 2116 2117 // Generally, we emit a warning that the declaration requires the 2118 // appropriate header. 2119 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2120 << getHeaderName(Context.BuiltinInfo, ID, Error) 2121 << Context.BuiltinInfo.getName(ID); 2122 return nullptr; 2123 } 2124 2125 if (!ForRedeclaration && 2126 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2127 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2128 Diag(Loc, diag::ext_implicit_lib_function_decl) 2129 << Context.BuiltinInfo.getName(ID) << R; 2130 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2131 Diag(Loc, diag::note_include_header_or_declare) 2132 << Header << Context.BuiltinInfo.getName(ID); 2133 } 2134 2135 if (R.isNull()) 2136 return nullptr; 2137 2138 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2139 RegisterLocallyScopedExternCDecl(New, S); 2140 2141 // TUScope is the translation-unit scope to insert this function into. 2142 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2143 // relate Scopes to DeclContexts, and probably eliminate CurContext 2144 // entirely, but we're not there yet. 2145 DeclContext *SavedContext = CurContext; 2146 CurContext = New->getDeclContext(); 2147 PushOnScopeChains(New, TUScope); 2148 CurContext = SavedContext; 2149 return New; 2150 } 2151 2152 /// Typedef declarations don't have linkage, but they still denote the same 2153 /// entity if their types are the same. 2154 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2155 /// isSameEntity. 2156 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2157 TypedefNameDecl *Decl, 2158 LookupResult &Previous) { 2159 // This is only interesting when modules are enabled. 2160 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2161 return; 2162 2163 // Empty sets are uninteresting. 2164 if (Previous.empty()) 2165 return; 2166 2167 LookupResult::Filter Filter = Previous.makeFilter(); 2168 while (Filter.hasNext()) { 2169 NamedDecl *Old = Filter.next(); 2170 2171 // Non-hidden declarations are never ignored. 2172 if (S.isVisible(Old)) 2173 continue; 2174 2175 // Declarations of the same entity are not ignored, even if they have 2176 // different linkages. 2177 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2178 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2179 Decl->getUnderlyingType())) 2180 continue; 2181 2182 // If both declarations give a tag declaration a typedef name for linkage 2183 // purposes, then they declare the same entity. 2184 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2185 Decl->getAnonDeclWithTypedefName()) 2186 continue; 2187 } 2188 2189 Filter.erase(); 2190 } 2191 2192 Filter.done(); 2193 } 2194 2195 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2196 QualType OldType; 2197 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2198 OldType = OldTypedef->getUnderlyingType(); 2199 else 2200 OldType = Context.getTypeDeclType(Old); 2201 QualType NewType = New->getUnderlyingType(); 2202 2203 if (NewType->isVariablyModifiedType()) { 2204 // Must not redefine a typedef with a variably-modified type. 2205 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2206 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2207 << Kind << NewType; 2208 if (Old->getLocation().isValid()) 2209 notePreviousDefinition(Old, New->getLocation()); 2210 New->setInvalidDecl(); 2211 return true; 2212 } 2213 2214 if (OldType != NewType && 2215 !OldType->isDependentType() && 2216 !NewType->isDependentType() && 2217 !Context.hasSameType(OldType, NewType)) { 2218 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2219 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2220 << Kind << NewType << OldType; 2221 if (Old->getLocation().isValid()) 2222 notePreviousDefinition(Old, New->getLocation()); 2223 New->setInvalidDecl(); 2224 return true; 2225 } 2226 return false; 2227 } 2228 2229 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2230 /// same name and scope as a previous declaration 'Old'. Figure out 2231 /// how to resolve this situation, merging decls or emitting 2232 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2233 /// 2234 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2235 LookupResult &OldDecls) { 2236 // If the new decl is known invalid already, don't bother doing any 2237 // merging checks. 2238 if (New->isInvalidDecl()) return; 2239 2240 // Allow multiple definitions for ObjC built-in typedefs. 2241 // FIXME: Verify the underlying types are equivalent! 2242 if (getLangOpts().ObjC) { 2243 const IdentifierInfo *TypeID = New->getIdentifier(); 2244 switch (TypeID->getLength()) { 2245 default: break; 2246 case 2: 2247 { 2248 if (!TypeID->isStr("id")) 2249 break; 2250 QualType T = New->getUnderlyingType(); 2251 if (!T->isPointerType()) 2252 break; 2253 if (!T->isVoidPointerType()) { 2254 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2255 if (!PT->isStructureType()) 2256 break; 2257 } 2258 Context.setObjCIdRedefinitionType(T); 2259 // Install the built-in type for 'id', ignoring the current definition. 2260 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2261 return; 2262 } 2263 case 5: 2264 if (!TypeID->isStr("Class")) 2265 break; 2266 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2267 // Install the built-in type for 'Class', ignoring the current definition. 2268 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2269 return; 2270 case 3: 2271 if (!TypeID->isStr("SEL")) 2272 break; 2273 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2274 // Install the built-in type for 'SEL', ignoring the current definition. 2275 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2276 return; 2277 } 2278 // Fall through - the typedef name was not a builtin type. 2279 } 2280 2281 // Verify the old decl was also a type. 2282 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2283 if (!Old) { 2284 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2285 << New->getDeclName(); 2286 2287 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2288 if (OldD->getLocation().isValid()) 2289 notePreviousDefinition(OldD, New->getLocation()); 2290 2291 return New->setInvalidDecl(); 2292 } 2293 2294 // If the old declaration is invalid, just give up here. 2295 if (Old->isInvalidDecl()) 2296 return New->setInvalidDecl(); 2297 2298 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2299 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2300 auto *NewTag = New->getAnonDeclWithTypedefName(); 2301 NamedDecl *Hidden = nullptr; 2302 if (OldTag && NewTag && 2303 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2304 !hasVisibleDefinition(OldTag, &Hidden)) { 2305 // There is a definition of this tag, but it is not visible. Use it 2306 // instead of our tag. 2307 New->setTypeForDecl(OldTD->getTypeForDecl()); 2308 if (OldTD->isModed()) 2309 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2310 OldTD->getUnderlyingType()); 2311 else 2312 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2313 2314 // Make the old tag definition visible. 2315 makeMergedDefinitionVisible(Hidden); 2316 2317 // If this was an unscoped enumeration, yank all of its enumerators 2318 // out of the scope. 2319 if (isa<EnumDecl>(NewTag)) { 2320 Scope *EnumScope = getNonFieldDeclScope(S); 2321 for (auto *D : NewTag->decls()) { 2322 auto *ED = cast<EnumConstantDecl>(D); 2323 assert(EnumScope->isDeclScope(ED)); 2324 EnumScope->RemoveDecl(ED); 2325 IdResolver.RemoveDecl(ED); 2326 ED->getLexicalDeclContext()->removeDecl(ED); 2327 } 2328 } 2329 } 2330 } 2331 2332 // If the typedef types are not identical, reject them in all languages and 2333 // with any extensions enabled. 2334 if (isIncompatibleTypedef(Old, New)) 2335 return; 2336 2337 // The types match. Link up the redeclaration chain and merge attributes if 2338 // the old declaration was a typedef. 2339 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2340 New->setPreviousDecl(Typedef); 2341 mergeDeclAttributes(New, Old); 2342 } 2343 2344 if (getLangOpts().MicrosoftExt) 2345 return; 2346 2347 if (getLangOpts().CPlusPlus) { 2348 // C++ [dcl.typedef]p2: 2349 // In a given non-class scope, a typedef specifier can be used to 2350 // redefine the name of any type declared in that scope to refer 2351 // to the type to which it already refers. 2352 if (!isa<CXXRecordDecl>(CurContext)) 2353 return; 2354 2355 // C++0x [dcl.typedef]p4: 2356 // In a given class scope, a typedef specifier can be used to redefine 2357 // any class-name declared in that scope that is not also a typedef-name 2358 // to refer to the type to which it already refers. 2359 // 2360 // This wording came in via DR424, which was a correction to the 2361 // wording in DR56, which accidentally banned code like: 2362 // 2363 // struct S { 2364 // typedef struct A { } A; 2365 // }; 2366 // 2367 // in the C++03 standard. We implement the C++0x semantics, which 2368 // allow the above but disallow 2369 // 2370 // struct S { 2371 // typedef int I; 2372 // typedef int I; 2373 // }; 2374 // 2375 // since that was the intent of DR56. 2376 if (!isa<TypedefNameDecl>(Old)) 2377 return; 2378 2379 Diag(New->getLocation(), diag::err_redefinition) 2380 << New->getDeclName(); 2381 notePreviousDefinition(Old, New->getLocation()); 2382 return New->setInvalidDecl(); 2383 } 2384 2385 // Modules always permit redefinition of typedefs, as does C11. 2386 if (getLangOpts().Modules || getLangOpts().C11) 2387 return; 2388 2389 // If we have a redefinition of a typedef in C, emit a warning. This warning 2390 // is normally mapped to an error, but can be controlled with 2391 // -Wtypedef-redefinition. If either the original or the redefinition is 2392 // in a system header, don't emit this for compatibility with GCC. 2393 if (getDiagnostics().getSuppressSystemWarnings() && 2394 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2395 (Old->isImplicit() || 2396 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2397 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2398 return; 2399 2400 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2401 << New->getDeclName(); 2402 notePreviousDefinition(Old, New->getLocation()); 2403 } 2404 2405 /// DeclhasAttr - returns true if decl Declaration already has the target 2406 /// attribute. 2407 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2408 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2409 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2410 for (const auto *i : D->attrs()) 2411 if (i->getKind() == A->getKind()) { 2412 if (Ann) { 2413 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2414 return true; 2415 continue; 2416 } 2417 // FIXME: Don't hardcode this check 2418 if (OA && isa<OwnershipAttr>(i)) 2419 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2420 return true; 2421 } 2422 2423 return false; 2424 } 2425 2426 static bool isAttributeTargetADefinition(Decl *D) { 2427 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2428 return VD->isThisDeclarationADefinition(); 2429 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2430 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2431 return true; 2432 } 2433 2434 /// Merge alignment attributes from \p Old to \p New, taking into account the 2435 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2436 /// 2437 /// \return \c true if any attributes were added to \p New. 2438 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2439 // Look for alignas attributes on Old, and pick out whichever attribute 2440 // specifies the strictest alignment requirement. 2441 AlignedAttr *OldAlignasAttr = nullptr; 2442 AlignedAttr *OldStrictestAlignAttr = nullptr; 2443 unsigned OldAlign = 0; 2444 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2445 // FIXME: We have no way of representing inherited dependent alignments 2446 // in a case like: 2447 // template<int A, int B> struct alignas(A) X; 2448 // template<int A, int B> struct alignas(B) X {}; 2449 // For now, we just ignore any alignas attributes which are not on the 2450 // definition in such a case. 2451 if (I->isAlignmentDependent()) 2452 return false; 2453 2454 if (I->isAlignas()) 2455 OldAlignasAttr = I; 2456 2457 unsigned Align = I->getAlignment(S.Context); 2458 if (Align > OldAlign) { 2459 OldAlign = Align; 2460 OldStrictestAlignAttr = I; 2461 } 2462 } 2463 2464 // Look for alignas attributes on New. 2465 AlignedAttr *NewAlignasAttr = nullptr; 2466 unsigned NewAlign = 0; 2467 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2468 if (I->isAlignmentDependent()) 2469 return false; 2470 2471 if (I->isAlignas()) 2472 NewAlignasAttr = I; 2473 2474 unsigned Align = I->getAlignment(S.Context); 2475 if (Align > NewAlign) 2476 NewAlign = Align; 2477 } 2478 2479 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2480 // Both declarations have 'alignas' attributes. We require them to match. 2481 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2482 // fall short. (If two declarations both have alignas, they must both match 2483 // every definition, and so must match each other if there is a definition.) 2484 2485 // If either declaration only contains 'alignas(0)' specifiers, then it 2486 // specifies the natural alignment for the type. 2487 if (OldAlign == 0 || NewAlign == 0) { 2488 QualType Ty; 2489 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2490 Ty = VD->getType(); 2491 else 2492 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2493 2494 if (OldAlign == 0) 2495 OldAlign = S.Context.getTypeAlign(Ty); 2496 if (NewAlign == 0) 2497 NewAlign = S.Context.getTypeAlign(Ty); 2498 } 2499 2500 if (OldAlign != NewAlign) { 2501 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2502 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2503 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2504 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2505 } 2506 } 2507 2508 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2509 // C++11 [dcl.align]p6: 2510 // if any declaration of an entity has an alignment-specifier, 2511 // every defining declaration of that entity shall specify an 2512 // equivalent alignment. 2513 // C11 6.7.5/7: 2514 // If the definition of an object does not have an alignment 2515 // specifier, any other declaration of that object shall also 2516 // have no alignment specifier. 2517 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2518 << OldAlignasAttr; 2519 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2520 << OldAlignasAttr; 2521 } 2522 2523 bool AnyAdded = false; 2524 2525 // Ensure we have an attribute representing the strictest alignment. 2526 if (OldAlign > NewAlign) { 2527 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2528 Clone->setInherited(true); 2529 New->addAttr(Clone); 2530 AnyAdded = true; 2531 } 2532 2533 // Ensure we have an alignas attribute if the old declaration had one. 2534 if (OldAlignasAttr && !NewAlignasAttr && 2535 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2536 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2537 Clone->setInherited(true); 2538 New->addAttr(Clone); 2539 AnyAdded = true; 2540 } 2541 2542 return AnyAdded; 2543 } 2544 2545 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2546 const InheritableAttr *Attr, 2547 Sema::AvailabilityMergeKind AMK) { 2548 // This function copies an attribute Attr from a previous declaration to the 2549 // new declaration D if the new declaration doesn't itself have that attribute 2550 // yet or if that attribute allows duplicates. 2551 // If you're adding a new attribute that requires logic different from 2552 // "use explicit attribute on decl if present, else use attribute from 2553 // previous decl", for example if the attribute needs to be consistent 2554 // between redeclarations, you need to call a custom merge function here. 2555 InheritableAttr *NewAttr = nullptr; 2556 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2557 NewAttr = S.mergeAvailabilityAttr( 2558 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2559 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2560 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2561 AA->getPriority()); 2562 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2563 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2564 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2565 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2566 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2567 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2568 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2569 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2570 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2571 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2572 FA->getFirstArg()); 2573 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2574 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2575 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2576 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2577 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2578 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2579 IA->getInheritanceModel()); 2580 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2581 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2582 &S.Context.Idents.get(AA->getSpelling())); 2583 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2584 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2585 isa<CUDAGlobalAttr>(Attr))) { 2586 // CUDA target attributes are part of function signature for 2587 // overloading purposes and must not be merged. 2588 return false; 2589 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2590 NewAttr = S.mergeMinSizeAttr(D, *MA); 2591 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2592 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2593 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2594 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2595 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2596 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2597 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2598 NewAttr = S.mergeCommonAttr(D, *CommonA); 2599 else if (isa<AlignedAttr>(Attr)) 2600 // AlignedAttrs are handled separately, because we need to handle all 2601 // such attributes on a declaration at the same time. 2602 NewAttr = nullptr; 2603 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2604 (AMK == Sema::AMK_Override || 2605 AMK == Sema::AMK_ProtocolImplementation)) 2606 NewAttr = nullptr; 2607 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2608 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2609 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2610 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2611 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2612 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2613 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2614 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2615 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2616 NewAttr = S.mergeImportNameAttr(D, *INA); 2617 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2618 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2619 2620 if (NewAttr) { 2621 NewAttr->setInherited(true); 2622 D->addAttr(NewAttr); 2623 if (isa<MSInheritanceAttr>(NewAttr)) 2624 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2625 return true; 2626 } 2627 2628 return false; 2629 } 2630 2631 static const NamedDecl *getDefinition(const Decl *D) { 2632 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2633 return TD->getDefinition(); 2634 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2635 const VarDecl *Def = VD->getDefinition(); 2636 if (Def) 2637 return Def; 2638 return VD->getActingDefinition(); 2639 } 2640 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2641 return FD->getDefinition(); 2642 return nullptr; 2643 } 2644 2645 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2646 for (const auto *Attribute : D->attrs()) 2647 if (Attribute->getKind() == Kind) 2648 return true; 2649 return false; 2650 } 2651 2652 /// checkNewAttributesAfterDef - If we already have a definition, check that 2653 /// there are no new attributes in this declaration. 2654 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2655 if (!New->hasAttrs()) 2656 return; 2657 2658 const NamedDecl *Def = getDefinition(Old); 2659 if (!Def || Def == New) 2660 return; 2661 2662 AttrVec &NewAttributes = New->getAttrs(); 2663 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2664 const Attr *NewAttribute = NewAttributes[I]; 2665 2666 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2667 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2668 Sema::SkipBodyInfo SkipBody; 2669 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2670 2671 // If we're skipping this definition, drop the "alias" attribute. 2672 if (SkipBody.ShouldSkip) { 2673 NewAttributes.erase(NewAttributes.begin() + I); 2674 --E; 2675 continue; 2676 } 2677 } else { 2678 VarDecl *VD = cast<VarDecl>(New); 2679 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2680 VarDecl::TentativeDefinition 2681 ? diag::err_alias_after_tentative 2682 : diag::err_redefinition; 2683 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2684 if (Diag == diag::err_redefinition) 2685 S.notePreviousDefinition(Def, VD->getLocation()); 2686 else 2687 S.Diag(Def->getLocation(), diag::note_previous_definition); 2688 VD->setInvalidDecl(); 2689 } 2690 ++I; 2691 continue; 2692 } 2693 2694 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2695 // Tentative definitions are only interesting for the alias check above. 2696 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2697 ++I; 2698 continue; 2699 } 2700 } 2701 2702 if (hasAttribute(Def, NewAttribute->getKind())) { 2703 ++I; 2704 continue; // regular attr merging will take care of validating this. 2705 } 2706 2707 if (isa<C11NoReturnAttr>(NewAttribute)) { 2708 // C's _Noreturn is allowed to be added to a function after it is defined. 2709 ++I; 2710 continue; 2711 } else if (isa<UuidAttr>(NewAttribute)) { 2712 // msvc will allow a subsequent definition to add an uuid to a class 2713 ++I; 2714 continue; 2715 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2716 if (AA->isAlignas()) { 2717 // C++11 [dcl.align]p6: 2718 // if any declaration of an entity has an alignment-specifier, 2719 // every defining declaration of that entity shall specify an 2720 // equivalent alignment. 2721 // C11 6.7.5/7: 2722 // If the definition of an object does not have an alignment 2723 // specifier, any other declaration of that object shall also 2724 // have no alignment specifier. 2725 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2726 << AA; 2727 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2728 << AA; 2729 NewAttributes.erase(NewAttributes.begin() + I); 2730 --E; 2731 continue; 2732 } 2733 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2734 // If there is a C definition followed by a redeclaration with this 2735 // attribute then there are two different definitions. In C++, prefer the 2736 // standard diagnostics. 2737 if (!S.getLangOpts().CPlusPlus) { 2738 S.Diag(NewAttribute->getLocation(), 2739 diag::err_loader_uninitialized_redeclaration); 2740 S.Diag(Def->getLocation(), diag::note_previous_definition); 2741 NewAttributes.erase(NewAttributes.begin() + I); 2742 --E; 2743 continue; 2744 } 2745 } else if (isa<SelectAnyAttr>(NewAttribute) && 2746 cast<VarDecl>(New)->isInline() && 2747 !cast<VarDecl>(New)->isInlineSpecified()) { 2748 // Don't warn about applying selectany to implicitly inline variables. 2749 // Older compilers and language modes would require the use of selectany 2750 // to make such variables inline, and it would have no effect if we 2751 // honored it. 2752 ++I; 2753 continue; 2754 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2755 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2756 // declarations after defintions. 2757 ++I; 2758 continue; 2759 } 2760 2761 S.Diag(NewAttribute->getLocation(), 2762 diag::warn_attribute_precede_definition); 2763 S.Diag(Def->getLocation(), diag::note_previous_definition); 2764 NewAttributes.erase(NewAttributes.begin() + I); 2765 --E; 2766 } 2767 } 2768 2769 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2770 const ConstInitAttr *CIAttr, 2771 bool AttrBeforeInit) { 2772 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2773 2774 // Figure out a good way to write this specifier on the old declaration. 2775 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2776 // enough of the attribute list spelling information to extract that without 2777 // heroics. 2778 std::string SuitableSpelling; 2779 if (S.getLangOpts().CPlusPlus20) 2780 SuitableSpelling = std::string( 2781 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2782 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2783 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2784 InsertLoc, {tok::l_square, tok::l_square, 2785 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2786 S.PP.getIdentifierInfo("require_constant_initialization"), 2787 tok::r_square, tok::r_square})); 2788 if (SuitableSpelling.empty()) 2789 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2790 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2791 S.PP.getIdentifierInfo("require_constant_initialization"), 2792 tok::r_paren, tok::r_paren})); 2793 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2794 SuitableSpelling = "constinit"; 2795 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2796 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2797 if (SuitableSpelling.empty()) 2798 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2799 SuitableSpelling += " "; 2800 2801 if (AttrBeforeInit) { 2802 // extern constinit int a; 2803 // int a = 0; // error (missing 'constinit'), accepted as extension 2804 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2805 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2806 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2807 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2808 } else { 2809 // int a = 0; 2810 // constinit extern int a; // error (missing 'constinit') 2811 S.Diag(CIAttr->getLocation(), 2812 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2813 : diag::warn_require_const_init_added_too_late) 2814 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2815 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2816 << CIAttr->isConstinit() 2817 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2818 } 2819 } 2820 2821 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2822 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2823 AvailabilityMergeKind AMK) { 2824 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2825 UsedAttr *NewAttr = OldAttr->clone(Context); 2826 NewAttr->setInherited(true); 2827 New->addAttr(NewAttr); 2828 } 2829 2830 if (!Old->hasAttrs() && !New->hasAttrs()) 2831 return; 2832 2833 // [dcl.constinit]p1: 2834 // If the [constinit] specifier is applied to any declaration of a 2835 // variable, it shall be applied to the initializing declaration. 2836 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2837 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2838 if (bool(OldConstInit) != bool(NewConstInit)) { 2839 const auto *OldVD = cast<VarDecl>(Old); 2840 auto *NewVD = cast<VarDecl>(New); 2841 2842 // Find the initializing declaration. Note that we might not have linked 2843 // the new declaration into the redeclaration chain yet. 2844 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2845 if (!InitDecl && 2846 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2847 InitDecl = NewVD; 2848 2849 if (InitDecl == NewVD) { 2850 // This is the initializing declaration. If it would inherit 'constinit', 2851 // that's ill-formed. (Note that we do not apply this to the attribute 2852 // form). 2853 if (OldConstInit && OldConstInit->isConstinit()) 2854 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2855 /*AttrBeforeInit=*/true); 2856 } else if (NewConstInit) { 2857 // This is the first time we've been told that this declaration should 2858 // have a constant initializer. If we already saw the initializing 2859 // declaration, this is too late. 2860 if (InitDecl && InitDecl != NewVD) { 2861 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2862 /*AttrBeforeInit=*/false); 2863 NewVD->dropAttr<ConstInitAttr>(); 2864 } 2865 } 2866 } 2867 2868 // Attributes declared post-definition are currently ignored. 2869 checkNewAttributesAfterDef(*this, New, Old); 2870 2871 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2872 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2873 if (!OldA->isEquivalent(NewA)) { 2874 // This redeclaration changes __asm__ label. 2875 Diag(New->getLocation(), diag::err_different_asm_label); 2876 Diag(OldA->getLocation(), diag::note_previous_declaration); 2877 } 2878 } else if (Old->isUsed()) { 2879 // This redeclaration adds an __asm__ label to a declaration that has 2880 // already been ODR-used. 2881 Diag(New->getLocation(), diag::err_late_asm_label_name) 2882 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2883 } 2884 } 2885 2886 // Re-declaration cannot add abi_tag's. 2887 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2888 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2889 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2890 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2891 NewTag) == OldAbiTagAttr->tags_end()) { 2892 Diag(NewAbiTagAttr->getLocation(), 2893 diag::err_new_abi_tag_on_redeclaration) 2894 << NewTag; 2895 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2896 } 2897 } 2898 } else { 2899 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2900 Diag(Old->getLocation(), diag::note_previous_declaration); 2901 } 2902 } 2903 2904 // This redeclaration adds a section attribute. 2905 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2906 if (auto *VD = dyn_cast<VarDecl>(New)) { 2907 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2908 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2909 Diag(Old->getLocation(), diag::note_previous_declaration); 2910 } 2911 } 2912 } 2913 2914 // Redeclaration adds code-seg attribute. 2915 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2916 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2917 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2918 Diag(New->getLocation(), diag::warn_mismatched_section) 2919 << 0 /*codeseg*/; 2920 Diag(Old->getLocation(), diag::note_previous_declaration); 2921 } 2922 2923 if (!Old->hasAttrs()) 2924 return; 2925 2926 bool foundAny = New->hasAttrs(); 2927 2928 // Ensure that any moving of objects within the allocated map is done before 2929 // we process them. 2930 if (!foundAny) New->setAttrs(AttrVec()); 2931 2932 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2933 // Ignore deprecated/unavailable/availability attributes if requested. 2934 AvailabilityMergeKind LocalAMK = AMK_None; 2935 if (isa<DeprecatedAttr>(I) || 2936 isa<UnavailableAttr>(I) || 2937 isa<AvailabilityAttr>(I)) { 2938 switch (AMK) { 2939 case AMK_None: 2940 continue; 2941 2942 case AMK_Redeclaration: 2943 case AMK_Override: 2944 case AMK_ProtocolImplementation: 2945 LocalAMK = AMK; 2946 break; 2947 } 2948 } 2949 2950 // Already handled. 2951 if (isa<UsedAttr>(I)) 2952 continue; 2953 2954 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2955 foundAny = true; 2956 } 2957 2958 if (mergeAlignedAttrs(*this, New, Old)) 2959 foundAny = true; 2960 2961 if (!foundAny) New->dropAttrs(); 2962 } 2963 2964 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2965 /// to the new one. 2966 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2967 const ParmVarDecl *oldDecl, 2968 Sema &S) { 2969 // C++11 [dcl.attr.depend]p2: 2970 // The first declaration of a function shall specify the 2971 // carries_dependency attribute for its declarator-id if any declaration 2972 // of the function specifies the carries_dependency attribute. 2973 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2974 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2975 S.Diag(CDA->getLocation(), 2976 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2977 // Find the first declaration of the parameter. 2978 // FIXME: Should we build redeclaration chains for function parameters? 2979 const FunctionDecl *FirstFD = 2980 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2981 const ParmVarDecl *FirstVD = 2982 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2983 S.Diag(FirstVD->getLocation(), 2984 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2985 } 2986 2987 if (!oldDecl->hasAttrs()) 2988 return; 2989 2990 bool foundAny = newDecl->hasAttrs(); 2991 2992 // Ensure that any moving of objects within the allocated map is 2993 // done before we process them. 2994 if (!foundAny) newDecl->setAttrs(AttrVec()); 2995 2996 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2997 if (!DeclHasAttr(newDecl, I)) { 2998 InheritableAttr *newAttr = 2999 cast<InheritableParamAttr>(I->clone(S.Context)); 3000 newAttr->setInherited(true); 3001 newDecl->addAttr(newAttr); 3002 foundAny = true; 3003 } 3004 } 3005 3006 if (!foundAny) newDecl->dropAttrs(); 3007 } 3008 3009 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3010 const ParmVarDecl *OldParam, 3011 Sema &S) { 3012 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3013 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3014 if (*Oldnullability != *Newnullability) { 3015 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3016 << DiagNullabilityKind( 3017 *Newnullability, 3018 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3019 != 0)) 3020 << DiagNullabilityKind( 3021 *Oldnullability, 3022 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3023 != 0)); 3024 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3025 } 3026 } else { 3027 QualType NewT = NewParam->getType(); 3028 NewT = S.Context.getAttributedType( 3029 AttributedType::getNullabilityAttrKind(*Oldnullability), 3030 NewT, NewT); 3031 NewParam->setType(NewT); 3032 } 3033 } 3034 } 3035 3036 namespace { 3037 3038 /// Used in MergeFunctionDecl to keep track of function parameters in 3039 /// C. 3040 struct GNUCompatibleParamWarning { 3041 ParmVarDecl *OldParm; 3042 ParmVarDecl *NewParm; 3043 QualType PromotedType; 3044 }; 3045 3046 } // end anonymous namespace 3047 3048 // Determine whether the previous declaration was a definition, implicit 3049 // declaration, or a declaration. 3050 template <typename T> 3051 static std::pair<diag::kind, SourceLocation> 3052 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3053 diag::kind PrevDiag; 3054 SourceLocation OldLocation = Old->getLocation(); 3055 if (Old->isThisDeclarationADefinition()) 3056 PrevDiag = diag::note_previous_definition; 3057 else if (Old->isImplicit()) { 3058 PrevDiag = diag::note_previous_implicit_declaration; 3059 if (OldLocation.isInvalid()) 3060 OldLocation = New->getLocation(); 3061 } else 3062 PrevDiag = diag::note_previous_declaration; 3063 return std::make_pair(PrevDiag, OldLocation); 3064 } 3065 3066 /// canRedefineFunction - checks if a function can be redefined. Currently, 3067 /// only extern inline functions can be redefined, and even then only in 3068 /// GNU89 mode. 3069 static bool canRedefineFunction(const FunctionDecl *FD, 3070 const LangOptions& LangOpts) { 3071 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3072 !LangOpts.CPlusPlus && 3073 FD->isInlineSpecified() && 3074 FD->getStorageClass() == SC_Extern); 3075 } 3076 3077 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3078 const AttributedType *AT = T->getAs<AttributedType>(); 3079 while (AT && !AT->isCallingConv()) 3080 AT = AT->getModifiedType()->getAs<AttributedType>(); 3081 return AT; 3082 } 3083 3084 template <typename T> 3085 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3086 const DeclContext *DC = Old->getDeclContext(); 3087 if (DC->isRecord()) 3088 return false; 3089 3090 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3091 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3092 return true; 3093 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3094 return true; 3095 return false; 3096 } 3097 3098 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3099 static bool isExternC(VarTemplateDecl *) { return false; } 3100 3101 /// Check whether a redeclaration of an entity introduced by a 3102 /// using-declaration is valid, given that we know it's not an overload 3103 /// (nor a hidden tag declaration). 3104 template<typename ExpectedDecl> 3105 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3106 ExpectedDecl *New) { 3107 // C++11 [basic.scope.declarative]p4: 3108 // Given a set of declarations in a single declarative region, each of 3109 // which specifies the same unqualified name, 3110 // -- they shall all refer to the same entity, or all refer to functions 3111 // and function templates; or 3112 // -- exactly one declaration shall declare a class name or enumeration 3113 // name that is not a typedef name and the other declarations shall all 3114 // refer to the same variable or enumerator, or all refer to functions 3115 // and function templates; in this case the class name or enumeration 3116 // name is hidden (3.3.10). 3117 3118 // C++11 [namespace.udecl]p14: 3119 // If a function declaration in namespace scope or block scope has the 3120 // same name and the same parameter-type-list as a function introduced 3121 // by a using-declaration, and the declarations do not declare the same 3122 // function, the program is ill-formed. 3123 3124 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3125 if (Old && 3126 !Old->getDeclContext()->getRedeclContext()->Equals( 3127 New->getDeclContext()->getRedeclContext()) && 3128 !(isExternC(Old) && isExternC(New))) 3129 Old = nullptr; 3130 3131 if (!Old) { 3132 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3133 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3134 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3135 return true; 3136 } 3137 return false; 3138 } 3139 3140 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3141 const FunctionDecl *B) { 3142 assert(A->getNumParams() == B->getNumParams()); 3143 3144 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3145 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3146 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3147 if (AttrA == AttrB) 3148 return true; 3149 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3150 AttrA->isDynamic() == AttrB->isDynamic(); 3151 }; 3152 3153 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3154 } 3155 3156 /// If necessary, adjust the semantic declaration context for a qualified 3157 /// declaration to name the correct inline namespace within the qualifier. 3158 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3159 DeclaratorDecl *OldD) { 3160 // The only case where we need to update the DeclContext is when 3161 // redeclaration lookup for a qualified name finds a declaration 3162 // in an inline namespace within the context named by the qualifier: 3163 // 3164 // inline namespace N { int f(); } 3165 // int ::f(); // Sema DC needs adjusting from :: to N::. 3166 // 3167 // For unqualified declarations, the semantic context *can* change 3168 // along the redeclaration chain (for local extern declarations, 3169 // extern "C" declarations, and friend declarations in particular). 3170 if (!NewD->getQualifier()) 3171 return; 3172 3173 // NewD is probably already in the right context. 3174 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3175 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3176 if (NamedDC->Equals(SemaDC)) 3177 return; 3178 3179 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3180 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3181 "unexpected context for redeclaration"); 3182 3183 auto *LexDC = NewD->getLexicalDeclContext(); 3184 auto FixSemaDC = [=](NamedDecl *D) { 3185 if (!D) 3186 return; 3187 D->setDeclContext(SemaDC); 3188 D->setLexicalDeclContext(LexDC); 3189 }; 3190 3191 FixSemaDC(NewD); 3192 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3193 FixSemaDC(FD->getDescribedFunctionTemplate()); 3194 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3195 FixSemaDC(VD->getDescribedVarTemplate()); 3196 } 3197 3198 /// MergeFunctionDecl - We just parsed a function 'New' from 3199 /// declarator D which has the same name and scope as a previous 3200 /// declaration 'Old'. Figure out how to resolve this situation, 3201 /// merging decls or emitting diagnostics as appropriate. 3202 /// 3203 /// In C++, New and Old must be declarations that are not 3204 /// overloaded. Use IsOverload to determine whether New and Old are 3205 /// overloaded, and to select the Old declaration that New should be 3206 /// merged with. 3207 /// 3208 /// Returns true if there was an error, false otherwise. 3209 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3210 Scope *S, bool MergeTypeWithOld) { 3211 // Verify the old decl was also a function. 3212 FunctionDecl *Old = OldD->getAsFunction(); 3213 if (!Old) { 3214 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3215 if (New->getFriendObjectKind()) { 3216 Diag(New->getLocation(), diag::err_using_decl_friend); 3217 Diag(Shadow->getTargetDecl()->getLocation(), 3218 diag::note_using_decl_target); 3219 Diag(Shadow->getUsingDecl()->getLocation(), 3220 diag::note_using_decl) << 0; 3221 return true; 3222 } 3223 3224 // Check whether the two declarations might declare the same function. 3225 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3226 return true; 3227 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3228 } else { 3229 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3230 << New->getDeclName(); 3231 notePreviousDefinition(OldD, New->getLocation()); 3232 return true; 3233 } 3234 } 3235 3236 // If the old declaration is invalid, just give up here. 3237 if (Old->isInvalidDecl()) 3238 return true; 3239 3240 // Disallow redeclaration of some builtins. 3241 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3242 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3243 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3244 << Old << Old->getType(); 3245 return true; 3246 } 3247 3248 diag::kind PrevDiag; 3249 SourceLocation OldLocation; 3250 std::tie(PrevDiag, OldLocation) = 3251 getNoteDiagForInvalidRedeclaration(Old, New); 3252 3253 // Don't complain about this if we're in GNU89 mode and the old function 3254 // is an extern inline function. 3255 // Don't complain about specializations. They are not supposed to have 3256 // storage classes. 3257 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3258 New->getStorageClass() == SC_Static && 3259 Old->hasExternalFormalLinkage() && 3260 !New->getTemplateSpecializationInfo() && 3261 !canRedefineFunction(Old, getLangOpts())) { 3262 if (getLangOpts().MicrosoftExt) { 3263 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3264 Diag(OldLocation, PrevDiag); 3265 } else { 3266 Diag(New->getLocation(), diag::err_static_non_static) << New; 3267 Diag(OldLocation, PrevDiag); 3268 return true; 3269 } 3270 } 3271 3272 if (New->hasAttr<InternalLinkageAttr>() && 3273 !Old->hasAttr<InternalLinkageAttr>()) { 3274 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3275 << New->getDeclName(); 3276 notePreviousDefinition(Old, New->getLocation()); 3277 New->dropAttr<InternalLinkageAttr>(); 3278 } 3279 3280 if (CheckRedeclarationModuleOwnership(New, Old)) 3281 return true; 3282 3283 if (!getLangOpts().CPlusPlus) { 3284 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3285 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3286 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3287 << New << OldOvl; 3288 3289 // Try our best to find a decl that actually has the overloadable 3290 // attribute for the note. In most cases (e.g. programs with only one 3291 // broken declaration/definition), this won't matter. 3292 // 3293 // FIXME: We could do this if we juggled some extra state in 3294 // OverloadableAttr, rather than just removing it. 3295 const Decl *DiagOld = Old; 3296 if (OldOvl) { 3297 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3298 const auto *A = D->getAttr<OverloadableAttr>(); 3299 return A && !A->isImplicit(); 3300 }); 3301 // If we've implicitly added *all* of the overloadable attrs to this 3302 // chain, emitting a "previous redecl" note is pointless. 3303 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3304 } 3305 3306 if (DiagOld) 3307 Diag(DiagOld->getLocation(), 3308 diag::note_attribute_overloadable_prev_overload) 3309 << OldOvl; 3310 3311 if (OldOvl) 3312 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3313 else 3314 New->dropAttr<OverloadableAttr>(); 3315 } 3316 } 3317 3318 // If a function is first declared with a calling convention, but is later 3319 // declared or defined without one, all following decls assume the calling 3320 // convention of the first. 3321 // 3322 // It's OK if a function is first declared without a calling convention, 3323 // but is later declared or defined with the default calling convention. 3324 // 3325 // To test if either decl has an explicit calling convention, we look for 3326 // AttributedType sugar nodes on the type as written. If they are missing or 3327 // were canonicalized away, we assume the calling convention was implicit. 3328 // 3329 // Note also that we DO NOT return at this point, because we still have 3330 // other tests to run. 3331 QualType OldQType = Context.getCanonicalType(Old->getType()); 3332 QualType NewQType = Context.getCanonicalType(New->getType()); 3333 const FunctionType *OldType = cast<FunctionType>(OldQType); 3334 const FunctionType *NewType = cast<FunctionType>(NewQType); 3335 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3336 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3337 bool RequiresAdjustment = false; 3338 3339 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3340 FunctionDecl *First = Old->getFirstDecl(); 3341 const FunctionType *FT = 3342 First->getType().getCanonicalType()->castAs<FunctionType>(); 3343 FunctionType::ExtInfo FI = FT->getExtInfo(); 3344 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3345 if (!NewCCExplicit) { 3346 // Inherit the CC from the previous declaration if it was specified 3347 // there but not here. 3348 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3349 RequiresAdjustment = true; 3350 } else if (Old->getBuiltinID()) { 3351 // Builtin attribute isn't propagated to the new one yet at this point, 3352 // so we check if the old one is a builtin. 3353 3354 // Calling Conventions on a Builtin aren't really useful and setting a 3355 // default calling convention and cdecl'ing some builtin redeclarations is 3356 // common, so warn and ignore the calling convention on the redeclaration. 3357 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3358 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3359 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3360 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3361 RequiresAdjustment = true; 3362 } else { 3363 // Calling conventions aren't compatible, so complain. 3364 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3365 Diag(New->getLocation(), diag::err_cconv_change) 3366 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3367 << !FirstCCExplicit 3368 << (!FirstCCExplicit ? "" : 3369 FunctionType::getNameForCallConv(FI.getCC())); 3370 3371 // Put the note on the first decl, since it is the one that matters. 3372 Diag(First->getLocation(), diag::note_previous_declaration); 3373 return true; 3374 } 3375 } 3376 3377 // FIXME: diagnose the other way around? 3378 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3379 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3380 RequiresAdjustment = true; 3381 } 3382 3383 // Merge regparm attribute. 3384 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3385 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3386 if (NewTypeInfo.getHasRegParm()) { 3387 Diag(New->getLocation(), diag::err_regparm_mismatch) 3388 << NewType->getRegParmType() 3389 << OldType->getRegParmType(); 3390 Diag(OldLocation, diag::note_previous_declaration); 3391 return true; 3392 } 3393 3394 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3395 RequiresAdjustment = true; 3396 } 3397 3398 // Merge ns_returns_retained attribute. 3399 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3400 if (NewTypeInfo.getProducesResult()) { 3401 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3402 << "'ns_returns_retained'"; 3403 Diag(OldLocation, diag::note_previous_declaration); 3404 return true; 3405 } 3406 3407 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3408 RequiresAdjustment = true; 3409 } 3410 3411 if (OldTypeInfo.getNoCallerSavedRegs() != 3412 NewTypeInfo.getNoCallerSavedRegs()) { 3413 if (NewTypeInfo.getNoCallerSavedRegs()) { 3414 AnyX86NoCallerSavedRegistersAttr *Attr = 3415 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3416 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3417 Diag(OldLocation, diag::note_previous_declaration); 3418 return true; 3419 } 3420 3421 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3422 RequiresAdjustment = true; 3423 } 3424 3425 if (RequiresAdjustment) { 3426 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3427 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3428 New->setType(QualType(AdjustedType, 0)); 3429 NewQType = Context.getCanonicalType(New->getType()); 3430 } 3431 3432 // If this redeclaration makes the function inline, we may need to add it to 3433 // UndefinedButUsed. 3434 if (!Old->isInlined() && New->isInlined() && 3435 !New->hasAttr<GNUInlineAttr>() && 3436 !getLangOpts().GNUInline && 3437 Old->isUsed(false) && 3438 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3439 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3440 SourceLocation())); 3441 3442 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3443 // about it. 3444 if (New->hasAttr<GNUInlineAttr>() && 3445 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3446 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3447 } 3448 3449 // If pass_object_size params don't match up perfectly, this isn't a valid 3450 // redeclaration. 3451 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3452 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3453 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3454 << New->getDeclName(); 3455 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3456 return true; 3457 } 3458 3459 if (getLangOpts().CPlusPlus) { 3460 // C++1z [over.load]p2 3461 // Certain function declarations cannot be overloaded: 3462 // -- Function declarations that differ only in the return type, 3463 // the exception specification, or both cannot be overloaded. 3464 3465 // Check the exception specifications match. This may recompute the type of 3466 // both Old and New if it resolved exception specifications, so grab the 3467 // types again after this. Because this updates the type, we do this before 3468 // any of the other checks below, which may update the "de facto" NewQType 3469 // but do not necessarily update the type of New. 3470 if (CheckEquivalentExceptionSpec(Old, New)) 3471 return true; 3472 OldQType = Context.getCanonicalType(Old->getType()); 3473 NewQType = Context.getCanonicalType(New->getType()); 3474 3475 // Go back to the type source info to compare the declared return types, 3476 // per C++1y [dcl.type.auto]p13: 3477 // Redeclarations or specializations of a function or function template 3478 // with a declared return type that uses a placeholder type shall also 3479 // use that placeholder, not a deduced type. 3480 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3481 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3482 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3483 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3484 OldDeclaredReturnType)) { 3485 QualType ResQT; 3486 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3487 OldDeclaredReturnType->isObjCObjectPointerType()) 3488 // FIXME: This does the wrong thing for a deduced return type. 3489 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3490 if (ResQT.isNull()) { 3491 if (New->isCXXClassMember() && New->isOutOfLine()) 3492 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3493 << New << New->getReturnTypeSourceRange(); 3494 else 3495 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3496 << New->getReturnTypeSourceRange(); 3497 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3498 << Old->getReturnTypeSourceRange(); 3499 return true; 3500 } 3501 else 3502 NewQType = ResQT; 3503 } 3504 3505 QualType OldReturnType = OldType->getReturnType(); 3506 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3507 if (OldReturnType != NewReturnType) { 3508 // If this function has a deduced return type and has already been 3509 // defined, copy the deduced value from the old declaration. 3510 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3511 if (OldAT && OldAT->isDeduced()) { 3512 New->setType( 3513 SubstAutoType(New->getType(), 3514 OldAT->isDependentType() ? Context.DependentTy 3515 : OldAT->getDeducedType())); 3516 NewQType = Context.getCanonicalType( 3517 SubstAutoType(NewQType, 3518 OldAT->isDependentType() ? Context.DependentTy 3519 : OldAT->getDeducedType())); 3520 } 3521 } 3522 3523 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3524 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3525 if (OldMethod && NewMethod) { 3526 // Preserve triviality. 3527 NewMethod->setTrivial(OldMethod->isTrivial()); 3528 3529 // MSVC allows explicit template specialization at class scope: 3530 // 2 CXXMethodDecls referring to the same function will be injected. 3531 // We don't want a redeclaration error. 3532 bool IsClassScopeExplicitSpecialization = 3533 OldMethod->isFunctionTemplateSpecialization() && 3534 NewMethod->isFunctionTemplateSpecialization(); 3535 bool isFriend = NewMethod->getFriendObjectKind(); 3536 3537 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3538 !IsClassScopeExplicitSpecialization) { 3539 // -- Member function declarations with the same name and the 3540 // same parameter types cannot be overloaded if any of them 3541 // is a static member function declaration. 3542 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3543 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3544 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3545 return true; 3546 } 3547 3548 // C++ [class.mem]p1: 3549 // [...] A member shall not be declared twice in the 3550 // member-specification, except that a nested class or member 3551 // class template can be declared and then later defined. 3552 if (!inTemplateInstantiation()) { 3553 unsigned NewDiag; 3554 if (isa<CXXConstructorDecl>(OldMethod)) 3555 NewDiag = diag::err_constructor_redeclared; 3556 else if (isa<CXXDestructorDecl>(NewMethod)) 3557 NewDiag = diag::err_destructor_redeclared; 3558 else if (isa<CXXConversionDecl>(NewMethod)) 3559 NewDiag = diag::err_conv_function_redeclared; 3560 else 3561 NewDiag = diag::err_member_redeclared; 3562 3563 Diag(New->getLocation(), NewDiag); 3564 } else { 3565 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3566 << New << New->getType(); 3567 } 3568 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3569 return true; 3570 3571 // Complain if this is an explicit declaration of a special 3572 // member that was initially declared implicitly. 3573 // 3574 // As an exception, it's okay to befriend such methods in order 3575 // to permit the implicit constructor/destructor/operator calls. 3576 } else if (OldMethod->isImplicit()) { 3577 if (isFriend) { 3578 NewMethod->setImplicit(); 3579 } else { 3580 Diag(NewMethod->getLocation(), 3581 diag::err_definition_of_implicitly_declared_member) 3582 << New << getSpecialMember(OldMethod); 3583 return true; 3584 } 3585 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3586 Diag(NewMethod->getLocation(), 3587 diag::err_definition_of_explicitly_defaulted_member) 3588 << getSpecialMember(OldMethod); 3589 return true; 3590 } 3591 } 3592 3593 // C++11 [dcl.attr.noreturn]p1: 3594 // The first declaration of a function shall specify the noreturn 3595 // attribute if any declaration of that function specifies the noreturn 3596 // attribute. 3597 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3598 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3599 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3600 Diag(Old->getFirstDecl()->getLocation(), 3601 diag::note_noreturn_missing_first_decl); 3602 } 3603 3604 // C++11 [dcl.attr.depend]p2: 3605 // The first declaration of a function shall specify the 3606 // carries_dependency attribute for its declarator-id if any declaration 3607 // of the function specifies the carries_dependency attribute. 3608 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3609 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3610 Diag(CDA->getLocation(), 3611 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3612 Diag(Old->getFirstDecl()->getLocation(), 3613 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3614 } 3615 3616 // (C++98 8.3.5p3): 3617 // All declarations for a function shall agree exactly in both the 3618 // return type and the parameter-type-list. 3619 // We also want to respect all the extended bits except noreturn. 3620 3621 // noreturn should now match unless the old type info didn't have it. 3622 QualType OldQTypeForComparison = OldQType; 3623 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3624 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3625 const FunctionType *OldTypeForComparison 3626 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3627 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3628 assert(OldQTypeForComparison.isCanonical()); 3629 } 3630 3631 if (haveIncompatibleLanguageLinkages(Old, New)) { 3632 // As a special case, retain the language linkage from previous 3633 // declarations of a friend function as an extension. 3634 // 3635 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3636 // and is useful because there's otherwise no way to specify language 3637 // linkage within class scope. 3638 // 3639 // Check cautiously as the friend object kind isn't yet complete. 3640 if (New->getFriendObjectKind() != Decl::FOK_None) { 3641 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3642 Diag(OldLocation, PrevDiag); 3643 } else { 3644 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3645 Diag(OldLocation, PrevDiag); 3646 return true; 3647 } 3648 } 3649 3650 // If the function types are compatible, merge the declarations. Ignore the 3651 // exception specifier because it was already checked above in 3652 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3653 // about incompatible types under -fms-compatibility. 3654 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3655 NewQType)) 3656 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3657 3658 // If the types are imprecise (due to dependent constructs in friends or 3659 // local extern declarations), it's OK if they differ. We'll check again 3660 // during instantiation. 3661 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3662 return false; 3663 3664 // Fall through for conflicting redeclarations and redefinitions. 3665 } 3666 3667 // C: Function types need to be compatible, not identical. This handles 3668 // duplicate function decls like "void f(int); void f(enum X);" properly. 3669 if (!getLangOpts().CPlusPlus && 3670 Context.typesAreCompatible(OldQType, NewQType)) { 3671 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3672 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3673 const FunctionProtoType *OldProto = nullptr; 3674 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3675 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3676 // The old declaration provided a function prototype, but the 3677 // new declaration does not. Merge in the prototype. 3678 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3679 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3680 NewQType = 3681 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3682 OldProto->getExtProtoInfo()); 3683 New->setType(NewQType); 3684 New->setHasInheritedPrototype(); 3685 3686 // Synthesize parameters with the same types. 3687 SmallVector<ParmVarDecl*, 16> Params; 3688 for (const auto &ParamType : OldProto->param_types()) { 3689 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3690 SourceLocation(), nullptr, 3691 ParamType, /*TInfo=*/nullptr, 3692 SC_None, nullptr); 3693 Param->setScopeInfo(0, Params.size()); 3694 Param->setImplicit(); 3695 Params.push_back(Param); 3696 } 3697 3698 New->setParams(Params); 3699 } 3700 3701 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3702 } 3703 3704 // Check if the function types are compatible when pointer size address 3705 // spaces are ignored. 3706 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3707 return false; 3708 3709 // GNU C permits a K&R definition to follow a prototype declaration 3710 // if the declared types of the parameters in the K&R definition 3711 // match the types in the prototype declaration, even when the 3712 // promoted types of the parameters from the K&R definition differ 3713 // from the types in the prototype. GCC then keeps the types from 3714 // the prototype. 3715 // 3716 // If a variadic prototype is followed by a non-variadic K&R definition, 3717 // the K&R definition becomes variadic. This is sort of an edge case, but 3718 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3719 // C99 6.9.1p8. 3720 if (!getLangOpts().CPlusPlus && 3721 Old->hasPrototype() && !New->hasPrototype() && 3722 New->getType()->getAs<FunctionProtoType>() && 3723 Old->getNumParams() == New->getNumParams()) { 3724 SmallVector<QualType, 16> ArgTypes; 3725 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3726 const FunctionProtoType *OldProto 3727 = Old->getType()->getAs<FunctionProtoType>(); 3728 const FunctionProtoType *NewProto 3729 = New->getType()->getAs<FunctionProtoType>(); 3730 3731 // Determine whether this is the GNU C extension. 3732 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3733 NewProto->getReturnType()); 3734 bool LooseCompatible = !MergedReturn.isNull(); 3735 for (unsigned Idx = 0, End = Old->getNumParams(); 3736 LooseCompatible && Idx != End; ++Idx) { 3737 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3738 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3739 if (Context.typesAreCompatible(OldParm->getType(), 3740 NewProto->getParamType(Idx))) { 3741 ArgTypes.push_back(NewParm->getType()); 3742 } else if (Context.typesAreCompatible(OldParm->getType(), 3743 NewParm->getType(), 3744 /*CompareUnqualified=*/true)) { 3745 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3746 NewProto->getParamType(Idx) }; 3747 Warnings.push_back(Warn); 3748 ArgTypes.push_back(NewParm->getType()); 3749 } else 3750 LooseCompatible = false; 3751 } 3752 3753 if (LooseCompatible) { 3754 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3755 Diag(Warnings[Warn].NewParm->getLocation(), 3756 diag::ext_param_promoted_not_compatible_with_prototype) 3757 << Warnings[Warn].PromotedType 3758 << Warnings[Warn].OldParm->getType(); 3759 if (Warnings[Warn].OldParm->getLocation().isValid()) 3760 Diag(Warnings[Warn].OldParm->getLocation(), 3761 diag::note_previous_declaration); 3762 } 3763 3764 if (MergeTypeWithOld) 3765 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3766 OldProto->getExtProtoInfo())); 3767 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3768 } 3769 3770 // Fall through to diagnose conflicting types. 3771 } 3772 3773 // A function that has already been declared has been redeclared or 3774 // defined with a different type; show an appropriate diagnostic. 3775 3776 // If the previous declaration was an implicitly-generated builtin 3777 // declaration, then at the very least we should use a specialized note. 3778 unsigned BuiltinID; 3779 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3780 // If it's actually a library-defined builtin function like 'malloc' 3781 // or 'printf', just warn about the incompatible redeclaration. 3782 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3783 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3784 Diag(OldLocation, diag::note_previous_builtin_declaration) 3785 << Old << Old->getType(); 3786 return false; 3787 } 3788 3789 PrevDiag = diag::note_previous_builtin_declaration; 3790 } 3791 3792 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3793 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3794 return true; 3795 } 3796 3797 /// Completes the merge of two function declarations that are 3798 /// known to be compatible. 3799 /// 3800 /// This routine handles the merging of attributes and other 3801 /// properties of function declarations from the old declaration to 3802 /// the new declaration, once we know that New is in fact a 3803 /// redeclaration of Old. 3804 /// 3805 /// \returns false 3806 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3807 Scope *S, bool MergeTypeWithOld) { 3808 // Merge the attributes 3809 mergeDeclAttributes(New, Old); 3810 3811 // Merge "pure" flag. 3812 if (Old->isPure()) 3813 New->setPure(); 3814 3815 // Merge "used" flag. 3816 if (Old->getMostRecentDecl()->isUsed(false)) 3817 New->setIsUsed(); 3818 3819 // Merge attributes from the parameters. These can mismatch with K&R 3820 // declarations. 3821 if (New->getNumParams() == Old->getNumParams()) 3822 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3823 ParmVarDecl *NewParam = New->getParamDecl(i); 3824 ParmVarDecl *OldParam = Old->getParamDecl(i); 3825 mergeParamDeclAttributes(NewParam, OldParam, *this); 3826 mergeParamDeclTypes(NewParam, OldParam, *this); 3827 } 3828 3829 if (getLangOpts().CPlusPlus) 3830 return MergeCXXFunctionDecl(New, Old, S); 3831 3832 // Merge the function types so the we get the composite types for the return 3833 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3834 // was visible. 3835 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3836 if (!Merged.isNull() && MergeTypeWithOld) 3837 New->setType(Merged); 3838 3839 return false; 3840 } 3841 3842 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3843 ObjCMethodDecl *oldMethod) { 3844 // Merge the attributes, including deprecated/unavailable 3845 AvailabilityMergeKind MergeKind = 3846 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3847 ? AMK_ProtocolImplementation 3848 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3849 : AMK_Override; 3850 3851 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3852 3853 // Merge attributes from the parameters. 3854 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3855 oe = oldMethod->param_end(); 3856 for (ObjCMethodDecl::param_iterator 3857 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3858 ni != ne && oi != oe; ++ni, ++oi) 3859 mergeParamDeclAttributes(*ni, *oi, *this); 3860 3861 CheckObjCMethodOverride(newMethod, oldMethod); 3862 } 3863 3864 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3865 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3866 3867 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3868 ? diag::err_redefinition_different_type 3869 : diag::err_redeclaration_different_type) 3870 << New->getDeclName() << New->getType() << Old->getType(); 3871 3872 diag::kind PrevDiag; 3873 SourceLocation OldLocation; 3874 std::tie(PrevDiag, OldLocation) 3875 = getNoteDiagForInvalidRedeclaration(Old, New); 3876 S.Diag(OldLocation, PrevDiag); 3877 New->setInvalidDecl(); 3878 } 3879 3880 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3881 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3882 /// emitting diagnostics as appropriate. 3883 /// 3884 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3885 /// to here in AddInitializerToDecl. We can't check them before the initializer 3886 /// is attached. 3887 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3888 bool MergeTypeWithOld) { 3889 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3890 return; 3891 3892 QualType MergedT; 3893 if (getLangOpts().CPlusPlus) { 3894 if (New->getType()->isUndeducedType()) { 3895 // We don't know what the new type is until the initializer is attached. 3896 return; 3897 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3898 // These could still be something that needs exception specs checked. 3899 return MergeVarDeclExceptionSpecs(New, Old); 3900 } 3901 // C++ [basic.link]p10: 3902 // [...] the types specified by all declarations referring to a given 3903 // object or function shall be identical, except that declarations for an 3904 // array object can specify array types that differ by the presence or 3905 // absence of a major array bound (8.3.4). 3906 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3907 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3908 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3909 3910 // We are merging a variable declaration New into Old. If it has an array 3911 // bound, and that bound differs from Old's bound, we should diagnose the 3912 // mismatch. 3913 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3914 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3915 PrevVD = PrevVD->getPreviousDecl()) { 3916 QualType PrevVDTy = PrevVD->getType(); 3917 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3918 continue; 3919 3920 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3921 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3922 } 3923 } 3924 3925 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3926 if (Context.hasSameType(OldArray->getElementType(), 3927 NewArray->getElementType())) 3928 MergedT = New->getType(); 3929 } 3930 // FIXME: Check visibility. New is hidden but has a complete type. If New 3931 // has no array bound, it should not inherit one from Old, if Old is not 3932 // visible. 3933 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3934 if (Context.hasSameType(OldArray->getElementType(), 3935 NewArray->getElementType())) 3936 MergedT = Old->getType(); 3937 } 3938 } 3939 else if (New->getType()->isObjCObjectPointerType() && 3940 Old->getType()->isObjCObjectPointerType()) { 3941 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3942 Old->getType()); 3943 } 3944 } else { 3945 // C 6.2.7p2: 3946 // All declarations that refer to the same object or function shall have 3947 // compatible type. 3948 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3949 } 3950 if (MergedT.isNull()) { 3951 // It's OK if we couldn't merge types if either type is dependent, for a 3952 // block-scope variable. In other cases (static data members of class 3953 // templates, variable templates, ...), we require the types to be 3954 // equivalent. 3955 // FIXME: The C++ standard doesn't say anything about this. 3956 if ((New->getType()->isDependentType() || 3957 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3958 // If the old type was dependent, we can't merge with it, so the new type 3959 // becomes dependent for now. We'll reproduce the original type when we 3960 // instantiate the TypeSourceInfo for the variable. 3961 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3962 New->setType(Context.DependentTy); 3963 return; 3964 } 3965 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3966 } 3967 3968 // Don't actually update the type on the new declaration if the old 3969 // declaration was an extern declaration in a different scope. 3970 if (MergeTypeWithOld) 3971 New->setType(MergedT); 3972 } 3973 3974 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3975 LookupResult &Previous) { 3976 // C11 6.2.7p4: 3977 // For an identifier with internal or external linkage declared 3978 // in a scope in which a prior declaration of that identifier is 3979 // visible, if the prior declaration specifies internal or 3980 // external linkage, the type of the identifier at the later 3981 // declaration becomes the composite type. 3982 // 3983 // If the variable isn't visible, we do not merge with its type. 3984 if (Previous.isShadowed()) 3985 return false; 3986 3987 if (S.getLangOpts().CPlusPlus) { 3988 // C++11 [dcl.array]p3: 3989 // If there is a preceding declaration of the entity in the same 3990 // scope in which the bound was specified, an omitted array bound 3991 // is taken to be the same as in that earlier declaration. 3992 return NewVD->isPreviousDeclInSameBlockScope() || 3993 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3994 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3995 } else { 3996 // If the old declaration was function-local, don't merge with its 3997 // type unless we're in the same function. 3998 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3999 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4000 } 4001 } 4002 4003 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4004 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4005 /// situation, merging decls or emitting diagnostics as appropriate. 4006 /// 4007 /// Tentative definition rules (C99 6.9.2p2) are checked by 4008 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4009 /// definitions here, since the initializer hasn't been attached. 4010 /// 4011 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4012 // If the new decl is already invalid, don't do any other checking. 4013 if (New->isInvalidDecl()) 4014 return; 4015 4016 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4017 return; 4018 4019 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4020 4021 // Verify the old decl was also a variable or variable template. 4022 VarDecl *Old = nullptr; 4023 VarTemplateDecl *OldTemplate = nullptr; 4024 if (Previous.isSingleResult()) { 4025 if (NewTemplate) { 4026 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4027 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4028 4029 if (auto *Shadow = 4030 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4031 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4032 return New->setInvalidDecl(); 4033 } else { 4034 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4035 4036 if (auto *Shadow = 4037 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4038 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4039 return New->setInvalidDecl(); 4040 } 4041 } 4042 if (!Old) { 4043 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4044 << New->getDeclName(); 4045 notePreviousDefinition(Previous.getRepresentativeDecl(), 4046 New->getLocation()); 4047 return New->setInvalidDecl(); 4048 } 4049 4050 // Ensure the template parameters are compatible. 4051 if (NewTemplate && 4052 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4053 OldTemplate->getTemplateParameters(), 4054 /*Complain=*/true, TPL_TemplateMatch)) 4055 return New->setInvalidDecl(); 4056 4057 // C++ [class.mem]p1: 4058 // A member shall not be declared twice in the member-specification [...] 4059 // 4060 // Here, we need only consider static data members. 4061 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4062 Diag(New->getLocation(), diag::err_duplicate_member) 4063 << New->getIdentifier(); 4064 Diag(Old->getLocation(), diag::note_previous_declaration); 4065 New->setInvalidDecl(); 4066 } 4067 4068 mergeDeclAttributes(New, Old); 4069 // Warn if an already-declared variable is made a weak_import in a subsequent 4070 // declaration 4071 if (New->hasAttr<WeakImportAttr>() && 4072 Old->getStorageClass() == SC_None && 4073 !Old->hasAttr<WeakImportAttr>()) { 4074 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4075 notePreviousDefinition(Old, New->getLocation()); 4076 // Remove weak_import attribute on new declaration. 4077 New->dropAttr<WeakImportAttr>(); 4078 } 4079 4080 if (New->hasAttr<InternalLinkageAttr>() && 4081 !Old->hasAttr<InternalLinkageAttr>()) { 4082 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4083 << New->getDeclName(); 4084 notePreviousDefinition(Old, New->getLocation()); 4085 New->dropAttr<InternalLinkageAttr>(); 4086 } 4087 4088 // Merge the types. 4089 VarDecl *MostRecent = Old->getMostRecentDecl(); 4090 if (MostRecent != Old) { 4091 MergeVarDeclTypes(New, MostRecent, 4092 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4093 if (New->isInvalidDecl()) 4094 return; 4095 } 4096 4097 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4098 if (New->isInvalidDecl()) 4099 return; 4100 4101 diag::kind PrevDiag; 4102 SourceLocation OldLocation; 4103 std::tie(PrevDiag, OldLocation) = 4104 getNoteDiagForInvalidRedeclaration(Old, New); 4105 4106 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4107 if (New->getStorageClass() == SC_Static && 4108 !New->isStaticDataMember() && 4109 Old->hasExternalFormalLinkage()) { 4110 if (getLangOpts().MicrosoftExt) { 4111 Diag(New->getLocation(), diag::ext_static_non_static) 4112 << New->getDeclName(); 4113 Diag(OldLocation, PrevDiag); 4114 } else { 4115 Diag(New->getLocation(), diag::err_static_non_static) 4116 << New->getDeclName(); 4117 Diag(OldLocation, PrevDiag); 4118 return New->setInvalidDecl(); 4119 } 4120 } 4121 // C99 6.2.2p4: 4122 // For an identifier declared with the storage-class specifier 4123 // extern in a scope in which a prior declaration of that 4124 // identifier is visible,23) if the prior declaration specifies 4125 // internal or external linkage, the linkage of the identifier at 4126 // the later declaration is the same as the linkage specified at 4127 // the prior declaration. If no prior declaration is visible, or 4128 // if the prior declaration specifies no linkage, then the 4129 // identifier has external linkage. 4130 if (New->hasExternalStorage() && Old->hasLinkage()) 4131 /* Okay */; 4132 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4133 !New->isStaticDataMember() && 4134 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4135 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4136 Diag(OldLocation, PrevDiag); 4137 return New->setInvalidDecl(); 4138 } 4139 4140 // Check if extern is followed by non-extern and vice-versa. 4141 if (New->hasExternalStorage() && 4142 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4143 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4144 Diag(OldLocation, PrevDiag); 4145 return New->setInvalidDecl(); 4146 } 4147 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4148 !New->hasExternalStorage()) { 4149 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4150 Diag(OldLocation, PrevDiag); 4151 return New->setInvalidDecl(); 4152 } 4153 4154 if (CheckRedeclarationModuleOwnership(New, Old)) 4155 return; 4156 4157 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4158 4159 // FIXME: The test for external storage here seems wrong? We still 4160 // need to check for mismatches. 4161 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4162 // Don't complain about out-of-line definitions of static members. 4163 !(Old->getLexicalDeclContext()->isRecord() && 4164 !New->getLexicalDeclContext()->isRecord())) { 4165 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4166 Diag(OldLocation, PrevDiag); 4167 return New->setInvalidDecl(); 4168 } 4169 4170 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4171 if (VarDecl *Def = Old->getDefinition()) { 4172 // C++1z [dcl.fcn.spec]p4: 4173 // If the definition of a variable appears in a translation unit before 4174 // its first declaration as inline, the program is ill-formed. 4175 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4176 Diag(Def->getLocation(), diag::note_previous_definition); 4177 } 4178 } 4179 4180 // If this redeclaration makes the variable inline, we may need to add it to 4181 // UndefinedButUsed. 4182 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4183 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4184 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4185 SourceLocation())); 4186 4187 if (New->getTLSKind() != Old->getTLSKind()) { 4188 if (!Old->getTLSKind()) { 4189 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4190 Diag(OldLocation, PrevDiag); 4191 } else if (!New->getTLSKind()) { 4192 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4193 Diag(OldLocation, PrevDiag); 4194 } else { 4195 // Do not allow redeclaration to change the variable between requiring 4196 // static and dynamic initialization. 4197 // FIXME: GCC allows this, but uses the TLS keyword on the first 4198 // declaration to determine the kind. Do we need to be compatible here? 4199 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4200 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4201 Diag(OldLocation, PrevDiag); 4202 } 4203 } 4204 4205 // C++ doesn't have tentative definitions, so go right ahead and check here. 4206 if (getLangOpts().CPlusPlus && 4207 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4208 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4209 Old->getCanonicalDecl()->isConstexpr()) { 4210 // This definition won't be a definition any more once it's been merged. 4211 Diag(New->getLocation(), 4212 diag::warn_deprecated_redundant_constexpr_static_def); 4213 } else if (VarDecl *Def = Old->getDefinition()) { 4214 if (checkVarDeclRedefinition(Def, New)) 4215 return; 4216 } 4217 } 4218 4219 if (haveIncompatibleLanguageLinkages(Old, New)) { 4220 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4221 Diag(OldLocation, PrevDiag); 4222 New->setInvalidDecl(); 4223 return; 4224 } 4225 4226 // Merge "used" flag. 4227 if (Old->getMostRecentDecl()->isUsed(false)) 4228 New->setIsUsed(); 4229 4230 // Keep a chain of previous declarations. 4231 New->setPreviousDecl(Old); 4232 if (NewTemplate) 4233 NewTemplate->setPreviousDecl(OldTemplate); 4234 adjustDeclContextForDeclaratorDecl(New, Old); 4235 4236 // Inherit access appropriately. 4237 New->setAccess(Old->getAccess()); 4238 if (NewTemplate) 4239 NewTemplate->setAccess(New->getAccess()); 4240 4241 if (Old->isInline()) 4242 New->setImplicitlyInline(); 4243 } 4244 4245 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4246 SourceManager &SrcMgr = getSourceManager(); 4247 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4248 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4249 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4250 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4251 auto &HSI = PP.getHeaderSearchInfo(); 4252 StringRef HdrFilename = 4253 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4254 4255 auto noteFromModuleOrInclude = [&](Module *Mod, 4256 SourceLocation IncLoc) -> bool { 4257 // Redefinition errors with modules are common with non modular mapped 4258 // headers, example: a non-modular header H in module A that also gets 4259 // included directly in a TU. Pointing twice to the same header/definition 4260 // is confusing, try to get better diagnostics when modules is on. 4261 if (IncLoc.isValid()) { 4262 if (Mod) { 4263 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4264 << HdrFilename.str() << Mod->getFullModuleName(); 4265 if (!Mod->DefinitionLoc.isInvalid()) 4266 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4267 << Mod->getFullModuleName(); 4268 } else { 4269 Diag(IncLoc, diag::note_redefinition_include_same_file) 4270 << HdrFilename.str(); 4271 } 4272 return true; 4273 } 4274 4275 return false; 4276 }; 4277 4278 // Is it the same file and same offset? Provide more information on why 4279 // this leads to a redefinition error. 4280 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4281 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4282 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4283 bool EmittedDiag = 4284 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4285 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4286 4287 // If the header has no guards, emit a note suggesting one. 4288 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4289 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4290 4291 if (EmittedDiag) 4292 return; 4293 } 4294 4295 // Redefinition coming from different files or couldn't do better above. 4296 if (Old->getLocation().isValid()) 4297 Diag(Old->getLocation(), diag::note_previous_definition); 4298 } 4299 4300 /// We've just determined that \p Old and \p New both appear to be definitions 4301 /// of the same variable. Either diagnose or fix the problem. 4302 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4303 if (!hasVisibleDefinition(Old) && 4304 (New->getFormalLinkage() == InternalLinkage || 4305 New->isInline() || 4306 New->getDescribedVarTemplate() || 4307 New->getNumTemplateParameterLists() || 4308 New->getDeclContext()->isDependentContext())) { 4309 // The previous definition is hidden, and multiple definitions are 4310 // permitted (in separate TUs). Demote this to a declaration. 4311 New->demoteThisDefinitionToDeclaration(); 4312 4313 // Make the canonical definition visible. 4314 if (auto *OldTD = Old->getDescribedVarTemplate()) 4315 makeMergedDefinitionVisible(OldTD); 4316 makeMergedDefinitionVisible(Old); 4317 return false; 4318 } else { 4319 Diag(New->getLocation(), diag::err_redefinition) << New; 4320 notePreviousDefinition(Old, New->getLocation()); 4321 New->setInvalidDecl(); 4322 return true; 4323 } 4324 } 4325 4326 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4327 /// no declarator (e.g. "struct foo;") is parsed. 4328 Decl * 4329 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4330 RecordDecl *&AnonRecord) { 4331 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4332 AnonRecord); 4333 } 4334 4335 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4336 // disambiguate entities defined in different scopes. 4337 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4338 // compatibility. 4339 // We will pick our mangling number depending on which version of MSVC is being 4340 // targeted. 4341 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4342 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4343 ? S->getMSCurManglingNumber() 4344 : S->getMSLastManglingNumber(); 4345 } 4346 4347 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4348 if (!Context.getLangOpts().CPlusPlus) 4349 return; 4350 4351 if (isa<CXXRecordDecl>(Tag->getParent())) { 4352 // If this tag is the direct child of a class, number it if 4353 // it is anonymous. 4354 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4355 return; 4356 MangleNumberingContext &MCtx = 4357 Context.getManglingNumberContext(Tag->getParent()); 4358 Context.setManglingNumber( 4359 Tag, MCtx.getManglingNumber( 4360 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4361 return; 4362 } 4363 4364 // If this tag isn't a direct child of a class, number it if it is local. 4365 MangleNumberingContext *MCtx; 4366 Decl *ManglingContextDecl; 4367 std::tie(MCtx, ManglingContextDecl) = 4368 getCurrentMangleNumberContext(Tag->getDeclContext()); 4369 if (MCtx) { 4370 Context.setManglingNumber( 4371 Tag, MCtx->getManglingNumber( 4372 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4373 } 4374 } 4375 4376 namespace { 4377 struct NonCLikeKind { 4378 enum { 4379 None, 4380 BaseClass, 4381 DefaultMemberInit, 4382 Lambda, 4383 Friend, 4384 OtherMember, 4385 Invalid, 4386 } Kind = None; 4387 SourceRange Range; 4388 4389 explicit operator bool() { return Kind != None; } 4390 }; 4391 } 4392 4393 /// Determine whether a class is C-like, according to the rules of C++ 4394 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4395 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4396 if (RD->isInvalidDecl()) 4397 return {NonCLikeKind::Invalid, {}}; 4398 4399 // C++ [dcl.typedef]p9: [P1766R1] 4400 // An unnamed class with a typedef name for linkage purposes shall not 4401 // 4402 // -- have any base classes 4403 if (RD->getNumBases()) 4404 return {NonCLikeKind::BaseClass, 4405 SourceRange(RD->bases_begin()->getBeginLoc(), 4406 RD->bases_end()[-1].getEndLoc())}; 4407 bool Invalid = false; 4408 for (Decl *D : RD->decls()) { 4409 // Don't complain about things we already diagnosed. 4410 if (D->isInvalidDecl()) { 4411 Invalid = true; 4412 continue; 4413 } 4414 4415 // -- have any [...] default member initializers 4416 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4417 if (FD->hasInClassInitializer()) { 4418 auto *Init = FD->getInClassInitializer(); 4419 return {NonCLikeKind::DefaultMemberInit, 4420 Init ? Init->getSourceRange() : D->getSourceRange()}; 4421 } 4422 continue; 4423 } 4424 4425 // FIXME: We don't allow friend declarations. This violates the wording of 4426 // P1766, but not the intent. 4427 if (isa<FriendDecl>(D)) 4428 return {NonCLikeKind::Friend, D->getSourceRange()}; 4429 4430 // -- declare any members other than non-static data members, member 4431 // enumerations, or member classes, 4432 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4433 isa<EnumDecl>(D)) 4434 continue; 4435 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4436 if (!MemberRD) { 4437 if (D->isImplicit()) 4438 continue; 4439 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4440 } 4441 4442 // -- contain a lambda-expression, 4443 if (MemberRD->isLambda()) 4444 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4445 4446 // and all member classes shall also satisfy these requirements 4447 // (recursively). 4448 if (MemberRD->isThisDeclarationADefinition()) { 4449 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4450 return Kind; 4451 } 4452 } 4453 4454 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4455 } 4456 4457 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4458 TypedefNameDecl *NewTD) { 4459 if (TagFromDeclSpec->isInvalidDecl()) 4460 return; 4461 4462 // Do nothing if the tag already has a name for linkage purposes. 4463 if (TagFromDeclSpec->hasNameForLinkage()) 4464 return; 4465 4466 // A well-formed anonymous tag must always be a TUK_Definition. 4467 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4468 4469 // The type must match the tag exactly; no qualifiers allowed. 4470 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4471 Context.getTagDeclType(TagFromDeclSpec))) { 4472 if (getLangOpts().CPlusPlus) 4473 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4474 return; 4475 } 4476 4477 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4478 // An unnamed class with a typedef name for linkage purposes shall [be 4479 // C-like]. 4480 // 4481 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4482 // shouldn't happen, but there are constructs that the language rule doesn't 4483 // disallow for which we can't reasonably avoid computing linkage early. 4484 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4485 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4486 : NonCLikeKind(); 4487 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4488 if (NonCLike || ChangesLinkage) { 4489 if (NonCLike.Kind == NonCLikeKind::Invalid) 4490 return; 4491 4492 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4493 if (ChangesLinkage) { 4494 // If the linkage changes, we can't accept this as an extension. 4495 if (NonCLike.Kind == NonCLikeKind::None) 4496 DiagID = diag::err_typedef_changes_linkage; 4497 else 4498 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4499 } 4500 4501 SourceLocation FixitLoc = 4502 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4503 llvm::SmallString<40> TextToInsert; 4504 TextToInsert += ' '; 4505 TextToInsert += NewTD->getIdentifier()->getName(); 4506 4507 Diag(FixitLoc, DiagID) 4508 << isa<TypeAliasDecl>(NewTD) 4509 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4510 if (NonCLike.Kind != NonCLikeKind::None) { 4511 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4512 << NonCLike.Kind - 1 << NonCLike.Range; 4513 } 4514 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4515 << NewTD << isa<TypeAliasDecl>(NewTD); 4516 4517 if (ChangesLinkage) 4518 return; 4519 } 4520 4521 // Otherwise, set this as the anon-decl typedef for the tag. 4522 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4523 } 4524 4525 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4526 switch (T) { 4527 case DeclSpec::TST_class: 4528 return 0; 4529 case DeclSpec::TST_struct: 4530 return 1; 4531 case DeclSpec::TST_interface: 4532 return 2; 4533 case DeclSpec::TST_union: 4534 return 3; 4535 case DeclSpec::TST_enum: 4536 return 4; 4537 default: 4538 llvm_unreachable("unexpected type specifier"); 4539 } 4540 } 4541 4542 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4543 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4544 /// parameters to cope with template friend declarations. 4545 Decl * 4546 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4547 MultiTemplateParamsArg TemplateParams, 4548 bool IsExplicitInstantiation, 4549 RecordDecl *&AnonRecord) { 4550 Decl *TagD = nullptr; 4551 TagDecl *Tag = nullptr; 4552 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4553 DS.getTypeSpecType() == DeclSpec::TST_struct || 4554 DS.getTypeSpecType() == DeclSpec::TST_interface || 4555 DS.getTypeSpecType() == DeclSpec::TST_union || 4556 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4557 TagD = DS.getRepAsDecl(); 4558 4559 if (!TagD) // We probably had an error 4560 return nullptr; 4561 4562 // Note that the above type specs guarantee that the 4563 // type rep is a Decl, whereas in many of the others 4564 // it's a Type. 4565 if (isa<TagDecl>(TagD)) 4566 Tag = cast<TagDecl>(TagD); 4567 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4568 Tag = CTD->getTemplatedDecl(); 4569 } 4570 4571 if (Tag) { 4572 handleTagNumbering(Tag, S); 4573 Tag->setFreeStanding(); 4574 if (Tag->isInvalidDecl()) 4575 return Tag; 4576 } 4577 4578 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4579 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4580 // or incomplete types shall not be restrict-qualified." 4581 if (TypeQuals & DeclSpec::TQ_restrict) 4582 Diag(DS.getRestrictSpecLoc(), 4583 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4584 << DS.getSourceRange(); 4585 } 4586 4587 if (DS.isInlineSpecified()) 4588 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4589 << getLangOpts().CPlusPlus17; 4590 4591 if (DS.hasConstexprSpecifier()) { 4592 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4593 // and definitions of functions and variables. 4594 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4595 // the declaration of a function or function template 4596 if (Tag) 4597 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4598 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4599 << DS.getConstexprSpecifier(); 4600 else 4601 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4602 << DS.getConstexprSpecifier(); 4603 // Don't emit warnings after this error. 4604 return TagD; 4605 } 4606 4607 DiagnoseFunctionSpecifiers(DS); 4608 4609 if (DS.isFriendSpecified()) { 4610 // If we're dealing with a decl but not a TagDecl, assume that 4611 // whatever routines created it handled the friendship aspect. 4612 if (TagD && !Tag) 4613 return nullptr; 4614 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4615 } 4616 4617 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4618 bool IsExplicitSpecialization = 4619 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4620 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4621 !IsExplicitInstantiation && !IsExplicitSpecialization && 4622 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4623 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4624 // nested-name-specifier unless it is an explicit instantiation 4625 // or an explicit specialization. 4626 // 4627 // FIXME: We allow class template partial specializations here too, per the 4628 // obvious intent of DR1819. 4629 // 4630 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4631 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4632 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4633 return nullptr; 4634 } 4635 4636 // Track whether this decl-specifier declares anything. 4637 bool DeclaresAnything = true; 4638 4639 // Handle anonymous struct definitions. 4640 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4641 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4642 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4643 if (getLangOpts().CPlusPlus || 4644 Record->getDeclContext()->isRecord()) { 4645 // If CurContext is a DeclContext that can contain statements, 4646 // RecursiveASTVisitor won't visit the decls that 4647 // BuildAnonymousStructOrUnion() will put into CurContext. 4648 // Also store them here so that they can be part of the 4649 // DeclStmt that gets created in this case. 4650 // FIXME: Also return the IndirectFieldDecls created by 4651 // BuildAnonymousStructOr union, for the same reason? 4652 if (CurContext->isFunctionOrMethod()) 4653 AnonRecord = Record; 4654 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4655 Context.getPrintingPolicy()); 4656 } 4657 4658 DeclaresAnything = false; 4659 } 4660 } 4661 4662 // C11 6.7.2.1p2: 4663 // A struct-declaration that does not declare an anonymous structure or 4664 // anonymous union shall contain a struct-declarator-list. 4665 // 4666 // This rule also existed in C89 and C99; the grammar for struct-declaration 4667 // did not permit a struct-declaration without a struct-declarator-list. 4668 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4669 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4670 // Check for Microsoft C extension: anonymous struct/union member. 4671 // Handle 2 kinds of anonymous struct/union: 4672 // struct STRUCT; 4673 // union UNION; 4674 // and 4675 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4676 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4677 if ((Tag && Tag->getDeclName()) || 4678 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4679 RecordDecl *Record = nullptr; 4680 if (Tag) 4681 Record = dyn_cast<RecordDecl>(Tag); 4682 else if (const RecordType *RT = 4683 DS.getRepAsType().get()->getAsStructureType()) 4684 Record = RT->getDecl(); 4685 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4686 Record = UT->getDecl(); 4687 4688 if (Record && getLangOpts().MicrosoftExt) { 4689 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4690 << Record->isUnion() << DS.getSourceRange(); 4691 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4692 } 4693 4694 DeclaresAnything = false; 4695 } 4696 } 4697 4698 // Skip all the checks below if we have a type error. 4699 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4700 (TagD && TagD->isInvalidDecl())) 4701 return TagD; 4702 4703 if (getLangOpts().CPlusPlus && 4704 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4705 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4706 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4707 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4708 DeclaresAnything = false; 4709 4710 if (!DS.isMissingDeclaratorOk()) { 4711 // Customize diagnostic for a typedef missing a name. 4712 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4713 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4714 << DS.getSourceRange(); 4715 else 4716 DeclaresAnything = false; 4717 } 4718 4719 if (DS.isModulePrivateSpecified() && 4720 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4721 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4722 << Tag->getTagKind() 4723 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4724 4725 ActOnDocumentableDecl(TagD); 4726 4727 // C 6.7/2: 4728 // A declaration [...] shall declare at least a declarator [...], a tag, 4729 // or the members of an enumeration. 4730 // C++ [dcl.dcl]p3: 4731 // [If there are no declarators], and except for the declaration of an 4732 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4733 // names into the program, or shall redeclare a name introduced by a 4734 // previous declaration. 4735 if (!DeclaresAnything) { 4736 // In C, we allow this as a (popular) extension / bug. Don't bother 4737 // producing further diagnostics for redundant qualifiers after this. 4738 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4739 ? diag::err_no_declarators 4740 : diag::ext_no_declarators) 4741 << DS.getSourceRange(); 4742 return TagD; 4743 } 4744 4745 // C++ [dcl.stc]p1: 4746 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4747 // init-declarator-list of the declaration shall not be empty. 4748 // C++ [dcl.fct.spec]p1: 4749 // If a cv-qualifier appears in a decl-specifier-seq, the 4750 // init-declarator-list of the declaration shall not be empty. 4751 // 4752 // Spurious qualifiers here appear to be valid in C. 4753 unsigned DiagID = diag::warn_standalone_specifier; 4754 if (getLangOpts().CPlusPlus) 4755 DiagID = diag::ext_standalone_specifier; 4756 4757 // Note that a linkage-specification sets a storage class, but 4758 // 'extern "C" struct foo;' is actually valid and not theoretically 4759 // useless. 4760 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4761 if (SCS == DeclSpec::SCS_mutable) 4762 // Since mutable is not a viable storage class specifier in C, there is 4763 // no reason to treat it as an extension. Instead, diagnose as an error. 4764 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4765 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4766 Diag(DS.getStorageClassSpecLoc(), DiagID) 4767 << DeclSpec::getSpecifierName(SCS); 4768 } 4769 4770 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4771 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4772 << DeclSpec::getSpecifierName(TSCS); 4773 if (DS.getTypeQualifiers()) { 4774 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4775 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4776 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4777 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4778 // Restrict is covered above. 4779 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4780 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4781 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4782 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4783 } 4784 4785 // Warn about ignored type attributes, for example: 4786 // __attribute__((aligned)) struct A; 4787 // Attributes should be placed after tag to apply to type declaration. 4788 if (!DS.getAttributes().empty()) { 4789 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4790 if (TypeSpecType == DeclSpec::TST_class || 4791 TypeSpecType == DeclSpec::TST_struct || 4792 TypeSpecType == DeclSpec::TST_interface || 4793 TypeSpecType == DeclSpec::TST_union || 4794 TypeSpecType == DeclSpec::TST_enum) { 4795 for (const ParsedAttr &AL : DS.getAttributes()) 4796 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4797 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4798 } 4799 } 4800 4801 return TagD; 4802 } 4803 4804 /// We are trying to inject an anonymous member into the given scope; 4805 /// check if there's an existing declaration that can't be overloaded. 4806 /// 4807 /// \return true if this is a forbidden redeclaration 4808 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4809 Scope *S, 4810 DeclContext *Owner, 4811 DeclarationName Name, 4812 SourceLocation NameLoc, 4813 bool IsUnion) { 4814 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4815 Sema::ForVisibleRedeclaration); 4816 if (!SemaRef.LookupName(R, S)) return false; 4817 4818 // Pick a representative declaration. 4819 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4820 assert(PrevDecl && "Expected a non-null Decl"); 4821 4822 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4823 return false; 4824 4825 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4826 << IsUnion << Name; 4827 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4828 4829 return true; 4830 } 4831 4832 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4833 /// anonymous struct or union AnonRecord into the owning context Owner 4834 /// and scope S. This routine will be invoked just after we realize 4835 /// that an unnamed union or struct is actually an anonymous union or 4836 /// struct, e.g., 4837 /// 4838 /// @code 4839 /// union { 4840 /// int i; 4841 /// float f; 4842 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4843 /// // f into the surrounding scope.x 4844 /// @endcode 4845 /// 4846 /// This routine is recursive, injecting the names of nested anonymous 4847 /// structs/unions into the owning context and scope as well. 4848 static bool 4849 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4850 RecordDecl *AnonRecord, AccessSpecifier AS, 4851 SmallVectorImpl<NamedDecl *> &Chaining) { 4852 bool Invalid = false; 4853 4854 // Look every FieldDecl and IndirectFieldDecl with a name. 4855 for (auto *D : AnonRecord->decls()) { 4856 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4857 cast<NamedDecl>(D)->getDeclName()) { 4858 ValueDecl *VD = cast<ValueDecl>(D); 4859 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4860 VD->getLocation(), 4861 AnonRecord->isUnion())) { 4862 // C++ [class.union]p2: 4863 // The names of the members of an anonymous union shall be 4864 // distinct from the names of any other entity in the 4865 // scope in which the anonymous union is declared. 4866 Invalid = true; 4867 } else { 4868 // C++ [class.union]p2: 4869 // For the purpose of name lookup, after the anonymous union 4870 // definition, the members of the anonymous union are 4871 // considered to have been defined in the scope in which the 4872 // anonymous union is declared. 4873 unsigned OldChainingSize = Chaining.size(); 4874 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4875 Chaining.append(IF->chain_begin(), IF->chain_end()); 4876 else 4877 Chaining.push_back(VD); 4878 4879 assert(Chaining.size() >= 2); 4880 NamedDecl **NamedChain = 4881 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4882 for (unsigned i = 0; i < Chaining.size(); i++) 4883 NamedChain[i] = Chaining[i]; 4884 4885 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4886 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4887 VD->getType(), {NamedChain, Chaining.size()}); 4888 4889 for (const auto *Attr : VD->attrs()) 4890 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4891 4892 IndirectField->setAccess(AS); 4893 IndirectField->setImplicit(); 4894 SemaRef.PushOnScopeChains(IndirectField, S); 4895 4896 // That includes picking up the appropriate access specifier. 4897 if (AS != AS_none) IndirectField->setAccess(AS); 4898 4899 Chaining.resize(OldChainingSize); 4900 } 4901 } 4902 } 4903 4904 return Invalid; 4905 } 4906 4907 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4908 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4909 /// illegal input values are mapped to SC_None. 4910 static StorageClass 4911 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4912 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4913 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4914 "Parser allowed 'typedef' as storage class VarDecl."); 4915 switch (StorageClassSpec) { 4916 case DeclSpec::SCS_unspecified: return SC_None; 4917 case DeclSpec::SCS_extern: 4918 if (DS.isExternInLinkageSpec()) 4919 return SC_None; 4920 return SC_Extern; 4921 case DeclSpec::SCS_static: return SC_Static; 4922 case DeclSpec::SCS_auto: return SC_Auto; 4923 case DeclSpec::SCS_register: return SC_Register; 4924 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4925 // Illegal SCSs map to None: error reporting is up to the caller. 4926 case DeclSpec::SCS_mutable: // Fall through. 4927 case DeclSpec::SCS_typedef: return SC_None; 4928 } 4929 llvm_unreachable("unknown storage class specifier"); 4930 } 4931 4932 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4933 assert(Record->hasInClassInitializer()); 4934 4935 for (const auto *I : Record->decls()) { 4936 const auto *FD = dyn_cast<FieldDecl>(I); 4937 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4938 FD = IFD->getAnonField(); 4939 if (FD && FD->hasInClassInitializer()) 4940 return FD->getLocation(); 4941 } 4942 4943 llvm_unreachable("couldn't find in-class initializer"); 4944 } 4945 4946 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4947 SourceLocation DefaultInitLoc) { 4948 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4949 return; 4950 4951 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4952 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4953 } 4954 4955 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4956 CXXRecordDecl *AnonUnion) { 4957 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4958 return; 4959 4960 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4961 } 4962 4963 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4964 /// anonymous structure or union. Anonymous unions are a C++ feature 4965 /// (C++ [class.union]) and a C11 feature; anonymous structures 4966 /// are a C11 feature and GNU C++ extension. 4967 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4968 AccessSpecifier AS, 4969 RecordDecl *Record, 4970 const PrintingPolicy &Policy) { 4971 DeclContext *Owner = Record->getDeclContext(); 4972 4973 // Diagnose whether this anonymous struct/union is an extension. 4974 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4975 Diag(Record->getLocation(), diag::ext_anonymous_union); 4976 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4977 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4978 else if (!Record->isUnion() && !getLangOpts().C11) 4979 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4980 4981 // C and C++ require different kinds of checks for anonymous 4982 // structs/unions. 4983 bool Invalid = false; 4984 if (getLangOpts().CPlusPlus) { 4985 const char *PrevSpec = nullptr; 4986 if (Record->isUnion()) { 4987 // C++ [class.union]p6: 4988 // C++17 [class.union.anon]p2: 4989 // Anonymous unions declared in a named namespace or in the 4990 // global namespace shall be declared static. 4991 unsigned DiagID; 4992 DeclContext *OwnerScope = Owner->getRedeclContext(); 4993 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4994 (OwnerScope->isTranslationUnit() || 4995 (OwnerScope->isNamespace() && 4996 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4997 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4998 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4999 5000 // Recover by adding 'static'. 5001 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5002 PrevSpec, DiagID, Policy); 5003 } 5004 // C++ [class.union]p6: 5005 // A storage class is not allowed in a declaration of an 5006 // anonymous union in a class scope. 5007 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5008 isa<RecordDecl>(Owner)) { 5009 Diag(DS.getStorageClassSpecLoc(), 5010 diag::err_anonymous_union_with_storage_spec) 5011 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5012 5013 // Recover by removing the storage specifier. 5014 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5015 SourceLocation(), 5016 PrevSpec, DiagID, Context.getPrintingPolicy()); 5017 } 5018 } 5019 5020 // Ignore const/volatile/restrict qualifiers. 5021 if (DS.getTypeQualifiers()) { 5022 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5023 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5024 << Record->isUnion() << "const" 5025 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5026 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5027 Diag(DS.getVolatileSpecLoc(), 5028 diag::ext_anonymous_struct_union_qualified) 5029 << Record->isUnion() << "volatile" 5030 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5031 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5032 Diag(DS.getRestrictSpecLoc(), 5033 diag::ext_anonymous_struct_union_qualified) 5034 << Record->isUnion() << "restrict" 5035 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5036 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5037 Diag(DS.getAtomicSpecLoc(), 5038 diag::ext_anonymous_struct_union_qualified) 5039 << Record->isUnion() << "_Atomic" 5040 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5041 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5042 Diag(DS.getUnalignedSpecLoc(), 5043 diag::ext_anonymous_struct_union_qualified) 5044 << Record->isUnion() << "__unaligned" 5045 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5046 5047 DS.ClearTypeQualifiers(); 5048 } 5049 5050 // C++ [class.union]p2: 5051 // The member-specification of an anonymous union shall only 5052 // define non-static data members. [Note: nested types and 5053 // functions cannot be declared within an anonymous union. ] 5054 for (auto *Mem : Record->decls()) { 5055 // Ignore invalid declarations; we already diagnosed them. 5056 if (Mem->isInvalidDecl()) 5057 continue; 5058 5059 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5060 // C++ [class.union]p3: 5061 // An anonymous union shall not have private or protected 5062 // members (clause 11). 5063 assert(FD->getAccess() != AS_none); 5064 if (FD->getAccess() != AS_public) { 5065 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5066 << Record->isUnion() << (FD->getAccess() == AS_protected); 5067 Invalid = true; 5068 } 5069 5070 // C++ [class.union]p1 5071 // An object of a class with a non-trivial constructor, a non-trivial 5072 // copy constructor, a non-trivial destructor, or a non-trivial copy 5073 // assignment operator cannot be a member of a union, nor can an 5074 // array of such objects. 5075 if (CheckNontrivialField(FD)) 5076 Invalid = true; 5077 } else if (Mem->isImplicit()) { 5078 // Any implicit members are fine. 5079 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5080 // This is a type that showed up in an 5081 // elaborated-type-specifier inside the anonymous struct or 5082 // union, but which actually declares a type outside of the 5083 // anonymous struct or union. It's okay. 5084 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5085 if (!MemRecord->isAnonymousStructOrUnion() && 5086 MemRecord->getDeclName()) { 5087 // Visual C++ allows type definition in anonymous struct or union. 5088 if (getLangOpts().MicrosoftExt) 5089 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5090 << Record->isUnion(); 5091 else { 5092 // This is a nested type declaration. 5093 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5094 << Record->isUnion(); 5095 Invalid = true; 5096 } 5097 } else { 5098 // This is an anonymous type definition within another anonymous type. 5099 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5100 // not part of standard C++. 5101 Diag(MemRecord->getLocation(), 5102 diag::ext_anonymous_record_with_anonymous_type) 5103 << Record->isUnion(); 5104 } 5105 } else if (isa<AccessSpecDecl>(Mem)) { 5106 // Any access specifier is fine. 5107 } else if (isa<StaticAssertDecl>(Mem)) { 5108 // In C++1z, static_assert declarations are also fine. 5109 } else { 5110 // We have something that isn't a non-static data 5111 // member. Complain about it. 5112 unsigned DK = diag::err_anonymous_record_bad_member; 5113 if (isa<TypeDecl>(Mem)) 5114 DK = diag::err_anonymous_record_with_type; 5115 else if (isa<FunctionDecl>(Mem)) 5116 DK = diag::err_anonymous_record_with_function; 5117 else if (isa<VarDecl>(Mem)) 5118 DK = diag::err_anonymous_record_with_static; 5119 5120 // Visual C++ allows type definition in anonymous struct or union. 5121 if (getLangOpts().MicrosoftExt && 5122 DK == diag::err_anonymous_record_with_type) 5123 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5124 << Record->isUnion(); 5125 else { 5126 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5127 Invalid = true; 5128 } 5129 } 5130 } 5131 5132 // C++11 [class.union]p8 (DR1460): 5133 // At most one variant member of a union may have a 5134 // brace-or-equal-initializer. 5135 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5136 Owner->isRecord()) 5137 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5138 cast<CXXRecordDecl>(Record)); 5139 } 5140 5141 if (!Record->isUnion() && !Owner->isRecord()) { 5142 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5143 << getLangOpts().CPlusPlus; 5144 Invalid = true; 5145 } 5146 5147 // C++ [dcl.dcl]p3: 5148 // [If there are no declarators], and except for the declaration of an 5149 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5150 // names into the program 5151 // C++ [class.mem]p2: 5152 // each such member-declaration shall either declare at least one member 5153 // name of the class or declare at least one unnamed bit-field 5154 // 5155 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5156 if (getLangOpts().CPlusPlus && Record->field_empty()) 5157 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5158 5159 // Mock up a declarator. 5160 Declarator Dc(DS, DeclaratorContext::MemberContext); 5161 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5162 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5163 5164 // Create a declaration for this anonymous struct/union. 5165 NamedDecl *Anon = nullptr; 5166 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5167 Anon = FieldDecl::Create( 5168 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5169 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5170 /*BitWidth=*/nullptr, /*Mutable=*/false, 5171 /*InitStyle=*/ICIS_NoInit); 5172 Anon->setAccess(AS); 5173 ProcessDeclAttributes(S, Anon, Dc); 5174 5175 if (getLangOpts().CPlusPlus) 5176 FieldCollector->Add(cast<FieldDecl>(Anon)); 5177 } else { 5178 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5179 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5180 if (SCSpec == DeclSpec::SCS_mutable) { 5181 // mutable can only appear on non-static class members, so it's always 5182 // an error here 5183 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5184 Invalid = true; 5185 SC = SC_None; 5186 } 5187 5188 assert(DS.getAttributes().empty() && "No attribute expected"); 5189 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5190 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5191 Context.getTypeDeclType(Record), TInfo, SC); 5192 5193 // Default-initialize the implicit variable. This initialization will be 5194 // trivial in almost all cases, except if a union member has an in-class 5195 // initializer: 5196 // union { int n = 0; }; 5197 ActOnUninitializedDecl(Anon); 5198 } 5199 Anon->setImplicit(); 5200 5201 // Mark this as an anonymous struct/union type. 5202 Record->setAnonymousStructOrUnion(true); 5203 5204 // Add the anonymous struct/union object to the current 5205 // context. We'll be referencing this object when we refer to one of 5206 // its members. 5207 Owner->addDecl(Anon); 5208 5209 // Inject the members of the anonymous struct/union into the owning 5210 // context and into the identifier resolver chain for name lookup 5211 // purposes. 5212 SmallVector<NamedDecl*, 2> Chain; 5213 Chain.push_back(Anon); 5214 5215 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5216 Invalid = true; 5217 5218 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5219 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5220 MangleNumberingContext *MCtx; 5221 Decl *ManglingContextDecl; 5222 std::tie(MCtx, ManglingContextDecl) = 5223 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5224 if (MCtx) { 5225 Context.setManglingNumber( 5226 NewVD, MCtx->getManglingNumber( 5227 NewVD, getMSManglingNumber(getLangOpts(), S))); 5228 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5229 } 5230 } 5231 } 5232 5233 if (Invalid) 5234 Anon->setInvalidDecl(); 5235 5236 return Anon; 5237 } 5238 5239 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5240 /// Microsoft C anonymous structure. 5241 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5242 /// Example: 5243 /// 5244 /// struct A { int a; }; 5245 /// struct B { struct A; int b; }; 5246 /// 5247 /// void foo() { 5248 /// B var; 5249 /// var.a = 3; 5250 /// } 5251 /// 5252 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5253 RecordDecl *Record) { 5254 assert(Record && "expected a record!"); 5255 5256 // Mock up a declarator. 5257 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5258 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5259 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5260 5261 auto *ParentDecl = cast<RecordDecl>(CurContext); 5262 QualType RecTy = Context.getTypeDeclType(Record); 5263 5264 // Create a declaration for this anonymous struct. 5265 NamedDecl *Anon = 5266 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5267 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5268 /*BitWidth=*/nullptr, /*Mutable=*/false, 5269 /*InitStyle=*/ICIS_NoInit); 5270 Anon->setImplicit(); 5271 5272 // Add the anonymous struct object to the current context. 5273 CurContext->addDecl(Anon); 5274 5275 // Inject the members of the anonymous struct into the current 5276 // context and into the identifier resolver chain for name lookup 5277 // purposes. 5278 SmallVector<NamedDecl*, 2> Chain; 5279 Chain.push_back(Anon); 5280 5281 RecordDecl *RecordDef = Record->getDefinition(); 5282 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5283 diag::err_field_incomplete_or_sizeless) || 5284 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5285 AS_none, Chain)) { 5286 Anon->setInvalidDecl(); 5287 ParentDecl->setInvalidDecl(); 5288 } 5289 5290 return Anon; 5291 } 5292 5293 /// GetNameForDeclarator - Determine the full declaration name for the 5294 /// given Declarator. 5295 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5296 return GetNameFromUnqualifiedId(D.getName()); 5297 } 5298 5299 /// Retrieves the declaration name from a parsed unqualified-id. 5300 DeclarationNameInfo 5301 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5302 DeclarationNameInfo NameInfo; 5303 NameInfo.setLoc(Name.StartLocation); 5304 5305 switch (Name.getKind()) { 5306 5307 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5308 case UnqualifiedIdKind::IK_Identifier: 5309 NameInfo.setName(Name.Identifier); 5310 return NameInfo; 5311 5312 case UnqualifiedIdKind::IK_DeductionGuideName: { 5313 // C++ [temp.deduct.guide]p3: 5314 // The simple-template-id shall name a class template specialization. 5315 // The template-name shall be the same identifier as the template-name 5316 // of the simple-template-id. 5317 // These together intend to imply that the template-name shall name a 5318 // class template. 5319 // FIXME: template<typename T> struct X {}; 5320 // template<typename T> using Y = X<T>; 5321 // Y(int) -> Y<int>; 5322 // satisfies these rules but does not name a class template. 5323 TemplateName TN = Name.TemplateName.get().get(); 5324 auto *Template = TN.getAsTemplateDecl(); 5325 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5326 Diag(Name.StartLocation, 5327 diag::err_deduction_guide_name_not_class_template) 5328 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5329 if (Template) 5330 Diag(Template->getLocation(), diag::note_template_decl_here); 5331 return DeclarationNameInfo(); 5332 } 5333 5334 NameInfo.setName( 5335 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5336 return NameInfo; 5337 } 5338 5339 case UnqualifiedIdKind::IK_OperatorFunctionId: 5340 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5341 Name.OperatorFunctionId.Operator)); 5342 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5343 = Name.OperatorFunctionId.SymbolLocations[0]; 5344 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5345 = Name.EndLocation.getRawEncoding(); 5346 return NameInfo; 5347 5348 case UnqualifiedIdKind::IK_LiteralOperatorId: 5349 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5350 Name.Identifier)); 5351 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5352 return NameInfo; 5353 5354 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5355 TypeSourceInfo *TInfo; 5356 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5357 if (Ty.isNull()) 5358 return DeclarationNameInfo(); 5359 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5360 Context.getCanonicalType(Ty))); 5361 NameInfo.setNamedTypeInfo(TInfo); 5362 return NameInfo; 5363 } 5364 5365 case UnqualifiedIdKind::IK_ConstructorName: { 5366 TypeSourceInfo *TInfo; 5367 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5368 if (Ty.isNull()) 5369 return DeclarationNameInfo(); 5370 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5371 Context.getCanonicalType(Ty))); 5372 NameInfo.setNamedTypeInfo(TInfo); 5373 return NameInfo; 5374 } 5375 5376 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5377 // In well-formed code, we can only have a constructor 5378 // template-id that refers to the current context, so go there 5379 // to find the actual type being constructed. 5380 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5381 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5382 return DeclarationNameInfo(); 5383 5384 // Determine the type of the class being constructed. 5385 QualType CurClassType = Context.getTypeDeclType(CurClass); 5386 5387 // FIXME: Check two things: that the template-id names the same type as 5388 // CurClassType, and that the template-id does not occur when the name 5389 // was qualified. 5390 5391 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5392 Context.getCanonicalType(CurClassType))); 5393 // FIXME: should we retrieve TypeSourceInfo? 5394 NameInfo.setNamedTypeInfo(nullptr); 5395 return NameInfo; 5396 } 5397 5398 case UnqualifiedIdKind::IK_DestructorName: { 5399 TypeSourceInfo *TInfo; 5400 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5401 if (Ty.isNull()) 5402 return DeclarationNameInfo(); 5403 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5404 Context.getCanonicalType(Ty))); 5405 NameInfo.setNamedTypeInfo(TInfo); 5406 return NameInfo; 5407 } 5408 5409 case UnqualifiedIdKind::IK_TemplateId: { 5410 TemplateName TName = Name.TemplateId->Template.get(); 5411 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5412 return Context.getNameForTemplate(TName, TNameLoc); 5413 } 5414 5415 } // switch (Name.getKind()) 5416 5417 llvm_unreachable("Unknown name kind"); 5418 } 5419 5420 static QualType getCoreType(QualType Ty) { 5421 do { 5422 if (Ty->isPointerType() || Ty->isReferenceType()) 5423 Ty = Ty->getPointeeType(); 5424 else if (Ty->isArrayType()) 5425 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5426 else 5427 return Ty.withoutLocalFastQualifiers(); 5428 } while (true); 5429 } 5430 5431 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5432 /// and Definition have "nearly" matching parameters. This heuristic is 5433 /// used to improve diagnostics in the case where an out-of-line function 5434 /// definition doesn't match any declaration within the class or namespace. 5435 /// Also sets Params to the list of indices to the parameters that differ 5436 /// between the declaration and the definition. If hasSimilarParameters 5437 /// returns true and Params is empty, then all of the parameters match. 5438 static bool hasSimilarParameters(ASTContext &Context, 5439 FunctionDecl *Declaration, 5440 FunctionDecl *Definition, 5441 SmallVectorImpl<unsigned> &Params) { 5442 Params.clear(); 5443 if (Declaration->param_size() != Definition->param_size()) 5444 return false; 5445 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5446 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5447 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5448 5449 // The parameter types are identical 5450 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5451 continue; 5452 5453 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5454 QualType DefParamBaseTy = getCoreType(DefParamTy); 5455 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5456 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5457 5458 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5459 (DeclTyName && DeclTyName == DefTyName)) 5460 Params.push_back(Idx); 5461 else // The two parameters aren't even close 5462 return false; 5463 } 5464 5465 return true; 5466 } 5467 5468 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5469 /// declarator needs to be rebuilt in the current instantiation. 5470 /// Any bits of declarator which appear before the name are valid for 5471 /// consideration here. That's specifically the type in the decl spec 5472 /// and the base type in any member-pointer chunks. 5473 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5474 DeclarationName Name) { 5475 // The types we specifically need to rebuild are: 5476 // - typenames, typeofs, and decltypes 5477 // - types which will become injected class names 5478 // Of course, we also need to rebuild any type referencing such a 5479 // type. It's safest to just say "dependent", but we call out a 5480 // few cases here. 5481 5482 DeclSpec &DS = D.getMutableDeclSpec(); 5483 switch (DS.getTypeSpecType()) { 5484 case DeclSpec::TST_typename: 5485 case DeclSpec::TST_typeofType: 5486 case DeclSpec::TST_underlyingType: 5487 case DeclSpec::TST_atomic: { 5488 // Grab the type from the parser. 5489 TypeSourceInfo *TSI = nullptr; 5490 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5491 if (T.isNull() || !T->isDependentType()) break; 5492 5493 // Make sure there's a type source info. This isn't really much 5494 // of a waste; most dependent types should have type source info 5495 // attached already. 5496 if (!TSI) 5497 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5498 5499 // Rebuild the type in the current instantiation. 5500 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5501 if (!TSI) return true; 5502 5503 // Store the new type back in the decl spec. 5504 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5505 DS.UpdateTypeRep(LocType); 5506 break; 5507 } 5508 5509 case DeclSpec::TST_decltype: 5510 case DeclSpec::TST_typeofExpr: { 5511 Expr *E = DS.getRepAsExpr(); 5512 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5513 if (Result.isInvalid()) return true; 5514 DS.UpdateExprRep(Result.get()); 5515 break; 5516 } 5517 5518 default: 5519 // Nothing to do for these decl specs. 5520 break; 5521 } 5522 5523 // It doesn't matter what order we do this in. 5524 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5525 DeclaratorChunk &Chunk = D.getTypeObject(I); 5526 5527 // The only type information in the declarator which can come 5528 // before the declaration name is the base type of a member 5529 // pointer. 5530 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5531 continue; 5532 5533 // Rebuild the scope specifier in-place. 5534 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5535 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5536 return true; 5537 } 5538 5539 return false; 5540 } 5541 5542 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5543 D.setFunctionDefinitionKind(FDK_Declaration); 5544 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5545 5546 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5547 Dcl && Dcl->getDeclContext()->isFileContext()) 5548 Dcl->setTopLevelDeclInObjCContainer(); 5549 5550 if (getLangOpts().OpenCL) 5551 setCurrentOpenCLExtensionForDecl(Dcl); 5552 5553 return Dcl; 5554 } 5555 5556 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5557 /// If T is the name of a class, then each of the following shall have a 5558 /// name different from T: 5559 /// - every static data member of class T; 5560 /// - every member function of class T 5561 /// - every member of class T that is itself a type; 5562 /// \returns true if the declaration name violates these rules. 5563 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5564 DeclarationNameInfo NameInfo) { 5565 DeclarationName Name = NameInfo.getName(); 5566 5567 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5568 while (Record && Record->isAnonymousStructOrUnion()) 5569 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5570 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5571 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5572 return true; 5573 } 5574 5575 return false; 5576 } 5577 5578 /// Diagnose a declaration whose declarator-id has the given 5579 /// nested-name-specifier. 5580 /// 5581 /// \param SS The nested-name-specifier of the declarator-id. 5582 /// 5583 /// \param DC The declaration context to which the nested-name-specifier 5584 /// resolves. 5585 /// 5586 /// \param Name The name of the entity being declared. 5587 /// 5588 /// \param Loc The location of the name of the entity being declared. 5589 /// 5590 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5591 /// we're declaring an explicit / partial specialization / instantiation. 5592 /// 5593 /// \returns true if we cannot safely recover from this error, false otherwise. 5594 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5595 DeclarationName Name, 5596 SourceLocation Loc, bool IsTemplateId) { 5597 DeclContext *Cur = CurContext; 5598 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5599 Cur = Cur->getParent(); 5600 5601 // If the user provided a superfluous scope specifier that refers back to the 5602 // class in which the entity is already declared, diagnose and ignore it. 5603 // 5604 // class X { 5605 // void X::f(); 5606 // }; 5607 // 5608 // Note, it was once ill-formed to give redundant qualification in all 5609 // contexts, but that rule was removed by DR482. 5610 if (Cur->Equals(DC)) { 5611 if (Cur->isRecord()) { 5612 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5613 : diag::err_member_extra_qualification) 5614 << Name << FixItHint::CreateRemoval(SS.getRange()); 5615 SS.clear(); 5616 } else { 5617 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5618 } 5619 return false; 5620 } 5621 5622 // Check whether the qualifying scope encloses the scope of the original 5623 // declaration. For a template-id, we perform the checks in 5624 // CheckTemplateSpecializationScope. 5625 if (!Cur->Encloses(DC) && !IsTemplateId) { 5626 if (Cur->isRecord()) 5627 Diag(Loc, diag::err_member_qualification) 5628 << Name << SS.getRange(); 5629 else if (isa<TranslationUnitDecl>(DC)) 5630 Diag(Loc, diag::err_invalid_declarator_global_scope) 5631 << Name << SS.getRange(); 5632 else if (isa<FunctionDecl>(Cur)) 5633 Diag(Loc, diag::err_invalid_declarator_in_function) 5634 << Name << SS.getRange(); 5635 else if (isa<BlockDecl>(Cur)) 5636 Diag(Loc, diag::err_invalid_declarator_in_block) 5637 << Name << SS.getRange(); 5638 else 5639 Diag(Loc, diag::err_invalid_declarator_scope) 5640 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5641 5642 return true; 5643 } 5644 5645 if (Cur->isRecord()) { 5646 // Cannot qualify members within a class. 5647 Diag(Loc, diag::err_member_qualification) 5648 << Name << SS.getRange(); 5649 SS.clear(); 5650 5651 // C++ constructors and destructors with incorrect scopes can break 5652 // our AST invariants by having the wrong underlying types. If 5653 // that's the case, then drop this declaration entirely. 5654 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5655 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5656 !Context.hasSameType(Name.getCXXNameType(), 5657 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5658 return true; 5659 5660 return false; 5661 } 5662 5663 // C++11 [dcl.meaning]p1: 5664 // [...] "The nested-name-specifier of the qualified declarator-id shall 5665 // not begin with a decltype-specifer" 5666 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5667 while (SpecLoc.getPrefix()) 5668 SpecLoc = SpecLoc.getPrefix(); 5669 if (dyn_cast_or_null<DecltypeType>( 5670 SpecLoc.getNestedNameSpecifier()->getAsType())) 5671 Diag(Loc, diag::err_decltype_in_declarator) 5672 << SpecLoc.getTypeLoc().getSourceRange(); 5673 5674 return false; 5675 } 5676 5677 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5678 MultiTemplateParamsArg TemplateParamLists) { 5679 // TODO: consider using NameInfo for diagnostic. 5680 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5681 DeclarationName Name = NameInfo.getName(); 5682 5683 // All of these full declarators require an identifier. If it doesn't have 5684 // one, the ParsedFreeStandingDeclSpec action should be used. 5685 if (D.isDecompositionDeclarator()) { 5686 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5687 } else if (!Name) { 5688 if (!D.isInvalidType()) // Reject this if we think it is valid. 5689 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5690 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5691 return nullptr; 5692 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5693 return nullptr; 5694 5695 // The scope passed in may not be a decl scope. Zip up the scope tree until 5696 // we find one that is. 5697 while ((S->getFlags() & Scope::DeclScope) == 0 || 5698 (S->getFlags() & Scope::TemplateParamScope) != 0) 5699 S = S->getParent(); 5700 5701 DeclContext *DC = CurContext; 5702 if (D.getCXXScopeSpec().isInvalid()) 5703 D.setInvalidType(); 5704 else if (D.getCXXScopeSpec().isSet()) { 5705 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5706 UPPC_DeclarationQualifier)) 5707 return nullptr; 5708 5709 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5710 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5711 if (!DC || isa<EnumDecl>(DC)) { 5712 // If we could not compute the declaration context, it's because the 5713 // declaration context is dependent but does not refer to a class, 5714 // class template, or class template partial specialization. Complain 5715 // and return early, to avoid the coming semantic disaster. 5716 Diag(D.getIdentifierLoc(), 5717 diag::err_template_qualified_declarator_no_match) 5718 << D.getCXXScopeSpec().getScopeRep() 5719 << D.getCXXScopeSpec().getRange(); 5720 return nullptr; 5721 } 5722 bool IsDependentContext = DC->isDependentContext(); 5723 5724 if (!IsDependentContext && 5725 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5726 return nullptr; 5727 5728 // If a class is incomplete, do not parse entities inside it. 5729 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5730 Diag(D.getIdentifierLoc(), 5731 diag::err_member_def_undefined_record) 5732 << Name << DC << D.getCXXScopeSpec().getRange(); 5733 return nullptr; 5734 } 5735 if (!D.getDeclSpec().isFriendSpecified()) { 5736 if (diagnoseQualifiedDeclaration( 5737 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5738 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5739 if (DC->isRecord()) 5740 return nullptr; 5741 5742 D.setInvalidType(); 5743 } 5744 } 5745 5746 // Check whether we need to rebuild the type of the given 5747 // declaration in the current instantiation. 5748 if (EnteringContext && IsDependentContext && 5749 TemplateParamLists.size() != 0) { 5750 ContextRAII SavedContext(*this, DC); 5751 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5752 D.setInvalidType(); 5753 } 5754 } 5755 5756 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5757 QualType R = TInfo->getType(); 5758 5759 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5760 UPPC_DeclarationType)) 5761 D.setInvalidType(); 5762 5763 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5764 forRedeclarationInCurContext()); 5765 5766 // See if this is a redefinition of a variable in the same scope. 5767 if (!D.getCXXScopeSpec().isSet()) { 5768 bool IsLinkageLookup = false; 5769 bool CreateBuiltins = false; 5770 5771 // If the declaration we're planning to build will be a function 5772 // or object with linkage, then look for another declaration with 5773 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5774 // 5775 // If the declaration we're planning to build will be declared with 5776 // external linkage in the translation unit, create any builtin with 5777 // the same name. 5778 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5779 /* Do nothing*/; 5780 else if (CurContext->isFunctionOrMethod() && 5781 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5782 R->isFunctionType())) { 5783 IsLinkageLookup = true; 5784 CreateBuiltins = 5785 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5786 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5787 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5788 CreateBuiltins = true; 5789 5790 if (IsLinkageLookup) { 5791 Previous.clear(LookupRedeclarationWithLinkage); 5792 Previous.setRedeclarationKind(ForExternalRedeclaration); 5793 } 5794 5795 LookupName(Previous, S, CreateBuiltins); 5796 } else { // Something like "int foo::x;" 5797 LookupQualifiedName(Previous, DC); 5798 5799 // C++ [dcl.meaning]p1: 5800 // When the declarator-id is qualified, the declaration shall refer to a 5801 // previously declared member of the class or namespace to which the 5802 // qualifier refers (or, in the case of a namespace, of an element of the 5803 // inline namespace set of that namespace (7.3.1)) or to a specialization 5804 // thereof; [...] 5805 // 5806 // Note that we already checked the context above, and that we do not have 5807 // enough information to make sure that Previous contains the declaration 5808 // we want to match. For example, given: 5809 // 5810 // class X { 5811 // void f(); 5812 // void f(float); 5813 // }; 5814 // 5815 // void X::f(int) { } // ill-formed 5816 // 5817 // In this case, Previous will point to the overload set 5818 // containing the two f's declared in X, but neither of them 5819 // matches. 5820 5821 // C++ [dcl.meaning]p1: 5822 // [...] the member shall not merely have been introduced by a 5823 // using-declaration in the scope of the class or namespace nominated by 5824 // the nested-name-specifier of the declarator-id. 5825 RemoveUsingDecls(Previous); 5826 } 5827 5828 if (Previous.isSingleResult() && 5829 Previous.getFoundDecl()->isTemplateParameter()) { 5830 // Maybe we will complain about the shadowed template parameter. 5831 if (!D.isInvalidType()) 5832 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5833 Previous.getFoundDecl()); 5834 5835 // Just pretend that we didn't see the previous declaration. 5836 Previous.clear(); 5837 } 5838 5839 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5840 // Forget that the previous declaration is the injected-class-name. 5841 Previous.clear(); 5842 5843 // In C++, the previous declaration we find might be a tag type 5844 // (class or enum). In this case, the new declaration will hide the 5845 // tag type. Note that this applies to functions, function templates, and 5846 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5847 if (Previous.isSingleTagDecl() && 5848 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5849 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5850 Previous.clear(); 5851 5852 // Check that there are no default arguments other than in the parameters 5853 // of a function declaration (C++ only). 5854 if (getLangOpts().CPlusPlus) 5855 CheckExtraCXXDefaultArguments(D); 5856 5857 NamedDecl *New; 5858 5859 bool AddToScope = true; 5860 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5861 if (TemplateParamLists.size()) { 5862 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5863 return nullptr; 5864 } 5865 5866 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5867 } else if (R->isFunctionType()) { 5868 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5869 TemplateParamLists, 5870 AddToScope); 5871 } else { 5872 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5873 AddToScope); 5874 } 5875 5876 if (!New) 5877 return nullptr; 5878 5879 // If this has an identifier and is not a function template specialization, 5880 // add it to the scope stack. 5881 if (New->getDeclName() && AddToScope) 5882 PushOnScopeChains(New, S); 5883 5884 if (isInOpenMPDeclareTargetContext()) 5885 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5886 5887 return New; 5888 } 5889 5890 /// Helper method to turn variable array types into constant array 5891 /// types in certain situations which would otherwise be errors (for 5892 /// GCC compatibility). 5893 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5894 ASTContext &Context, 5895 bool &SizeIsNegative, 5896 llvm::APSInt &Oversized) { 5897 // This method tries to turn a variable array into a constant 5898 // array even when the size isn't an ICE. This is necessary 5899 // for compatibility with code that depends on gcc's buggy 5900 // constant expression folding, like struct {char x[(int)(char*)2];} 5901 SizeIsNegative = false; 5902 Oversized = 0; 5903 5904 if (T->isDependentType()) 5905 return QualType(); 5906 5907 QualifierCollector Qs; 5908 const Type *Ty = Qs.strip(T); 5909 5910 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5911 QualType Pointee = PTy->getPointeeType(); 5912 QualType FixedType = 5913 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5914 Oversized); 5915 if (FixedType.isNull()) return FixedType; 5916 FixedType = Context.getPointerType(FixedType); 5917 return Qs.apply(Context, FixedType); 5918 } 5919 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5920 QualType Inner = PTy->getInnerType(); 5921 QualType FixedType = 5922 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5923 Oversized); 5924 if (FixedType.isNull()) return FixedType; 5925 FixedType = Context.getParenType(FixedType); 5926 return Qs.apply(Context, FixedType); 5927 } 5928 5929 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5930 if (!VLATy) 5931 return QualType(); 5932 5933 QualType ElemTy = VLATy->getElementType(); 5934 if (ElemTy->isVariablyModifiedType()) { 5935 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 5936 SizeIsNegative, Oversized); 5937 if (ElemTy.isNull()) 5938 return QualType(); 5939 } 5940 5941 Expr::EvalResult Result; 5942 if (!VLATy->getSizeExpr() || 5943 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5944 return QualType(); 5945 5946 llvm::APSInt Res = Result.Val.getInt(); 5947 5948 // Check whether the array size is negative. 5949 if (Res.isSigned() && Res.isNegative()) { 5950 SizeIsNegative = true; 5951 return QualType(); 5952 } 5953 5954 // Check whether the array is too large to be addressed. 5955 unsigned ActiveSizeBits = 5956 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 5957 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 5958 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 5959 : Res.getActiveBits(); 5960 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5961 Oversized = Res; 5962 return QualType(); 5963 } 5964 5965 return Context.getConstantArrayType(ElemTy, Res, VLATy->getSizeExpr(), 5966 ArrayType::Normal, 0); 5967 } 5968 5969 static void 5970 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5971 SrcTL = SrcTL.getUnqualifiedLoc(); 5972 DstTL = DstTL.getUnqualifiedLoc(); 5973 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5974 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5975 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5976 DstPTL.getPointeeLoc()); 5977 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5978 return; 5979 } 5980 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5981 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5982 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5983 DstPTL.getInnerLoc()); 5984 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5985 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5986 return; 5987 } 5988 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5989 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5990 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5991 TypeLoc DstElemTL = DstATL.getElementLoc(); 5992 if (VariableArrayTypeLoc SrcElemATL = 5993 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 5994 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 5995 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 5996 } else { 5997 DstElemTL.initializeFullCopy(SrcElemTL); 5998 } 5999 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6000 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6001 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6002 } 6003 6004 /// Helper method to turn variable array types into constant array 6005 /// types in certain situations which would otherwise be errors (for 6006 /// GCC compatibility). 6007 static TypeSourceInfo* 6008 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6009 ASTContext &Context, 6010 bool &SizeIsNegative, 6011 llvm::APSInt &Oversized) { 6012 QualType FixedTy 6013 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6014 SizeIsNegative, Oversized); 6015 if (FixedTy.isNull()) 6016 return nullptr; 6017 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6018 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6019 FixedTInfo->getTypeLoc()); 6020 return FixedTInfo; 6021 } 6022 6023 /// Register the given locally-scoped extern "C" declaration so 6024 /// that it can be found later for redeclarations. We include any extern "C" 6025 /// declaration that is not visible in the translation unit here, not just 6026 /// function-scope declarations. 6027 void 6028 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6029 if (!getLangOpts().CPlusPlus && 6030 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6031 // Don't need to track declarations in the TU in C. 6032 return; 6033 6034 // Note that we have a locally-scoped external with this name. 6035 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6036 } 6037 6038 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6039 // FIXME: We can have multiple results via __attribute__((overloadable)). 6040 auto Result = Context.getExternCContextDecl()->lookup(Name); 6041 return Result.empty() ? nullptr : *Result.begin(); 6042 } 6043 6044 /// Diagnose function specifiers on a declaration of an identifier that 6045 /// does not identify a function. 6046 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6047 // FIXME: We should probably indicate the identifier in question to avoid 6048 // confusion for constructs like "virtual int a(), b;" 6049 if (DS.isVirtualSpecified()) 6050 Diag(DS.getVirtualSpecLoc(), 6051 diag::err_virtual_non_function); 6052 6053 if (DS.hasExplicitSpecifier()) 6054 Diag(DS.getExplicitSpecLoc(), 6055 diag::err_explicit_non_function); 6056 6057 if (DS.isNoreturnSpecified()) 6058 Diag(DS.getNoreturnSpecLoc(), 6059 diag::err_noreturn_non_function); 6060 } 6061 6062 NamedDecl* 6063 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6064 TypeSourceInfo *TInfo, LookupResult &Previous) { 6065 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6066 if (D.getCXXScopeSpec().isSet()) { 6067 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6068 << D.getCXXScopeSpec().getRange(); 6069 D.setInvalidType(); 6070 // Pretend we didn't see the scope specifier. 6071 DC = CurContext; 6072 Previous.clear(); 6073 } 6074 6075 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6076 6077 if (D.getDeclSpec().isInlineSpecified()) 6078 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6079 << getLangOpts().CPlusPlus17; 6080 if (D.getDeclSpec().hasConstexprSpecifier()) 6081 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6082 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6083 6084 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6085 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6086 Diag(D.getName().StartLocation, 6087 diag::err_deduction_guide_invalid_specifier) 6088 << "typedef"; 6089 else 6090 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6091 << D.getName().getSourceRange(); 6092 return nullptr; 6093 } 6094 6095 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6096 if (!NewTD) return nullptr; 6097 6098 // Handle attributes prior to checking for duplicates in MergeVarDecl 6099 ProcessDeclAttributes(S, NewTD, D); 6100 6101 CheckTypedefForVariablyModifiedType(S, NewTD); 6102 6103 bool Redeclaration = D.isRedeclaration(); 6104 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6105 D.setRedeclaration(Redeclaration); 6106 return ND; 6107 } 6108 6109 void 6110 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6111 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6112 // then it shall have block scope. 6113 // Note that variably modified types must be fixed before merging the decl so 6114 // that redeclarations will match. 6115 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6116 QualType T = TInfo->getType(); 6117 if (T->isVariablyModifiedType()) { 6118 setFunctionHasBranchProtectedScope(); 6119 6120 if (S->getFnParent() == nullptr) { 6121 bool SizeIsNegative; 6122 llvm::APSInt Oversized; 6123 TypeSourceInfo *FixedTInfo = 6124 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6125 SizeIsNegative, 6126 Oversized); 6127 if (FixedTInfo) { 6128 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6129 NewTD->setTypeSourceInfo(FixedTInfo); 6130 } else { 6131 if (SizeIsNegative) 6132 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6133 else if (T->isVariableArrayType()) 6134 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6135 else if (Oversized.getBoolValue()) 6136 Diag(NewTD->getLocation(), diag::err_array_too_large) 6137 << Oversized.toString(10); 6138 else 6139 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6140 NewTD->setInvalidDecl(); 6141 } 6142 } 6143 } 6144 } 6145 6146 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6147 /// declares a typedef-name, either using the 'typedef' type specifier or via 6148 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6149 NamedDecl* 6150 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6151 LookupResult &Previous, bool &Redeclaration) { 6152 6153 // Find the shadowed declaration before filtering for scope. 6154 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6155 6156 // Merge the decl with the existing one if appropriate. If the decl is 6157 // in an outer scope, it isn't the same thing. 6158 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6159 /*AllowInlineNamespace*/false); 6160 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6161 if (!Previous.empty()) { 6162 Redeclaration = true; 6163 MergeTypedefNameDecl(S, NewTD, Previous); 6164 } else { 6165 inferGslPointerAttribute(NewTD); 6166 } 6167 6168 if (ShadowedDecl && !Redeclaration) 6169 CheckShadow(NewTD, ShadowedDecl, Previous); 6170 6171 // If this is the C FILE type, notify the AST context. 6172 if (IdentifierInfo *II = NewTD->getIdentifier()) 6173 if (!NewTD->isInvalidDecl() && 6174 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6175 if (II->isStr("FILE")) 6176 Context.setFILEDecl(NewTD); 6177 else if (II->isStr("jmp_buf")) 6178 Context.setjmp_bufDecl(NewTD); 6179 else if (II->isStr("sigjmp_buf")) 6180 Context.setsigjmp_bufDecl(NewTD); 6181 else if (II->isStr("ucontext_t")) 6182 Context.setucontext_tDecl(NewTD); 6183 } 6184 6185 return NewTD; 6186 } 6187 6188 /// Determines whether the given declaration is an out-of-scope 6189 /// previous declaration. 6190 /// 6191 /// This routine should be invoked when name lookup has found a 6192 /// previous declaration (PrevDecl) that is not in the scope where a 6193 /// new declaration by the same name is being introduced. If the new 6194 /// declaration occurs in a local scope, previous declarations with 6195 /// linkage may still be considered previous declarations (C99 6196 /// 6.2.2p4-5, C++ [basic.link]p6). 6197 /// 6198 /// \param PrevDecl the previous declaration found by name 6199 /// lookup 6200 /// 6201 /// \param DC the context in which the new declaration is being 6202 /// declared. 6203 /// 6204 /// \returns true if PrevDecl is an out-of-scope previous declaration 6205 /// for a new delcaration with the same name. 6206 static bool 6207 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6208 ASTContext &Context) { 6209 if (!PrevDecl) 6210 return false; 6211 6212 if (!PrevDecl->hasLinkage()) 6213 return false; 6214 6215 if (Context.getLangOpts().CPlusPlus) { 6216 // C++ [basic.link]p6: 6217 // If there is a visible declaration of an entity with linkage 6218 // having the same name and type, ignoring entities declared 6219 // outside the innermost enclosing namespace scope, the block 6220 // scope declaration declares that same entity and receives the 6221 // linkage of the previous declaration. 6222 DeclContext *OuterContext = DC->getRedeclContext(); 6223 if (!OuterContext->isFunctionOrMethod()) 6224 // This rule only applies to block-scope declarations. 6225 return false; 6226 6227 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6228 if (PrevOuterContext->isRecord()) 6229 // We found a member function: ignore it. 6230 return false; 6231 6232 // Find the innermost enclosing namespace for the new and 6233 // previous declarations. 6234 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6235 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6236 6237 // The previous declaration is in a different namespace, so it 6238 // isn't the same function. 6239 if (!OuterContext->Equals(PrevOuterContext)) 6240 return false; 6241 } 6242 6243 return true; 6244 } 6245 6246 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6247 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6248 if (!SS.isSet()) return; 6249 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6250 } 6251 6252 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6253 QualType type = decl->getType(); 6254 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6255 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6256 // Various kinds of declaration aren't allowed to be __autoreleasing. 6257 unsigned kind = -1U; 6258 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6259 if (var->hasAttr<BlocksAttr>()) 6260 kind = 0; // __block 6261 else if (!var->hasLocalStorage()) 6262 kind = 1; // global 6263 } else if (isa<ObjCIvarDecl>(decl)) { 6264 kind = 3; // ivar 6265 } else if (isa<FieldDecl>(decl)) { 6266 kind = 2; // field 6267 } 6268 6269 if (kind != -1U) { 6270 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6271 << kind; 6272 } 6273 } else if (lifetime == Qualifiers::OCL_None) { 6274 // Try to infer lifetime. 6275 if (!type->isObjCLifetimeType()) 6276 return false; 6277 6278 lifetime = type->getObjCARCImplicitLifetime(); 6279 type = Context.getLifetimeQualifiedType(type, lifetime); 6280 decl->setType(type); 6281 } 6282 6283 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6284 // Thread-local variables cannot have lifetime. 6285 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6286 var->getTLSKind()) { 6287 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6288 << var->getType(); 6289 return true; 6290 } 6291 } 6292 6293 return false; 6294 } 6295 6296 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6297 if (Decl->getType().hasAddressSpace()) 6298 return; 6299 if (Decl->getType()->isDependentType()) 6300 return; 6301 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6302 QualType Type = Var->getType(); 6303 if (Type->isSamplerT() || Type->isVoidType()) 6304 return; 6305 LangAS ImplAS = LangAS::opencl_private; 6306 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6307 Var->hasGlobalStorage()) 6308 ImplAS = LangAS::opencl_global; 6309 // If the original type from a decayed type is an array type and that array 6310 // type has no address space yet, deduce it now. 6311 if (auto DT = dyn_cast<DecayedType>(Type)) { 6312 auto OrigTy = DT->getOriginalType(); 6313 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6314 // Add the address space to the original array type and then propagate 6315 // that to the element type through `getAsArrayType`. 6316 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6317 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6318 // Re-generate the decayed type. 6319 Type = Context.getDecayedType(OrigTy); 6320 } 6321 } 6322 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6323 // Apply any qualifiers (including address space) from the array type to 6324 // the element type. This implements C99 6.7.3p8: "If the specification of 6325 // an array type includes any type qualifiers, the element type is so 6326 // qualified, not the array type." 6327 if (Type->isArrayType()) 6328 Type = QualType(Context.getAsArrayType(Type), 0); 6329 Decl->setType(Type); 6330 } 6331 } 6332 6333 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6334 // Ensure that an auto decl is deduced otherwise the checks below might cache 6335 // the wrong linkage. 6336 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6337 6338 // 'weak' only applies to declarations with external linkage. 6339 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6340 if (!ND.isExternallyVisible()) { 6341 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6342 ND.dropAttr<WeakAttr>(); 6343 } 6344 } 6345 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6346 if (ND.isExternallyVisible()) { 6347 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6348 ND.dropAttr<WeakRefAttr>(); 6349 ND.dropAttr<AliasAttr>(); 6350 } 6351 } 6352 6353 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6354 if (VD->hasInit()) { 6355 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6356 assert(VD->isThisDeclarationADefinition() && 6357 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6358 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6359 VD->dropAttr<AliasAttr>(); 6360 } 6361 } 6362 } 6363 6364 // 'selectany' only applies to externally visible variable declarations. 6365 // It does not apply to functions. 6366 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6367 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6368 S.Diag(Attr->getLocation(), 6369 diag::err_attribute_selectany_non_extern_data); 6370 ND.dropAttr<SelectAnyAttr>(); 6371 } 6372 } 6373 6374 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6375 auto *VD = dyn_cast<VarDecl>(&ND); 6376 bool IsAnonymousNS = false; 6377 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6378 if (VD) { 6379 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6380 while (NS && !IsAnonymousNS) { 6381 IsAnonymousNS = NS->isAnonymousNamespace(); 6382 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6383 } 6384 } 6385 // dll attributes require external linkage. Static locals may have external 6386 // linkage but still cannot be explicitly imported or exported. 6387 // In Microsoft mode, a variable defined in anonymous namespace must have 6388 // external linkage in order to be exported. 6389 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6390 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6391 (!AnonNSInMicrosoftMode && 6392 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6393 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6394 << &ND << Attr; 6395 ND.setInvalidDecl(); 6396 } 6397 } 6398 6399 // Virtual functions cannot be marked as 'notail'. 6400 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6401 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6402 if (MD->isVirtual()) { 6403 S.Diag(ND.getLocation(), 6404 diag::err_invalid_attribute_on_virtual_function) 6405 << Attr; 6406 ND.dropAttr<NotTailCalledAttr>(); 6407 } 6408 6409 // Check the attributes on the function type, if any. 6410 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6411 // Don't declare this variable in the second operand of the for-statement; 6412 // GCC miscompiles that by ending its lifetime before evaluating the 6413 // third operand. See gcc.gnu.org/PR86769. 6414 AttributedTypeLoc ATL; 6415 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6416 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6417 TL = ATL.getModifiedLoc()) { 6418 // The [[lifetimebound]] attribute can be applied to the implicit object 6419 // parameter of a non-static member function (other than a ctor or dtor) 6420 // by applying it to the function type. 6421 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6422 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6423 if (!MD || MD->isStatic()) { 6424 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6425 << !MD << A->getRange(); 6426 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6427 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6428 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6429 } 6430 } 6431 } 6432 } 6433 } 6434 6435 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6436 NamedDecl *NewDecl, 6437 bool IsSpecialization, 6438 bool IsDefinition) { 6439 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6440 return; 6441 6442 bool IsTemplate = false; 6443 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6444 OldDecl = OldTD->getTemplatedDecl(); 6445 IsTemplate = true; 6446 if (!IsSpecialization) 6447 IsDefinition = false; 6448 } 6449 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6450 NewDecl = NewTD->getTemplatedDecl(); 6451 IsTemplate = true; 6452 } 6453 6454 if (!OldDecl || !NewDecl) 6455 return; 6456 6457 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6458 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6459 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6460 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6461 6462 // dllimport and dllexport are inheritable attributes so we have to exclude 6463 // inherited attribute instances. 6464 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6465 (NewExportAttr && !NewExportAttr->isInherited()); 6466 6467 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6468 // the only exception being explicit specializations. 6469 // Implicitly generated declarations are also excluded for now because there 6470 // is no other way to switch these to use dllimport or dllexport. 6471 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6472 6473 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6474 // Allow with a warning for free functions and global variables. 6475 bool JustWarn = false; 6476 if (!OldDecl->isCXXClassMember()) { 6477 auto *VD = dyn_cast<VarDecl>(OldDecl); 6478 if (VD && !VD->getDescribedVarTemplate()) 6479 JustWarn = true; 6480 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6481 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6482 JustWarn = true; 6483 } 6484 6485 // We cannot change a declaration that's been used because IR has already 6486 // been emitted. Dllimported functions will still work though (modulo 6487 // address equality) as they can use the thunk. 6488 if (OldDecl->isUsed()) 6489 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6490 JustWarn = false; 6491 6492 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6493 : diag::err_attribute_dll_redeclaration; 6494 S.Diag(NewDecl->getLocation(), DiagID) 6495 << NewDecl 6496 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6497 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6498 if (!JustWarn) { 6499 NewDecl->setInvalidDecl(); 6500 return; 6501 } 6502 } 6503 6504 // A redeclaration is not allowed to drop a dllimport attribute, the only 6505 // exceptions being inline function definitions (except for function 6506 // templates), local extern declarations, qualified friend declarations or 6507 // special MSVC extension: in the last case, the declaration is treated as if 6508 // it were marked dllexport. 6509 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6510 bool IsMicrosoft = 6511 S.Context.getTargetInfo().getCXXABI().isMicrosoft() || 6512 S.Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment(); 6513 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6514 // Ignore static data because out-of-line definitions are diagnosed 6515 // separately. 6516 IsStaticDataMember = VD->isStaticDataMember(); 6517 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6518 VarDecl::DeclarationOnly; 6519 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6520 IsInline = FD->isInlined(); 6521 IsQualifiedFriend = FD->getQualifier() && 6522 FD->getFriendObjectKind() == Decl::FOK_Declared; 6523 } 6524 6525 if (OldImportAttr && !HasNewAttr && 6526 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6527 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6528 if (IsMicrosoft && IsDefinition) { 6529 S.Diag(NewDecl->getLocation(), 6530 diag::warn_redeclaration_without_import_attribute) 6531 << NewDecl; 6532 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6533 NewDecl->dropAttr<DLLImportAttr>(); 6534 NewDecl->addAttr( 6535 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6536 } else { 6537 S.Diag(NewDecl->getLocation(), 6538 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6539 << NewDecl << OldImportAttr; 6540 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6541 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6542 OldDecl->dropAttr<DLLImportAttr>(); 6543 NewDecl->dropAttr<DLLImportAttr>(); 6544 } 6545 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6546 // In MinGW, seeing a function declared inline drops the dllimport 6547 // attribute. 6548 OldDecl->dropAttr<DLLImportAttr>(); 6549 NewDecl->dropAttr<DLLImportAttr>(); 6550 S.Diag(NewDecl->getLocation(), 6551 diag::warn_dllimport_dropped_from_inline_function) 6552 << NewDecl << OldImportAttr; 6553 } 6554 6555 // A specialization of a class template member function is processed here 6556 // since it's a redeclaration. If the parent class is dllexport, the 6557 // specialization inherits that attribute. This doesn't happen automatically 6558 // since the parent class isn't instantiated until later. 6559 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6560 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6561 !NewImportAttr && !NewExportAttr) { 6562 if (const DLLExportAttr *ParentExportAttr = 6563 MD->getParent()->getAttr<DLLExportAttr>()) { 6564 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6565 NewAttr->setInherited(true); 6566 NewDecl->addAttr(NewAttr); 6567 } 6568 } 6569 } 6570 } 6571 6572 /// Given that we are within the definition of the given function, 6573 /// will that definition behave like C99's 'inline', where the 6574 /// definition is discarded except for optimization purposes? 6575 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6576 // Try to avoid calling GetGVALinkageForFunction. 6577 6578 // All cases of this require the 'inline' keyword. 6579 if (!FD->isInlined()) return false; 6580 6581 // This is only possible in C++ with the gnu_inline attribute. 6582 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6583 return false; 6584 6585 // Okay, go ahead and call the relatively-more-expensive function. 6586 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6587 } 6588 6589 /// Determine whether a variable is extern "C" prior to attaching 6590 /// an initializer. We can't just call isExternC() here, because that 6591 /// will also compute and cache whether the declaration is externally 6592 /// visible, which might change when we attach the initializer. 6593 /// 6594 /// This can only be used if the declaration is known to not be a 6595 /// redeclaration of an internal linkage declaration. 6596 /// 6597 /// For instance: 6598 /// 6599 /// auto x = []{}; 6600 /// 6601 /// Attaching the initializer here makes this declaration not externally 6602 /// visible, because its type has internal linkage. 6603 /// 6604 /// FIXME: This is a hack. 6605 template<typename T> 6606 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6607 if (S.getLangOpts().CPlusPlus) { 6608 // In C++, the overloadable attribute negates the effects of extern "C". 6609 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6610 return false; 6611 6612 // So do CUDA's host/device attributes. 6613 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6614 D->template hasAttr<CUDAHostAttr>())) 6615 return false; 6616 } 6617 return D->isExternC(); 6618 } 6619 6620 static bool shouldConsiderLinkage(const VarDecl *VD) { 6621 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6622 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6623 isa<OMPDeclareMapperDecl>(DC)) 6624 return VD->hasExternalStorage(); 6625 if (DC->isFileContext()) 6626 return true; 6627 if (DC->isRecord()) 6628 return false; 6629 if (isa<RequiresExprBodyDecl>(DC)) 6630 return false; 6631 llvm_unreachable("Unexpected context"); 6632 } 6633 6634 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6635 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6636 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6637 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6638 return true; 6639 if (DC->isRecord()) 6640 return false; 6641 llvm_unreachable("Unexpected context"); 6642 } 6643 6644 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6645 ParsedAttr::Kind Kind) { 6646 // Check decl attributes on the DeclSpec. 6647 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6648 return true; 6649 6650 // Walk the declarator structure, checking decl attributes that were in a type 6651 // position to the decl itself. 6652 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6653 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6654 return true; 6655 } 6656 6657 // Finally, check attributes on the decl itself. 6658 return PD.getAttributes().hasAttribute(Kind); 6659 } 6660 6661 /// Adjust the \c DeclContext for a function or variable that might be a 6662 /// function-local external declaration. 6663 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6664 if (!DC->isFunctionOrMethod()) 6665 return false; 6666 6667 // If this is a local extern function or variable declared within a function 6668 // template, don't add it into the enclosing namespace scope until it is 6669 // instantiated; it might have a dependent type right now. 6670 if (DC->isDependentContext()) 6671 return true; 6672 6673 // C++11 [basic.link]p7: 6674 // When a block scope declaration of an entity with linkage is not found to 6675 // refer to some other declaration, then that entity is a member of the 6676 // innermost enclosing namespace. 6677 // 6678 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6679 // semantically-enclosing namespace, not a lexically-enclosing one. 6680 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6681 DC = DC->getParent(); 6682 return true; 6683 } 6684 6685 /// Returns true if given declaration has external C language linkage. 6686 static bool isDeclExternC(const Decl *D) { 6687 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6688 return FD->isExternC(); 6689 if (const auto *VD = dyn_cast<VarDecl>(D)) 6690 return VD->isExternC(); 6691 6692 llvm_unreachable("Unknown type of decl!"); 6693 } 6694 /// Returns true if there hasn't been any invalid type diagnosed. 6695 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6696 DeclContext *DC, QualType R) { 6697 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6698 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6699 // argument. 6700 if (R->isImageType() || R->isPipeType()) { 6701 Se.Diag(D.getIdentifierLoc(), 6702 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6703 << R; 6704 D.setInvalidType(); 6705 return false; 6706 } 6707 6708 // OpenCL v1.2 s6.9.r: 6709 // The event type cannot be used to declare a program scope variable. 6710 // OpenCL v2.0 s6.9.q: 6711 // The clk_event_t and reserve_id_t types cannot be declared in program 6712 // scope. 6713 if (NULL == S->getParent()) { 6714 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6715 Se.Diag(D.getIdentifierLoc(), 6716 diag::err_invalid_type_for_program_scope_var) 6717 << R; 6718 D.setInvalidType(); 6719 return false; 6720 } 6721 } 6722 6723 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6724 QualType NR = R; 6725 while (NR->isPointerType()) { 6726 if (NR->isFunctionPointerType()) { 6727 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6728 D.setInvalidType(); 6729 return false; 6730 } 6731 NR = NR->getPointeeType(); 6732 } 6733 6734 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6735 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6736 // half array type (unless the cl_khr_fp16 extension is enabled). 6737 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6738 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6739 D.setInvalidType(); 6740 return false; 6741 } 6742 } 6743 6744 // OpenCL v1.2 s6.9.r: 6745 // The event type cannot be used with the __local, __constant and __global 6746 // address space qualifiers. 6747 if (R->isEventT()) { 6748 if (R.getAddressSpace() != LangAS::opencl_private) { 6749 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6750 D.setInvalidType(); 6751 return false; 6752 } 6753 } 6754 6755 // C++ for OpenCL does not allow the thread_local storage qualifier. 6756 // OpenCL C does not support thread_local either, and 6757 // also reject all other thread storage class specifiers. 6758 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6759 if (TSC != TSCS_unspecified) { 6760 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6761 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6762 diag::err_opencl_unknown_type_specifier) 6763 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6764 << DeclSpec::getSpecifierName(TSC) << 1; 6765 D.setInvalidType(); 6766 return false; 6767 } 6768 6769 if (R->isSamplerT()) { 6770 // OpenCL v1.2 s6.9.b p4: 6771 // The sampler type cannot be used with the __local and __global address 6772 // space qualifiers. 6773 if (R.getAddressSpace() == LangAS::opencl_local || 6774 R.getAddressSpace() == LangAS::opencl_global) { 6775 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6776 D.setInvalidType(); 6777 } 6778 6779 // OpenCL v1.2 s6.12.14.1: 6780 // A global sampler must be declared with either the constant address 6781 // space qualifier or with the const qualifier. 6782 if (DC->isTranslationUnit() && 6783 !(R.getAddressSpace() == LangAS::opencl_constant || 6784 R.isConstQualified())) { 6785 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6786 D.setInvalidType(); 6787 } 6788 if (D.isInvalidType()) 6789 return false; 6790 } 6791 return true; 6792 } 6793 6794 NamedDecl *Sema::ActOnVariableDeclarator( 6795 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6796 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6797 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6798 QualType R = TInfo->getType(); 6799 DeclarationName Name = GetNameForDeclarator(D).getName(); 6800 6801 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6802 6803 if (D.isDecompositionDeclarator()) { 6804 // Take the name of the first declarator as our name for diagnostic 6805 // purposes. 6806 auto &Decomp = D.getDecompositionDeclarator(); 6807 if (!Decomp.bindings().empty()) { 6808 II = Decomp.bindings()[0].Name; 6809 Name = II; 6810 } 6811 } else if (!II) { 6812 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6813 return nullptr; 6814 } 6815 6816 6817 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6818 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6819 6820 // dllimport globals without explicit storage class are treated as extern. We 6821 // have to change the storage class this early to get the right DeclContext. 6822 if (SC == SC_None && !DC->isRecord() && 6823 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6824 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6825 SC = SC_Extern; 6826 6827 DeclContext *OriginalDC = DC; 6828 bool IsLocalExternDecl = SC == SC_Extern && 6829 adjustContextForLocalExternDecl(DC); 6830 6831 if (SCSpec == DeclSpec::SCS_mutable) { 6832 // mutable can only appear on non-static class members, so it's always 6833 // an error here 6834 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6835 D.setInvalidType(); 6836 SC = SC_None; 6837 } 6838 6839 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6840 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6841 D.getDeclSpec().getStorageClassSpecLoc())) { 6842 // In C++11, the 'register' storage class specifier is deprecated. 6843 // Suppress the warning in system macros, it's used in macros in some 6844 // popular C system headers, such as in glibc's htonl() macro. 6845 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6846 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6847 : diag::warn_deprecated_register) 6848 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6849 } 6850 6851 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6852 6853 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6854 // C99 6.9p2: The storage-class specifiers auto and register shall not 6855 // appear in the declaration specifiers in an external declaration. 6856 // Global Register+Asm is a GNU extension we support. 6857 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6858 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6859 D.setInvalidType(); 6860 } 6861 } 6862 6863 bool IsMemberSpecialization = false; 6864 bool IsVariableTemplateSpecialization = false; 6865 bool IsPartialSpecialization = false; 6866 bool IsVariableTemplate = false; 6867 VarDecl *NewVD = nullptr; 6868 VarTemplateDecl *NewTemplate = nullptr; 6869 TemplateParameterList *TemplateParams = nullptr; 6870 if (!getLangOpts().CPlusPlus) { 6871 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6872 II, R, TInfo, SC); 6873 6874 if (R->getContainedDeducedType()) 6875 ParsingInitForAutoVars.insert(NewVD); 6876 6877 if (D.isInvalidType()) 6878 NewVD->setInvalidDecl(); 6879 6880 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6881 NewVD->hasLocalStorage()) 6882 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6883 NTCUC_AutoVar, NTCUK_Destruct); 6884 } else { 6885 bool Invalid = false; 6886 6887 if (DC->isRecord() && !CurContext->isRecord()) { 6888 // This is an out-of-line definition of a static data member. 6889 switch (SC) { 6890 case SC_None: 6891 break; 6892 case SC_Static: 6893 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6894 diag::err_static_out_of_line) 6895 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6896 break; 6897 case SC_Auto: 6898 case SC_Register: 6899 case SC_Extern: 6900 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6901 // to names of variables declared in a block or to function parameters. 6902 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6903 // of class members 6904 6905 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6906 diag::err_storage_class_for_static_member) 6907 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6908 break; 6909 case SC_PrivateExtern: 6910 llvm_unreachable("C storage class in c++!"); 6911 } 6912 } 6913 6914 if (SC == SC_Static && CurContext->isRecord()) { 6915 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6916 // Walk up the enclosing DeclContexts to check for any that are 6917 // incompatible with static data members. 6918 const DeclContext *FunctionOrMethod = nullptr; 6919 const CXXRecordDecl *AnonStruct = nullptr; 6920 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6921 if (Ctxt->isFunctionOrMethod()) { 6922 FunctionOrMethod = Ctxt; 6923 break; 6924 } 6925 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6926 if (ParentDecl && !ParentDecl->getDeclName()) { 6927 AnonStruct = ParentDecl; 6928 break; 6929 } 6930 } 6931 if (FunctionOrMethod) { 6932 // C++ [class.static.data]p5: A local class shall not have static data 6933 // members. 6934 Diag(D.getIdentifierLoc(), 6935 diag::err_static_data_member_not_allowed_in_local_class) 6936 << Name << RD->getDeclName() << RD->getTagKind(); 6937 } else if (AnonStruct) { 6938 // C++ [class.static.data]p4: Unnamed classes and classes contained 6939 // directly or indirectly within unnamed classes shall not contain 6940 // static data members. 6941 Diag(D.getIdentifierLoc(), 6942 diag::err_static_data_member_not_allowed_in_anon_struct) 6943 << Name << AnonStruct->getTagKind(); 6944 Invalid = true; 6945 } else if (RD->isUnion()) { 6946 // C++98 [class.union]p1: If a union contains a static data member, 6947 // the program is ill-formed. C++11 drops this restriction. 6948 Diag(D.getIdentifierLoc(), 6949 getLangOpts().CPlusPlus11 6950 ? diag::warn_cxx98_compat_static_data_member_in_union 6951 : diag::ext_static_data_member_in_union) << Name; 6952 } 6953 } 6954 } 6955 6956 // Match up the template parameter lists with the scope specifier, then 6957 // determine whether we have a template or a template specialization. 6958 bool InvalidScope = false; 6959 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6960 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6961 D.getCXXScopeSpec(), 6962 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6963 ? D.getName().TemplateId 6964 : nullptr, 6965 TemplateParamLists, 6966 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6967 Invalid |= InvalidScope; 6968 6969 if (TemplateParams) { 6970 if (!TemplateParams->size() && 6971 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6972 // There is an extraneous 'template<>' for this variable. Complain 6973 // about it, but allow the declaration of the variable. 6974 Diag(TemplateParams->getTemplateLoc(), 6975 diag::err_template_variable_noparams) 6976 << II 6977 << SourceRange(TemplateParams->getTemplateLoc(), 6978 TemplateParams->getRAngleLoc()); 6979 TemplateParams = nullptr; 6980 } else { 6981 // Check that we can declare a template here. 6982 if (CheckTemplateDeclScope(S, TemplateParams)) 6983 return nullptr; 6984 6985 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6986 // This is an explicit specialization or a partial specialization. 6987 IsVariableTemplateSpecialization = true; 6988 IsPartialSpecialization = TemplateParams->size() > 0; 6989 } else { // if (TemplateParams->size() > 0) 6990 // This is a template declaration. 6991 IsVariableTemplate = true; 6992 6993 // Only C++1y supports variable templates (N3651). 6994 Diag(D.getIdentifierLoc(), 6995 getLangOpts().CPlusPlus14 6996 ? diag::warn_cxx11_compat_variable_template 6997 : diag::ext_variable_template); 6998 } 6999 } 7000 } else { 7001 // Check that we can declare a member specialization here. 7002 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7003 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7004 return nullptr; 7005 assert((Invalid || 7006 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7007 "should have a 'template<>' for this decl"); 7008 } 7009 7010 if (IsVariableTemplateSpecialization) { 7011 SourceLocation TemplateKWLoc = 7012 TemplateParamLists.size() > 0 7013 ? TemplateParamLists[0]->getTemplateLoc() 7014 : SourceLocation(); 7015 DeclResult Res = ActOnVarTemplateSpecialization( 7016 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7017 IsPartialSpecialization); 7018 if (Res.isInvalid()) 7019 return nullptr; 7020 NewVD = cast<VarDecl>(Res.get()); 7021 AddToScope = false; 7022 } else if (D.isDecompositionDeclarator()) { 7023 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7024 D.getIdentifierLoc(), R, TInfo, SC, 7025 Bindings); 7026 } else 7027 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7028 D.getIdentifierLoc(), II, R, TInfo, SC); 7029 7030 // If this is supposed to be a variable template, create it as such. 7031 if (IsVariableTemplate) { 7032 NewTemplate = 7033 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7034 TemplateParams, NewVD); 7035 NewVD->setDescribedVarTemplate(NewTemplate); 7036 } 7037 7038 // If this decl has an auto type in need of deduction, make a note of the 7039 // Decl so we can diagnose uses of it in its own initializer. 7040 if (R->getContainedDeducedType()) 7041 ParsingInitForAutoVars.insert(NewVD); 7042 7043 if (D.isInvalidType() || Invalid) { 7044 NewVD->setInvalidDecl(); 7045 if (NewTemplate) 7046 NewTemplate->setInvalidDecl(); 7047 } 7048 7049 SetNestedNameSpecifier(*this, NewVD, D); 7050 7051 // If we have any template parameter lists that don't directly belong to 7052 // the variable (matching the scope specifier), store them. 7053 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7054 if (TemplateParamLists.size() > VDTemplateParamLists) 7055 NewVD->setTemplateParameterListsInfo( 7056 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7057 } 7058 7059 if (D.getDeclSpec().isInlineSpecified()) { 7060 if (!getLangOpts().CPlusPlus) { 7061 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7062 << 0; 7063 } else if (CurContext->isFunctionOrMethod()) { 7064 // 'inline' is not allowed on block scope variable declaration. 7065 Diag(D.getDeclSpec().getInlineSpecLoc(), 7066 diag::err_inline_declaration_block_scope) << Name 7067 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7068 } else { 7069 Diag(D.getDeclSpec().getInlineSpecLoc(), 7070 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7071 : diag::ext_inline_variable); 7072 NewVD->setInlineSpecified(); 7073 } 7074 } 7075 7076 // Set the lexical context. If the declarator has a C++ scope specifier, the 7077 // lexical context will be different from the semantic context. 7078 NewVD->setLexicalDeclContext(CurContext); 7079 if (NewTemplate) 7080 NewTemplate->setLexicalDeclContext(CurContext); 7081 7082 if (IsLocalExternDecl) { 7083 if (D.isDecompositionDeclarator()) 7084 for (auto *B : Bindings) 7085 B->setLocalExternDecl(); 7086 else 7087 NewVD->setLocalExternDecl(); 7088 } 7089 7090 bool EmitTLSUnsupportedError = false; 7091 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7092 // C++11 [dcl.stc]p4: 7093 // When thread_local is applied to a variable of block scope the 7094 // storage-class-specifier static is implied if it does not appear 7095 // explicitly. 7096 // Core issue: 'static' is not implied if the variable is declared 7097 // 'extern'. 7098 if (NewVD->hasLocalStorage() && 7099 (SCSpec != DeclSpec::SCS_unspecified || 7100 TSCS != DeclSpec::TSCS_thread_local || 7101 !DC->isFunctionOrMethod())) 7102 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7103 diag::err_thread_non_global) 7104 << DeclSpec::getSpecifierName(TSCS); 7105 else if (!Context.getTargetInfo().isTLSSupported()) { 7106 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7107 getLangOpts().SYCLIsDevice) { 7108 // Postpone error emission until we've collected attributes required to 7109 // figure out whether it's a host or device variable and whether the 7110 // error should be ignored. 7111 EmitTLSUnsupportedError = true; 7112 // We still need to mark the variable as TLS so it shows up in AST with 7113 // proper storage class for other tools to use even if we're not going 7114 // to emit any code for it. 7115 NewVD->setTSCSpec(TSCS); 7116 } else 7117 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7118 diag::err_thread_unsupported); 7119 } else 7120 NewVD->setTSCSpec(TSCS); 7121 } 7122 7123 switch (D.getDeclSpec().getConstexprSpecifier()) { 7124 case CSK_unspecified: 7125 break; 7126 7127 case CSK_consteval: 7128 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7129 diag::err_constexpr_wrong_decl_kind) 7130 << D.getDeclSpec().getConstexprSpecifier(); 7131 LLVM_FALLTHROUGH; 7132 7133 case CSK_constexpr: 7134 NewVD->setConstexpr(true); 7135 MaybeAddCUDAConstantAttr(NewVD); 7136 // C++1z [dcl.spec.constexpr]p1: 7137 // A static data member declared with the constexpr specifier is 7138 // implicitly an inline variable. 7139 if (NewVD->isStaticDataMember() && 7140 (getLangOpts().CPlusPlus17 || 7141 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7142 NewVD->setImplicitlyInline(); 7143 break; 7144 7145 case CSK_constinit: 7146 if (!NewVD->hasGlobalStorage()) 7147 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7148 diag::err_constinit_local_variable); 7149 else 7150 NewVD->addAttr(ConstInitAttr::Create( 7151 Context, D.getDeclSpec().getConstexprSpecLoc(), 7152 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7153 break; 7154 } 7155 7156 // C99 6.7.4p3 7157 // An inline definition of a function with external linkage shall 7158 // not contain a definition of a modifiable object with static or 7159 // thread storage duration... 7160 // We only apply this when the function is required to be defined 7161 // elsewhere, i.e. when the function is not 'extern inline'. Note 7162 // that a local variable with thread storage duration still has to 7163 // be marked 'static'. Also note that it's possible to get these 7164 // semantics in C++ using __attribute__((gnu_inline)). 7165 if (SC == SC_Static && S->getFnParent() != nullptr && 7166 !NewVD->getType().isConstQualified()) { 7167 FunctionDecl *CurFD = getCurFunctionDecl(); 7168 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7169 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7170 diag::warn_static_local_in_extern_inline); 7171 MaybeSuggestAddingStaticToDecl(CurFD); 7172 } 7173 } 7174 7175 if (D.getDeclSpec().isModulePrivateSpecified()) { 7176 if (IsVariableTemplateSpecialization) 7177 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7178 << (IsPartialSpecialization ? 1 : 0) 7179 << FixItHint::CreateRemoval( 7180 D.getDeclSpec().getModulePrivateSpecLoc()); 7181 else if (IsMemberSpecialization) 7182 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7183 << 2 7184 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7185 else if (NewVD->hasLocalStorage()) 7186 Diag(NewVD->getLocation(), diag::err_module_private_local) 7187 << 0 << NewVD 7188 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7189 << FixItHint::CreateRemoval( 7190 D.getDeclSpec().getModulePrivateSpecLoc()); 7191 else { 7192 NewVD->setModulePrivate(); 7193 if (NewTemplate) 7194 NewTemplate->setModulePrivate(); 7195 for (auto *B : Bindings) 7196 B->setModulePrivate(); 7197 } 7198 } 7199 7200 if (getLangOpts().OpenCL) { 7201 7202 deduceOpenCLAddressSpace(NewVD); 7203 7204 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7205 } 7206 7207 // Handle attributes prior to checking for duplicates in MergeVarDecl 7208 ProcessDeclAttributes(S, NewVD, D); 7209 7210 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7211 getLangOpts().SYCLIsDevice) { 7212 if (EmitTLSUnsupportedError && 7213 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7214 (getLangOpts().OpenMPIsDevice && 7215 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7216 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7217 diag::err_thread_unsupported); 7218 7219 if (EmitTLSUnsupportedError && 7220 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7221 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7222 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7223 // storage [duration]." 7224 if (SC == SC_None && S->getFnParent() != nullptr && 7225 (NewVD->hasAttr<CUDASharedAttr>() || 7226 NewVD->hasAttr<CUDAConstantAttr>())) { 7227 NewVD->setStorageClass(SC_Static); 7228 } 7229 } 7230 7231 // Ensure that dllimport globals without explicit storage class are treated as 7232 // extern. The storage class is set above using parsed attributes. Now we can 7233 // check the VarDecl itself. 7234 assert(!NewVD->hasAttr<DLLImportAttr>() || 7235 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7236 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7237 7238 // In auto-retain/release, infer strong retension for variables of 7239 // retainable type. 7240 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7241 NewVD->setInvalidDecl(); 7242 7243 // Handle GNU asm-label extension (encoded as an attribute). 7244 if (Expr *E = (Expr*)D.getAsmLabel()) { 7245 // The parser guarantees this is a string. 7246 StringLiteral *SE = cast<StringLiteral>(E); 7247 StringRef Label = SE->getString(); 7248 if (S->getFnParent() != nullptr) { 7249 switch (SC) { 7250 case SC_None: 7251 case SC_Auto: 7252 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7253 break; 7254 case SC_Register: 7255 // Local Named register 7256 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7257 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7258 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7259 break; 7260 case SC_Static: 7261 case SC_Extern: 7262 case SC_PrivateExtern: 7263 break; 7264 } 7265 } else if (SC == SC_Register) { 7266 // Global Named register 7267 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7268 const auto &TI = Context.getTargetInfo(); 7269 bool HasSizeMismatch; 7270 7271 if (!TI.isValidGCCRegisterName(Label)) 7272 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7273 else if (!TI.validateGlobalRegisterVariable(Label, 7274 Context.getTypeSize(R), 7275 HasSizeMismatch)) 7276 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7277 else if (HasSizeMismatch) 7278 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7279 } 7280 7281 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7282 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7283 NewVD->setInvalidDecl(true); 7284 } 7285 } 7286 7287 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7288 /*IsLiteralLabel=*/true, 7289 SE->getStrTokenLoc(0))); 7290 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7291 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7292 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7293 if (I != ExtnameUndeclaredIdentifiers.end()) { 7294 if (isDeclExternC(NewVD)) { 7295 NewVD->addAttr(I->second); 7296 ExtnameUndeclaredIdentifiers.erase(I); 7297 } else 7298 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7299 << /*Variable*/1 << NewVD; 7300 } 7301 } 7302 7303 // Find the shadowed declaration before filtering for scope. 7304 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7305 ? getShadowedDeclaration(NewVD, Previous) 7306 : nullptr; 7307 7308 // Don't consider existing declarations that are in a different 7309 // scope and are out-of-semantic-context declarations (if the new 7310 // declaration has linkage). 7311 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7312 D.getCXXScopeSpec().isNotEmpty() || 7313 IsMemberSpecialization || 7314 IsVariableTemplateSpecialization); 7315 7316 // Check whether the previous declaration is in the same block scope. This 7317 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7318 if (getLangOpts().CPlusPlus && 7319 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7320 NewVD->setPreviousDeclInSameBlockScope( 7321 Previous.isSingleResult() && !Previous.isShadowed() && 7322 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7323 7324 if (!getLangOpts().CPlusPlus) { 7325 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7326 } else { 7327 // If this is an explicit specialization of a static data member, check it. 7328 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7329 CheckMemberSpecialization(NewVD, Previous)) 7330 NewVD->setInvalidDecl(); 7331 7332 // Merge the decl with the existing one if appropriate. 7333 if (!Previous.empty()) { 7334 if (Previous.isSingleResult() && 7335 isa<FieldDecl>(Previous.getFoundDecl()) && 7336 D.getCXXScopeSpec().isSet()) { 7337 // The user tried to define a non-static data member 7338 // out-of-line (C++ [dcl.meaning]p1). 7339 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7340 << D.getCXXScopeSpec().getRange(); 7341 Previous.clear(); 7342 NewVD->setInvalidDecl(); 7343 } 7344 } else if (D.getCXXScopeSpec().isSet()) { 7345 // No previous declaration in the qualifying scope. 7346 Diag(D.getIdentifierLoc(), diag::err_no_member) 7347 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7348 << D.getCXXScopeSpec().getRange(); 7349 NewVD->setInvalidDecl(); 7350 } 7351 7352 if (!IsVariableTemplateSpecialization) 7353 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7354 7355 if (NewTemplate) { 7356 VarTemplateDecl *PrevVarTemplate = 7357 NewVD->getPreviousDecl() 7358 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7359 : nullptr; 7360 7361 // Check the template parameter list of this declaration, possibly 7362 // merging in the template parameter list from the previous variable 7363 // template declaration. 7364 if (CheckTemplateParameterList( 7365 TemplateParams, 7366 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7367 : nullptr, 7368 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7369 DC->isDependentContext()) 7370 ? TPC_ClassTemplateMember 7371 : TPC_VarTemplate)) 7372 NewVD->setInvalidDecl(); 7373 7374 // If we are providing an explicit specialization of a static variable 7375 // template, make a note of that. 7376 if (PrevVarTemplate && 7377 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7378 PrevVarTemplate->setMemberSpecialization(); 7379 } 7380 } 7381 7382 // Diagnose shadowed variables iff this isn't a redeclaration. 7383 if (ShadowedDecl && !D.isRedeclaration()) 7384 CheckShadow(NewVD, ShadowedDecl, Previous); 7385 7386 ProcessPragmaWeak(S, NewVD); 7387 7388 // If this is the first declaration of an extern C variable, update 7389 // the map of such variables. 7390 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7391 isIncompleteDeclExternC(*this, NewVD)) 7392 RegisterLocallyScopedExternCDecl(NewVD, S); 7393 7394 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7395 MangleNumberingContext *MCtx; 7396 Decl *ManglingContextDecl; 7397 std::tie(MCtx, ManglingContextDecl) = 7398 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7399 if (MCtx) { 7400 Context.setManglingNumber( 7401 NewVD, MCtx->getManglingNumber( 7402 NewVD, getMSManglingNumber(getLangOpts(), S))); 7403 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7404 } 7405 } 7406 7407 // Special handling of variable named 'main'. 7408 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7409 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7410 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7411 7412 // C++ [basic.start.main]p3 7413 // A program that declares a variable main at global scope is ill-formed. 7414 if (getLangOpts().CPlusPlus) 7415 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7416 7417 // In C, and external-linkage variable named main results in undefined 7418 // behavior. 7419 else if (NewVD->hasExternalFormalLinkage()) 7420 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7421 } 7422 7423 if (D.isRedeclaration() && !Previous.empty()) { 7424 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7425 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7426 D.isFunctionDefinition()); 7427 } 7428 7429 if (NewTemplate) { 7430 if (NewVD->isInvalidDecl()) 7431 NewTemplate->setInvalidDecl(); 7432 ActOnDocumentableDecl(NewTemplate); 7433 return NewTemplate; 7434 } 7435 7436 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7437 CompleteMemberSpecialization(NewVD, Previous); 7438 7439 return NewVD; 7440 } 7441 7442 /// Enum describing the %select options in diag::warn_decl_shadow. 7443 enum ShadowedDeclKind { 7444 SDK_Local, 7445 SDK_Global, 7446 SDK_StaticMember, 7447 SDK_Field, 7448 SDK_Typedef, 7449 SDK_Using 7450 }; 7451 7452 /// Determine what kind of declaration we're shadowing. 7453 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7454 const DeclContext *OldDC) { 7455 if (isa<TypeAliasDecl>(ShadowedDecl)) 7456 return SDK_Using; 7457 else if (isa<TypedefDecl>(ShadowedDecl)) 7458 return SDK_Typedef; 7459 else if (isa<RecordDecl>(OldDC)) 7460 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7461 7462 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7463 } 7464 7465 /// Return the location of the capture if the given lambda captures the given 7466 /// variable \p VD, or an invalid source location otherwise. 7467 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7468 const VarDecl *VD) { 7469 for (const Capture &Capture : LSI->Captures) { 7470 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7471 return Capture.getLocation(); 7472 } 7473 return SourceLocation(); 7474 } 7475 7476 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7477 const LookupResult &R) { 7478 // Only diagnose if we're shadowing an unambiguous field or variable. 7479 if (R.getResultKind() != LookupResult::Found) 7480 return false; 7481 7482 // Return false if warning is ignored. 7483 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7484 } 7485 7486 /// Return the declaration shadowed by the given variable \p D, or null 7487 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7488 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7489 const LookupResult &R) { 7490 if (!shouldWarnIfShadowedDecl(Diags, R)) 7491 return nullptr; 7492 7493 // Don't diagnose declarations at file scope. 7494 if (D->hasGlobalStorage()) 7495 return nullptr; 7496 7497 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7498 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7499 ? ShadowedDecl 7500 : nullptr; 7501 } 7502 7503 /// Return the declaration shadowed by the given typedef \p D, or null 7504 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7505 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7506 const LookupResult &R) { 7507 // Don't warn if typedef declaration is part of a class 7508 if (D->getDeclContext()->isRecord()) 7509 return nullptr; 7510 7511 if (!shouldWarnIfShadowedDecl(Diags, R)) 7512 return nullptr; 7513 7514 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7515 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7516 } 7517 7518 /// Diagnose variable or built-in function shadowing. Implements 7519 /// -Wshadow. 7520 /// 7521 /// This method is called whenever a VarDecl is added to a "useful" 7522 /// scope. 7523 /// 7524 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7525 /// \param R the lookup of the name 7526 /// 7527 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7528 const LookupResult &R) { 7529 DeclContext *NewDC = D->getDeclContext(); 7530 7531 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7532 // Fields are not shadowed by variables in C++ static methods. 7533 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7534 if (MD->isStatic()) 7535 return; 7536 7537 // Fields shadowed by constructor parameters are a special case. Usually 7538 // the constructor initializes the field with the parameter. 7539 if (isa<CXXConstructorDecl>(NewDC)) 7540 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7541 // Remember that this was shadowed so we can either warn about its 7542 // modification or its existence depending on warning settings. 7543 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7544 return; 7545 } 7546 } 7547 7548 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7549 if (shadowedVar->isExternC()) { 7550 // For shadowing external vars, make sure that we point to the global 7551 // declaration, not a locally scoped extern declaration. 7552 for (auto I : shadowedVar->redecls()) 7553 if (I->isFileVarDecl()) { 7554 ShadowedDecl = I; 7555 break; 7556 } 7557 } 7558 7559 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7560 7561 unsigned WarningDiag = diag::warn_decl_shadow; 7562 SourceLocation CaptureLoc; 7563 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7564 isa<CXXMethodDecl>(NewDC)) { 7565 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7566 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7567 if (RD->getLambdaCaptureDefault() == LCD_None) { 7568 // Try to avoid warnings for lambdas with an explicit capture list. 7569 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7570 // Warn only when the lambda captures the shadowed decl explicitly. 7571 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7572 if (CaptureLoc.isInvalid()) 7573 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7574 } else { 7575 // Remember that this was shadowed so we can avoid the warning if the 7576 // shadowed decl isn't captured and the warning settings allow it. 7577 cast<LambdaScopeInfo>(getCurFunction()) 7578 ->ShadowingDecls.push_back( 7579 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7580 return; 7581 } 7582 } 7583 7584 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7585 // A variable can't shadow a local variable in an enclosing scope, if 7586 // they are separated by a non-capturing declaration context. 7587 for (DeclContext *ParentDC = NewDC; 7588 ParentDC && !ParentDC->Equals(OldDC); 7589 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7590 // Only block literals, captured statements, and lambda expressions 7591 // can capture; other scopes don't. 7592 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7593 !isLambdaCallOperator(ParentDC)) { 7594 return; 7595 } 7596 } 7597 } 7598 } 7599 } 7600 7601 // Only warn about certain kinds of shadowing for class members. 7602 if (NewDC && NewDC->isRecord()) { 7603 // In particular, don't warn about shadowing non-class members. 7604 if (!OldDC->isRecord()) 7605 return; 7606 7607 // TODO: should we warn about static data members shadowing 7608 // static data members from base classes? 7609 7610 // TODO: don't diagnose for inaccessible shadowed members. 7611 // This is hard to do perfectly because we might friend the 7612 // shadowing context, but that's just a false negative. 7613 } 7614 7615 7616 DeclarationName Name = R.getLookupName(); 7617 7618 // Emit warning and note. 7619 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7620 return; 7621 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7622 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7623 if (!CaptureLoc.isInvalid()) 7624 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7625 << Name << /*explicitly*/ 1; 7626 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7627 } 7628 7629 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7630 /// when these variables are captured by the lambda. 7631 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7632 for (const auto &Shadow : LSI->ShadowingDecls) { 7633 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7634 // Try to avoid the warning when the shadowed decl isn't captured. 7635 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7636 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7637 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7638 ? diag::warn_decl_shadow_uncaptured_local 7639 : diag::warn_decl_shadow) 7640 << Shadow.VD->getDeclName() 7641 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7642 if (!CaptureLoc.isInvalid()) 7643 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7644 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7645 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7646 } 7647 } 7648 7649 /// Check -Wshadow without the advantage of a previous lookup. 7650 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7651 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7652 return; 7653 7654 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7655 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7656 LookupName(R, S); 7657 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7658 CheckShadow(D, ShadowedDecl, R); 7659 } 7660 7661 /// Check if 'E', which is an expression that is about to be modified, refers 7662 /// to a constructor parameter that shadows a field. 7663 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7664 // Quickly ignore expressions that can't be shadowing ctor parameters. 7665 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7666 return; 7667 E = E->IgnoreParenImpCasts(); 7668 auto *DRE = dyn_cast<DeclRefExpr>(E); 7669 if (!DRE) 7670 return; 7671 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7672 auto I = ShadowingDecls.find(D); 7673 if (I == ShadowingDecls.end()) 7674 return; 7675 const NamedDecl *ShadowedDecl = I->second; 7676 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7677 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7678 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7679 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7680 7681 // Avoid issuing multiple warnings about the same decl. 7682 ShadowingDecls.erase(I); 7683 } 7684 7685 /// Check for conflict between this global or extern "C" declaration and 7686 /// previous global or extern "C" declarations. This is only used in C++. 7687 template<typename T> 7688 static bool checkGlobalOrExternCConflict( 7689 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7690 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7691 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7692 7693 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7694 // The common case: this global doesn't conflict with any extern "C" 7695 // declaration. 7696 return false; 7697 } 7698 7699 if (Prev) { 7700 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7701 // Both the old and new declarations have C language linkage. This is a 7702 // redeclaration. 7703 Previous.clear(); 7704 Previous.addDecl(Prev); 7705 return true; 7706 } 7707 7708 // This is a global, non-extern "C" declaration, and there is a previous 7709 // non-global extern "C" declaration. Diagnose if this is a variable 7710 // declaration. 7711 if (!isa<VarDecl>(ND)) 7712 return false; 7713 } else { 7714 // The declaration is extern "C". Check for any declaration in the 7715 // translation unit which might conflict. 7716 if (IsGlobal) { 7717 // We have already performed the lookup into the translation unit. 7718 IsGlobal = false; 7719 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7720 I != E; ++I) { 7721 if (isa<VarDecl>(*I)) { 7722 Prev = *I; 7723 break; 7724 } 7725 } 7726 } else { 7727 DeclContext::lookup_result R = 7728 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7729 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7730 I != E; ++I) { 7731 if (isa<VarDecl>(*I)) { 7732 Prev = *I; 7733 break; 7734 } 7735 // FIXME: If we have any other entity with this name in global scope, 7736 // the declaration is ill-formed, but that is a defect: it breaks the 7737 // 'stat' hack, for instance. Only variables can have mangled name 7738 // clashes with extern "C" declarations, so only they deserve a 7739 // diagnostic. 7740 } 7741 } 7742 7743 if (!Prev) 7744 return false; 7745 } 7746 7747 // Use the first declaration's location to ensure we point at something which 7748 // is lexically inside an extern "C" linkage-spec. 7749 assert(Prev && "should have found a previous declaration to diagnose"); 7750 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7751 Prev = FD->getFirstDecl(); 7752 else 7753 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7754 7755 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7756 << IsGlobal << ND; 7757 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7758 << IsGlobal; 7759 return false; 7760 } 7761 7762 /// Apply special rules for handling extern "C" declarations. Returns \c true 7763 /// if we have found that this is a redeclaration of some prior entity. 7764 /// 7765 /// Per C++ [dcl.link]p6: 7766 /// Two declarations [for a function or variable] with C language linkage 7767 /// with the same name that appear in different scopes refer to the same 7768 /// [entity]. An entity with C language linkage shall not be declared with 7769 /// the same name as an entity in global scope. 7770 template<typename T> 7771 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7772 LookupResult &Previous) { 7773 if (!S.getLangOpts().CPlusPlus) { 7774 // In C, when declaring a global variable, look for a corresponding 'extern' 7775 // variable declared in function scope. We don't need this in C++, because 7776 // we find local extern decls in the surrounding file-scope DeclContext. 7777 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7778 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7779 Previous.clear(); 7780 Previous.addDecl(Prev); 7781 return true; 7782 } 7783 } 7784 return false; 7785 } 7786 7787 // A declaration in the translation unit can conflict with an extern "C" 7788 // declaration. 7789 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7790 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7791 7792 // An extern "C" declaration can conflict with a declaration in the 7793 // translation unit or can be a redeclaration of an extern "C" declaration 7794 // in another scope. 7795 if (isIncompleteDeclExternC(S,ND)) 7796 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7797 7798 // Neither global nor extern "C": nothing to do. 7799 return false; 7800 } 7801 7802 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7803 // If the decl is already known invalid, don't check it. 7804 if (NewVD->isInvalidDecl()) 7805 return; 7806 7807 QualType T = NewVD->getType(); 7808 7809 // Defer checking an 'auto' type until its initializer is attached. 7810 if (T->isUndeducedType()) 7811 return; 7812 7813 if (NewVD->hasAttrs()) 7814 CheckAlignasUnderalignment(NewVD); 7815 7816 if (T->isObjCObjectType()) { 7817 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7818 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7819 T = Context.getObjCObjectPointerType(T); 7820 NewVD->setType(T); 7821 } 7822 7823 // Emit an error if an address space was applied to decl with local storage. 7824 // This includes arrays of objects with address space qualifiers, but not 7825 // automatic variables that point to other address spaces. 7826 // ISO/IEC TR 18037 S5.1.2 7827 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7828 T.getAddressSpace() != LangAS::Default) { 7829 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7830 NewVD->setInvalidDecl(); 7831 return; 7832 } 7833 7834 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7835 // scope. 7836 if (getLangOpts().OpenCLVersion == 120 && 7837 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7838 NewVD->isStaticLocal()) { 7839 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7840 NewVD->setInvalidDecl(); 7841 return; 7842 } 7843 7844 if (getLangOpts().OpenCL) { 7845 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7846 if (NewVD->hasAttr<BlocksAttr>()) { 7847 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7848 return; 7849 } 7850 7851 if (T->isBlockPointerType()) { 7852 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7853 // can't use 'extern' storage class. 7854 if (!T.isConstQualified()) { 7855 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7856 << 0 /*const*/; 7857 NewVD->setInvalidDecl(); 7858 return; 7859 } 7860 if (NewVD->hasExternalStorage()) { 7861 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7862 NewVD->setInvalidDecl(); 7863 return; 7864 } 7865 } 7866 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7867 // __constant address space. 7868 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7869 // variables inside a function can also be declared in the global 7870 // address space. 7871 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7872 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7873 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7874 NewVD->hasExternalStorage()) { 7875 if (!T->isSamplerT() && 7876 !T->isDependentType() && 7877 !(T.getAddressSpace() == LangAS::opencl_constant || 7878 (T.getAddressSpace() == LangAS::opencl_global && 7879 (getLangOpts().OpenCLVersion == 200 || 7880 getLangOpts().OpenCLCPlusPlus)))) { 7881 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7882 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7883 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7884 << Scope << "global or constant"; 7885 else 7886 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7887 << Scope << "constant"; 7888 NewVD->setInvalidDecl(); 7889 return; 7890 } 7891 } else { 7892 if (T.getAddressSpace() == LangAS::opencl_global) { 7893 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7894 << 1 /*is any function*/ << "global"; 7895 NewVD->setInvalidDecl(); 7896 return; 7897 } 7898 if (T.getAddressSpace() == LangAS::opencl_constant || 7899 T.getAddressSpace() == LangAS::opencl_local) { 7900 FunctionDecl *FD = getCurFunctionDecl(); 7901 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7902 // in functions. 7903 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7904 if (T.getAddressSpace() == LangAS::opencl_constant) 7905 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7906 << 0 /*non-kernel only*/ << "constant"; 7907 else 7908 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7909 << 0 /*non-kernel only*/ << "local"; 7910 NewVD->setInvalidDecl(); 7911 return; 7912 } 7913 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7914 // in the outermost scope of a kernel function. 7915 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7916 if (!getCurScope()->isFunctionScope()) { 7917 if (T.getAddressSpace() == LangAS::opencl_constant) 7918 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7919 << "constant"; 7920 else 7921 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7922 << "local"; 7923 NewVD->setInvalidDecl(); 7924 return; 7925 } 7926 } 7927 } else if (T.getAddressSpace() != LangAS::opencl_private && 7928 // If we are parsing a template we didn't deduce an addr 7929 // space yet. 7930 T.getAddressSpace() != LangAS::Default) { 7931 // Do not allow other address spaces on automatic variable. 7932 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7933 NewVD->setInvalidDecl(); 7934 return; 7935 } 7936 } 7937 } 7938 7939 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7940 && !NewVD->hasAttr<BlocksAttr>()) { 7941 if (getLangOpts().getGC() != LangOptions::NonGC) 7942 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7943 else { 7944 assert(!getLangOpts().ObjCAutoRefCount); 7945 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7946 } 7947 } 7948 7949 bool isVM = T->isVariablyModifiedType(); 7950 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7951 NewVD->hasAttr<BlocksAttr>()) 7952 setFunctionHasBranchProtectedScope(); 7953 7954 if ((isVM && NewVD->hasLinkage()) || 7955 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7956 bool SizeIsNegative; 7957 llvm::APSInt Oversized; 7958 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7959 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7960 QualType FixedT; 7961 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7962 FixedT = FixedTInfo->getType(); 7963 else if (FixedTInfo) { 7964 // Type and type-as-written are canonically different. We need to fix up 7965 // both types separately. 7966 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7967 Oversized); 7968 } 7969 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7970 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7971 // FIXME: This won't give the correct result for 7972 // int a[10][n]; 7973 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7974 7975 if (NewVD->isFileVarDecl()) 7976 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7977 << SizeRange; 7978 else if (NewVD->isStaticLocal()) 7979 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7980 << SizeRange; 7981 else 7982 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7983 << SizeRange; 7984 NewVD->setInvalidDecl(); 7985 return; 7986 } 7987 7988 if (!FixedTInfo) { 7989 if (NewVD->isFileVarDecl()) 7990 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7991 else 7992 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7993 NewVD->setInvalidDecl(); 7994 return; 7995 } 7996 7997 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 7998 NewVD->setType(FixedT); 7999 NewVD->setTypeSourceInfo(FixedTInfo); 8000 } 8001 8002 if (T->isVoidType()) { 8003 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8004 // of objects and functions. 8005 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8006 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8007 << T; 8008 NewVD->setInvalidDecl(); 8009 return; 8010 } 8011 } 8012 8013 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8014 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8015 NewVD->setInvalidDecl(); 8016 return; 8017 } 8018 8019 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8020 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8021 NewVD->setInvalidDecl(); 8022 return; 8023 } 8024 8025 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8026 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8027 NewVD->setInvalidDecl(); 8028 return; 8029 } 8030 8031 if (NewVD->isConstexpr() && !T->isDependentType() && 8032 RequireLiteralType(NewVD->getLocation(), T, 8033 diag::err_constexpr_var_non_literal)) { 8034 NewVD->setInvalidDecl(); 8035 return; 8036 } 8037 } 8038 8039 /// Perform semantic checking on a newly-created variable 8040 /// declaration. 8041 /// 8042 /// This routine performs all of the type-checking required for a 8043 /// variable declaration once it has been built. It is used both to 8044 /// check variables after they have been parsed and their declarators 8045 /// have been translated into a declaration, and to check variables 8046 /// that have been instantiated from a template. 8047 /// 8048 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8049 /// 8050 /// Returns true if the variable declaration is a redeclaration. 8051 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8052 CheckVariableDeclarationType(NewVD); 8053 8054 // If the decl is already known invalid, don't check it. 8055 if (NewVD->isInvalidDecl()) 8056 return false; 8057 8058 // If we did not find anything by this name, look for a non-visible 8059 // extern "C" declaration with the same name. 8060 if (Previous.empty() && 8061 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8062 Previous.setShadowed(); 8063 8064 if (!Previous.empty()) { 8065 MergeVarDecl(NewVD, Previous); 8066 return true; 8067 } 8068 return false; 8069 } 8070 8071 namespace { 8072 struct FindOverriddenMethod { 8073 Sema *S; 8074 CXXMethodDecl *Method; 8075 8076 /// Member lookup function that determines whether a given C++ 8077 /// method overrides a method in a base class, to be used with 8078 /// CXXRecordDecl::lookupInBases(). 8079 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8080 RecordDecl *BaseRecord = 8081 Specifier->getType()->castAs<RecordType>()->getDecl(); 8082 8083 DeclarationName Name = Method->getDeclName(); 8084 8085 // FIXME: Do we care about other names here too? 8086 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8087 // We really want to find the base class destructor here. 8088 QualType T = S->Context.getTypeDeclType(BaseRecord); 8089 CanQualType CT = S->Context.getCanonicalType(T); 8090 8091 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8092 } 8093 8094 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8095 Path.Decls = Path.Decls.slice(1)) { 8096 NamedDecl *D = Path.Decls.front(); 8097 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8098 if (MD->isVirtual() && 8099 !S->IsOverload( 8100 Method, MD, /*UseMemberUsingDeclRules=*/false, 8101 /*ConsiderCudaAttrs=*/true, 8102 // C++2a [class.virtual]p2 does not consider requires clauses 8103 // when overriding. 8104 /*ConsiderRequiresClauses=*/false)) 8105 return true; 8106 } 8107 } 8108 8109 return false; 8110 } 8111 }; 8112 } // end anonymous namespace 8113 8114 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8115 /// and if so, check that it's a valid override and remember it. 8116 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8117 // Look for methods in base classes that this method might override. 8118 CXXBasePaths Paths; 8119 FindOverriddenMethod FOM; 8120 FOM.Method = MD; 8121 FOM.S = this; 8122 bool AddedAny = false; 8123 if (DC->lookupInBases(FOM, Paths)) { 8124 for (auto *I : Paths.found_decls()) { 8125 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8126 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8127 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8128 !CheckOverridingFunctionAttributes(MD, OldMD) && 8129 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8130 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8131 AddedAny = true; 8132 } 8133 } 8134 } 8135 } 8136 8137 return AddedAny; 8138 } 8139 8140 namespace { 8141 // Struct for holding all of the extra arguments needed by 8142 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8143 struct ActOnFDArgs { 8144 Scope *S; 8145 Declarator &D; 8146 MultiTemplateParamsArg TemplateParamLists; 8147 bool AddToScope; 8148 }; 8149 } // end anonymous namespace 8150 8151 namespace { 8152 8153 // Callback to only accept typo corrections that have a non-zero edit distance. 8154 // Also only accept corrections that have the same parent decl. 8155 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8156 public: 8157 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8158 CXXRecordDecl *Parent) 8159 : Context(Context), OriginalFD(TypoFD), 8160 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8161 8162 bool ValidateCandidate(const TypoCorrection &candidate) override { 8163 if (candidate.getEditDistance() == 0) 8164 return false; 8165 8166 SmallVector<unsigned, 1> MismatchedParams; 8167 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8168 CDeclEnd = candidate.end(); 8169 CDecl != CDeclEnd; ++CDecl) { 8170 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8171 8172 if (FD && !FD->hasBody() && 8173 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8174 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8175 CXXRecordDecl *Parent = MD->getParent(); 8176 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8177 return true; 8178 } else if (!ExpectedParent) { 8179 return true; 8180 } 8181 } 8182 } 8183 8184 return false; 8185 } 8186 8187 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8188 return std::make_unique<DifferentNameValidatorCCC>(*this); 8189 } 8190 8191 private: 8192 ASTContext &Context; 8193 FunctionDecl *OriginalFD; 8194 CXXRecordDecl *ExpectedParent; 8195 }; 8196 8197 } // end anonymous namespace 8198 8199 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8200 TypoCorrectedFunctionDefinitions.insert(F); 8201 } 8202 8203 /// Generate diagnostics for an invalid function redeclaration. 8204 /// 8205 /// This routine handles generating the diagnostic messages for an invalid 8206 /// function redeclaration, including finding possible similar declarations 8207 /// or performing typo correction if there are no previous declarations with 8208 /// the same name. 8209 /// 8210 /// Returns a NamedDecl iff typo correction was performed and substituting in 8211 /// the new declaration name does not cause new errors. 8212 static NamedDecl *DiagnoseInvalidRedeclaration( 8213 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8214 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8215 DeclarationName Name = NewFD->getDeclName(); 8216 DeclContext *NewDC = NewFD->getDeclContext(); 8217 SmallVector<unsigned, 1> MismatchedParams; 8218 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8219 TypoCorrection Correction; 8220 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8221 unsigned DiagMsg = 8222 IsLocalFriend ? diag::err_no_matching_local_friend : 8223 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8224 diag::err_member_decl_does_not_match; 8225 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8226 IsLocalFriend ? Sema::LookupLocalFriendName 8227 : Sema::LookupOrdinaryName, 8228 Sema::ForVisibleRedeclaration); 8229 8230 NewFD->setInvalidDecl(); 8231 if (IsLocalFriend) 8232 SemaRef.LookupName(Prev, S); 8233 else 8234 SemaRef.LookupQualifiedName(Prev, NewDC); 8235 assert(!Prev.isAmbiguous() && 8236 "Cannot have an ambiguity in previous-declaration lookup"); 8237 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8238 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8239 MD ? MD->getParent() : nullptr); 8240 if (!Prev.empty()) { 8241 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8242 Func != FuncEnd; ++Func) { 8243 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8244 if (FD && 8245 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8246 // Add 1 to the index so that 0 can mean the mismatch didn't 8247 // involve a parameter 8248 unsigned ParamNum = 8249 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8250 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8251 } 8252 } 8253 // If the qualified name lookup yielded nothing, try typo correction 8254 } else if ((Correction = SemaRef.CorrectTypo( 8255 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8256 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8257 IsLocalFriend ? nullptr : NewDC))) { 8258 // Set up everything for the call to ActOnFunctionDeclarator 8259 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8260 ExtraArgs.D.getIdentifierLoc()); 8261 Previous.clear(); 8262 Previous.setLookupName(Correction.getCorrection()); 8263 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8264 CDeclEnd = Correction.end(); 8265 CDecl != CDeclEnd; ++CDecl) { 8266 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8267 if (FD && !FD->hasBody() && 8268 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8269 Previous.addDecl(FD); 8270 } 8271 } 8272 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8273 8274 NamedDecl *Result; 8275 // Retry building the function declaration with the new previous 8276 // declarations, and with errors suppressed. 8277 { 8278 // Trap errors. 8279 Sema::SFINAETrap Trap(SemaRef); 8280 8281 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8282 // pieces need to verify the typo-corrected C++ declaration and hopefully 8283 // eliminate the need for the parameter pack ExtraArgs. 8284 Result = SemaRef.ActOnFunctionDeclarator( 8285 ExtraArgs.S, ExtraArgs.D, 8286 Correction.getCorrectionDecl()->getDeclContext(), 8287 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8288 ExtraArgs.AddToScope); 8289 8290 if (Trap.hasErrorOccurred()) 8291 Result = nullptr; 8292 } 8293 8294 if (Result) { 8295 // Determine which correction we picked. 8296 Decl *Canonical = Result->getCanonicalDecl(); 8297 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8298 I != E; ++I) 8299 if ((*I)->getCanonicalDecl() == Canonical) 8300 Correction.setCorrectionDecl(*I); 8301 8302 // Let Sema know about the correction. 8303 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8304 SemaRef.diagnoseTypo( 8305 Correction, 8306 SemaRef.PDiag(IsLocalFriend 8307 ? diag::err_no_matching_local_friend_suggest 8308 : diag::err_member_decl_does_not_match_suggest) 8309 << Name << NewDC << IsDefinition); 8310 return Result; 8311 } 8312 8313 // Pretend the typo correction never occurred 8314 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8315 ExtraArgs.D.getIdentifierLoc()); 8316 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8317 Previous.clear(); 8318 Previous.setLookupName(Name); 8319 } 8320 8321 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8322 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8323 8324 bool NewFDisConst = false; 8325 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8326 NewFDisConst = NewMD->isConst(); 8327 8328 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8329 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8330 NearMatch != NearMatchEnd; ++NearMatch) { 8331 FunctionDecl *FD = NearMatch->first; 8332 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8333 bool FDisConst = MD && MD->isConst(); 8334 bool IsMember = MD || !IsLocalFriend; 8335 8336 // FIXME: These notes are poorly worded for the local friend case. 8337 if (unsigned Idx = NearMatch->second) { 8338 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8339 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8340 if (Loc.isInvalid()) Loc = FD->getLocation(); 8341 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8342 : diag::note_local_decl_close_param_match) 8343 << Idx << FDParam->getType() 8344 << NewFD->getParamDecl(Idx - 1)->getType(); 8345 } else if (FDisConst != NewFDisConst) { 8346 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8347 << NewFDisConst << FD->getSourceRange().getEnd(); 8348 } else 8349 SemaRef.Diag(FD->getLocation(), 8350 IsMember ? diag::note_member_def_close_match 8351 : diag::note_local_decl_close_match); 8352 } 8353 return nullptr; 8354 } 8355 8356 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8357 switch (D.getDeclSpec().getStorageClassSpec()) { 8358 default: llvm_unreachable("Unknown storage class!"); 8359 case DeclSpec::SCS_auto: 8360 case DeclSpec::SCS_register: 8361 case DeclSpec::SCS_mutable: 8362 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8363 diag::err_typecheck_sclass_func); 8364 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8365 D.setInvalidType(); 8366 break; 8367 case DeclSpec::SCS_unspecified: break; 8368 case DeclSpec::SCS_extern: 8369 if (D.getDeclSpec().isExternInLinkageSpec()) 8370 return SC_None; 8371 return SC_Extern; 8372 case DeclSpec::SCS_static: { 8373 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8374 // C99 6.7.1p5: 8375 // The declaration of an identifier for a function that has 8376 // block scope shall have no explicit storage-class specifier 8377 // other than extern 8378 // See also (C++ [dcl.stc]p4). 8379 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8380 diag::err_static_block_func); 8381 break; 8382 } else 8383 return SC_Static; 8384 } 8385 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8386 } 8387 8388 // No explicit storage class has already been returned 8389 return SC_None; 8390 } 8391 8392 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8393 DeclContext *DC, QualType &R, 8394 TypeSourceInfo *TInfo, 8395 StorageClass SC, 8396 bool &IsVirtualOkay) { 8397 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8398 DeclarationName Name = NameInfo.getName(); 8399 8400 FunctionDecl *NewFD = nullptr; 8401 bool isInline = D.getDeclSpec().isInlineSpecified(); 8402 8403 if (!SemaRef.getLangOpts().CPlusPlus) { 8404 // Determine whether the function was written with a 8405 // prototype. This true when: 8406 // - there is a prototype in the declarator, or 8407 // - the type R of the function is some kind of typedef or other non- 8408 // attributed reference to a type name (which eventually refers to a 8409 // function type). 8410 bool HasPrototype = 8411 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8412 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8413 8414 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8415 R, TInfo, SC, isInline, HasPrototype, 8416 CSK_unspecified, 8417 /*TrailingRequiresClause=*/nullptr); 8418 if (D.isInvalidType()) 8419 NewFD->setInvalidDecl(); 8420 8421 return NewFD; 8422 } 8423 8424 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8425 8426 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8427 if (ConstexprKind == CSK_constinit) { 8428 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8429 diag::err_constexpr_wrong_decl_kind) 8430 << ConstexprKind; 8431 ConstexprKind = CSK_unspecified; 8432 D.getMutableDeclSpec().ClearConstexprSpec(); 8433 } 8434 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8435 8436 // Check that the return type is not an abstract class type. 8437 // For record types, this is done by the AbstractClassUsageDiagnoser once 8438 // the class has been completely parsed. 8439 if (!DC->isRecord() && 8440 SemaRef.RequireNonAbstractType( 8441 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8442 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8443 D.setInvalidType(); 8444 8445 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8446 // This is a C++ constructor declaration. 8447 assert(DC->isRecord() && 8448 "Constructors can only be declared in a member context"); 8449 8450 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8451 return CXXConstructorDecl::Create( 8452 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8453 TInfo, ExplicitSpecifier, isInline, 8454 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8455 TrailingRequiresClause); 8456 8457 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8458 // This is a C++ destructor declaration. 8459 if (DC->isRecord()) { 8460 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8461 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8462 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8463 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8464 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8465 TrailingRequiresClause); 8466 8467 // If the destructor needs an implicit exception specification, set it 8468 // now. FIXME: It'd be nice to be able to create the right type to start 8469 // with, but the type needs to reference the destructor declaration. 8470 if (SemaRef.getLangOpts().CPlusPlus11) 8471 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8472 8473 IsVirtualOkay = true; 8474 return NewDD; 8475 8476 } else { 8477 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8478 D.setInvalidType(); 8479 8480 // Create a FunctionDecl to satisfy the function definition parsing 8481 // code path. 8482 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8483 D.getIdentifierLoc(), Name, R, TInfo, SC, 8484 isInline, 8485 /*hasPrototype=*/true, ConstexprKind, 8486 TrailingRequiresClause); 8487 } 8488 8489 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8490 if (!DC->isRecord()) { 8491 SemaRef.Diag(D.getIdentifierLoc(), 8492 diag::err_conv_function_not_member); 8493 return nullptr; 8494 } 8495 8496 SemaRef.CheckConversionDeclarator(D, R, SC); 8497 if (D.isInvalidType()) 8498 return nullptr; 8499 8500 IsVirtualOkay = true; 8501 return CXXConversionDecl::Create( 8502 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8503 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8504 TrailingRequiresClause); 8505 8506 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8507 if (TrailingRequiresClause) 8508 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8509 diag::err_trailing_requires_clause_on_deduction_guide) 8510 << TrailingRequiresClause->getSourceRange(); 8511 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8512 8513 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8514 ExplicitSpecifier, NameInfo, R, TInfo, 8515 D.getEndLoc()); 8516 } else if (DC->isRecord()) { 8517 // If the name of the function is the same as the name of the record, 8518 // then this must be an invalid constructor that has a return type. 8519 // (The parser checks for a return type and makes the declarator a 8520 // constructor if it has no return type). 8521 if (Name.getAsIdentifierInfo() && 8522 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8523 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8524 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8525 << SourceRange(D.getIdentifierLoc()); 8526 return nullptr; 8527 } 8528 8529 // This is a C++ method declaration. 8530 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8531 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8532 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8533 TrailingRequiresClause); 8534 IsVirtualOkay = !Ret->isStatic(); 8535 return Ret; 8536 } else { 8537 bool isFriend = 8538 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8539 if (!isFriend && SemaRef.CurContext->isRecord()) 8540 return nullptr; 8541 8542 // Determine whether the function was written with a 8543 // prototype. This true when: 8544 // - we're in C++ (where every function has a prototype), 8545 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8546 R, TInfo, SC, isInline, true /*HasPrototype*/, 8547 ConstexprKind, TrailingRequiresClause); 8548 } 8549 } 8550 8551 enum OpenCLParamType { 8552 ValidKernelParam, 8553 PtrPtrKernelParam, 8554 PtrKernelParam, 8555 InvalidAddrSpacePtrKernelParam, 8556 InvalidKernelParam, 8557 RecordKernelParam 8558 }; 8559 8560 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8561 // Size dependent types are just typedefs to normal integer types 8562 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8563 // integers other than by their names. 8564 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8565 8566 // Remove typedefs one by one until we reach a typedef 8567 // for a size dependent type. 8568 QualType DesugaredTy = Ty; 8569 do { 8570 ArrayRef<StringRef> Names(SizeTypeNames); 8571 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8572 if (Names.end() != Match) 8573 return true; 8574 8575 Ty = DesugaredTy; 8576 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8577 } while (DesugaredTy != Ty); 8578 8579 return false; 8580 } 8581 8582 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8583 if (PT->isPointerType()) { 8584 QualType PointeeType = PT->getPointeeType(); 8585 if (PointeeType->isPointerType()) 8586 return PtrPtrKernelParam; 8587 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8588 PointeeType.getAddressSpace() == LangAS::opencl_private || 8589 PointeeType.getAddressSpace() == LangAS::Default) 8590 return InvalidAddrSpacePtrKernelParam; 8591 return PtrKernelParam; 8592 } 8593 8594 // OpenCL v1.2 s6.9.k: 8595 // Arguments to kernel functions in a program cannot be declared with the 8596 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8597 // uintptr_t or a struct and/or union that contain fields declared to be one 8598 // of these built-in scalar types. 8599 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8600 return InvalidKernelParam; 8601 8602 if (PT->isImageType()) 8603 return PtrKernelParam; 8604 8605 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8606 return InvalidKernelParam; 8607 8608 // OpenCL extension spec v1.2 s9.5: 8609 // This extension adds support for half scalar and vector types as built-in 8610 // types that can be used for arithmetic operations, conversions etc. 8611 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8612 return InvalidKernelParam; 8613 8614 if (PT->isRecordType()) 8615 return RecordKernelParam; 8616 8617 // Look into an array argument to check if it has a forbidden type. 8618 if (PT->isArrayType()) { 8619 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8620 // Call ourself to check an underlying type of an array. Since the 8621 // getPointeeOrArrayElementType returns an innermost type which is not an 8622 // array, this recursive call only happens once. 8623 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8624 } 8625 8626 return ValidKernelParam; 8627 } 8628 8629 static void checkIsValidOpenCLKernelParameter( 8630 Sema &S, 8631 Declarator &D, 8632 ParmVarDecl *Param, 8633 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8634 QualType PT = Param->getType(); 8635 8636 // Cache the valid types we encounter to avoid rechecking structs that are 8637 // used again 8638 if (ValidTypes.count(PT.getTypePtr())) 8639 return; 8640 8641 switch (getOpenCLKernelParameterType(S, PT)) { 8642 case PtrPtrKernelParam: 8643 // OpenCL v1.2 s6.9.a: 8644 // A kernel function argument cannot be declared as a 8645 // pointer to a pointer type. 8646 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8647 D.setInvalidType(); 8648 return; 8649 8650 case InvalidAddrSpacePtrKernelParam: 8651 // OpenCL v1.0 s6.5: 8652 // __kernel function arguments declared to be a pointer of a type can point 8653 // to one of the following address spaces only : __global, __local or 8654 // __constant. 8655 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8656 D.setInvalidType(); 8657 return; 8658 8659 // OpenCL v1.2 s6.9.k: 8660 // Arguments to kernel functions in a program cannot be declared with the 8661 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8662 // uintptr_t or a struct and/or union that contain fields declared to be 8663 // one of these built-in scalar types. 8664 8665 case InvalidKernelParam: 8666 // OpenCL v1.2 s6.8 n: 8667 // A kernel function argument cannot be declared 8668 // of event_t type. 8669 // Do not diagnose half type since it is diagnosed as invalid argument 8670 // type for any function elsewhere. 8671 if (!PT->isHalfType()) { 8672 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8673 8674 // Explain what typedefs are involved. 8675 const TypedefType *Typedef = nullptr; 8676 while ((Typedef = PT->getAs<TypedefType>())) { 8677 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8678 // SourceLocation may be invalid for a built-in type. 8679 if (Loc.isValid()) 8680 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8681 PT = Typedef->desugar(); 8682 } 8683 } 8684 8685 D.setInvalidType(); 8686 return; 8687 8688 case PtrKernelParam: 8689 case ValidKernelParam: 8690 ValidTypes.insert(PT.getTypePtr()); 8691 return; 8692 8693 case RecordKernelParam: 8694 break; 8695 } 8696 8697 // Track nested structs we will inspect 8698 SmallVector<const Decl *, 4> VisitStack; 8699 8700 // Track where we are in the nested structs. Items will migrate from 8701 // VisitStack to HistoryStack as we do the DFS for bad field. 8702 SmallVector<const FieldDecl *, 4> HistoryStack; 8703 HistoryStack.push_back(nullptr); 8704 8705 // At this point we already handled everything except of a RecordType or 8706 // an ArrayType of a RecordType. 8707 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8708 const RecordType *RecTy = 8709 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8710 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8711 8712 VisitStack.push_back(RecTy->getDecl()); 8713 assert(VisitStack.back() && "First decl null?"); 8714 8715 do { 8716 const Decl *Next = VisitStack.pop_back_val(); 8717 if (!Next) { 8718 assert(!HistoryStack.empty()); 8719 // Found a marker, we have gone up a level 8720 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8721 ValidTypes.insert(Hist->getType().getTypePtr()); 8722 8723 continue; 8724 } 8725 8726 // Adds everything except the original parameter declaration (which is not a 8727 // field itself) to the history stack. 8728 const RecordDecl *RD; 8729 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8730 HistoryStack.push_back(Field); 8731 8732 QualType FieldTy = Field->getType(); 8733 // Other field types (known to be valid or invalid) are handled while we 8734 // walk around RecordDecl::fields(). 8735 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8736 "Unexpected type."); 8737 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8738 8739 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8740 } else { 8741 RD = cast<RecordDecl>(Next); 8742 } 8743 8744 // Add a null marker so we know when we've gone back up a level 8745 VisitStack.push_back(nullptr); 8746 8747 for (const auto *FD : RD->fields()) { 8748 QualType QT = FD->getType(); 8749 8750 if (ValidTypes.count(QT.getTypePtr())) 8751 continue; 8752 8753 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8754 if (ParamType == ValidKernelParam) 8755 continue; 8756 8757 if (ParamType == RecordKernelParam) { 8758 VisitStack.push_back(FD); 8759 continue; 8760 } 8761 8762 // OpenCL v1.2 s6.9.p: 8763 // Arguments to kernel functions that are declared to be a struct or union 8764 // do not allow OpenCL objects to be passed as elements of the struct or 8765 // union. 8766 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8767 ParamType == InvalidAddrSpacePtrKernelParam) { 8768 S.Diag(Param->getLocation(), 8769 diag::err_record_with_pointers_kernel_param) 8770 << PT->isUnionType() 8771 << PT; 8772 } else { 8773 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8774 } 8775 8776 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8777 << OrigRecDecl->getDeclName(); 8778 8779 // We have an error, now let's go back up through history and show where 8780 // the offending field came from 8781 for (ArrayRef<const FieldDecl *>::const_iterator 8782 I = HistoryStack.begin() + 1, 8783 E = HistoryStack.end(); 8784 I != E; ++I) { 8785 const FieldDecl *OuterField = *I; 8786 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8787 << OuterField->getType(); 8788 } 8789 8790 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8791 << QT->isPointerType() 8792 << QT; 8793 D.setInvalidType(); 8794 return; 8795 } 8796 } while (!VisitStack.empty()); 8797 } 8798 8799 /// Find the DeclContext in which a tag is implicitly declared if we see an 8800 /// elaborated type specifier in the specified context, and lookup finds 8801 /// nothing. 8802 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8803 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8804 DC = DC->getParent(); 8805 return DC; 8806 } 8807 8808 /// Find the Scope in which a tag is implicitly declared if we see an 8809 /// elaborated type specifier in the specified context, and lookup finds 8810 /// nothing. 8811 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8812 while (S->isClassScope() || 8813 (LangOpts.CPlusPlus && 8814 S->isFunctionPrototypeScope()) || 8815 ((S->getFlags() & Scope::DeclScope) == 0) || 8816 (S->getEntity() && S->getEntity()->isTransparentContext())) 8817 S = S->getParent(); 8818 return S; 8819 } 8820 8821 NamedDecl* 8822 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8823 TypeSourceInfo *TInfo, LookupResult &Previous, 8824 MultiTemplateParamsArg TemplateParamListsRef, 8825 bool &AddToScope) { 8826 QualType R = TInfo->getType(); 8827 8828 assert(R->isFunctionType()); 8829 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8830 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8831 8832 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8833 for (TemplateParameterList *TPL : TemplateParamListsRef) 8834 TemplateParamLists.push_back(TPL); 8835 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8836 if (!TemplateParamLists.empty() && 8837 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8838 TemplateParamLists.back() = Invented; 8839 else 8840 TemplateParamLists.push_back(Invented); 8841 } 8842 8843 // TODO: consider using NameInfo for diagnostic. 8844 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8845 DeclarationName Name = NameInfo.getName(); 8846 StorageClass SC = getFunctionStorageClass(*this, D); 8847 8848 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8849 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8850 diag::err_invalid_thread) 8851 << DeclSpec::getSpecifierName(TSCS); 8852 8853 if (D.isFirstDeclarationOfMember()) 8854 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8855 D.getIdentifierLoc()); 8856 8857 bool isFriend = false; 8858 FunctionTemplateDecl *FunctionTemplate = nullptr; 8859 bool isMemberSpecialization = false; 8860 bool isFunctionTemplateSpecialization = false; 8861 8862 bool isDependentClassScopeExplicitSpecialization = false; 8863 bool HasExplicitTemplateArgs = false; 8864 TemplateArgumentListInfo TemplateArgs; 8865 8866 bool isVirtualOkay = false; 8867 8868 DeclContext *OriginalDC = DC; 8869 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8870 8871 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8872 isVirtualOkay); 8873 if (!NewFD) return nullptr; 8874 8875 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8876 NewFD->setTopLevelDeclInObjCContainer(); 8877 8878 // Set the lexical context. If this is a function-scope declaration, or has a 8879 // C++ scope specifier, or is the object of a friend declaration, the lexical 8880 // context will be different from the semantic context. 8881 NewFD->setLexicalDeclContext(CurContext); 8882 8883 if (IsLocalExternDecl) 8884 NewFD->setLocalExternDecl(); 8885 8886 if (getLangOpts().CPlusPlus) { 8887 bool isInline = D.getDeclSpec().isInlineSpecified(); 8888 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8889 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8890 isFriend = D.getDeclSpec().isFriendSpecified(); 8891 if (isFriend && !isInline && D.isFunctionDefinition()) { 8892 // C++ [class.friend]p5 8893 // A function can be defined in a friend declaration of a 8894 // class . . . . Such a function is implicitly inline. 8895 NewFD->setImplicitlyInline(); 8896 } 8897 8898 // If this is a method defined in an __interface, and is not a constructor 8899 // or an overloaded operator, then set the pure flag (isVirtual will already 8900 // return true). 8901 if (const CXXRecordDecl *Parent = 8902 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8903 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8904 NewFD->setPure(true); 8905 8906 // C++ [class.union]p2 8907 // A union can have member functions, but not virtual functions. 8908 if (isVirtual && Parent->isUnion()) 8909 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8910 } 8911 8912 SetNestedNameSpecifier(*this, NewFD, D); 8913 isMemberSpecialization = false; 8914 isFunctionTemplateSpecialization = false; 8915 if (D.isInvalidType()) 8916 NewFD->setInvalidDecl(); 8917 8918 // Match up the template parameter lists with the scope specifier, then 8919 // determine whether we have a template or a template specialization. 8920 bool Invalid = false; 8921 TemplateParameterList *TemplateParams = 8922 MatchTemplateParametersToScopeSpecifier( 8923 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8924 D.getCXXScopeSpec(), 8925 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8926 ? D.getName().TemplateId 8927 : nullptr, 8928 TemplateParamLists, isFriend, isMemberSpecialization, 8929 Invalid); 8930 if (TemplateParams) { 8931 // Check that we can declare a template here. 8932 if (CheckTemplateDeclScope(S, TemplateParams)) 8933 NewFD->setInvalidDecl(); 8934 8935 if (TemplateParams->size() > 0) { 8936 // This is a function template 8937 8938 // A destructor cannot be a template. 8939 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8940 Diag(NewFD->getLocation(), diag::err_destructor_template); 8941 NewFD->setInvalidDecl(); 8942 } 8943 8944 // If we're adding a template to a dependent context, we may need to 8945 // rebuilding some of the types used within the template parameter list, 8946 // now that we know what the current instantiation is. 8947 if (DC->isDependentContext()) { 8948 ContextRAII SavedContext(*this, DC); 8949 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8950 Invalid = true; 8951 } 8952 8953 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8954 NewFD->getLocation(), 8955 Name, TemplateParams, 8956 NewFD); 8957 FunctionTemplate->setLexicalDeclContext(CurContext); 8958 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8959 8960 // For source fidelity, store the other template param lists. 8961 if (TemplateParamLists.size() > 1) { 8962 NewFD->setTemplateParameterListsInfo(Context, 8963 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8964 .drop_back(1)); 8965 } 8966 } else { 8967 // This is a function template specialization. 8968 isFunctionTemplateSpecialization = true; 8969 // For source fidelity, store all the template param lists. 8970 if (TemplateParamLists.size() > 0) 8971 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8972 8973 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8974 if (isFriend) { 8975 // We want to remove the "template<>", found here. 8976 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8977 8978 // If we remove the template<> and the name is not a 8979 // template-id, we're actually silently creating a problem: 8980 // the friend declaration will refer to an untemplated decl, 8981 // and clearly the user wants a template specialization. So 8982 // we need to insert '<>' after the name. 8983 SourceLocation InsertLoc; 8984 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8985 InsertLoc = D.getName().getSourceRange().getEnd(); 8986 InsertLoc = getLocForEndOfToken(InsertLoc); 8987 } 8988 8989 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8990 << Name << RemoveRange 8991 << FixItHint::CreateRemoval(RemoveRange) 8992 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8993 } 8994 } 8995 } else { 8996 // Check that we can declare a template here. 8997 if (!TemplateParamLists.empty() && isMemberSpecialization && 8998 CheckTemplateDeclScope(S, TemplateParamLists.back())) 8999 NewFD->setInvalidDecl(); 9000 9001 // All template param lists were matched against the scope specifier: 9002 // this is NOT (an explicit specialization of) a template. 9003 if (TemplateParamLists.size() > 0) 9004 // For source fidelity, store all the template param lists. 9005 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9006 } 9007 9008 if (Invalid) { 9009 NewFD->setInvalidDecl(); 9010 if (FunctionTemplate) 9011 FunctionTemplate->setInvalidDecl(); 9012 } 9013 9014 // C++ [dcl.fct.spec]p5: 9015 // The virtual specifier shall only be used in declarations of 9016 // nonstatic class member functions that appear within a 9017 // member-specification of a class declaration; see 10.3. 9018 // 9019 if (isVirtual && !NewFD->isInvalidDecl()) { 9020 if (!isVirtualOkay) { 9021 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9022 diag::err_virtual_non_function); 9023 } else if (!CurContext->isRecord()) { 9024 // 'virtual' was specified outside of the class. 9025 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9026 diag::err_virtual_out_of_class) 9027 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9028 } else if (NewFD->getDescribedFunctionTemplate()) { 9029 // C++ [temp.mem]p3: 9030 // A member function template shall not be virtual. 9031 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9032 diag::err_virtual_member_function_template) 9033 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9034 } else { 9035 // Okay: Add virtual to the method. 9036 NewFD->setVirtualAsWritten(true); 9037 } 9038 9039 if (getLangOpts().CPlusPlus14 && 9040 NewFD->getReturnType()->isUndeducedType()) 9041 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9042 } 9043 9044 if (getLangOpts().CPlusPlus14 && 9045 (NewFD->isDependentContext() || 9046 (isFriend && CurContext->isDependentContext())) && 9047 NewFD->getReturnType()->isUndeducedType()) { 9048 // If the function template is referenced directly (for instance, as a 9049 // member of the current instantiation), pretend it has a dependent type. 9050 // This is not really justified by the standard, but is the only sane 9051 // thing to do. 9052 // FIXME: For a friend function, we have not marked the function as being 9053 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9054 const FunctionProtoType *FPT = 9055 NewFD->getType()->castAs<FunctionProtoType>(); 9056 QualType Result = 9057 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9058 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9059 FPT->getExtProtoInfo())); 9060 } 9061 9062 // C++ [dcl.fct.spec]p3: 9063 // The inline specifier shall not appear on a block scope function 9064 // declaration. 9065 if (isInline && !NewFD->isInvalidDecl()) { 9066 if (CurContext->isFunctionOrMethod()) { 9067 // 'inline' is not allowed on block scope function declaration. 9068 Diag(D.getDeclSpec().getInlineSpecLoc(), 9069 diag::err_inline_declaration_block_scope) << Name 9070 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9071 } 9072 } 9073 9074 // C++ [dcl.fct.spec]p6: 9075 // The explicit specifier shall be used only in the declaration of a 9076 // constructor or conversion function within its class definition; 9077 // see 12.3.1 and 12.3.2. 9078 if (hasExplicit && !NewFD->isInvalidDecl() && 9079 !isa<CXXDeductionGuideDecl>(NewFD)) { 9080 if (!CurContext->isRecord()) { 9081 // 'explicit' was specified outside of the class. 9082 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9083 diag::err_explicit_out_of_class) 9084 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9085 } else if (!isa<CXXConstructorDecl>(NewFD) && 9086 !isa<CXXConversionDecl>(NewFD)) { 9087 // 'explicit' was specified on a function that wasn't a constructor 9088 // or conversion function. 9089 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9090 diag::err_explicit_non_ctor_or_conv_function) 9091 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9092 } 9093 } 9094 9095 if (ConstexprSpecKind ConstexprKind = 9096 D.getDeclSpec().getConstexprSpecifier()) { 9097 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9098 // are implicitly inline. 9099 NewFD->setImplicitlyInline(); 9100 9101 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9102 // be either constructors or to return a literal type. Therefore, 9103 // destructors cannot be declared constexpr. 9104 if (isa<CXXDestructorDecl>(NewFD) && 9105 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9106 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9107 << ConstexprKind; 9108 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9109 } 9110 // C++20 [dcl.constexpr]p2: An allocation function, or a 9111 // deallocation function shall not be declared with the consteval 9112 // specifier. 9113 if (ConstexprKind == CSK_consteval && 9114 (NewFD->getOverloadedOperator() == OO_New || 9115 NewFD->getOverloadedOperator() == OO_Array_New || 9116 NewFD->getOverloadedOperator() == OO_Delete || 9117 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9118 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9119 diag::err_invalid_consteval_decl_kind) 9120 << NewFD; 9121 NewFD->setConstexprKind(CSK_constexpr); 9122 } 9123 } 9124 9125 // If __module_private__ was specified, mark the function accordingly. 9126 if (D.getDeclSpec().isModulePrivateSpecified()) { 9127 if (isFunctionTemplateSpecialization) { 9128 SourceLocation ModulePrivateLoc 9129 = D.getDeclSpec().getModulePrivateSpecLoc(); 9130 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9131 << 0 9132 << FixItHint::CreateRemoval(ModulePrivateLoc); 9133 } else { 9134 NewFD->setModulePrivate(); 9135 if (FunctionTemplate) 9136 FunctionTemplate->setModulePrivate(); 9137 } 9138 } 9139 9140 if (isFriend) { 9141 if (FunctionTemplate) { 9142 FunctionTemplate->setObjectOfFriendDecl(); 9143 FunctionTemplate->setAccess(AS_public); 9144 } 9145 NewFD->setObjectOfFriendDecl(); 9146 NewFD->setAccess(AS_public); 9147 } 9148 9149 // If a function is defined as defaulted or deleted, mark it as such now. 9150 // We'll do the relevant checks on defaulted / deleted functions later. 9151 switch (D.getFunctionDefinitionKind()) { 9152 case FDK_Declaration: 9153 case FDK_Definition: 9154 break; 9155 9156 case FDK_Defaulted: 9157 NewFD->setDefaulted(); 9158 break; 9159 9160 case FDK_Deleted: 9161 NewFD->setDeletedAsWritten(); 9162 break; 9163 } 9164 9165 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9166 D.isFunctionDefinition()) { 9167 // C++ [class.mfct]p2: 9168 // A member function may be defined (8.4) in its class definition, in 9169 // which case it is an inline member function (7.1.2) 9170 NewFD->setImplicitlyInline(); 9171 } 9172 9173 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9174 !CurContext->isRecord()) { 9175 // C++ [class.static]p1: 9176 // A data or function member of a class may be declared static 9177 // in a class definition, in which case it is a static member of 9178 // the class. 9179 9180 // Complain about the 'static' specifier if it's on an out-of-line 9181 // member function definition. 9182 9183 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9184 // member function template declaration and class member template 9185 // declaration (MSVC versions before 2015), warn about this. 9186 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9187 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9188 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9189 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9190 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9191 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9192 } 9193 9194 // C++11 [except.spec]p15: 9195 // A deallocation function with no exception-specification is treated 9196 // as if it were specified with noexcept(true). 9197 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9198 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9199 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9200 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9201 NewFD->setType(Context.getFunctionType( 9202 FPT->getReturnType(), FPT->getParamTypes(), 9203 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9204 } 9205 9206 // Filter out previous declarations that don't match the scope. 9207 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9208 D.getCXXScopeSpec().isNotEmpty() || 9209 isMemberSpecialization || 9210 isFunctionTemplateSpecialization); 9211 9212 // Handle GNU asm-label extension (encoded as an attribute). 9213 if (Expr *E = (Expr*) D.getAsmLabel()) { 9214 // The parser guarantees this is a string. 9215 StringLiteral *SE = cast<StringLiteral>(E); 9216 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9217 /*IsLiteralLabel=*/true, 9218 SE->getStrTokenLoc(0))); 9219 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9220 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9221 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9222 if (I != ExtnameUndeclaredIdentifiers.end()) { 9223 if (isDeclExternC(NewFD)) { 9224 NewFD->addAttr(I->second); 9225 ExtnameUndeclaredIdentifiers.erase(I); 9226 } else 9227 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9228 << /*Variable*/0 << NewFD; 9229 } 9230 } 9231 9232 // Copy the parameter declarations from the declarator D to the function 9233 // declaration NewFD, if they are available. First scavenge them into Params. 9234 SmallVector<ParmVarDecl*, 16> Params; 9235 unsigned FTIIdx; 9236 if (D.isFunctionDeclarator(FTIIdx)) { 9237 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9238 9239 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9240 // function that takes no arguments, not a function that takes a 9241 // single void argument. 9242 // We let through "const void" here because Sema::GetTypeForDeclarator 9243 // already checks for that case. 9244 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9245 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9246 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9247 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9248 Param->setDeclContext(NewFD); 9249 Params.push_back(Param); 9250 9251 if (Param->isInvalidDecl()) 9252 NewFD->setInvalidDecl(); 9253 } 9254 } 9255 9256 if (!getLangOpts().CPlusPlus) { 9257 // In C, find all the tag declarations from the prototype and move them 9258 // into the function DeclContext. Remove them from the surrounding tag 9259 // injection context of the function, which is typically but not always 9260 // the TU. 9261 DeclContext *PrototypeTagContext = 9262 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9263 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9264 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9265 9266 // We don't want to reparent enumerators. Look at their parent enum 9267 // instead. 9268 if (!TD) { 9269 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9270 TD = cast<EnumDecl>(ECD->getDeclContext()); 9271 } 9272 if (!TD) 9273 continue; 9274 DeclContext *TagDC = TD->getLexicalDeclContext(); 9275 if (!TagDC->containsDecl(TD)) 9276 continue; 9277 TagDC->removeDecl(TD); 9278 TD->setDeclContext(NewFD); 9279 NewFD->addDecl(TD); 9280 9281 // Preserve the lexical DeclContext if it is not the surrounding tag 9282 // injection context of the FD. In this example, the semantic context of 9283 // E will be f and the lexical context will be S, while both the 9284 // semantic and lexical contexts of S will be f: 9285 // void f(struct S { enum E { a } f; } s); 9286 if (TagDC != PrototypeTagContext) 9287 TD->setLexicalDeclContext(TagDC); 9288 } 9289 } 9290 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9291 // When we're declaring a function with a typedef, typeof, etc as in the 9292 // following example, we'll need to synthesize (unnamed) 9293 // parameters for use in the declaration. 9294 // 9295 // @code 9296 // typedef void fn(int); 9297 // fn f; 9298 // @endcode 9299 9300 // Synthesize a parameter for each argument type. 9301 for (const auto &AI : FT->param_types()) { 9302 ParmVarDecl *Param = 9303 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9304 Param->setScopeInfo(0, Params.size()); 9305 Params.push_back(Param); 9306 } 9307 } else { 9308 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9309 "Should not need args for typedef of non-prototype fn"); 9310 } 9311 9312 // Finally, we know we have the right number of parameters, install them. 9313 NewFD->setParams(Params); 9314 9315 if (D.getDeclSpec().isNoreturnSpecified()) 9316 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9317 D.getDeclSpec().getNoreturnSpecLoc(), 9318 AttributeCommonInfo::AS_Keyword)); 9319 9320 // Functions returning a variably modified type violate C99 6.7.5.2p2 9321 // because all functions have linkage. 9322 if (!NewFD->isInvalidDecl() && 9323 NewFD->getReturnType()->isVariablyModifiedType()) { 9324 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9325 NewFD->setInvalidDecl(); 9326 } 9327 9328 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9329 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9330 !NewFD->hasAttr<SectionAttr>()) 9331 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9332 Context, PragmaClangTextSection.SectionName, 9333 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9334 9335 // Apply an implicit SectionAttr if #pragma code_seg is active. 9336 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9337 !NewFD->hasAttr<SectionAttr>()) { 9338 NewFD->addAttr(SectionAttr::CreateImplicit( 9339 Context, CodeSegStack.CurrentValue->getString(), 9340 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9341 SectionAttr::Declspec_allocate)); 9342 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9343 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9344 ASTContext::PSF_Read, 9345 NewFD)) 9346 NewFD->dropAttr<SectionAttr>(); 9347 } 9348 9349 // Apply an implicit CodeSegAttr from class declspec or 9350 // apply an implicit SectionAttr from #pragma code_seg if active. 9351 if (!NewFD->hasAttr<CodeSegAttr>()) { 9352 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9353 D.isFunctionDefinition())) { 9354 NewFD->addAttr(SAttr); 9355 } 9356 } 9357 9358 // Handle attributes. 9359 ProcessDeclAttributes(S, NewFD, D); 9360 9361 if (getLangOpts().OpenCL) { 9362 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9363 // type declaration will generate a compilation error. 9364 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9365 if (AddressSpace != LangAS::Default) { 9366 Diag(NewFD->getLocation(), 9367 diag::err_opencl_return_value_with_address_space); 9368 NewFD->setInvalidDecl(); 9369 } 9370 } 9371 9372 if (!getLangOpts().CPlusPlus) { 9373 // Perform semantic checking on the function declaration. 9374 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9375 CheckMain(NewFD, D.getDeclSpec()); 9376 9377 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9378 CheckMSVCRTEntryPoint(NewFD); 9379 9380 if (!NewFD->isInvalidDecl()) 9381 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9382 isMemberSpecialization)); 9383 else if (!Previous.empty()) 9384 // Recover gracefully from an invalid redeclaration. 9385 D.setRedeclaration(true); 9386 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9387 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9388 "previous declaration set still overloaded"); 9389 9390 // Diagnose no-prototype function declarations with calling conventions that 9391 // don't support variadic calls. Only do this in C and do it after merging 9392 // possibly prototyped redeclarations. 9393 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9394 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9395 CallingConv CC = FT->getExtInfo().getCC(); 9396 if (!supportsVariadicCall(CC)) { 9397 // Windows system headers sometimes accidentally use stdcall without 9398 // (void) parameters, so we relax this to a warning. 9399 int DiagID = 9400 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9401 Diag(NewFD->getLocation(), DiagID) 9402 << FunctionType::getNameForCallConv(CC); 9403 } 9404 } 9405 9406 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9407 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9408 checkNonTrivialCUnion(NewFD->getReturnType(), 9409 NewFD->getReturnTypeSourceRange().getBegin(), 9410 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9411 } else { 9412 // C++11 [replacement.functions]p3: 9413 // The program's definitions shall not be specified as inline. 9414 // 9415 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9416 // 9417 // Suppress the diagnostic if the function is __attribute__((used)), since 9418 // that forces an external definition to be emitted. 9419 if (D.getDeclSpec().isInlineSpecified() && 9420 NewFD->isReplaceableGlobalAllocationFunction() && 9421 !NewFD->hasAttr<UsedAttr>()) 9422 Diag(D.getDeclSpec().getInlineSpecLoc(), 9423 diag::ext_operator_new_delete_declared_inline) 9424 << NewFD->getDeclName(); 9425 9426 // If the declarator is a template-id, translate the parser's template 9427 // argument list into our AST format. 9428 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9429 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9430 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9431 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9432 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9433 TemplateId->NumArgs); 9434 translateTemplateArguments(TemplateArgsPtr, 9435 TemplateArgs); 9436 9437 HasExplicitTemplateArgs = true; 9438 9439 if (NewFD->isInvalidDecl()) { 9440 HasExplicitTemplateArgs = false; 9441 } else if (FunctionTemplate) { 9442 // Function template with explicit template arguments. 9443 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9444 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9445 9446 HasExplicitTemplateArgs = false; 9447 } else { 9448 assert((isFunctionTemplateSpecialization || 9449 D.getDeclSpec().isFriendSpecified()) && 9450 "should have a 'template<>' for this decl"); 9451 // "friend void foo<>(int);" is an implicit specialization decl. 9452 isFunctionTemplateSpecialization = true; 9453 } 9454 } else if (isFriend && isFunctionTemplateSpecialization) { 9455 // This combination is only possible in a recovery case; the user 9456 // wrote something like: 9457 // template <> friend void foo(int); 9458 // which we're recovering from as if the user had written: 9459 // friend void foo<>(int); 9460 // Go ahead and fake up a template id. 9461 HasExplicitTemplateArgs = true; 9462 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9463 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9464 } 9465 9466 // We do not add HD attributes to specializations here because 9467 // they may have different constexpr-ness compared to their 9468 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9469 // may end up with different effective targets. Instead, a 9470 // specialization inherits its target attributes from its template 9471 // in the CheckFunctionTemplateSpecialization() call below. 9472 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9473 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9474 9475 // If it's a friend (and only if it's a friend), it's possible 9476 // that either the specialized function type or the specialized 9477 // template is dependent, and therefore matching will fail. In 9478 // this case, don't check the specialization yet. 9479 bool InstantiationDependent = false; 9480 if (isFunctionTemplateSpecialization && isFriend && 9481 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9482 TemplateSpecializationType::anyDependentTemplateArguments( 9483 TemplateArgs, 9484 InstantiationDependent))) { 9485 assert(HasExplicitTemplateArgs && 9486 "friend function specialization without template args"); 9487 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9488 Previous)) 9489 NewFD->setInvalidDecl(); 9490 } else if (isFunctionTemplateSpecialization) { 9491 if (CurContext->isDependentContext() && CurContext->isRecord() 9492 && !isFriend) { 9493 isDependentClassScopeExplicitSpecialization = true; 9494 } else if (!NewFD->isInvalidDecl() && 9495 CheckFunctionTemplateSpecialization( 9496 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9497 Previous)) 9498 NewFD->setInvalidDecl(); 9499 9500 // C++ [dcl.stc]p1: 9501 // A storage-class-specifier shall not be specified in an explicit 9502 // specialization (14.7.3) 9503 FunctionTemplateSpecializationInfo *Info = 9504 NewFD->getTemplateSpecializationInfo(); 9505 if (Info && SC != SC_None) { 9506 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9507 Diag(NewFD->getLocation(), 9508 diag::err_explicit_specialization_inconsistent_storage_class) 9509 << SC 9510 << FixItHint::CreateRemoval( 9511 D.getDeclSpec().getStorageClassSpecLoc()); 9512 9513 else 9514 Diag(NewFD->getLocation(), 9515 diag::ext_explicit_specialization_storage_class) 9516 << FixItHint::CreateRemoval( 9517 D.getDeclSpec().getStorageClassSpecLoc()); 9518 } 9519 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9520 if (CheckMemberSpecialization(NewFD, Previous)) 9521 NewFD->setInvalidDecl(); 9522 } 9523 9524 // Perform semantic checking on the function declaration. 9525 if (!isDependentClassScopeExplicitSpecialization) { 9526 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9527 CheckMain(NewFD, D.getDeclSpec()); 9528 9529 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9530 CheckMSVCRTEntryPoint(NewFD); 9531 9532 if (!NewFD->isInvalidDecl()) 9533 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9534 isMemberSpecialization)); 9535 else if (!Previous.empty()) 9536 // Recover gracefully from an invalid redeclaration. 9537 D.setRedeclaration(true); 9538 } 9539 9540 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9541 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9542 "previous declaration set still overloaded"); 9543 9544 NamedDecl *PrincipalDecl = (FunctionTemplate 9545 ? cast<NamedDecl>(FunctionTemplate) 9546 : NewFD); 9547 9548 if (isFriend && NewFD->getPreviousDecl()) { 9549 AccessSpecifier Access = AS_public; 9550 if (!NewFD->isInvalidDecl()) 9551 Access = NewFD->getPreviousDecl()->getAccess(); 9552 9553 NewFD->setAccess(Access); 9554 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9555 } 9556 9557 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9558 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9559 PrincipalDecl->setNonMemberOperator(); 9560 9561 // If we have a function template, check the template parameter 9562 // list. This will check and merge default template arguments. 9563 if (FunctionTemplate) { 9564 FunctionTemplateDecl *PrevTemplate = 9565 FunctionTemplate->getPreviousDecl(); 9566 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9567 PrevTemplate ? PrevTemplate->getTemplateParameters() 9568 : nullptr, 9569 D.getDeclSpec().isFriendSpecified() 9570 ? (D.isFunctionDefinition() 9571 ? TPC_FriendFunctionTemplateDefinition 9572 : TPC_FriendFunctionTemplate) 9573 : (D.getCXXScopeSpec().isSet() && 9574 DC && DC->isRecord() && 9575 DC->isDependentContext()) 9576 ? TPC_ClassTemplateMember 9577 : TPC_FunctionTemplate); 9578 } 9579 9580 if (NewFD->isInvalidDecl()) { 9581 // Ignore all the rest of this. 9582 } else if (!D.isRedeclaration()) { 9583 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9584 AddToScope }; 9585 // Fake up an access specifier if it's supposed to be a class member. 9586 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9587 NewFD->setAccess(AS_public); 9588 9589 // Qualified decls generally require a previous declaration. 9590 if (D.getCXXScopeSpec().isSet()) { 9591 // ...with the major exception of templated-scope or 9592 // dependent-scope friend declarations. 9593 9594 // TODO: we currently also suppress this check in dependent 9595 // contexts because (1) the parameter depth will be off when 9596 // matching friend templates and (2) we might actually be 9597 // selecting a friend based on a dependent factor. But there 9598 // are situations where these conditions don't apply and we 9599 // can actually do this check immediately. 9600 // 9601 // Unless the scope is dependent, it's always an error if qualified 9602 // redeclaration lookup found nothing at all. Diagnose that now; 9603 // nothing will diagnose that error later. 9604 if (isFriend && 9605 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9606 (!Previous.empty() && CurContext->isDependentContext()))) { 9607 // ignore these 9608 } else { 9609 // The user tried to provide an out-of-line definition for a 9610 // function that is a member of a class or namespace, but there 9611 // was no such member function declared (C++ [class.mfct]p2, 9612 // C++ [namespace.memdef]p2). For example: 9613 // 9614 // class X { 9615 // void f() const; 9616 // }; 9617 // 9618 // void X::f() { } // ill-formed 9619 // 9620 // Complain about this problem, and attempt to suggest close 9621 // matches (e.g., those that differ only in cv-qualifiers and 9622 // whether the parameter types are references). 9623 9624 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9625 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9626 AddToScope = ExtraArgs.AddToScope; 9627 return Result; 9628 } 9629 } 9630 9631 // Unqualified local friend declarations are required to resolve 9632 // to something. 9633 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9634 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9635 *this, Previous, NewFD, ExtraArgs, true, S)) { 9636 AddToScope = ExtraArgs.AddToScope; 9637 return Result; 9638 } 9639 } 9640 } else if (!D.isFunctionDefinition() && 9641 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9642 !isFriend && !isFunctionTemplateSpecialization && 9643 !isMemberSpecialization) { 9644 // An out-of-line member function declaration must also be a 9645 // definition (C++ [class.mfct]p2). 9646 // Note that this is not the case for explicit specializations of 9647 // function templates or member functions of class templates, per 9648 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9649 // extension for compatibility with old SWIG code which likes to 9650 // generate them. 9651 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9652 << D.getCXXScopeSpec().getRange(); 9653 } 9654 } 9655 9656 // If this is the first declaration of a library builtin function, add 9657 // attributes as appropriate. 9658 if (!D.isRedeclaration() && 9659 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9660 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9661 if (unsigned BuiltinID = II->getBuiltinID()) { 9662 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9663 // Validate the type matches unless this builtin is specified as 9664 // matching regardless of its declared type. 9665 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9666 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9667 } else { 9668 ASTContext::GetBuiltinTypeError Error; 9669 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9670 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9671 9672 if (!Error && !BuiltinType.isNull() && 9673 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9674 NewFD->getType(), BuiltinType)) 9675 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9676 } 9677 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9678 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9679 // FIXME: We should consider this a builtin only in the std namespace. 9680 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9681 } 9682 } 9683 } 9684 } 9685 9686 ProcessPragmaWeak(S, NewFD); 9687 checkAttributesAfterMerging(*this, *NewFD); 9688 9689 AddKnownFunctionAttributes(NewFD); 9690 9691 if (NewFD->hasAttr<OverloadableAttr>() && 9692 !NewFD->getType()->getAs<FunctionProtoType>()) { 9693 Diag(NewFD->getLocation(), 9694 diag::err_attribute_overloadable_no_prototype) 9695 << NewFD; 9696 9697 // Turn this into a variadic function with no parameters. 9698 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9699 FunctionProtoType::ExtProtoInfo EPI( 9700 Context.getDefaultCallingConvention(true, false)); 9701 EPI.Variadic = true; 9702 EPI.ExtInfo = FT->getExtInfo(); 9703 9704 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9705 NewFD->setType(R); 9706 } 9707 9708 // If there's a #pragma GCC visibility in scope, and this isn't a class 9709 // member, set the visibility of this function. 9710 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9711 AddPushedVisibilityAttribute(NewFD); 9712 9713 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9714 // marking the function. 9715 AddCFAuditedAttribute(NewFD); 9716 9717 // If this is a function definition, check if we have to apply optnone due to 9718 // a pragma. 9719 if(D.isFunctionDefinition()) 9720 AddRangeBasedOptnone(NewFD); 9721 9722 // If this is the first declaration of an extern C variable, update 9723 // the map of such variables. 9724 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9725 isIncompleteDeclExternC(*this, NewFD)) 9726 RegisterLocallyScopedExternCDecl(NewFD, S); 9727 9728 // Set this FunctionDecl's range up to the right paren. 9729 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9730 9731 if (D.isRedeclaration() && !Previous.empty()) { 9732 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9733 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9734 isMemberSpecialization || 9735 isFunctionTemplateSpecialization, 9736 D.isFunctionDefinition()); 9737 } 9738 9739 if (getLangOpts().CUDA) { 9740 IdentifierInfo *II = NewFD->getIdentifier(); 9741 if (II && II->isStr(getCudaConfigureFuncName()) && 9742 !NewFD->isInvalidDecl() && 9743 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9744 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9745 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9746 << getCudaConfigureFuncName(); 9747 Context.setcudaConfigureCallDecl(NewFD); 9748 } 9749 9750 // Variadic functions, other than a *declaration* of printf, are not allowed 9751 // in device-side CUDA code, unless someone passed 9752 // -fcuda-allow-variadic-functions. 9753 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9754 (NewFD->hasAttr<CUDADeviceAttr>() || 9755 NewFD->hasAttr<CUDAGlobalAttr>()) && 9756 !(II && II->isStr("printf") && NewFD->isExternC() && 9757 !D.isFunctionDefinition())) { 9758 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9759 } 9760 } 9761 9762 MarkUnusedFileScopedDecl(NewFD); 9763 9764 9765 9766 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9767 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9768 if ((getLangOpts().OpenCLVersion >= 120) 9769 && (SC == SC_Static)) { 9770 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9771 D.setInvalidType(); 9772 } 9773 9774 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9775 if (!NewFD->getReturnType()->isVoidType()) { 9776 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9777 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9778 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9779 : FixItHint()); 9780 D.setInvalidType(); 9781 } 9782 9783 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9784 for (auto Param : NewFD->parameters()) 9785 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9786 9787 if (getLangOpts().OpenCLCPlusPlus) { 9788 if (DC->isRecord()) { 9789 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9790 D.setInvalidType(); 9791 } 9792 if (FunctionTemplate) { 9793 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9794 D.setInvalidType(); 9795 } 9796 } 9797 } 9798 9799 if (getLangOpts().CPlusPlus) { 9800 if (FunctionTemplate) { 9801 if (NewFD->isInvalidDecl()) 9802 FunctionTemplate->setInvalidDecl(); 9803 return FunctionTemplate; 9804 } 9805 9806 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9807 CompleteMemberSpecialization(NewFD, Previous); 9808 } 9809 9810 for (const ParmVarDecl *Param : NewFD->parameters()) { 9811 QualType PT = Param->getType(); 9812 9813 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9814 // types. 9815 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9816 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9817 QualType ElemTy = PipeTy->getElementType(); 9818 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9819 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9820 D.setInvalidType(); 9821 } 9822 } 9823 } 9824 } 9825 9826 // Here we have an function template explicit specialization at class scope. 9827 // The actual specialization will be postponed to template instatiation 9828 // time via the ClassScopeFunctionSpecializationDecl node. 9829 if (isDependentClassScopeExplicitSpecialization) { 9830 ClassScopeFunctionSpecializationDecl *NewSpec = 9831 ClassScopeFunctionSpecializationDecl::Create( 9832 Context, CurContext, NewFD->getLocation(), 9833 cast<CXXMethodDecl>(NewFD), 9834 HasExplicitTemplateArgs, TemplateArgs); 9835 CurContext->addDecl(NewSpec); 9836 AddToScope = false; 9837 } 9838 9839 // Diagnose availability attributes. Availability cannot be used on functions 9840 // that are run during load/unload. 9841 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9842 if (NewFD->hasAttr<ConstructorAttr>()) { 9843 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9844 << 1; 9845 NewFD->dropAttr<AvailabilityAttr>(); 9846 } 9847 if (NewFD->hasAttr<DestructorAttr>()) { 9848 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9849 << 2; 9850 NewFD->dropAttr<AvailabilityAttr>(); 9851 } 9852 } 9853 9854 // Diagnose no_builtin attribute on function declaration that are not a 9855 // definition. 9856 // FIXME: We should really be doing this in 9857 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9858 // the FunctionDecl and at this point of the code 9859 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9860 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9861 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9862 switch (D.getFunctionDefinitionKind()) { 9863 case FDK_Defaulted: 9864 case FDK_Deleted: 9865 Diag(NBA->getLocation(), 9866 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9867 << NBA->getSpelling(); 9868 break; 9869 case FDK_Declaration: 9870 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9871 << NBA->getSpelling(); 9872 break; 9873 case FDK_Definition: 9874 break; 9875 } 9876 9877 return NewFD; 9878 } 9879 9880 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9881 /// when __declspec(code_seg) "is applied to a class, all member functions of 9882 /// the class and nested classes -- this includes compiler-generated special 9883 /// member functions -- are put in the specified segment." 9884 /// The actual behavior is a little more complicated. The Microsoft compiler 9885 /// won't check outer classes if there is an active value from #pragma code_seg. 9886 /// The CodeSeg is always applied from the direct parent but only from outer 9887 /// classes when the #pragma code_seg stack is empty. See: 9888 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9889 /// available since MS has removed the page. 9890 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9891 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9892 if (!Method) 9893 return nullptr; 9894 const CXXRecordDecl *Parent = Method->getParent(); 9895 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9896 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9897 NewAttr->setImplicit(true); 9898 return NewAttr; 9899 } 9900 9901 // The Microsoft compiler won't check outer classes for the CodeSeg 9902 // when the #pragma code_seg stack is active. 9903 if (S.CodeSegStack.CurrentValue) 9904 return nullptr; 9905 9906 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9907 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9908 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9909 NewAttr->setImplicit(true); 9910 return NewAttr; 9911 } 9912 } 9913 return nullptr; 9914 } 9915 9916 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9917 /// containing class. Otherwise it will return implicit SectionAttr if the 9918 /// function is a definition and there is an active value on CodeSegStack 9919 /// (from the current #pragma code-seg value). 9920 /// 9921 /// \param FD Function being declared. 9922 /// \param IsDefinition Whether it is a definition or just a declarartion. 9923 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9924 /// nullptr if no attribute should be added. 9925 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9926 bool IsDefinition) { 9927 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9928 return A; 9929 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9930 CodeSegStack.CurrentValue) 9931 return SectionAttr::CreateImplicit( 9932 getASTContext(), CodeSegStack.CurrentValue->getString(), 9933 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9934 SectionAttr::Declspec_allocate); 9935 return nullptr; 9936 } 9937 9938 /// Determines if we can perform a correct type check for \p D as a 9939 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9940 /// best-effort check. 9941 /// 9942 /// \param NewD The new declaration. 9943 /// \param OldD The old declaration. 9944 /// \param NewT The portion of the type of the new declaration to check. 9945 /// \param OldT The portion of the type of the old declaration to check. 9946 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9947 QualType NewT, QualType OldT) { 9948 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9949 return true; 9950 9951 // For dependently-typed local extern declarations and friends, we can't 9952 // perform a correct type check in general until instantiation: 9953 // 9954 // int f(); 9955 // template<typename T> void g() { T f(); } 9956 // 9957 // (valid if g() is only instantiated with T = int). 9958 if (NewT->isDependentType() && 9959 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9960 return false; 9961 9962 // Similarly, if the previous declaration was a dependent local extern 9963 // declaration, we don't really know its type yet. 9964 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9965 return false; 9966 9967 return true; 9968 } 9969 9970 /// Checks if the new declaration declared in dependent context must be 9971 /// put in the same redeclaration chain as the specified declaration. 9972 /// 9973 /// \param D Declaration that is checked. 9974 /// \param PrevDecl Previous declaration found with proper lookup method for the 9975 /// same declaration name. 9976 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9977 /// belongs to. 9978 /// 9979 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9980 if (!D->getLexicalDeclContext()->isDependentContext()) 9981 return true; 9982 9983 // Don't chain dependent friend function definitions until instantiation, to 9984 // permit cases like 9985 // 9986 // void func(); 9987 // template<typename T> class C1 { friend void func() {} }; 9988 // template<typename T> class C2 { friend void func() {} }; 9989 // 9990 // ... which is valid if only one of C1 and C2 is ever instantiated. 9991 // 9992 // FIXME: This need only apply to function definitions. For now, we proxy 9993 // this by checking for a file-scope function. We do not want this to apply 9994 // to friend declarations nominating member functions, because that gets in 9995 // the way of access checks. 9996 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9997 return false; 9998 9999 auto *VD = dyn_cast<ValueDecl>(D); 10000 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10001 return !VD || !PrevVD || 10002 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10003 PrevVD->getType()); 10004 } 10005 10006 /// Check the target attribute of the function for MultiVersion 10007 /// validity. 10008 /// 10009 /// Returns true if there was an error, false otherwise. 10010 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10011 const auto *TA = FD->getAttr<TargetAttr>(); 10012 assert(TA && "MultiVersion Candidate requires a target attribute"); 10013 ParsedTargetAttr ParseInfo = TA->parse(); 10014 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10015 enum ErrType { Feature = 0, Architecture = 1 }; 10016 10017 if (!ParseInfo.Architecture.empty() && 10018 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10019 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10020 << Architecture << ParseInfo.Architecture; 10021 return true; 10022 } 10023 10024 for (const auto &Feat : ParseInfo.Features) { 10025 auto BareFeat = StringRef{Feat}.substr(1); 10026 if (Feat[0] == '-') { 10027 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10028 << Feature << ("no-" + BareFeat).str(); 10029 return true; 10030 } 10031 10032 if (!TargetInfo.validateCpuSupports(BareFeat) || 10033 !TargetInfo.isValidFeatureName(BareFeat)) { 10034 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10035 << Feature << BareFeat; 10036 return true; 10037 } 10038 } 10039 return false; 10040 } 10041 10042 // Provide a white-list of attributes that are allowed to be combined with 10043 // multiversion functions. 10044 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10045 MultiVersionKind MVType) { 10046 // Note: this list/diagnosis must match the list in 10047 // checkMultiversionAttributesAllSame. 10048 switch (Kind) { 10049 default: 10050 return false; 10051 case attr::Used: 10052 return MVType == MultiVersionKind::Target; 10053 case attr::NonNull: 10054 case attr::NoThrow: 10055 return true; 10056 } 10057 } 10058 10059 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10060 const FunctionDecl *FD, 10061 const FunctionDecl *CausedFD, 10062 MultiVersionKind MVType) { 10063 bool IsCPUSpecificCPUDispatchMVType = 10064 MVType == MultiVersionKind::CPUDispatch || 10065 MVType == MultiVersionKind::CPUSpecific; 10066 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10067 Sema &S, const Attr *A) { 10068 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10069 << IsCPUSpecificCPUDispatchMVType << A; 10070 if (CausedFD) 10071 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10072 return true; 10073 }; 10074 10075 for (const Attr *A : FD->attrs()) { 10076 switch (A->getKind()) { 10077 case attr::CPUDispatch: 10078 case attr::CPUSpecific: 10079 if (MVType != MultiVersionKind::CPUDispatch && 10080 MVType != MultiVersionKind::CPUSpecific) 10081 return Diagnose(S, A); 10082 break; 10083 case attr::Target: 10084 if (MVType != MultiVersionKind::Target) 10085 return Diagnose(S, A); 10086 break; 10087 default: 10088 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10089 return Diagnose(S, A); 10090 break; 10091 } 10092 } 10093 return false; 10094 } 10095 10096 bool Sema::areMultiversionVariantFunctionsCompatible( 10097 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10098 const PartialDiagnostic &NoProtoDiagID, 10099 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10100 const PartialDiagnosticAt &NoSupportDiagIDAt, 10101 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10102 bool ConstexprSupported, bool CLinkageMayDiffer) { 10103 enum DoesntSupport { 10104 FuncTemplates = 0, 10105 VirtFuncs = 1, 10106 DeducedReturn = 2, 10107 Constructors = 3, 10108 Destructors = 4, 10109 DeletedFuncs = 5, 10110 DefaultedFuncs = 6, 10111 ConstexprFuncs = 7, 10112 ConstevalFuncs = 8, 10113 }; 10114 enum Different { 10115 CallingConv = 0, 10116 ReturnType = 1, 10117 ConstexprSpec = 2, 10118 InlineSpec = 3, 10119 StorageClass = 4, 10120 Linkage = 5, 10121 }; 10122 10123 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10124 !OldFD->getType()->getAs<FunctionProtoType>()) { 10125 Diag(OldFD->getLocation(), NoProtoDiagID); 10126 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10127 return true; 10128 } 10129 10130 if (NoProtoDiagID.getDiagID() != 0 && 10131 !NewFD->getType()->getAs<FunctionProtoType>()) 10132 return Diag(NewFD->getLocation(), NoProtoDiagID); 10133 10134 if (!TemplatesSupported && 10135 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10136 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10137 << FuncTemplates; 10138 10139 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10140 if (NewCXXFD->isVirtual()) 10141 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10142 << VirtFuncs; 10143 10144 if (isa<CXXConstructorDecl>(NewCXXFD)) 10145 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10146 << Constructors; 10147 10148 if (isa<CXXDestructorDecl>(NewCXXFD)) 10149 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10150 << Destructors; 10151 } 10152 10153 if (NewFD->isDeleted()) 10154 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10155 << DeletedFuncs; 10156 10157 if (NewFD->isDefaulted()) 10158 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10159 << DefaultedFuncs; 10160 10161 if (!ConstexprSupported && NewFD->isConstexpr()) 10162 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10163 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10164 10165 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10166 const auto *NewType = cast<FunctionType>(NewQType); 10167 QualType NewReturnType = NewType->getReturnType(); 10168 10169 if (NewReturnType->isUndeducedType()) 10170 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10171 << DeducedReturn; 10172 10173 // Ensure the return type is identical. 10174 if (OldFD) { 10175 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10176 const auto *OldType = cast<FunctionType>(OldQType); 10177 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10178 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10179 10180 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10181 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10182 10183 QualType OldReturnType = OldType->getReturnType(); 10184 10185 if (OldReturnType != NewReturnType) 10186 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10187 10188 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10189 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10190 10191 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10192 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10193 10194 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10195 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10196 10197 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10198 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10199 10200 if (CheckEquivalentExceptionSpec( 10201 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10202 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10203 return true; 10204 } 10205 return false; 10206 } 10207 10208 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10209 const FunctionDecl *NewFD, 10210 bool CausesMV, 10211 MultiVersionKind MVType) { 10212 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10213 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10214 if (OldFD) 10215 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10216 return true; 10217 } 10218 10219 bool IsCPUSpecificCPUDispatchMVType = 10220 MVType == MultiVersionKind::CPUDispatch || 10221 MVType == MultiVersionKind::CPUSpecific; 10222 10223 if (CausesMV && OldFD && 10224 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10225 return true; 10226 10227 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10228 return true; 10229 10230 // Only allow transition to MultiVersion if it hasn't been used. 10231 if (OldFD && CausesMV && OldFD->isUsed(false)) 10232 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10233 10234 return S.areMultiversionVariantFunctionsCompatible( 10235 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10236 PartialDiagnosticAt(NewFD->getLocation(), 10237 S.PDiag(diag::note_multiversioning_caused_here)), 10238 PartialDiagnosticAt(NewFD->getLocation(), 10239 S.PDiag(diag::err_multiversion_doesnt_support) 10240 << IsCPUSpecificCPUDispatchMVType), 10241 PartialDiagnosticAt(NewFD->getLocation(), 10242 S.PDiag(diag::err_multiversion_diff)), 10243 /*TemplatesSupported=*/false, 10244 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10245 /*CLinkageMayDiffer=*/false); 10246 } 10247 10248 /// Check the validity of a multiversion function declaration that is the 10249 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10250 /// 10251 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10252 /// 10253 /// Returns true if there was an error, false otherwise. 10254 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10255 MultiVersionKind MVType, 10256 const TargetAttr *TA) { 10257 assert(MVType != MultiVersionKind::None && 10258 "Function lacks multiversion attribute"); 10259 10260 // Target only causes MV if it is default, otherwise this is a normal 10261 // function. 10262 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10263 return false; 10264 10265 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10266 FD->setInvalidDecl(); 10267 return true; 10268 } 10269 10270 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10271 FD->setInvalidDecl(); 10272 return true; 10273 } 10274 10275 FD->setIsMultiVersion(); 10276 return false; 10277 } 10278 10279 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10280 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10281 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10282 return true; 10283 } 10284 10285 return false; 10286 } 10287 10288 static bool CheckTargetCausesMultiVersioning( 10289 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10290 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10291 LookupResult &Previous) { 10292 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10293 ParsedTargetAttr NewParsed = NewTA->parse(); 10294 // Sort order doesn't matter, it just needs to be consistent. 10295 llvm::sort(NewParsed.Features); 10296 10297 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10298 // to change, this is a simple redeclaration. 10299 if (!NewTA->isDefaultVersion() && 10300 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10301 return false; 10302 10303 // Otherwise, this decl causes MultiVersioning. 10304 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10305 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10306 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10307 NewFD->setInvalidDecl(); 10308 return true; 10309 } 10310 10311 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10312 MultiVersionKind::Target)) { 10313 NewFD->setInvalidDecl(); 10314 return true; 10315 } 10316 10317 if (CheckMultiVersionValue(S, NewFD)) { 10318 NewFD->setInvalidDecl(); 10319 return true; 10320 } 10321 10322 // If this is 'default', permit the forward declaration. 10323 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10324 Redeclaration = true; 10325 OldDecl = OldFD; 10326 OldFD->setIsMultiVersion(); 10327 NewFD->setIsMultiVersion(); 10328 return false; 10329 } 10330 10331 if (CheckMultiVersionValue(S, OldFD)) { 10332 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10333 NewFD->setInvalidDecl(); 10334 return true; 10335 } 10336 10337 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10338 10339 if (OldParsed == NewParsed) { 10340 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10341 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10342 NewFD->setInvalidDecl(); 10343 return true; 10344 } 10345 10346 for (const auto *FD : OldFD->redecls()) { 10347 const auto *CurTA = FD->getAttr<TargetAttr>(); 10348 // We allow forward declarations before ANY multiversioning attributes, but 10349 // nothing after the fact. 10350 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10351 (!CurTA || CurTA->isInherited())) { 10352 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10353 << 0; 10354 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10355 NewFD->setInvalidDecl(); 10356 return true; 10357 } 10358 } 10359 10360 OldFD->setIsMultiVersion(); 10361 NewFD->setIsMultiVersion(); 10362 Redeclaration = false; 10363 MergeTypeWithPrevious = false; 10364 OldDecl = nullptr; 10365 Previous.clear(); 10366 return false; 10367 } 10368 10369 /// Check the validity of a new function declaration being added to an existing 10370 /// multiversioned declaration collection. 10371 static bool CheckMultiVersionAdditionalDecl( 10372 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10373 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10374 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10375 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10376 LookupResult &Previous) { 10377 10378 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10379 // Disallow mixing of multiversioning types. 10380 if ((OldMVType == MultiVersionKind::Target && 10381 NewMVType != MultiVersionKind::Target) || 10382 (NewMVType == MultiVersionKind::Target && 10383 OldMVType != MultiVersionKind::Target)) { 10384 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10385 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10386 NewFD->setInvalidDecl(); 10387 return true; 10388 } 10389 10390 ParsedTargetAttr NewParsed; 10391 if (NewTA) { 10392 NewParsed = NewTA->parse(); 10393 llvm::sort(NewParsed.Features); 10394 } 10395 10396 bool UseMemberUsingDeclRules = 10397 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10398 10399 // Next, check ALL non-overloads to see if this is a redeclaration of a 10400 // previous member of the MultiVersion set. 10401 for (NamedDecl *ND : Previous) { 10402 FunctionDecl *CurFD = ND->getAsFunction(); 10403 if (!CurFD) 10404 continue; 10405 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10406 continue; 10407 10408 if (NewMVType == MultiVersionKind::Target) { 10409 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10410 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10411 NewFD->setIsMultiVersion(); 10412 Redeclaration = true; 10413 OldDecl = ND; 10414 return false; 10415 } 10416 10417 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10418 if (CurParsed == NewParsed) { 10419 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10420 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10421 NewFD->setInvalidDecl(); 10422 return true; 10423 } 10424 } else { 10425 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10426 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10427 // Handle CPUDispatch/CPUSpecific versions. 10428 // Only 1 CPUDispatch function is allowed, this will make it go through 10429 // the redeclaration errors. 10430 if (NewMVType == MultiVersionKind::CPUDispatch && 10431 CurFD->hasAttr<CPUDispatchAttr>()) { 10432 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10433 std::equal( 10434 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10435 NewCPUDisp->cpus_begin(), 10436 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10437 return Cur->getName() == New->getName(); 10438 })) { 10439 NewFD->setIsMultiVersion(); 10440 Redeclaration = true; 10441 OldDecl = ND; 10442 return false; 10443 } 10444 10445 // If the declarations don't match, this is an error condition. 10446 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10447 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10448 NewFD->setInvalidDecl(); 10449 return true; 10450 } 10451 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10452 10453 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10454 std::equal( 10455 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10456 NewCPUSpec->cpus_begin(), 10457 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10458 return Cur->getName() == New->getName(); 10459 })) { 10460 NewFD->setIsMultiVersion(); 10461 Redeclaration = true; 10462 OldDecl = ND; 10463 return false; 10464 } 10465 10466 // Only 1 version of CPUSpecific is allowed for each CPU. 10467 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10468 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10469 if (CurII == NewII) { 10470 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10471 << NewII; 10472 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10473 NewFD->setInvalidDecl(); 10474 return true; 10475 } 10476 } 10477 } 10478 } 10479 // If the two decls aren't the same MVType, there is no possible error 10480 // condition. 10481 } 10482 } 10483 10484 // Else, this is simply a non-redecl case. Checking the 'value' is only 10485 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10486 // handled in the attribute adding step. 10487 if (NewMVType == MultiVersionKind::Target && 10488 CheckMultiVersionValue(S, NewFD)) { 10489 NewFD->setInvalidDecl(); 10490 return true; 10491 } 10492 10493 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10494 !OldFD->isMultiVersion(), NewMVType)) { 10495 NewFD->setInvalidDecl(); 10496 return true; 10497 } 10498 10499 // Permit forward declarations in the case where these two are compatible. 10500 if (!OldFD->isMultiVersion()) { 10501 OldFD->setIsMultiVersion(); 10502 NewFD->setIsMultiVersion(); 10503 Redeclaration = true; 10504 OldDecl = OldFD; 10505 return false; 10506 } 10507 10508 NewFD->setIsMultiVersion(); 10509 Redeclaration = false; 10510 MergeTypeWithPrevious = false; 10511 OldDecl = nullptr; 10512 Previous.clear(); 10513 return false; 10514 } 10515 10516 10517 /// Check the validity of a mulitversion function declaration. 10518 /// Also sets the multiversion'ness' of the function itself. 10519 /// 10520 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10521 /// 10522 /// Returns true if there was an error, false otherwise. 10523 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10524 bool &Redeclaration, NamedDecl *&OldDecl, 10525 bool &MergeTypeWithPrevious, 10526 LookupResult &Previous) { 10527 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10528 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10529 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10530 10531 // Mixing Multiversioning types is prohibited. 10532 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10533 (NewCPUDisp && NewCPUSpec)) { 10534 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10535 NewFD->setInvalidDecl(); 10536 return true; 10537 } 10538 10539 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10540 10541 // Main isn't allowed to become a multiversion function, however it IS 10542 // permitted to have 'main' be marked with the 'target' optimization hint. 10543 if (NewFD->isMain()) { 10544 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10545 MVType == MultiVersionKind::CPUDispatch || 10546 MVType == MultiVersionKind::CPUSpecific) { 10547 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10548 NewFD->setInvalidDecl(); 10549 return true; 10550 } 10551 return false; 10552 } 10553 10554 if (!OldDecl || !OldDecl->getAsFunction() || 10555 OldDecl->getDeclContext()->getRedeclContext() != 10556 NewFD->getDeclContext()->getRedeclContext()) { 10557 // If there's no previous declaration, AND this isn't attempting to cause 10558 // multiversioning, this isn't an error condition. 10559 if (MVType == MultiVersionKind::None) 10560 return false; 10561 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10562 } 10563 10564 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10565 10566 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10567 return false; 10568 10569 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10570 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10571 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10572 NewFD->setInvalidDecl(); 10573 return true; 10574 } 10575 10576 // Handle the target potentially causes multiversioning case. 10577 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10578 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10579 Redeclaration, OldDecl, 10580 MergeTypeWithPrevious, Previous); 10581 10582 // At this point, we have a multiversion function decl (in OldFD) AND an 10583 // appropriate attribute in the current function decl. Resolve that these are 10584 // still compatible with previous declarations. 10585 return CheckMultiVersionAdditionalDecl( 10586 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10587 OldDecl, MergeTypeWithPrevious, Previous); 10588 } 10589 10590 /// Perform semantic checking of a new function declaration. 10591 /// 10592 /// Performs semantic analysis of the new function declaration 10593 /// NewFD. This routine performs all semantic checking that does not 10594 /// require the actual declarator involved in the declaration, and is 10595 /// used both for the declaration of functions as they are parsed 10596 /// (called via ActOnDeclarator) and for the declaration of functions 10597 /// that have been instantiated via C++ template instantiation (called 10598 /// via InstantiateDecl). 10599 /// 10600 /// \param IsMemberSpecialization whether this new function declaration is 10601 /// a member specialization (that replaces any definition provided by the 10602 /// previous declaration). 10603 /// 10604 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10605 /// 10606 /// \returns true if the function declaration is a redeclaration. 10607 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10608 LookupResult &Previous, 10609 bool IsMemberSpecialization) { 10610 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10611 "Variably modified return types are not handled here"); 10612 10613 // Determine whether the type of this function should be merged with 10614 // a previous visible declaration. This never happens for functions in C++, 10615 // and always happens in C if the previous declaration was visible. 10616 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10617 !Previous.isShadowed(); 10618 10619 bool Redeclaration = false; 10620 NamedDecl *OldDecl = nullptr; 10621 bool MayNeedOverloadableChecks = false; 10622 10623 // Merge or overload the declaration with an existing declaration of 10624 // the same name, if appropriate. 10625 if (!Previous.empty()) { 10626 // Determine whether NewFD is an overload of PrevDecl or 10627 // a declaration that requires merging. If it's an overload, 10628 // there's no more work to do here; we'll just add the new 10629 // function to the scope. 10630 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10631 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10632 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10633 Redeclaration = true; 10634 OldDecl = Candidate; 10635 } 10636 } else { 10637 MayNeedOverloadableChecks = true; 10638 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10639 /*NewIsUsingDecl*/ false)) { 10640 case Ovl_Match: 10641 Redeclaration = true; 10642 break; 10643 10644 case Ovl_NonFunction: 10645 Redeclaration = true; 10646 break; 10647 10648 case Ovl_Overload: 10649 Redeclaration = false; 10650 break; 10651 } 10652 } 10653 } 10654 10655 // Check for a previous extern "C" declaration with this name. 10656 if (!Redeclaration && 10657 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10658 if (!Previous.empty()) { 10659 // This is an extern "C" declaration with the same name as a previous 10660 // declaration, and thus redeclares that entity... 10661 Redeclaration = true; 10662 OldDecl = Previous.getFoundDecl(); 10663 MergeTypeWithPrevious = false; 10664 10665 // ... except in the presence of __attribute__((overloadable)). 10666 if (OldDecl->hasAttr<OverloadableAttr>() || 10667 NewFD->hasAttr<OverloadableAttr>()) { 10668 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10669 MayNeedOverloadableChecks = true; 10670 Redeclaration = false; 10671 OldDecl = nullptr; 10672 } 10673 } 10674 } 10675 } 10676 10677 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10678 MergeTypeWithPrevious, Previous)) 10679 return Redeclaration; 10680 10681 // C++11 [dcl.constexpr]p8: 10682 // A constexpr specifier for a non-static member function that is not 10683 // a constructor declares that member function to be const. 10684 // 10685 // This needs to be delayed until we know whether this is an out-of-line 10686 // definition of a static member function. 10687 // 10688 // This rule is not present in C++1y, so we produce a backwards 10689 // compatibility warning whenever it happens in C++11. 10690 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10691 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10692 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10693 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10694 CXXMethodDecl *OldMD = nullptr; 10695 if (OldDecl) 10696 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10697 if (!OldMD || !OldMD->isStatic()) { 10698 const FunctionProtoType *FPT = 10699 MD->getType()->castAs<FunctionProtoType>(); 10700 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10701 EPI.TypeQuals.addConst(); 10702 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10703 FPT->getParamTypes(), EPI)); 10704 10705 // Warn that we did this, if we're not performing template instantiation. 10706 // In that case, we'll have warned already when the template was defined. 10707 if (!inTemplateInstantiation()) { 10708 SourceLocation AddConstLoc; 10709 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10710 .IgnoreParens().getAs<FunctionTypeLoc>()) 10711 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10712 10713 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10714 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10715 } 10716 } 10717 } 10718 10719 if (Redeclaration) { 10720 // NewFD and OldDecl represent declarations that need to be 10721 // merged. 10722 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10723 NewFD->setInvalidDecl(); 10724 return Redeclaration; 10725 } 10726 10727 Previous.clear(); 10728 Previous.addDecl(OldDecl); 10729 10730 if (FunctionTemplateDecl *OldTemplateDecl = 10731 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10732 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10733 FunctionTemplateDecl *NewTemplateDecl 10734 = NewFD->getDescribedFunctionTemplate(); 10735 assert(NewTemplateDecl && "Template/non-template mismatch"); 10736 10737 // The call to MergeFunctionDecl above may have created some state in 10738 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10739 // can add it as a redeclaration. 10740 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10741 10742 NewFD->setPreviousDeclaration(OldFD); 10743 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10744 if (NewFD->isCXXClassMember()) { 10745 NewFD->setAccess(OldTemplateDecl->getAccess()); 10746 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10747 } 10748 10749 // If this is an explicit specialization of a member that is a function 10750 // template, mark it as a member specialization. 10751 if (IsMemberSpecialization && 10752 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10753 NewTemplateDecl->setMemberSpecialization(); 10754 assert(OldTemplateDecl->isMemberSpecialization()); 10755 // Explicit specializations of a member template do not inherit deleted 10756 // status from the parent member template that they are specializing. 10757 if (OldFD->isDeleted()) { 10758 // FIXME: This assert will not hold in the presence of modules. 10759 assert(OldFD->getCanonicalDecl() == OldFD); 10760 // FIXME: We need an update record for this AST mutation. 10761 OldFD->setDeletedAsWritten(false); 10762 } 10763 } 10764 10765 } else { 10766 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10767 auto *OldFD = cast<FunctionDecl>(OldDecl); 10768 // This needs to happen first so that 'inline' propagates. 10769 NewFD->setPreviousDeclaration(OldFD); 10770 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10771 if (NewFD->isCXXClassMember()) 10772 NewFD->setAccess(OldFD->getAccess()); 10773 } 10774 } 10775 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10776 !NewFD->getAttr<OverloadableAttr>()) { 10777 assert((Previous.empty() || 10778 llvm::any_of(Previous, 10779 [](const NamedDecl *ND) { 10780 return ND->hasAttr<OverloadableAttr>(); 10781 })) && 10782 "Non-redecls shouldn't happen without overloadable present"); 10783 10784 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10785 const auto *FD = dyn_cast<FunctionDecl>(ND); 10786 return FD && !FD->hasAttr<OverloadableAttr>(); 10787 }); 10788 10789 if (OtherUnmarkedIter != Previous.end()) { 10790 Diag(NewFD->getLocation(), 10791 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10792 Diag((*OtherUnmarkedIter)->getLocation(), 10793 diag::note_attribute_overloadable_prev_overload) 10794 << false; 10795 10796 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10797 } 10798 } 10799 10800 // Semantic checking for this function declaration (in isolation). 10801 10802 if (getLangOpts().CPlusPlus) { 10803 // C++-specific checks. 10804 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10805 CheckConstructor(Constructor); 10806 } else if (CXXDestructorDecl *Destructor = 10807 dyn_cast<CXXDestructorDecl>(NewFD)) { 10808 CXXRecordDecl *Record = Destructor->getParent(); 10809 QualType ClassType = Context.getTypeDeclType(Record); 10810 10811 // FIXME: Shouldn't we be able to perform this check even when the class 10812 // type is dependent? Both gcc and edg can handle that. 10813 if (!ClassType->isDependentType()) { 10814 DeclarationName Name 10815 = Context.DeclarationNames.getCXXDestructorName( 10816 Context.getCanonicalType(ClassType)); 10817 if (NewFD->getDeclName() != Name) { 10818 Diag(NewFD->getLocation(), diag::err_destructor_name); 10819 NewFD->setInvalidDecl(); 10820 return Redeclaration; 10821 } 10822 } 10823 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10824 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10825 CheckDeductionGuideTemplate(TD); 10826 10827 // A deduction guide is not on the list of entities that can be 10828 // explicitly specialized. 10829 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10830 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10831 << /*explicit specialization*/ 1; 10832 } 10833 10834 // Find any virtual functions that this function overrides. 10835 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10836 if (!Method->isFunctionTemplateSpecialization() && 10837 !Method->getDescribedFunctionTemplate() && 10838 Method->isCanonicalDecl()) { 10839 AddOverriddenMethods(Method->getParent(), Method); 10840 } 10841 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10842 // C++2a [class.virtual]p6 10843 // A virtual method shall not have a requires-clause. 10844 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10845 diag::err_constrained_virtual_method); 10846 10847 if (Method->isStatic()) 10848 checkThisInStaticMemberFunctionType(Method); 10849 } 10850 10851 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10852 ActOnConversionDeclarator(Conversion); 10853 10854 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10855 if (NewFD->isOverloadedOperator() && 10856 CheckOverloadedOperatorDeclaration(NewFD)) { 10857 NewFD->setInvalidDecl(); 10858 return Redeclaration; 10859 } 10860 10861 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10862 if (NewFD->getLiteralIdentifier() && 10863 CheckLiteralOperatorDeclaration(NewFD)) { 10864 NewFD->setInvalidDecl(); 10865 return Redeclaration; 10866 } 10867 10868 // In C++, check default arguments now that we have merged decls. Unless 10869 // the lexical context is the class, because in this case this is done 10870 // during delayed parsing anyway. 10871 if (!CurContext->isRecord()) 10872 CheckCXXDefaultArguments(NewFD); 10873 10874 // If this function declares a builtin function, check the type of this 10875 // declaration against the expected type for the builtin. 10876 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10877 ASTContext::GetBuiltinTypeError Error; 10878 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10879 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10880 // If the type of the builtin differs only in its exception 10881 // specification, that's OK. 10882 // FIXME: If the types do differ in this way, it would be better to 10883 // retain the 'noexcept' form of the type. 10884 if (!T.isNull() && 10885 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10886 NewFD->getType())) 10887 // The type of this function differs from the type of the builtin, 10888 // so forget about the builtin entirely. 10889 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10890 } 10891 10892 // If this function is declared as being extern "C", then check to see if 10893 // the function returns a UDT (class, struct, or union type) that is not C 10894 // compatible, and if it does, warn the user. 10895 // But, issue any diagnostic on the first declaration only. 10896 if (Previous.empty() && NewFD->isExternC()) { 10897 QualType R = NewFD->getReturnType(); 10898 if (R->isIncompleteType() && !R->isVoidType()) 10899 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10900 << NewFD << R; 10901 else if (!R.isPODType(Context) && !R->isVoidType() && 10902 !R->isObjCObjectPointerType()) 10903 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10904 } 10905 10906 // C++1z [dcl.fct]p6: 10907 // [...] whether the function has a non-throwing exception-specification 10908 // [is] part of the function type 10909 // 10910 // This results in an ABI break between C++14 and C++17 for functions whose 10911 // declared type includes an exception-specification in a parameter or 10912 // return type. (Exception specifications on the function itself are OK in 10913 // most cases, and exception specifications are not permitted in most other 10914 // contexts where they could make it into a mangling.) 10915 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10916 auto HasNoexcept = [&](QualType T) -> bool { 10917 // Strip off declarator chunks that could be between us and a function 10918 // type. We don't need to look far, exception specifications are very 10919 // restricted prior to C++17. 10920 if (auto *RT = T->getAs<ReferenceType>()) 10921 T = RT->getPointeeType(); 10922 else if (T->isAnyPointerType()) 10923 T = T->getPointeeType(); 10924 else if (auto *MPT = T->getAs<MemberPointerType>()) 10925 T = MPT->getPointeeType(); 10926 if (auto *FPT = T->getAs<FunctionProtoType>()) 10927 if (FPT->isNothrow()) 10928 return true; 10929 return false; 10930 }; 10931 10932 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10933 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10934 for (QualType T : FPT->param_types()) 10935 AnyNoexcept |= HasNoexcept(T); 10936 if (AnyNoexcept) 10937 Diag(NewFD->getLocation(), 10938 diag::warn_cxx17_compat_exception_spec_in_signature) 10939 << NewFD; 10940 } 10941 10942 if (!Redeclaration && LangOpts.CUDA) 10943 checkCUDATargetOverload(NewFD, Previous); 10944 } 10945 return Redeclaration; 10946 } 10947 10948 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10949 // C++11 [basic.start.main]p3: 10950 // A program that [...] declares main to be inline, static or 10951 // constexpr is ill-formed. 10952 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10953 // appear in a declaration of main. 10954 // static main is not an error under C99, but we should warn about it. 10955 // We accept _Noreturn main as an extension. 10956 if (FD->getStorageClass() == SC_Static) 10957 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10958 ? diag::err_static_main : diag::warn_static_main) 10959 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10960 if (FD->isInlineSpecified()) 10961 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10962 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10963 if (DS.isNoreturnSpecified()) { 10964 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10965 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10966 Diag(NoreturnLoc, diag::ext_noreturn_main); 10967 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10968 << FixItHint::CreateRemoval(NoreturnRange); 10969 } 10970 if (FD->isConstexpr()) { 10971 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10972 << FD->isConsteval() 10973 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10974 FD->setConstexprKind(CSK_unspecified); 10975 } 10976 10977 if (getLangOpts().OpenCL) { 10978 Diag(FD->getLocation(), diag::err_opencl_no_main) 10979 << FD->hasAttr<OpenCLKernelAttr>(); 10980 FD->setInvalidDecl(); 10981 return; 10982 } 10983 10984 QualType T = FD->getType(); 10985 assert(T->isFunctionType() && "function decl is not of function type"); 10986 const FunctionType* FT = T->castAs<FunctionType>(); 10987 10988 // Set default calling convention for main() 10989 if (FT->getCallConv() != CC_C) { 10990 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10991 FD->setType(QualType(FT, 0)); 10992 T = Context.getCanonicalType(FD->getType()); 10993 } 10994 10995 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10996 // In C with GNU extensions we allow main() to have non-integer return 10997 // type, but we should warn about the extension, and we disable the 10998 // implicit-return-zero rule. 10999 11000 // GCC in C mode accepts qualified 'int'. 11001 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11002 FD->setHasImplicitReturnZero(true); 11003 else { 11004 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11005 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11006 if (RTRange.isValid()) 11007 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11008 << FixItHint::CreateReplacement(RTRange, "int"); 11009 } 11010 } else { 11011 // In C and C++, main magically returns 0 if you fall off the end; 11012 // set the flag which tells us that. 11013 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11014 11015 // All the standards say that main() should return 'int'. 11016 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11017 FD->setHasImplicitReturnZero(true); 11018 else { 11019 // Otherwise, this is just a flat-out error. 11020 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11021 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11022 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11023 : FixItHint()); 11024 FD->setInvalidDecl(true); 11025 } 11026 } 11027 11028 // Treat protoless main() as nullary. 11029 if (isa<FunctionNoProtoType>(FT)) return; 11030 11031 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11032 unsigned nparams = FTP->getNumParams(); 11033 assert(FD->getNumParams() == nparams); 11034 11035 bool HasExtraParameters = (nparams > 3); 11036 11037 if (FTP->isVariadic()) { 11038 Diag(FD->getLocation(), diag::ext_variadic_main); 11039 // FIXME: if we had information about the location of the ellipsis, we 11040 // could add a FixIt hint to remove it as a parameter. 11041 } 11042 11043 // Darwin passes an undocumented fourth argument of type char**. If 11044 // other platforms start sprouting these, the logic below will start 11045 // getting shifty. 11046 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11047 HasExtraParameters = false; 11048 11049 if (HasExtraParameters) { 11050 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11051 FD->setInvalidDecl(true); 11052 nparams = 3; 11053 } 11054 11055 // FIXME: a lot of the following diagnostics would be improved 11056 // if we had some location information about types. 11057 11058 QualType CharPP = 11059 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11060 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11061 11062 for (unsigned i = 0; i < nparams; ++i) { 11063 QualType AT = FTP->getParamType(i); 11064 11065 bool mismatch = true; 11066 11067 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11068 mismatch = false; 11069 else if (Expected[i] == CharPP) { 11070 // As an extension, the following forms are okay: 11071 // char const ** 11072 // char const * const * 11073 // char * const * 11074 11075 QualifierCollector qs; 11076 const PointerType* PT; 11077 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11078 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11079 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11080 Context.CharTy)) { 11081 qs.removeConst(); 11082 mismatch = !qs.empty(); 11083 } 11084 } 11085 11086 if (mismatch) { 11087 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11088 // TODO: suggest replacing given type with expected type 11089 FD->setInvalidDecl(true); 11090 } 11091 } 11092 11093 if (nparams == 1 && !FD->isInvalidDecl()) { 11094 Diag(FD->getLocation(), diag::warn_main_one_arg); 11095 } 11096 11097 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11098 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11099 FD->setInvalidDecl(); 11100 } 11101 } 11102 11103 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11104 QualType T = FD->getType(); 11105 assert(T->isFunctionType() && "function decl is not of function type"); 11106 const FunctionType *FT = T->castAs<FunctionType>(); 11107 11108 // Set an implicit return of 'zero' if the function can return some integral, 11109 // enumeration, pointer or nullptr type. 11110 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11111 FT->getReturnType()->isAnyPointerType() || 11112 FT->getReturnType()->isNullPtrType()) 11113 // DllMain is exempt because a return value of zero means it failed. 11114 if (FD->getName() != "DllMain") 11115 FD->setHasImplicitReturnZero(true); 11116 11117 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11118 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11119 FD->setInvalidDecl(); 11120 } 11121 } 11122 11123 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11124 // FIXME: Need strict checking. In C89, we need to check for 11125 // any assignment, increment, decrement, function-calls, or 11126 // commas outside of a sizeof. In C99, it's the same list, 11127 // except that the aforementioned are allowed in unevaluated 11128 // expressions. Everything else falls under the 11129 // "may accept other forms of constant expressions" exception. 11130 // 11131 // Regular C++ code will not end up here (exceptions: language extensions, 11132 // OpenCL C++ etc), so the constant expression rules there don't matter. 11133 if (Init->isValueDependent()) { 11134 assert(Init->containsErrors() && 11135 "Dependent code should only occur in error-recovery path."); 11136 return true; 11137 } 11138 const Expr *Culprit; 11139 if (Init->isConstantInitializer(Context, false, &Culprit)) 11140 return false; 11141 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11142 << Culprit->getSourceRange(); 11143 return true; 11144 } 11145 11146 namespace { 11147 // Visits an initialization expression to see if OrigDecl is evaluated in 11148 // its own initialization and throws a warning if it does. 11149 class SelfReferenceChecker 11150 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11151 Sema &S; 11152 Decl *OrigDecl; 11153 bool isRecordType; 11154 bool isPODType; 11155 bool isReferenceType; 11156 11157 bool isInitList; 11158 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11159 11160 public: 11161 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11162 11163 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11164 S(S), OrigDecl(OrigDecl) { 11165 isPODType = false; 11166 isRecordType = false; 11167 isReferenceType = false; 11168 isInitList = false; 11169 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11170 isPODType = VD->getType().isPODType(S.Context); 11171 isRecordType = VD->getType()->isRecordType(); 11172 isReferenceType = VD->getType()->isReferenceType(); 11173 } 11174 } 11175 11176 // For most expressions, just call the visitor. For initializer lists, 11177 // track the index of the field being initialized since fields are 11178 // initialized in order allowing use of previously initialized fields. 11179 void CheckExpr(Expr *E) { 11180 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11181 if (!InitList) { 11182 Visit(E); 11183 return; 11184 } 11185 11186 // Track and increment the index here. 11187 isInitList = true; 11188 InitFieldIndex.push_back(0); 11189 for (auto Child : InitList->children()) { 11190 CheckExpr(cast<Expr>(Child)); 11191 ++InitFieldIndex.back(); 11192 } 11193 InitFieldIndex.pop_back(); 11194 } 11195 11196 // Returns true if MemberExpr is checked and no further checking is needed. 11197 // Returns false if additional checking is required. 11198 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11199 llvm::SmallVector<FieldDecl*, 4> Fields; 11200 Expr *Base = E; 11201 bool ReferenceField = false; 11202 11203 // Get the field members used. 11204 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11205 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11206 if (!FD) 11207 return false; 11208 Fields.push_back(FD); 11209 if (FD->getType()->isReferenceType()) 11210 ReferenceField = true; 11211 Base = ME->getBase()->IgnoreParenImpCasts(); 11212 } 11213 11214 // Keep checking only if the base Decl is the same. 11215 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11216 if (!DRE || DRE->getDecl() != OrigDecl) 11217 return false; 11218 11219 // A reference field can be bound to an unininitialized field. 11220 if (CheckReference && !ReferenceField) 11221 return true; 11222 11223 // Convert FieldDecls to their index number. 11224 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11225 for (const FieldDecl *I : llvm::reverse(Fields)) 11226 UsedFieldIndex.push_back(I->getFieldIndex()); 11227 11228 // See if a warning is needed by checking the first difference in index 11229 // numbers. If field being used has index less than the field being 11230 // initialized, then the use is safe. 11231 for (auto UsedIter = UsedFieldIndex.begin(), 11232 UsedEnd = UsedFieldIndex.end(), 11233 OrigIter = InitFieldIndex.begin(), 11234 OrigEnd = InitFieldIndex.end(); 11235 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11236 if (*UsedIter < *OrigIter) 11237 return true; 11238 if (*UsedIter > *OrigIter) 11239 break; 11240 } 11241 11242 // TODO: Add a different warning which will print the field names. 11243 HandleDeclRefExpr(DRE); 11244 return true; 11245 } 11246 11247 // For most expressions, the cast is directly above the DeclRefExpr. 11248 // For conditional operators, the cast can be outside the conditional 11249 // operator if both expressions are DeclRefExpr's. 11250 void HandleValue(Expr *E) { 11251 E = E->IgnoreParens(); 11252 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11253 HandleDeclRefExpr(DRE); 11254 return; 11255 } 11256 11257 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11258 Visit(CO->getCond()); 11259 HandleValue(CO->getTrueExpr()); 11260 HandleValue(CO->getFalseExpr()); 11261 return; 11262 } 11263 11264 if (BinaryConditionalOperator *BCO = 11265 dyn_cast<BinaryConditionalOperator>(E)) { 11266 Visit(BCO->getCond()); 11267 HandleValue(BCO->getFalseExpr()); 11268 return; 11269 } 11270 11271 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11272 HandleValue(OVE->getSourceExpr()); 11273 return; 11274 } 11275 11276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11277 if (BO->getOpcode() == BO_Comma) { 11278 Visit(BO->getLHS()); 11279 HandleValue(BO->getRHS()); 11280 return; 11281 } 11282 } 11283 11284 if (isa<MemberExpr>(E)) { 11285 if (isInitList) { 11286 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11287 false /*CheckReference*/)) 11288 return; 11289 } 11290 11291 Expr *Base = E->IgnoreParenImpCasts(); 11292 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11293 // Check for static member variables and don't warn on them. 11294 if (!isa<FieldDecl>(ME->getMemberDecl())) 11295 return; 11296 Base = ME->getBase()->IgnoreParenImpCasts(); 11297 } 11298 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11299 HandleDeclRefExpr(DRE); 11300 return; 11301 } 11302 11303 Visit(E); 11304 } 11305 11306 // Reference types not handled in HandleValue are handled here since all 11307 // uses of references are bad, not just r-value uses. 11308 void VisitDeclRefExpr(DeclRefExpr *E) { 11309 if (isReferenceType) 11310 HandleDeclRefExpr(E); 11311 } 11312 11313 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11314 if (E->getCastKind() == CK_LValueToRValue) { 11315 HandleValue(E->getSubExpr()); 11316 return; 11317 } 11318 11319 Inherited::VisitImplicitCastExpr(E); 11320 } 11321 11322 void VisitMemberExpr(MemberExpr *E) { 11323 if (isInitList) { 11324 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11325 return; 11326 } 11327 11328 // Don't warn on arrays since they can be treated as pointers. 11329 if (E->getType()->canDecayToPointerType()) return; 11330 11331 // Warn when a non-static method call is followed by non-static member 11332 // field accesses, which is followed by a DeclRefExpr. 11333 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11334 bool Warn = (MD && !MD->isStatic()); 11335 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11336 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11337 if (!isa<FieldDecl>(ME->getMemberDecl())) 11338 Warn = false; 11339 Base = ME->getBase()->IgnoreParenImpCasts(); 11340 } 11341 11342 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11343 if (Warn) 11344 HandleDeclRefExpr(DRE); 11345 return; 11346 } 11347 11348 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11349 // Visit that expression. 11350 Visit(Base); 11351 } 11352 11353 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11354 Expr *Callee = E->getCallee(); 11355 11356 if (isa<UnresolvedLookupExpr>(Callee)) 11357 return Inherited::VisitCXXOperatorCallExpr(E); 11358 11359 Visit(Callee); 11360 for (auto Arg: E->arguments()) 11361 HandleValue(Arg->IgnoreParenImpCasts()); 11362 } 11363 11364 void VisitUnaryOperator(UnaryOperator *E) { 11365 // For POD record types, addresses of its own members are well-defined. 11366 if (E->getOpcode() == UO_AddrOf && isRecordType && 11367 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11368 if (!isPODType) 11369 HandleValue(E->getSubExpr()); 11370 return; 11371 } 11372 11373 if (E->isIncrementDecrementOp()) { 11374 HandleValue(E->getSubExpr()); 11375 return; 11376 } 11377 11378 Inherited::VisitUnaryOperator(E); 11379 } 11380 11381 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11382 11383 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11384 if (E->getConstructor()->isCopyConstructor()) { 11385 Expr *ArgExpr = E->getArg(0); 11386 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11387 if (ILE->getNumInits() == 1) 11388 ArgExpr = ILE->getInit(0); 11389 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11390 if (ICE->getCastKind() == CK_NoOp) 11391 ArgExpr = ICE->getSubExpr(); 11392 HandleValue(ArgExpr); 11393 return; 11394 } 11395 Inherited::VisitCXXConstructExpr(E); 11396 } 11397 11398 void VisitCallExpr(CallExpr *E) { 11399 // Treat std::move as a use. 11400 if (E->isCallToStdMove()) { 11401 HandleValue(E->getArg(0)); 11402 return; 11403 } 11404 11405 Inherited::VisitCallExpr(E); 11406 } 11407 11408 void VisitBinaryOperator(BinaryOperator *E) { 11409 if (E->isCompoundAssignmentOp()) { 11410 HandleValue(E->getLHS()); 11411 Visit(E->getRHS()); 11412 return; 11413 } 11414 11415 Inherited::VisitBinaryOperator(E); 11416 } 11417 11418 // A custom visitor for BinaryConditionalOperator is needed because the 11419 // regular visitor would check the condition and true expression separately 11420 // but both point to the same place giving duplicate diagnostics. 11421 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11422 Visit(E->getCond()); 11423 Visit(E->getFalseExpr()); 11424 } 11425 11426 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11427 Decl* ReferenceDecl = DRE->getDecl(); 11428 if (OrigDecl != ReferenceDecl) return; 11429 unsigned diag; 11430 if (isReferenceType) { 11431 diag = diag::warn_uninit_self_reference_in_reference_init; 11432 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11433 diag = diag::warn_static_self_reference_in_init; 11434 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11435 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11436 DRE->getDecl()->getType()->isRecordType()) { 11437 diag = diag::warn_uninit_self_reference_in_init; 11438 } else { 11439 // Local variables will be handled by the CFG analysis. 11440 return; 11441 } 11442 11443 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11444 S.PDiag(diag) 11445 << DRE->getDecl() << OrigDecl->getLocation() 11446 << DRE->getSourceRange()); 11447 } 11448 }; 11449 11450 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11451 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11452 bool DirectInit) { 11453 // Parameters arguments are occassionially constructed with itself, 11454 // for instance, in recursive functions. Skip them. 11455 if (isa<ParmVarDecl>(OrigDecl)) 11456 return; 11457 11458 E = E->IgnoreParens(); 11459 11460 // Skip checking T a = a where T is not a record or reference type. 11461 // Doing so is a way to silence uninitialized warnings. 11462 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11463 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11464 if (ICE->getCastKind() == CK_LValueToRValue) 11465 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11466 if (DRE->getDecl() == OrigDecl) 11467 return; 11468 11469 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11470 } 11471 } // end anonymous namespace 11472 11473 namespace { 11474 // Simple wrapper to add the name of a variable or (if no variable is 11475 // available) a DeclarationName into a diagnostic. 11476 struct VarDeclOrName { 11477 VarDecl *VDecl; 11478 DeclarationName Name; 11479 11480 friend const Sema::SemaDiagnosticBuilder & 11481 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11482 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11483 } 11484 }; 11485 } // end anonymous namespace 11486 11487 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11488 DeclarationName Name, QualType Type, 11489 TypeSourceInfo *TSI, 11490 SourceRange Range, bool DirectInit, 11491 Expr *Init) { 11492 bool IsInitCapture = !VDecl; 11493 assert((!VDecl || !VDecl->isInitCapture()) && 11494 "init captures are expected to be deduced prior to initialization"); 11495 11496 VarDeclOrName VN{VDecl, Name}; 11497 11498 DeducedType *Deduced = Type->getContainedDeducedType(); 11499 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11500 11501 // C++11 [dcl.spec.auto]p3 11502 if (!Init) { 11503 assert(VDecl && "no init for init capture deduction?"); 11504 11505 // Except for class argument deduction, and then for an initializing 11506 // declaration only, i.e. no static at class scope or extern. 11507 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11508 VDecl->hasExternalStorage() || 11509 VDecl->isStaticDataMember()) { 11510 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11511 << VDecl->getDeclName() << Type; 11512 return QualType(); 11513 } 11514 } 11515 11516 ArrayRef<Expr*> DeduceInits; 11517 if (Init) 11518 DeduceInits = Init; 11519 11520 if (DirectInit) { 11521 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11522 DeduceInits = PL->exprs(); 11523 } 11524 11525 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11526 assert(VDecl && "non-auto type for init capture deduction?"); 11527 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11528 InitializationKind Kind = InitializationKind::CreateForInit( 11529 VDecl->getLocation(), DirectInit, Init); 11530 // FIXME: Initialization should not be taking a mutable list of inits. 11531 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11532 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11533 InitsCopy); 11534 } 11535 11536 if (DirectInit) { 11537 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11538 DeduceInits = IL->inits(); 11539 } 11540 11541 // Deduction only works if we have exactly one source expression. 11542 if (DeduceInits.empty()) { 11543 // It isn't possible to write this directly, but it is possible to 11544 // end up in this situation with "auto x(some_pack...);" 11545 Diag(Init->getBeginLoc(), IsInitCapture 11546 ? diag::err_init_capture_no_expression 11547 : diag::err_auto_var_init_no_expression) 11548 << VN << Type << Range; 11549 return QualType(); 11550 } 11551 11552 if (DeduceInits.size() > 1) { 11553 Diag(DeduceInits[1]->getBeginLoc(), 11554 IsInitCapture ? diag::err_init_capture_multiple_expressions 11555 : diag::err_auto_var_init_multiple_expressions) 11556 << VN << Type << Range; 11557 return QualType(); 11558 } 11559 11560 Expr *DeduceInit = DeduceInits[0]; 11561 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11562 Diag(Init->getBeginLoc(), IsInitCapture 11563 ? diag::err_init_capture_paren_braces 11564 : diag::err_auto_var_init_paren_braces) 11565 << isa<InitListExpr>(Init) << VN << Type << Range; 11566 return QualType(); 11567 } 11568 11569 // Expressions default to 'id' when we're in a debugger. 11570 bool DefaultedAnyToId = false; 11571 if (getLangOpts().DebuggerCastResultToId && 11572 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11573 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11574 if (Result.isInvalid()) { 11575 return QualType(); 11576 } 11577 Init = Result.get(); 11578 DefaultedAnyToId = true; 11579 } 11580 11581 // C++ [dcl.decomp]p1: 11582 // If the assignment-expression [...] has array type A and no ref-qualifier 11583 // is present, e has type cv A 11584 if (VDecl && isa<DecompositionDecl>(VDecl) && 11585 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11586 DeduceInit->getType()->isConstantArrayType()) 11587 return Context.getQualifiedType(DeduceInit->getType(), 11588 Type.getQualifiers()); 11589 11590 QualType DeducedType; 11591 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11592 if (!IsInitCapture) 11593 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11594 else if (isa<InitListExpr>(Init)) 11595 Diag(Range.getBegin(), 11596 diag::err_init_capture_deduction_failure_from_init_list) 11597 << VN 11598 << (DeduceInit->getType().isNull() ? TSI->getType() 11599 : DeduceInit->getType()) 11600 << DeduceInit->getSourceRange(); 11601 else 11602 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11603 << VN << TSI->getType() 11604 << (DeduceInit->getType().isNull() ? TSI->getType() 11605 : DeduceInit->getType()) 11606 << DeduceInit->getSourceRange(); 11607 } 11608 11609 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11610 // 'id' instead of a specific object type prevents most of our usual 11611 // checks. 11612 // We only want to warn outside of template instantiations, though: 11613 // inside a template, the 'id' could have come from a parameter. 11614 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11615 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11616 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11617 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11618 } 11619 11620 return DeducedType; 11621 } 11622 11623 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11624 Expr *Init) { 11625 assert(!Init || !Init->containsErrors()); 11626 QualType DeducedType = deduceVarTypeFromInitializer( 11627 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11628 VDecl->getSourceRange(), DirectInit, Init); 11629 if (DeducedType.isNull()) { 11630 VDecl->setInvalidDecl(); 11631 return true; 11632 } 11633 11634 VDecl->setType(DeducedType); 11635 assert(VDecl->isLinkageValid()); 11636 11637 // In ARC, infer lifetime. 11638 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11639 VDecl->setInvalidDecl(); 11640 11641 if (getLangOpts().OpenCL) 11642 deduceOpenCLAddressSpace(VDecl); 11643 11644 // If this is a redeclaration, check that the type we just deduced matches 11645 // the previously declared type. 11646 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11647 // We never need to merge the type, because we cannot form an incomplete 11648 // array of auto, nor deduce such a type. 11649 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11650 } 11651 11652 // Check the deduced type is valid for a variable declaration. 11653 CheckVariableDeclarationType(VDecl); 11654 return VDecl->isInvalidDecl(); 11655 } 11656 11657 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11658 SourceLocation Loc) { 11659 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11660 Init = EWC->getSubExpr(); 11661 11662 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11663 Init = CE->getSubExpr(); 11664 11665 QualType InitType = Init->getType(); 11666 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11667 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11668 "shouldn't be called if type doesn't have a non-trivial C struct"); 11669 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11670 for (auto I : ILE->inits()) { 11671 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11672 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11673 continue; 11674 SourceLocation SL = I->getExprLoc(); 11675 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11676 } 11677 return; 11678 } 11679 11680 if (isa<ImplicitValueInitExpr>(Init)) { 11681 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11682 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11683 NTCUK_Init); 11684 } else { 11685 // Assume all other explicit initializers involving copying some existing 11686 // object. 11687 // TODO: ignore any explicit initializers where we can guarantee 11688 // copy-elision. 11689 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11690 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11691 } 11692 } 11693 11694 namespace { 11695 11696 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11697 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11698 // in the source code or implicitly by the compiler if it is in a union 11699 // defined in a system header and has non-trivial ObjC ownership 11700 // qualifications. We don't want those fields to participate in determining 11701 // whether the containing union is non-trivial. 11702 return FD->hasAttr<UnavailableAttr>(); 11703 } 11704 11705 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11706 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11707 void> { 11708 using Super = 11709 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11710 void>; 11711 11712 DiagNonTrivalCUnionDefaultInitializeVisitor( 11713 QualType OrigTy, SourceLocation OrigLoc, 11714 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11715 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11716 11717 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11718 const FieldDecl *FD, bool InNonTrivialUnion) { 11719 if (const auto *AT = S.Context.getAsArrayType(QT)) 11720 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11721 InNonTrivialUnion); 11722 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11723 } 11724 11725 void visitARCStrong(QualType QT, const FieldDecl *FD, 11726 bool InNonTrivialUnion) { 11727 if (InNonTrivialUnion) 11728 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11729 << 1 << 0 << QT << FD->getName(); 11730 } 11731 11732 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11733 if (InNonTrivialUnion) 11734 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11735 << 1 << 0 << QT << FD->getName(); 11736 } 11737 11738 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11739 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11740 if (RD->isUnion()) { 11741 if (OrigLoc.isValid()) { 11742 bool IsUnion = false; 11743 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11744 IsUnion = OrigRD->isUnion(); 11745 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11746 << 0 << OrigTy << IsUnion << UseContext; 11747 // Reset OrigLoc so that this diagnostic is emitted only once. 11748 OrigLoc = SourceLocation(); 11749 } 11750 InNonTrivialUnion = true; 11751 } 11752 11753 if (InNonTrivialUnion) 11754 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11755 << 0 << 0 << QT.getUnqualifiedType() << ""; 11756 11757 for (const FieldDecl *FD : RD->fields()) 11758 if (!shouldIgnoreForRecordTriviality(FD)) 11759 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11760 } 11761 11762 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11763 11764 // The non-trivial C union type or the struct/union type that contains a 11765 // non-trivial C union. 11766 QualType OrigTy; 11767 SourceLocation OrigLoc; 11768 Sema::NonTrivialCUnionContext UseContext; 11769 Sema &S; 11770 }; 11771 11772 struct DiagNonTrivalCUnionDestructedTypeVisitor 11773 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11774 using Super = 11775 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11776 11777 DiagNonTrivalCUnionDestructedTypeVisitor( 11778 QualType OrigTy, SourceLocation OrigLoc, 11779 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11780 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11781 11782 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11783 const FieldDecl *FD, bool InNonTrivialUnion) { 11784 if (const auto *AT = S.Context.getAsArrayType(QT)) 11785 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11786 InNonTrivialUnion); 11787 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11788 } 11789 11790 void visitARCStrong(QualType QT, const FieldDecl *FD, 11791 bool InNonTrivialUnion) { 11792 if (InNonTrivialUnion) 11793 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11794 << 1 << 1 << QT << FD->getName(); 11795 } 11796 11797 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11798 if (InNonTrivialUnion) 11799 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11800 << 1 << 1 << QT << FD->getName(); 11801 } 11802 11803 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11804 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11805 if (RD->isUnion()) { 11806 if (OrigLoc.isValid()) { 11807 bool IsUnion = false; 11808 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11809 IsUnion = OrigRD->isUnion(); 11810 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11811 << 1 << OrigTy << IsUnion << UseContext; 11812 // Reset OrigLoc so that this diagnostic is emitted only once. 11813 OrigLoc = SourceLocation(); 11814 } 11815 InNonTrivialUnion = true; 11816 } 11817 11818 if (InNonTrivialUnion) 11819 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11820 << 0 << 1 << QT.getUnqualifiedType() << ""; 11821 11822 for (const FieldDecl *FD : RD->fields()) 11823 if (!shouldIgnoreForRecordTriviality(FD)) 11824 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11825 } 11826 11827 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11828 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11829 bool InNonTrivialUnion) {} 11830 11831 // The non-trivial C union type or the struct/union type that contains a 11832 // non-trivial C union. 11833 QualType OrigTy; 11834 SourceLocation OrigLoc; 11835 Sema::NonTrivialCUnionContext UseContext; 11836 Sema &S; 11837 }; 11838 11839 struct DiagNonTrivalCUnionCopyVisitor 11840 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11841 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11842 11843 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11844 Sema::NonTrivialCUnionContext UseContext, 11845 Sema &S) 11846 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11847 11848 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11849 const FieldDecl *FD, bool InNonTrivialUnion) { 11850 if (const auto *AT = S.Context.getAsArrayType(QT)) 11851 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11852 InNonTrivialUnion); 11853 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11854 } 11855 11856 void visitARCStrong(QualType QT, const FieldDecl *FD, 11857 bool InNonTrivialUnion) { 11858 if (InNonTrivialUnion) 11859 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11860 << 1 << 2 << QT << FD->getName(); 11861 } 11862 11863 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11864 if (InNonTrivialUnion) 11865 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11866 << 1 << 2 << QT << FD->getName(); 11867 } 11868 11869 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11870 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11871 if (RD->isUnion()) { 11872 if (OrigLoc.isValid()) { 11873 bool IsUnion = false; 11874 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11875 IsUnion = OrigRD->isUnion(); 11876 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11877 << 2 << OrigTy << IsUnion << UseContext; 11878 // Reset OrigLoc so that this diagnostic is emitted only once. 11879 OrigLoc = SourceLocation(); 11880 } 11881 InNonTrivialUnion = true; 11882 } 11883 11884 if (InNonTrivialUnion) 11885 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11886 << 0 << 2 << QT.getUnqualifiedType() << ""; 11887 11888 for (const FieldDecl *FD : RD->fields()) 11889 if (!shouldIgnoreForRecordTriviality(FD)) 11890 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11891 } 11892 11893 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11894 const FieldDecl *FD, bool InNonTrivialUnion) {} 11895 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11896 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11897 bool InNonTrivialUnion) {} 11898 11899 // The non-trivial C union type or the struct/union type that contains a 11900 // non-trivial C union. 11901 QualType OrigTy; 11902 SourceLocation OrigLoc; 11903 Sema::NonTrivialCUnionContext UseContext; 11904 Sema &S; 11905 }; 11906 11907 } // namespace 11908 11909 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11910 NonTrivialCUnionContext UseContext, 11911 unsigned NonTrivialKind) { 11912 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11913 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11914 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11915 "shouldn't be called if type doesn't have a non-trivial C union"); 11916 11917 if ((NonTrivialKind & NTCUK_Init) && 11918 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11919 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11920 .visit(QT, nullptr, false); 11921 if ((NonTrivialKind & NTCUK_Destruct) && 11922 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11923 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11924 .visit(QT, nullptr, false); 11925 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11926 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11927 .visit(QT, nullptr, false); 11928 } 11929 11930 /// AddInitializerToDecl - Adds the initializer Init to the 11931 /// declaration dcl. If DirectInit is true, this is C++ direct 11932 /// initialization rather than copy initialization. 11933 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11934 // If there is no declaration, there was an error parsing it. Just ignore 11935 // the initializer. 11936 if (!RealDecl || RealDecl->isInvalidDecl()) { 11937 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11938 return; 11939 } 11940 11941 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11942 // Pure-specifiers are handled in ActOnPureSpecifier. 11943 Diag(Method->getLocation(), diag::err_member_function_initialization) 11944 << Method->getDeclName() << Init->getSourceRange(); 11945 Method->setInvalidDecl(); 11946 return; 11947 } 11948 11949 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11950 if (!VDecl) { 11951 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11952 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11953 RealDecl->setInvalidDecl(); 11954 return; 11955 } 11956 11957 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11958 if (VDecl->getType()->isUndeducedType()) { 11959 // Attempt typo correction early so that the type of the init expression can 11960 // be deduced based on the chosen correction if the original init contains a 11961 // TypoExpr. 11962 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11963 if (!Res.isUsable()) { 11964 // There are unresolved typos in Init, just drop them. 11965 // FIXME: improve the recovery strategy to preserve the Init. 11966 RealDecl->setInvalidDecl(); 11967 return; 11968 } 11969 if (Res.get()->containsErrors()) { 11970 // Invalidate the decl as we don't know the type for recovery-expr yet. 11971 RealDecl->setInvalidDecl(); 11972 VDecl->setInit(Res.get()); 11973 return; 11974 } 11975 Init = Res.get(); 11976 11977 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11978 return; 11979 } 11980 11981 // dllimport cannot be used on variable definitions. 11982 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11983 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11984 VDecl->setInvalidDecl(); 11985 return; 11986 } 11987 11988 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11989 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11990 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11991 VDecl->setInvalidDecl(); 11992 return; 11993 } 11994 11995 if (!VDecl->getType()->isDependentType()) { 11996 // A definition must end up with a complete type, which means it must be 11997 // complete with the restriction that an array type might be completed by 11998 // the initializer; note that later code assumes this restriction. 11999 QualType BaseDeclType = VDecl->getType(); 12000 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12001 BaseDeclType = Array->getElementType(); 12002 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12003 diag::err_typecheck_decl_incomplete_type)) { 12004 RealDecl->setInvalidDecl(); 12005 return; 12006 } 12007 12008 // The variable can not have an abstract class type. 12009 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12010 diag::err_abstract_type_in_decl, 12011 AbstractVariableType)) 12012 VDecl->setInvalidDecl(); 12013 } 12014 12015 // If adding the initializer will turn this declaration into a definition, 12016 // and we already have a definition for this variable, diagnose or otherwise 12017 // handle the situation. 12018 VarDecl *Def; 12019 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12020 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12021 !VDecl->isThisDeclarationADemotedDefinition() && 12022 checkVarDeclRedefinition(Def, VDecl)) 12023 return; 12024 12025 if (getLangOpts().CPlusPlus) { 12026 // C++ [class.static.data]p4 12027 // If a static data member is of const integral or const 12028 // enumeration type, its declaration in the class definition can 12029 // specify a constant-initializer which shall be an integral 12030 // constant expression (5.19). In that case, the member can appear 12031 // in integral constant expressions. The member shall still be 12032 // defined in a namespace scope if it is used in the program and the 12033 // namespace scope definition shall not contain an initializer. 12034 // 12035 // We already performed a redefinition check above, but for static 12036 // data members we also need to check whether there was an in-class 12037 // declaration with an initializer. 12038 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12039 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12040 << VDecl->getDeclName(); 12041 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12042 diag::note_previous_initializer) 12043 << 0; 12044 return; 12045 } 12046 12047 if (VDecl->hasLocalStorage()) 12048 setFunctionHasBranchProtectedScope(); 12049 12050 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12051 VDecl->setInvalidDecl(); 12052 return; 12053 } 12054 } 12055 12056 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12057 // a kernel function cannot be initialized." 12058 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12059 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12060 VDecl->setInvalidDecl(); 12061 return; 12062 } 12063 12064 // The LoaderUninitialized attribute acts as a definition (of undef). 12065 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12066 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12067 VDecl->setInvalidDecl(); 12068 return; 12069 } 12070 12071 // Get the decls type and save a reference for later, since 12072 // CheckInitializerTypes may change it. 12073 QualType DclT = VDecl->getType(), SavT = DclT; 12074 12075 // Expressions default to 'id' when we're in a debugger 12076 // and we are assigning it to a variable of Objective-C pointer type. 12077 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12078 Init->getType() == Context.UnknownAnyTy) { 12079 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12080 if (Result.isInvalid()) { 12081 VDecl->setInvalidDecl(); 12082 return; 12083 } 12084 Init = Result.get(); 12085 } 12086 12087 // Perform the initialization. 12088 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12089 if (!VDecl->isInvalidDecl()) { 12090 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12091 InitializationKind Kind = InitializationKind::CreateForInit( 12092 VDecl->getLocation(), DirectInit, Init); 12093 12094 MultiExprArg Args = Init; 12095 if (CXXDirectInit) 12096 Args = MultiExprArg(CXXDirectInit->getExprs(), 12097 CXXDirectInit->getNumExprs()); 12098 12099 // Try to correct any TypoExprs in the initialization arguments. 12100 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12101 ExprResult Res = CorrectDelayedTyposInExpr( 12102 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12103 [this, Entity, Kind](Expr *E) { 12104 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12105 return Init.Failed() ? ExprError() : E; 12106 }); 12107 if (Res.isInvalid()) { 12108 VDecl->setInvalidDecl(); 12109 } else if (Res.get() != Args[Idx]) { 12110 Args[Idx] = Res.get(); 12111 } 12112 } 12113 if (VDecl->isInvalidDecl()) 12114 return; 12115 12116 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12117 /*TopLevelOfInitList=*/false, 12118 /*TreatUnavailableAsInvalid=*/false); 12119 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12120 if (Result.isInvalid()) { 12121 // If the provied initializer fails to initialize the var decl, 12122 // we attach a recovery expr for better recovery. 12123 auto RecoveryExpr = 12124 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12125 if (RecoveryExpr.get()) 12126 VDecl->setInit(RecoveryExpr.get()); 12127 return; 12128 } 12129 12130 Init = Result.getAs<Expr>(); 12131 } 12132 12133 // Check for self-references within variable initializers. 12134 // Variables declared within a function/method body (except for references) 12135 // are handled by a dataflow analysis. 12136 // This is undefined behavior in C++, but valid in C. 12137 if (getLangOpts().CPlusPlus) { 12138 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12139 VDecl->getType()->isReferenceType()) { 12140 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12141 } 12142 } 12143 12144 // If the type changed, it means we had an incomplete type that was 12145 // completed by the initializer. For example: 12146 // int ary[] = { 1, 3, 5 }; 12147 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12148 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12149 VDecl->setType(DclT); 12150 12151 if (!VDecl->isInvalidDecl()) { 12152 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12153 12154 if (VDecl->hasAttr<BlocksAttr>()) 12155 checkRetainCycles(VDecl, Init); 12156 12157 // It is safe to assign a weak reference into a strong variable. 12158 // Although this code can still have problems: 12159 // id x = self.weakProp; 12160 // id y = self.weakProp; 12161 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12162 // paths through the function. This should be revisited if 12163 // -Wrepeated-use-of-weak is made flow-sensitive. 12164 if (FunctionScopeInfo *FSI = getCurFunction()) 12165 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12166 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12167 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12168 Init->getBeginLoc())) 12169 FSI->markSafeWeakUse(Init); 12170 } 12171 12172 // The initialization is usually a full-expression. 12173 // 12174 // FIXME: If this is a braced initialization of an aggregate, it is not 12175 // an expression, and each individual field initializer is a separate 12176 // full-expression. For instance, in: 12177 // 12178 // struct Temp { ~Temp(); }; 12179 // struct S { S(Temp); }; 12180 // struct T { S a, b; } t = { Temp(), Temp() } 12181 // 12182 // we should destroy the first Temp before constructing the second. 12183 ExprResult Result = 12184 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12185 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12186 if (Result.isInvalid()) { 12187 VDecl->setInvalidDecl(); 12188 return; 12189 } 12190 Init = Result.get(); 12191 12192 // Attach the initializer to the decl. 12193 VDecl->setInit(Init); 12194 12195 if (VDecl->isLocalVarDecl()) { 12196 // Don't check the initializer if the declaration is malformed. 12197 if (VDecl->isInvalidDecl()) { 12198 // do nothing 12199 12200 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12201 // This is true even in C++ for OpenCL. 12202 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12203 CheckForConstantInitializer(Init, DclT); 12204 12205 // Otherwise, C++ does not restrict the initializer. 12206 } else if (getLangOpts().CPlusPlus) { 12207 // do nothing 12208 12209 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12210 // static storage duration shall be constant expressions or string literals. 12211 } else if (VDecl->getStorageClass() == SC_Static) { 12212 CheckForConstantInitializer(Init, DclT); 12213 12214 // C89 is stricter than C99 for aggregate initializers. 12215 // C89 6.5.7p3: All the expressions [...] in an initializer list 12216 // for an object that has aggregate or union type shall be 12217 // constant expressions. 12218 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12219 isa<InitListExpr>(Init)) { 12220 const Expr *Culprit; 12221 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12222 Diag(Culprit->getExprLoc(), 12223 diag::ext_aggregate_init_not_constant) 12224 << Culprit->getSourceRange(); 12225 } 12226 } 12227 12228 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12229 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12230 if (VDecl->hasLocalStorage()) 12231 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12232 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12233 VDecl->getLexicalDeclContext()->isRecord()) { 12234 // This is an in-class initialization for a static data member, e.g., 12235 // 12236 // struct S { 12237 // static const int value = 17; 12238 // }; 12239 12240 // C++ [class.mem]p4: 12241 // A member-declarator can contain a constant-initializer only 12242 // if it declares a static member (9.4) of const integral or 12243 // const enumeration type, see 9.4.2. 12244 // 12245 // C++11 [class.static.data]p3: 12246 // If a non-volatile non-inline const static data member is of integral 12247 // or enumeration type, its declaration in the class definition can 12248 // specify a brace-or-equal-initializer in which every initializer-clause 12249 // that is an assignment-expression is a constant expression. A static 12250 // data member of literal type can be declared in the class definition 12251 // with the constexpr specifier; if so, its declaration shall specify a 12252 // brace-or-equal-initializer in which every initializer-clause that is 12253 // an assignment-expression is a constant expression. 12254 12255 // Do nothing on dependent types. 12256 if (DclT->isDependentType()) { 12257 12258 // Allow any 'static constexpr' members, whether or not they are of literal 12259 // type. We separately check that every constexpr variable is of literal 12260 // type. 12261 } else if (VDecl->isConstexpr()) { 12262 12263 // Require constness. 12264 } else if (!DclT.isConstQualified()) { 12265 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12266 << Init->getSourceRange(); 12267 VDecl->setInvalidDecl(); 12268 12269 // We allow integer constant expressions in all cases. 12270 } else if (DclT->isIntegralOrEnumerationType()) { 12271 // Check whether the expression is a constant expression. 12272 SourceLocation Loc; 12273 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12274 // In C++11, a non-constexpr const static data member with an 12275 // in-class initializer cannot be volatile. 12276 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12277 else if (Init->isValueDependent()) 12278 ; // Nothing to check. 12279 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12280 ; // Ok, it's an ICE! 12281 else if (Init->getType()->isScopedEnumeralType() && 12282 Init->isCXX11ConstantExpr(Context)) 12283 ; // Ok, it is a scoped-enum constant expression. 12284 else if (Init->isEvaluatable(Context)) { 12285 // If we can constant fold the initializer through heroics, accept it, 12286 // but report this as a use of an extension for -pedantic. 12287 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12288 << Init->getSourceRange(); 12289 } else { 12290 // Otherwise, this is some crazy unknown case. Report the issue at the 12291 // location provided by the isIntegerConstantExpr failed check. 12292 Diag(Loc, diag::err_in_class_initializer_non_constant) 12293 << Init->getSourceRange(); 12294 VDecl->setInvalidDecl(); 12295 } 12296 12297 // We allow foldable floating-point constants as an extension. 12298 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12299 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12300 // it anyway and provide a fixit to add the 'constexpr'. 12301 if (getLangOpts().CPlusPlus11) { 12302 Diag(VDecl->getLocation(), 12303 diag::ext_in_class_initializer_float_type_cxx11) 12304 << DclT << Init->getSourceRange(); 12305 Diag(VDecl->getBeginLoc(), 12306 diag::note_in_class_initializer_float_type_cxx11) 12307 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12308 } else { 12309 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12310 << DclT << Init->getSourceRange(); 12311 12312 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12313 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12314 << Init->getSourceRange(); 12315 VDecl->setInvalidDecl(); 12316 } 12317 } 12318 12319 // Suggest adding 'constexpr' in C++11 for literal types. 12320 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12321 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12322 << DclT << Init->getSourceRange() 12323 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12324 VDecl->setConstexpr(true); 12325 12326 } else { 12327 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12328 << DclT << Init->getSourceRange(); 12329 VDecl->setInvalidDecl(); 12330 } 12331 } else if (VDecl->isFileVarDecl()) { 12332 // In C, extern is typically used to avoid tentative definitions when 12333 // declaring variables in headers, but adding an intializer makes it a 12334 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12335 // In C++, extern is often used to give implictly static const variables 12336 // external linkage, so don't warn in that case. If selectany is present, 12337 // this might be header code intended for C and C++ inclusion, so apply the 12338 // C++ rules. 12339 if (VDecl->getStorageClass() == SC_Extern && 12340 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12341 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12342 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12343 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12344 Diag(VDecl->getLocation(), diag::warn_extern_init); 12345 12346 // In Microsoft C++ mode, a const variable defined in namespace scope has 12347 // external linkage by default if the variable is declared with 12348 // __declspec(dllexport). 12349 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12350 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12351 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12352 VDecl->setStorageClass(SC_Extern); 12353 12354 // C99 6.7.8p4. All file scoped initializers need to be constant. 12355 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12356 CheckForConstantInitializer(Init, DclT); 12357 } 12358 12359 QualType InitType = Init->getType(); 12360 if (!InitType.isNull() && 12361 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12362 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12363 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12364 12365 // We will represent direct-initialization similarly to copy-initialization: 12366 // int x(1); -as-> int x = 1; 12367 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12368 // 12369 // Clients that want to distinguish between the two forms, can check for 12370 // direct initializer using VarDecl::getInitStyle(). 12371 // A major benefit is that clients that don't particularly care about which 12372 // exactly form was it (like the CodeGen) can handle both cases without 12373 // special case code. 12374 12375 // C++ 8.5p11: 12376 // The form of initialization (using parentheses or '=') is generally 12377 // insignificant, but does matter when the entity being initialized has a 12378 // class type. 12379 if (CXXDirectInit) { 12380 assert(DirectInit && "Call-style initializer must be direct init."); 12381 VDecl->setInitStyle(VarDecl::CallInit); 12382 } else if (DirectInit) { 12383 // This must be list-initialization. No other way is direct-initialization. 12384 VDecl->setInitStyle(VarDecl::ListInit); 12385 } 12386 12387 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12388 DeclsToCheckForDeferredDiags.push_back(VDecl); 12389 CheckCompleteVariableDeclaration(VDecl); 12390 } 12391 12392 /// ActOnInitializerError - Given that there was an error parsing an 12393 /// initializer for the given declaration, try to return to some form 12394 /// of sanity. 12395 void Sema::ActOnInitializerError(Decl *D) { 12396 // Our main concern here is re-establishing invariants like "a 12397 // variable's type is either dependent or complete". 12398 if (!D || D->isInvalidDecl()) return; 12399 12400 VarDecl *VD = dyn_cast<VarDecl>(D); 12401 if (!VD) return; 12402 12403 // Bindings are not usable if we can't make sense of the initializer. 12404 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12405 for (auto *BD : DD->bindings()) 12406 BD->setInvalidDecl(); 12407 12408 // Auto types are meaningless if we can't make sense of the initializer. 12409 if (VD->getType()->isUndeducedType()) { 12410 D->setInvalidDecl(); 12411 return; 12412 } 12413 12414 QualType Ty = VD->getType(); 12415 if (Ty->isDependentType()) return; 12416 12417 // Require a complete type. 12418 if (RequireCompleteType(VD->getLocation(), 12419 Context.getBaseElementType(Ty), 12420 diag::err_typecheck_decl_incomplete_type)) { 12421 VD->setInvalidDecl(); 12422 return; 12423 } 12424 12425 // Require a non-abstract type. 12426 if (RequireNonAbstractType(VD->getLocation(), Ty, 12427 diag::err_abstract_type_in_decl, 12428 AbstractVariableType)) { 12429 VD->setInvalidDecl(); 12430 return; 12431 } 12432 12433 // Don't bother complaining about constructors or destructors, 12434 // though. 12435 } 12436 12437 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12438 // If there is no declaration, there was an error parsing it. Just ignore it. 12439 if (!RealDecl) 12440 return; 12441 12442 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12443 QualType Type = Var->getType(); 12444 12445 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12446 if (isa<DecompositionDecl>(RealDecl)) { 12447 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12448 Var->setInvalidDecl(); 12449 return; 12450 } 12451 12452 if (Type->isUndeducedType() && 12453 DeduceVariableDeclarationType(Var, false, nullptr)) 12454 return; 12455 12456 // C++11 [class.static.data]p3: A static data member can be declared with 12457 // the constexpr specifier; if so, its declaration shall specify 12458 // a brace-or-equal-initializer. 12459 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12460 // the definition of a variable [...] or the declaration of a static data 12461 // member. 12462 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12463 !Var->isThisDeclarationADemotedDefinition()) { 12464 if (Var->isStaticDataMember()) { 12465 // C++1z removes the relevant rule; the in-class declaration is always 12466 // a definition there. 12467 if (!getLangOpts().CPlusPlus17 && 12468 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12469 Diag(Var->getLocation(), 12470 diag::err_constexpr_static_mem_var_requires_init) 12471 << Var; 12472 Var->setInvalidDecl(); 12473 return; 12474 } 12475 } else { 12476 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12477 Var->setInvalidDecl(); 12478 return; 12479 } 12480 } 12481 12482 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12483 // be initialized. 12484 if (!Var->isInvalidDecl() && 12485 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12486 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12487 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12488 Var->setInvalidDecl(); 12489 return; 12490 } 12491 12492 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12493 if (Var->getStorageClass() == SC_Extern) { 12494 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12495 << Var; 12496 Var->setInvalidDecl(); 12497 return; 12498 } 12499 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12500 diag::err_typecheck_decl_incomplete_type)) { 12501 Var->setInvalidDecl(); 12502 return; 12503 } 12504 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12505 if (!RD->hasTrivialDefaultConstructor()) { 12506 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12507 Var->setInvalidDecl(); 12508 return; 12509 } 12510 } 12511 } 12512 12513 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12514 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12515 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12516 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12517 NTCUC_DefaultInitializedObject, NTCUK_Init); 12518 12519 12520 switch (DefKind) { 12521 case VarDecl::Definition: 12522 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12523 break; 12524 12525 // We have an out-of-line definition of a static data member 12526 // that has an in-class initializer, so we type-check this like 12527 // a declaration. 12528 // 12529 LLVM_FALLTHROUGH; 12530 12531 case VarDecl::DeclarationOnly: 12532 // It's only a declaration. 12533 12534 // Block scope. C99 6.7p7: If an identifier for an object is 12535 // declared with no linkage (C99 6.2.2p6), the type for the 12536 // object shall be complete. 12537 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12538 !Var->hasLinkage() && !Var->isInvalidDecl() && 12539 RequireCompleteType(Var->getLocation(), Type, 12540 diag::err_typecheck_decl_incomplete_type)) 12541 Var->setInvalidDecl(); 12542 12543 // Make sure that the type is not abstract. 12544 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12545 RequireNonAbstractType(Var->getLocation(), Type, 12546 diag::err_abstract_type_in_decl, 12547 AbstractVariableType)) 12548 Var->setInvalidDecl(); 12549 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12550 Var->getStorageClass() == SC_PrivateExtern) { 12551 Diag(Var->getLocation(), diag::warn_private_extern); 12552 Diag(Var->getLocation(), diag::note_private_extern); 12553 } 12554 12555 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12556 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12557 ExternalDeclarations.push_back(Var); 12558 12559 return; 12560 12561 case VarDecl::TentativeDefinition: 12562 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12563 // object that has file scope without an initializer, and without a 12564 // storage-class specifier or with the storage-class specifier "static", 12565 // constitutes a tentative definition. Note: A tentative definition with 12566 // external linkage is valid (C99 6.2.2p5). 12567 if (!Var->isInvalidDecl()) { 12568 if (const IncompleteArrayType *ArrayT 12569 = Context.getAsIncompleteArrayType(Type)) { 12570 if (RequireCompleteSizedType( 12571 Var->getLocation(), ArrayT->getElementType(), 12572 diag::err_array_incomplete_or_sizeless_type)) 12573 Var->setInvalidDecl(); 12574 } else if (Var->getStorageClass() == SC_Static) { 12575 // C99 6.9.2p3: If the declaration of an identifier for an object is 12576 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12577 // declared type shall not be an incomplete type. 12578 // NOTE: code such as the following 12579 // static struct s; 12580 // struct s { int a; }; 12581 // is accepted by gcc. Hence here we issue a warning instead of 12582 // an error and we do not invalidate the static declaration. 12583 // NOTE: to avoid multiple warnings, only check the first declaration. 12584 if (Var->isFirstDecl()) 12585 RequireCompleteType(Var->getLocation(), Type, 12586 diag::ext_typecheck_decl_incomplete_type); 12587 } 12588 } 12589 12590 // Record the tentative definition; we're done. 12591 if (!Var->isInvalidDecl()) 12592 TentativeDefinitions.push_back(Var); 12593 return; 12594 } 12595 12596 // Provide a specific diagnostic for uninitialized variable 12597 // definitions with incomplete array type. 12598 if (Type->isIncompleteArrayType()) { 12599 Diag(Var->getLocation(), 12600 diag::err_typecheck_incomplete_array_needs_initializer); 12601 Var->setInvalidDecl(); 12602 return; 12603 } 12604 12605 // Provide a specific diagnostic for uninitialized variable 12606 // definitions with reference type. 12607 if (Type->isReferenceType()) { 12608 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12609 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12610 Var->setInvalidDecl(); 12611 return; 12612 } 12613 12614 // Do not attempt to type-check the default initializer for a 12615 // variable with dependent type. 12616 if (Type->isDependentType()) 12617 return; 12618 12619 if (Var->isInvalidDecl()) 12620 return; 12621 12622 if (!Var->hasAttr<AliasAttr>()) { 12623 if (RequireCompleteType(Var->getLocation(), 12624 Context.getBaseElementType(Type), 12625 diag::err_typecheck_decl_incomplete_type)) { 12626 Var->setInvalidDecl(); 12627 return; 12628 } 12629 } else { 12630 return; 12631 } 12632 12633 // The variable can not have an abstract class type. 12634 if (RequireNonAbstractType(Var->getLocation(), Type, 12635 diag::err_abstract_type_in_decl, 12636 AbstractVariableType)) { 12637 Var->setInvalidDecl(); 12638 return; 12639 } 12640 12641 // Check for jumps past the implicit initializer. C++0x 12642 // clarifies that this applies to a "variable with automatic 12643 // storage duration", not a "local variable". 12644 // C++11 [stmt.dcl]p3 12645 // A program that jumps from a point where a variable with automatic 12646 // storage duration is not in scope to a point where it is in scope is 12647 // ill-formed unless the variable has scalar type, class type with a 12648 // trivial default constructor and a trivial destructor, a cv-qualified 12649 // version of one of these types, or an array of one of the preceding 12650 // types and is declared without an initializer. 12651 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12652 if (const RecordType *Record 12653 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12654 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12655 // Mark the function (if we're in one) for further checking even if the 12656 // looser rules of C++11 do not require such checks, so that we can 12657 // diagnose incompatibilities with C++98. 12658 if (!CXXRecord->isPOD()) 12659 setFunctionHasBranchProtectedScope(); 12660 } 12661 } 12662 // In OpenCL, we can't initialize objects in the __local address space, 12663 // even implicitly, so don't synthesize an implicit initializer. 12664 if (getLangOpts().OpenCL && 12665 Var->getType().getAddressSpace() == LangAS::opencl_local) 12666 return; 12667 // C++03 [dcl.init]p9: 12668 // If no initializer is specified for an object, and the 12669 // object is of (possibly cv-qualified) non-POD class type (or 12670 // array thereof), the object shall be default-initialized; if 12671 // the object is of const-qualified type, the underlying class 12672 // type shall have a user-declared default 12673 // constructor. Otherwise, if no initializer is specified for 12674 // a non- static object, the object and its subobjects, if 12675 // any, have an indeterminate initial value); if the object 12676 // or any of its subobjects are of const-qualified type, the 12677 // program is ill-formed. 12678 // C++0x [dcl.init]p11: 12679 // If no initializer is specified for an object, the object is 12680 // default-initialized; [...]. 12681 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12682 InitializationKind Kind 12683 = InitializationKind::CreateDefault(Var->getLocation()); 12684 12685 InitializationSequence InitSeq(*this, Entity, Kind, None); 12686 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12687 12688 if (Init.get()) { 12689 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12690 // This is important for template substitution. 12691 Var->setInitStyle(VarDecl::CallInit); 12692 } else if (Init.isInvalid()) { 12693 // If default-init fails, attach a recovery-expr initializer to track 12694 // that initialization was attempted and failed. 12695 auto RecoveryExpr = 12696 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12697 if (RecoveryExpr.get()) 12698 Var->setInit(RecoveryExpr.get()); 12699 } 12700 12701 CheckCompleteVariableDeclaration(Var); 12702 } 12703 } 12704 12705 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12706 // If there is no declaration, there was an error parsing it. Ignore it. 12707 if (!D) 12708 return; 12709 12710 VarDecl *VD = dyn_cast<VarDecl>(D); 12711 if (!VD) { 12712 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12713 D->setInvalidDecl(); 12714 return; 12715 } 12716 12717 VD->setCXXForRangeDecl(true); 12718 12719 // for-range-declaration cannot be given a storage class specifier. 12720 int Error = -1; 12721 switch (VD->getStorageClass()) { 12722 case SC_None: 12723 break; 12724 case SC_Extern: 12725 Error = 0; 12726 break; 12727 case SC_Static: 12728 Error = 1; 12729 break; 12730 case SC_PrivateExtern: 12731 Error = 2; 12732 break; 12733 case SC_Auto: 12734 Error = 3; 12735 break; 12736 case SC_Register: 12737 Error = 4; 12738 break; 12739 } 12740 if (Error != -1) { 12741 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12742 << VD << Error; 12743 D->setInvalidDecl(); 12744 } 12745 } 12746 12747 StmtResult 12748 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12749 IdentifierInfo *Ident, 12750 ParsedAttributes &Attrs, 12751 SourceLocation AttrEnd) { 12752 // C++1y [stmt.iter]p1: 12753 // A range-based for statement of the form 12754 // for ( for-range-identifier : for-range-initializer ) statement 12755 // is equivalent to 12756 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12757 DeclSpec DS(Attrs.getPool().getFactory()); 12758 12759 const char *PrevSpec; 12760 unsigned DiagID; 12761 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12762 getPrintingPolicy()); 12763 12764 Declarator D(DS, DeclaratorContext::ForContext); 12765 D.SetIdentifier(Ident, IdentLoc); 12766 D.takeAttributes(Attrs, AttrEnd); 12767 12768 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12769 IdentLoc); 12770 Decl *Var = ActOnDeclarator(S, D); 12771 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12772 FinalizeDeclaration(Var); 12773 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12774 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12775 } 12776 12777 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12778 if (var->isInvalidDecl()) return; 12779 12780 if (getLangOpts().OpenCL) { 12781 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12782 // initialiser 12783 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12784 !var->hasInit()) { 12785 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12786 << 1 /*Init*/; 12787 var->setInvalidDecl(); 12788 return; 12789 } 12790 } 12791 12792 // In Objective-C, don't allow jumps past the implicit initialization of a 12793 // local retaining variable. 12794 if (getLangOpts().ObjC && 12795 var->hasLocalStorage()) { 12796 switch (var->getType().getObjCLifetime()) { 12797 case Qualifiers::OCL_None: 12798 case Qualifiers::OCL_ExplicitNone: 12799 case Qualifiers::OCL_Autoreleasing: 12800 break; 12801 12802 case Qualifiers::OCL_Weak: 12803 case Qualifiers::OCL_Strong: 12804 setFunctionHasBranchProtectedScope(); 12805 break; 12806 } 12807 } 12808 12809 if (var->hasLocalStorage() && 12810 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12811 setFunctionHasBranchProtectedScope(); 12812 12813 // Warn about externally-visible variables being defined without a 12814 // prior declaration. We only want to do this for global 12815 // declarations, but we also specifically need to avoid doing it for 12816 // class members because the linkage of an anonymous class can 12817 // change if it's later given a typedef name. 12818 if (var->isThisDeclarationADefinition() && 12819 var->getDeclContext()->getRedeclContext()->isFileContext() && 12820 var->isExternallyVisible() && var->hasLinkage() && 12821 !var->isInline() && !var->getDescribedVarTemplate() && 12822 !isa<VarTemplatePartialSpecializationDecl>(var) && 12823 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12824 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12825 var->getLocation())) { 12826 // Find a previous declaration that's not a definition. 12827 VarDecl *prev = var->getPreviousDecl(); 12828 while (prev && prev->isThisDeclarationADefinition()) 12829 prev = prev->getPreviousDecl(); 12830 12831 if (!prev) { 12832 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12833 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12834 << /* variable */ 0; 12835 } 12836 } 12837 12838 // Cache the result of checking for constant initialization. 12839 Optional<bool> CacheHasConstInit; 12840 const Expr *CacheCulprit = nullptr; 12841 auto checkConstInit = [&]() mutable { 12842 if (!CacheHasConstInit) 12843 CacheHasConstInit = var->getInit()->isConstantInitializer( 12844 Context, var->getType()->isReferenceType(), &CacheCulprit); 12845 return *CacheHasConstInit; 12846 }; 12847 12848 if (var->getTLSKind() == VarDecl::TLS_Static) { 12849 if (var->getType().isDestructedType()) { 12850 // GNU C++98 edits for __thread, [basic.start.term]p3: 12851 // The type of an object with thread storage duration shall not 12852 // have a non-trivial destructor. 12853 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12854 if (getLangOpts().CPlusPlus11) 12855 Diag(var->getLocation(), diag::note_use_thread_local); 12856 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12857 if (!checkConstInit()) { 12858 // GNU C++98 edits for __thread, [basic.start.init]p4: 12859 // An object of thread storage duration shall not require dynamic 12860 // initialization. 12861 // FIXME: Need strict checking here. 12862 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12863 << CacheCulprit->getSourceRange(); 12864 if (getLangOpts().CPlusPlus11) 12865 Diag(var->getLocation(), diag::note_use_thread_local); 12866 } 12867 } 12868 } 12869 12870 // Apply section attributes and pragmas to global variables. 12871 bool GlobalStorage = var->hasGlobalStorage(); 12872 if (GlobalStorage && var->isThisDeclarationADefinition() && 12873 !inTemplateInstantiation()) { 12874 PragmaStack<StringLiteral *> *Stack = nullptr; 12875 int SectionFlags = ASTContext::PSF_Read; 12876 if (var->getType().isConstQualified()) 12877 Stack = &ConstSegStack; 12878 else if (!var->getInit()) { 12879 Stack = &BSSSegStack; 12880 SectionFlags |= ASTContext::PSF_Write; 12881 } else { 12882 Stack = &DataSegStack; 12883 SectionFlags |= ASTContext::PSF_Write; 12884 } 12885 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12886 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12887 SectionFlags |= ASTContext::PSF_Implicit; 12888 UnifySection(SA->getName(), SectionFlags, var); 12889 } else if (Stack->CurrentValue) { 12890 SectionFlags |= ASTContext::PSF_Implicit; 12891 auto SectionName = Stack->CurrentValue->getString(); 12892 var->addAttr(SectionAttr::CreateImplicit( 12893 Context, SectionName, Stack->CurrentPragmaLocation, 12894 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12895 if (UnifySection(SectionName, SectionFlags, var)) 12896 var->dropAttr<SectionAttr>(); 12897 } 12898 12899 // Apply the init_seg attribute if this has an initializer. If the 12900 // initializer turns out to not be dynamic, we'll end up ignoring this 12901 // attribute. 12902 if (CurInitSeg && var->getInit()) 12903 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12904 CurInitSegLoc, 12905 AttributeCommonInfo::AS_Pragma)); 12906 } 12907 12908 if (!var->getType()->isStructureType() && var->hasInit() && 12909 isa<InitListExpr>(var->getInit())) { 12910 const auto *ILE = cast<InitListExpr>(var->getInit()); 12911 unsigned NumInits = ILE->getNumInits(); 12912 if (NumInits > 2) 12913 for (unsigned I = 0; I < NumInits; ++I) { 12914 const auto *Init = ILE->getInit(I); 12915 if (!Init) 12916 break; 12917 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12918 if (!SL) 12919 break; 12920 12921 unsigned NumConcat = SL->getNumConcatenated(); 12922 // Diagnose missing comma in string array initialization. 12923 // Do not warn when all the elements in the initializer are concatenated 12924 // together. Do not warn for macros too. 12925 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 12926 bool OnlyOneMissingComma = true; 12927 for (unsigned J = I + 1; J < NumInits; ++J) { 12928 const auto *Init = ILE->getInit(J); 12929 if (!Init) 12930 break; 12931 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12932 if (!SLJ || SLJ->getNumConcatenated() > 1) { 12933 OnlyOneMissingComma = false; 12934 break; 12935 } 12936 } 12937 12938 if (OnlyOneMissingComma) { 12939 SmallVector<FixItHint, 1> Hints; 12940 for (unsigned i = 0; i < NumConcat - 1; ++i) 12941 Hints.push_back(FixItHint::CreateInsertion( 12942 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 12943 12944 Diag(SL->getStrTokenLoc(1), 12945 diag::warn_concatenated_literal_array_init) 12946 << Hints; 12947 Diag(SL->getBeginLoc(), 12948 diag::note_concatenated_string_literal_silence); 12949 } 12950 // In any case, stop now. 12951 break; 12952 } 12953 } 12954 } 12955 12956 // All the following checks are C++ only. 12957 if (!getLangOpts().CPlusPlus) { 12958 // If this variable must be emitted, add it as an initializer for the 12959 // current module. 12960 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12961 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12962 return; 12963 } 12964 12965 QualType type = var->getType(); 12966 12967 if (var->hasAttr<BlocksAttr>()) 12968 getCurFunction()->addByrefBlockVar(var); 12969 12970 Expr *Init = var->getInit(); 12971 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12972 QualType baseType = Context.getBaseElementType(type); 12973 12974 // Check whether the initializer is sufficiently constant. 12975 if (!type->isDependentType() && Init && !Init->isValueDependent() && 12976 (GlobalStorage || var->isConstexpr() || 12977 var->mightBeUsableInConstantExpressions(Context))) { 12978 // If this variable might have a constant initializer or might be usable in 12979 // constant expressions, check whether or not it actually is now. We can't 12980 // do this lazily, because the result might depend on things that change 12981 // later, such as which constexpr functions happen to be defined. 12982 SmallVector<PartialDiagnosticAt, 8> Notes; 12983 bool HasConstInit; 12984 if (!getLangOpts().CPlusPlus11) { 12985 // Prior to C++11, in contexts where a constant initializer is required, 12986 // the set of valid constant initializers is described by syntactic rules 12987 // in [expr.const]p2-6. 12988 // FIXME: Stricter checking for these rules would be useful for constinit / 12989 // -Wglobal-constructors. 12990 HasConstInit = checkConstInit(); 12991 12992 // Compute and cache the constant value, and remember that we have a 12993 // constant initializer. 12994 if (HasConstInit) { 12995 (void)var->checkForConstantInitialization(Notes); 12996 Notes.clear(); 12997 } else if (CacheCulprit) { 12998 Notes.emplace_back(CacheCulprit->getExprLoc(), 12999 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13000 Notes.back().second << CacheCulprit->getSourceRange(); 13001 } 13002 } else { 13003 // Evaluate the initializer to see if it's a constant initializer. 13004 HasConstInit = var->checkForConstantInitialization(Notes); 13005 } 13006 13007 if (HasConstInit) { 13008 // FIXME: Consider replacing the initializer with a ConstantExpr. 13009 } else if (var->isConstexpr()) { 13010 SourceLocation DiagLoc = var->getLocation(); 13011 // If the note doesn't add any useful information other than a source 13012 // location, fold it into the primary diagnostic. 13013 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13014 diag::note_invalid_subexpr_in_const_expr) { 13015 DiagLoc = Notes[0].first; 13016 Notes.clear(); 13017 } 13018 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13019 << var << Init->getSourceRange(); 13020 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13021 Diag(Notes[I].first, Notes[I].second); 13022 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13023 auto *Attr = var->getAttr<ConstInitAttr>(); 13024 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13025 << Init->getSourceRange(); 13026 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13027 << Attr->getRange() << Attr->isConstinit(); 13028 for (auto &it : Notes) 13029 Diag(it.first, it.second); 13030 } else if (IsGlobal && 13031 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13032 var->getLocation())) { 13033 // Warn about globals which don't have a constant initializer. Don't 13034 // warn about globals with a non-trivial destructor because we already 13035 // warned about them. 13036 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13037 if (!(RD && !RD->hasTrivialDestructor())) { 13038 // checkConstInit() here permits trivial default initialization even in 13039 // C++11 onwards, where such an initializer is not a constant initializer 13040 // but nonetheless doesn't require a global constructor. 13041 if (!checkConstInit()) 13042 Diag(var->getLocation(), diag::warn_global_constructor) 13043 << Init->getSourceRange(); 13044 } 13045 } 13046 } 13047 13048 // Require the destructor. 13049 if (!type->isDependentType()) 13050 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13051 FinalizeVarWithDestructor(var, recordType); 13052 13053 // If this variable must be emitted, add it as an initializer for the current 13054 // module. 13055 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13056 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13057 13058 // Build the bindings if this is a structured binding declaration. 13059 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13060 CheckCompleteDecompositionDeclaration(DD); 13061 } 13062 13063 /// Determines if a variable's alignment is dependent. 13064 static bool hasDependentAlignment(VarDecl *VD) { 13065 if (VD->getType()->isDependentType()) 13066 return true; 13067 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13068 if (I->isAlignmentDependent()) 13069 return true; 13070 return false; 13071 } 13072 13073 /// Check if VD needs to be dllexport/dllimport due to being in a 13074 /// dllexport/import function. 13075 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13076 assert(VD->isStaticLocal()); 13077 13078 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13079 13080 // Find outermost function when VD is in lambda function. 13081 while (FD && !getDLLAttr(FD) && 13082 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13083 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13084 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13085 } 13086 13087 if (!FD) 13088 return; 13089 13090 // Static locals inherit dll attributes from their function. 13091 if (Attr *A = getDLLAttr(FD)) { 13092 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13093 NewAttr->setInherited(true); 13094 VD->addAttr(NewAttr); 13095 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13096 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13097 NewAttr->setInherited(true); 13098 VD->addAttr(NewAttr); 13099 13100 // Export this function to enforce exporting this static variable even 13101 // if it is not used in this compilation unit. 13102 if (!FD->hasAttr<DLLExportAttr>()) 13103 FD->addAttr(NewAttr); 13104 13105 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13106 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13107 NewAttr->setInherited(true); 13108 VD->addAttr(NewAttr); 13109 } 13110 } 13111 13112 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13113 /// any semantic actions necessary after any initializer has been attached. 13114 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13115 // Note that we are no longer parsing the initializer for this declaration. 13116 ParsingInitForAutoVars.erase(ThisDecl); 13117 13118 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13119 if (!VD) 13120 return; 13121 13122 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13123 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13124 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13125 if (PragmaClangBSSSection.Valid) 13126 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13127 Context, PragmaClangBSSSection.SectionName, 13128 PragmaClangBSSSection.PragmaLocation, 13129 AttributeCommonInfo::AS_Pragma)); 13130 if (PragmaClangDataSection.Valid) 13131 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13132 Context, PragmaClangDataSection.SectionName, 13133 PragmaClangDataSection.PragmaLocation, 13134 AttributeCommonInfo::AS_Pragma)); 13135 if (PragmaClangRodataSection.Valid) 13136 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13137 Context, PragmaClangRodataSection.SectionName, 13138 PragmaClangRodataSection.PragmaLocation, 13139 AttributeCommonInfo::AS_Pragma)); 13140 if (PragmaClangRelroSection.Valid) 13141 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13142 Context, PragmaClangRelroSection.SectionName, 13143 PragmaClangRelroSection.PragmaLocation, 13144 AttributeCommonInfo::AS_Pragma)); 13145 } 13146 13147 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13148 for (auto *BD : DD->bindings()) { 13149 FinalizeDeclaration(BD); 13150 } 13151 } 13152 13153 checkAttributesAfterMerging(*this, *VD); 13154 13155 // Perform TLS alignment check here after attributes attached to the variable 13156 // which may affect the alignment have been processed. Only perform the check 13157 // if the target has a maximum TLS alignment (zero means no constraints). 13158 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13159 // Protect the check so that it's not performed on dependent types and 13160 // dependent alignments (we can't determine the alignment in that case). 13161 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13162 !VD->isInvalidDecl()) { 13163 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13164 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13165 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13166 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13167 << (unsigned)MaxAlignChars.getQuantity(); 13168 } 13169 } 13170 } 13171 13172 if (VD->isStaticLocal()) { 13173 CheckStaticLocalForDllExport(VD); 13174 13175 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 13176 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 13177 // function, only __shared__ variables or variables without any device 13178 // memory qualifiers may be declared with static storage class. 13179 // Note: It is unclear how a function-scope non-const static variable 13180 // without device memory qualifier is implemented, therefore only static 13181 // const variable without device memory qualifier is allowed. 13182 [&]() { 13183 if (!getLangOpts().CUDA) 13184 return; 13185 if (VD->hasAttr<CUDASharedAttr>()) 13186 return; 13187 if (VD->getType().isConstQualified() && 13188 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13189 return; 13190 if (CUDADiagIfDeviceCode(VD->getLocation(), 13191 diag::err_device_static_local_var) 13192 << CurrentCUDATarget()) 13193 VD->setInvalidDecl(); 13194 }(); 13195 } 13196 } 13197 13198 // Perform check for initializers of device-side global variables. 13199 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13200 // 7.5). We must also apply the same checks to all __shared__ 13201 // variables whether they are local or not. CUDA also allows 13202 // constant initializers for __constant__ and __device__ variables. 13203 if (getLangOpts().CUDA) 13204 checkAllowedCUDAInitializer(VD); 13205 13206 // Grab the dllimport or dllexport attribute off of the VarDecl. 13207 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13208 13209 // Imported static data members cannot be defined out-of-line. 13210 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13211 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13212 VD->isThisDeclarationADefinition()) { 13213 // We allow definitions of dllimport class template static data members 13214 // with a warning. 13215 CXXRecordDecl *Context = 13216 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13217 bool IsClassTemplateMember = 13218 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13219 Context->getDescribedClassTemplate(); 13220 13221 Diag(VD->getLocation(), 13222 IsClassTemplateMember 13223 ? diag::warn_attribute_dllimport_static_field_definition 13224 : diag::err_attribute_dllimport_static_field_definition); 13225 Diag(IA->getLocation(), diag::note_attribute); 13226 if (!IsClassTemplateMember) 13227 VD->setInvalidDecl(); 13228 } 13229 } 13230 13231 // dllimport/dllexport variables cannot be thread local, their TLS index 13232 // isn't exported with the variable. 13233 if (DLLAttr && VD->getTLSKind()) { 13234 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13235 if (F && getDLLAttr(F)) { 13236 assert(VD->isStaticLocal()); 13237 // But if this is a static local in a dlimport/dllexport function, the 13238 // function will never be inlined, which means the var would never be 13239 // imported, so having it marked import/export is safe. 13240 } else { 13241 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13242 << DLLAttr; 13243 VD->setInvalidDecl(); 13244 } 13245 } 13246 13247 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13248 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13249 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13250 VD->dropAttr<UsedAttr>(); 13251 } 13252 } 13253 13254 const DeclContext *DC = VD->getDeclContext(); 13255 // If there's a #pragma GCC visibility in scope, and this isn't a class 13256 // member, set the visibility of this variable. 13257 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13258 AddPushedVisibilityAttribute(VD); 13259 13260 // FIXME: Warn on unused var template partial specializations. 13261 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13262 MarkUnusedFileScopedDecl(VD); 13263 13264 // Now we have parsed the initializer and can update the table of magic 13265 // tag values. 13266 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13267 !VD->getType()->isIntegralOrEnumerationType()) 13268 return; 13269 13270 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13271 const Expr *MagicValueExpr = VD->getInit(); 13272 if (!MagicValueExpr) { 13273 continue; 13274 } 13275 Optional<llvm::APSInt> MagicValueInt; 13276 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13277 Diag(I->getRange().getBegin(), 13278 diag::err_type_tag_for_datatype_not_ice) 13279 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13280 continue; 13281 } 13282 if (MagicValueInt->getActiveBits() > 64) { 13283 Diag(I->getRange().getBegin(), 13284 diag::err_type_tag_for_datatype_too_large) 13285 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13286 continue; 13287 } 13288 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13289 RegisterTypeTagForDatatype(I->getArgumentKind(), 13290 MagicValue, 13291 I->getMatchingCType(), 13292 I->getLayoutCompatible(), 13293 I->getMustBeNull()); 13294 } 13295 } 13296 13297 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13298 auto *VD = dyn_cast<VarDecl>(DD); 13299 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13300 } 13301 13302 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13303 ArrayRef<Decl *> Group) { 13304 SmallVector<Decl*, 8> Decls; 13305 13306 if (DS.isTypeSpecOwned()) 13307 Decls.push_back(DS.getRepAsDecl()); 13308 13309 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13310 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13311 bool DiagnosedMultipleDecomps = false; 13312 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13313 bool DiagnosedNonDeducedAuto = false; 13314 13315 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13316 if (Decl *D = Group[i]) { 13317 // For declarators, there are some additional syntactic-ish checks we need 13318 // to perform. 13319 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13320 if (!FirstDeclaratorInGroup) 13321 FirstDeclaratorInGroup = DD; 13322 if (!FirstDecompDeclaratorInGroup) 13323 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13324 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13325 !hasDeducedAuto(DD)) 13326 FirstNonDeducedAutoInGroup = DD; 13327 13328 if (FirstDeclaratorInGroup != DD) { 13329 // A decomposition declaration cannot be combined with any other 13330 // declaration in the same group. 13331 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13332 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13333 diag::err_decomp_decl_not_alone) 13334 << FirstDeclaratorInGroup->getSourceRange() 13335 << DD->getSourceRange(); 13336 DiagnosedMultipleDecomps = true; 13337 } 13338 13339 // A declarator that uses 'auto' in any way other than to declare a 13340 // variable with a deduced type cannot be combined with any other 13341 // declarator in the same group. 13342 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13343 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13344 diag::err_auto_non_deduced_not_alone) 13345 << FirstNonDeducedAutoInGroup->getType() 13346 ->hasAutoForTrailingReturnType() 13347 << FirstDeclaratorInGroup->getSourceRange() 13348 << DD->getSourceRange(); 13349 DiagnosedNonDeducedAuto = true; 13350 } 13351 } 13352 } 13353 13354 Decls.push_back(D); 13355 } 13356 } 13357 13358 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13359 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13360 handleTagNumbering(Tag, S); 13361 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13362 getLangOpts().CPlusPlus) 13363 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13364 } 13365 } 13366 13367 return BuildDeclaratorGroup(Decls); 13368 } 13369 13370 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13371 /// group, performing any necessary semantic checking. 13372 Sema::DeclGroupPtrTy 13373 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13374 // C++14 [dcl.spec.auto]p7: (DR1347) 13375 // If the type that replaces the placeholder type is not the same in each 13376 // deduction, the program is ill-formed. 13377 if (Group.size() > 1) { 13378 QualType Deduced; 13379 VarDecl *DeducedDecl = nullptr; 13380 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13381 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13382 if (!D || D->isInvalidDecl()) 13383 break; 13384 DeducedType *DT = D->getType()->getContainedDeducedType(); 13385 if (!DT || DT->getDeducedType().isNull()) 13386 continue; 13387 if (Deduced.isNull()) { 13388 Deduced = DT->getDeducedType(); 13389 DeducedDecl = D; 13390 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13391 auto *AT = dyn_cast<AutoType>(DT); 13392 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13393 diag::err_auto_different_deductions) 13394 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13395 << DeducedDecl->getDeclName() << DT->getDeducedType() 13396 << D->getDeclName(); 13397 if (DeducedDecl->hasInit()) 13398 Dia << DeducedDecl->getInit()->getSourceRange(); 13399 if (D->getInit()) 13400 Dia << D->getInit()->getSourceRange(); 13401 D->setInvalidDecl(); 13402 break; 13403 } 13404 } 13405 } 13406 13407 ActOnDocumentableDecls(Group); 13408 13409 return DeclGroupPtrTy::make( 13410 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13411 } 13412 13413 void Sema::ActOnDocumentableDecl(Decl *D) { 13414 ActOnDocumentableDecls(D); 13415 } 13416 13417 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13418 // Don't parse the comment if Doxygen diagnostics are ignored. 13419 if (Group.empty() || !Group[0]) 13420 return; 13421 13422 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13423 Group[0]->getLocation()) && 13424 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13425 Group[0]->getLocation())) 13426 return; 13427 13428 if (Group.size() >= 2) { 13429 // This is a decl group. Normally it will contain only declarations 13430 // produced from declarator list. But in case we have any definitions or 13431 // additional declaration references: 13432 // 'typedef struct S {} S;' 13433 // 'typedef struct S *S;' 13434 // 'struct S *pS;' 13435 // FinalizeDeclaratorGroup adds these as separate declarations. 13436 Decl *MaybeTagDecl = Group[0]; 13437 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13438 Group = Group.slice(1); 13439 } 13440 } 13441 13442 // FIMXE: We assume every Decl in the group is in the same file. 13443 // This is false when preprocessor constructs the group from decls in 13444 // different files (e. g. macros or #include). 13445 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13446 } 13447 13448 /// Common checks for a parameter-declaration that should apply to both function 13449 /// parameters and non-type template parameters. 13450 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13451 // Check that there are no default arguments inside the type of this 13452 // parameter. 13453 if (getLangOpts().CPlusPlus) 13454 CheckExtraCXXDefaultArguments(D); 13455 13456 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13457 if (D.getCXXScopeSpec().isSet()) { 13458 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13459 << D.getCXXScopeSpec().getRange(); 13460 } 13461 13462 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13463 // simple identifier except [...irrelevant cases...]. 13464 switch (D.getName().getKind()) { 13465 case UnqualifiedIdKind::IK_Identifier: 13466 break; 13467 13468 case UnqualifiedIdKind::IK_OperatorFunctionId: 13469 case UnqualifiedIdKind::IK_ConversionFunctionId: 13470 case UnqualifiedIdKind::IK_LiteralOperatorId: 13471 case UnqualifiedIdKind::IK_ConstructorName: 13472 case UnqualifiedIdKind::IK_DestructorName: 13473 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13474 case UnqualifiedIdKind::IK_DeductionGuideName: 13475 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13476 << GetNameForDeclarator(D).getName(); 13477 break; 13478 13479 case UnqualifiedIdKind::IK_TemplateId: 13480 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13481 // GetNameForDeclarator would not produce a useful name in this case. 13482 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13483 break; 13484 } 13485 } 13486 13487 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13488 /// to introduce parameters into function prototype scope. 13489 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13490 const DeclSpec &DS = D.getDeclSpec(); 13491 13492 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13493 13494 // C++03 [dcl.stc]p2 also permits 'auto'. 13495 StorageClass SC = SC_None; 13496 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13497 SC = SC_Register; 13498 // In C++11, the 'register' storage class specifier is deprecated. 13499 // In C++17, it is not allowed, but we tolerate it as an extension. 13500 if (getLangOpts().CPlusPlus11) { 13501 Diag(DS.getStorageClassSpecLoc(), 13502 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13503 : diag::warn_deprecated_register) 13504 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13505 } 13506 } else if (getLangOpts().CPlusPlus && 13507 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13508 SC = SC_Auto; 13509 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13510 Diag(DS.getStorageClassSpecLoc(), 13511 diag::err_invalid_storage_class_in_func_decl); 13512 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13513 } 13514 13515 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13516 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13517 << DeclSpec::getSpecifierName(TSCS); 13518 if (DS.isInlineSpecified()) 13519 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13520 << getLangOpts().CPlusPlus17; 13521 if (DS.hasConstexprSpecifier()) 13522 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13523 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13524 13525 DiagnoseFunctionSpecifiers(DS); 13526 13527 CheckFunctionOrTemplateParamDeclarator(S, D); 13528 13529 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13530 QualType parmDeclType = TInfo->getType(); 13531 13532 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13533 IdentifierInfo *II = D.getIdentifier(); 13534 if (II) { 13535 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13536 ForVisibleRedeclaration); 13537 LookupName(R, S); 13538 if (R.isSingleResult()) { 13539 NamedDecl *PrevDecl = R.getFoundDecl(); 13540 if (PrevDecl->isTemplateParameter()) { 13541 // Maybe we will complain about the shadowed template parameter. 13542 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13543 // Just pretend that we didn't see the previous declaration. 13544 PrevDecl = nullptr; 13545 } else if (S->isDeclScope(PrevDecl)) { 13546 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13547 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13548 13549 // Recover by removing the name 13550 II = nullptr; 13551 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13552 D.setInvalidType(true); 13553 } 13554 } 13555 } 13556 13557 // Temporarily put parameter variables in the translation unit, not 13558 // the enclosing context. This prevents them from accidentally 13559 // looking like class members in C++. 13560 ParmVarDecl *New = 13561 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13562 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13563 13564 if (D.isInvalidType()) 13565 New->setInvalidDecl(); 13566 13567 assert(S->isFunctionPrototypeScope()); 13568 assert(S->getFunctionPrototypeDepth() >= 1); 13569 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13570 S->getNextFunctionPrototypeIndex()); 13571 13572 // Add the parameter declaration into this scope. 13573 S->AddDecl(New); 13574 if (II) 13575 IdResolver.AddDecl(New); 13576 13577 ProcessDeclAttributes(S, New, D); 13578 13579 if (D.getDeclSpec().isModulePrivateSpecified()) 13580 Diag(New->getLocation(), diag::err_module_private_local) 13581 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13582 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13583 13584 if (New->hasAttr<BlocksAttr>()) { 13585 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13586 } 13587 13588 if (getLangOpts().OpenCL) 13589 deduceOpenCLAddressSpace(New); 13590 13591 return New; 13592 } 13593 13594 /// Synthesizes a variable for a parameter arising from a 13595 /// typedef. 13596 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13597 SourceLocation Loc, 13598 QualType T) { 13599 /* FIXME: setting StartLoc == Loc. 13600 Would it be worth to modify callers so as to provide proper source 13601 location for the unnamed parameters, embedding the parameter's type? */ 13602 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13603 T, Context.getTrivialTypeSourceInfo(T, Loc), 13604 SC_None, nullptr); 13605 Param->setImplicit(); 13606 return Param; 13607 } 13608 13609 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13610 // Don't diagnose unused-parameter errors in template instantiations; we 13611 // will already have done so in the template itself. 13612 if (inTemplateInstantiation()) 13613 return; 13614 13615 for (const ParmVarDecl *Parameter : Parameters) { 13616 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13617 !Parameter->hasAttr<UnusedAttr>()) { 13618 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13619 << Parameter->getDeclName(); 13620 } 13621 } 13622 } 13623 13624 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13625 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13626 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13627 return; 13628 13629 // Warn if the return value is pass-by-value and larger than the specified 13630 // threshold. 13631 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13632 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13633 if (Size > LangOpts.NumLargeByValueCopy) 13634 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13635 } 13636 13637 // Warn if any parameter is pass-by-value and larger than the specified 13638 // threshold. 13639 for (const ParmVarDecl *Parameter : Parameters) { 13640 QualType T = Parameter->getType(); 13641 if (T->isDependentType() || !T.isPODType(Context)) 13642 continue; 13643 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13644 if (Size > LangOpts.NumLargeByValueCopy) 13645 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13646 << Parameter << Size; 13647 } 13648 } 13649 13650 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13651 SourceLocation NameLoc, IdentifierInfo *Name, 13652 QualType T, TypeSourceInfo *TSInfo, 13653 StorageClass SC) { 13654 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13655 if (getLangOpts().ObjCAutoRefCount && 13656 T.getObjCLifetime() == Qualifiers::OCL_None && 13657 T->isObjCLifetimeType()) { 13658 13659 Qualifiers::ObjCLifetime lifetime; 13660 13661 // Special cases for arrays: 13662 // - if it's const, use __unsafe_unretained 13663 // - otherwise, it's an error 13664 if (T->isArrayType()) { 13665 if (!T.isConstQualified()) { 13666 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13667 DelayedDiagnostics.add( 13668 sema::DelayedDiagnostic::makeForbiddenType( 13669 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13670 else 13671 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13672 << TSInfo->getTypeLoc().getSourceRange(); 13673 } 13674 lifetime = Qualifiers::OCL_ExplicitNone; 13675 } else { 13676 lifetime = T->getObjCARCImplicitLifetime(); 13677 } 13678 T = Context.getLifetimeQualifiedType(T, lifetime); 13679 } 13680 13681 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13682 Context.getAdjustedParameterType(T), 13683 TSInfo, SC, nullptr); 13684 13685 // Make a note if we created a new pack in the scope of a lambda, so that 13686 // we know that references to that pack must also be expanded within the 13687 // lambda scope. 13688 if (New->isParameterPack()) 13689 if (auto *LSI = getEnclosingLambda()) 13690 LSI->LocalPacks.push_back(New); 13691 13692 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13693 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13694 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13695 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13696 13697 // Parameters can not be abstract class types. 13698 // For record types, this is done by the AbstractClassUsageDiagnoser once 13699 // the class has been completely parsed. 13700 if (!CurContext->isRecord() && 13701 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13702 AbstractParamType)) 13703 New->setInvalidDecl(); 13704 13705 // Parameter declarators cannot be interface types. All ObjC objects are 13706 // passed by reference. 13707 if (T->isObjCObjectType()) { 13708 SourceLocation TypeEndLoc = 13709 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13710 Diag(NameLoc, 13711 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13712 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13713 T = Context.getObjCObjectPointerType(T); 13714 New->setType(T); 13715 } 13716 13717 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13718 // duration shall not be qualified by an address-space qualifier." 13719 // Since all parameters have automatic store duration, they can not have 13720 // an address space. 13721 if (T.getAddressSpace() != LangAS::Default && 13722 // OpenCL allows function arguments declared to be an array of a type 13723 // to be qualified with an address space. 13724 !(getLangOpts().OpenCL && 13725 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13726 Diag(NameLoc, diag::err_arg_with_address_space); 13727 New->setInvalidDecl(); 13728 } 13729 13730 return New; 13731 } 13732 13733 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13734 SourceLocation LocAfterDecls) { 13735 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13736 13737 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13738 // for a K&R function. 13739 if (!FTI.hasPrototype) { 13740 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13741 --i; 13742 if (FTI.Params[i].Param == nullptr) { 13743 SmallString<256> Code; 13744 llvm::raw_svector_ostream(Code) 13745 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13746 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13747 << FTI.Params[i].Ident 13748 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13749 13750 // Implicitly declare the argument as type 'int' for lack of a better 13751 // type. 13752 AttributeFactory attrs; 13753 DeclSpec DS(attrs); 13754 const char* PrevSpec; // unused 13755 unsigned DiagID; // unused 13756 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13757 DiagID, Context.getPrintingPolicy()); 13758 // Use the identifier location for the type source range. 13759 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13760 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13761 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13762 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13763 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13764 } 13765 } 13766 } 13767 } 13768 13769 Decl * 13770 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13771 MultiTemplateParamsArg TemplateParameterLists, 13772 SkipBodyInfo *SkipBody) { 13773 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13774 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13775 Scope *ParentScope = FnBodyScope->getParent(); 13776 13777 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13778 // we define a non-templated function definition, we will create a declaration 13779 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13780 // The base function declaration will have the equivalent of an `omp declare 13781 // variant` annotation which specifies the mangled definition as a 13782 // specialization function under the OpenMP context defined as part of the 13783 // `omp begin declare variant`. 13784 SmallVector<FunctionDecl *, 4> Bases; 13785 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13786 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13787 ParentScope, D, TemplateParameterLists, Bases); 13788 13789 D.setFunctionDefinitionKind(FDK_Definition); 13790 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13791 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13792 13793 if (!Bases.empty()) 13794 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13795 13796 return Dcl; 13797 } 13798 13799 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13800 Consumer.HandleInlineFunctionDefinition(D); 13801 } 13802 13803 static bool 13804 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13805 const FunctionDecl *&PossiblePrototype) { 13806 // Don't warn about invalid declarations. 13807 if (FD->isInvalidDecl()) 13808 return false; 13809 13810 // Or declarations that aren't global. 13811 if (!FD->isGlobal()) 13812 return false; 13813 13814 // Don't warn about C++ member functions. 13815 if (isa<CXXMethodDecl>(FD)) 13816 return false; 13817 13818 // Don't warn about 'main'. 13819 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13820 if (IdentifierInfo *II = FD->getIdentifier()) 13821 if (II->isStr("main")) 13822 return false; 13823 13824 // Don't warn about inline functions. 13825 if (FD->isInlined()) 13826 return false; 13827 13828 // Don't warn about function templates. 13829 if (FD->getDescribedFunctionTemplate()) 13830 return false; 13831 13832 // Don't warn about function template specializations. 13833 if (FD->isFunctionTemplateSpecialization()) 13834 return false; 13835 13836 // Don't warn for OpenCL kernels. 13837 if (FD->hasAttr<OpenCLKernelAttr>()) 13838 return false; 13839 13840 // Don't warn on explicitly deleted functions. 13841 if (FD->isDeleted()) 13842 return false; 13843 13844 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13845 Prev; Prev = Prev->getPreviousDecl()) { 13846 // Ignore any declarations that occur in function or method 13847 // scope, because they aren't visible from the header. 13848 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13849 continue; 13850 13851 PossiblePrototype = Prev; 13852 return Prev->getType()->isFunctionNoProtoType(); 13853 } 13854 13855 return true; 13856 } 13857 13858 void 13859 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13860 const FunctionDecl *EffectiveDefinition, 13861 SkipBodyInfo *SkipBody) { 13862 const FunctionDecl *Definition = EffectiveDefinition; 13863 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13864 // If this is a friend function defined in a class template, it does not 13865 // have a body until it is used, nevertheless it is a definition, see 13866 // [temp.inst]p2: 13867 // 13868 // ... for the purpose of determining whether an instantiated redeclaration 13869 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13870 // corresponds to a definition in the template is considered to be a 13871 // definition. 13872 // 13873 // The following code must produce redefinition error: 13874 // 13875 // template<typename T> struct C20 { friend void func_20() {} }; 13876 // C20<int> c20i; 13877 // void func_20() {} 13878 // 13879 for (auto I : FD->redecls()) { 13880 if (I != FD && !I->isInvalidDecl() && 13881 I->getFriendObjectKind() != Decl::FOK_None) { 13882 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13883 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13884 // A merged copy of the same function, instantiated as a member of 13885 // the same class, is OK. 13886 if (declaresSameEntity(OrigFD, Original) && 13887 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13888 cast<Decl>(FD->getLexicalDeclContext()))) 13889 continue; 13890 } 13891 13892 if (Original->isThisDeclarationADefinition()) { 13893 Definition = I; 13894 break; 13895 } 13896 } 13897 } 13898 } 13899 } 13900 13901 if (!Definition) 13902 // Similar to friend functions a friend function template may be a 13903 // definition and do not have a body if it is instantiated in a class 13904 // template. 13905 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13906 for (auto I : FTD->redecls()) { 13907 auto D = cast<FunctionTemplateDecl>(I); 13908 if (D != FTD) { 13909 assert(!D->isThisDeclarationADefinition() && 13910 "More than one definition in redeclaration chain"); 13911 if (D->getFriendObjectKind() != Decl::FOK_None) 13912 if (FunctionTemplateDecl *FT = 13913 D->getInstantiatedFromMemberTemplate()) { 13914 if (FT->isThisDeclarationADefinition()) { 13915 Definition = D->getTemplatedDecl(); 13916 break; 13917 } 13918 } 13919 } 13920 } 13921 } 13922 13923 if (!Definition) 13924 return; 13925 13926 if (canRedefineFunction(Definition, getLangOpts())) 13927 return; 13928 13929 // Don't emit an error when this is redefinition of a typo-corrected 13930 // definition. 13931 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13932 return; 13933 13934 // If we don't have a visible definition of the function, and it's inline or 13935 // a template, skip the new definition. 13936 if (SkipBody && !hasVisibleDefinition(Definition) && 13937 (Definition->getFormalLinkage() == InternalLinkage || 13938 Definition->isInlined() || 13939 Definition->getDescribedFunctionTemplate() || 13940 Definition->getNumTemplateParameterLists())) { 13941 SkipBody->ShouldSkip = true; 13942 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13943 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13944 makeMergedDefinitionVisible(TD); 13945 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13946 return; 13947 } 13948 13949 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13950 Definition->getStorageClass() == SC_Extern) 13951 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13952 << FD << getLangOpts().CPlusPlus; 13953 else 13954 Diag(FD->getLocation(), diag::err_redefinition) << FD; 13955 13956 Diag(Definition->getLocation(), diag::note_previous_definition); 13957 FD->setInvalidDecl(); 13958 } 13959 13960 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13961 Sema &S) { 13962 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13963 13964 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13965 LSI->CallOperator = CallOperator; 13966 LSI->Lambda = LambdaClass; 13967 LSI->ReturnType = CallOperator->getReturnType(); 13968 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13969 13970 if (LCD == LCD_None) 13971 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13972 else if (LCD == LCD_ByCopy) 13973 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13974 else if (LCD == LCD_ByRef) 13975 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13976 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13977 13978 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13979 LSI->Mutable = !CallOperator->isConst(); 13980 13981 // Add the captures to the LSI so they can be noted as already 13982 // captured within tryCaptureVar. 13983 auto I = LambdaClass->field_begin(); 13984 for (const auto &C : LambdaClass->captures()) { 13985 if (C.capturesVariable()) { 13986 VarDecl *VD = C.getCapturedVar(); 13987 if (VD->isInitCapture()) 13988 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13989 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13990 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13991 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13992 /*EllipsisLoc*/C.isPackExpansion() 13993 ? C.getEllipsisLoc() : SourceLocation(), 13994 I->getType(), /*Invalid*/false); 13995 13996 } else if (C.capturesThis()) { 13997 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13998 C.getCaptureKind() == LCK_StarThis); 13999 } else { 14000 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14001 I->getType()); 14002 } 14003 ++I; 14004 } 14005 } 14006 14007 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14008 SkipBodyInfo *SkipBody) { 14009 if (!D) { 14010 // Parsing the function declaration failed in some way. Push on a fake scope 14011 // anyway so we can try to parse the function body. 14012 PushFunctionScope(); 14013 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14014 return D; 14015 } 14016 14017 FunctionDecl *FD = nullptr; 14018 14019 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14020 FD = FunTmpl->getTemplatedDecl(); 14021 else 14022 FD = cast<FunctionDecl>(D); 14023 14024 // Do not push if it is a lambda because one is already pushed when building 14025 // the lambda in ActOnStartOfLambdaDefinition(). 14026 if (!isLambdaCallOperator(FD)) 14027 PushExpressionEvaluationContext( 14028 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14029 : ExprEvalContexts.back().Context); 14030 14031 // Check for defining attributes before the check for redefinition. 14032 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14033 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14034 FD->dropAttr<AliasAttr>(); 14035 FD->setInvalidDecl(); 14036 } 14037 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14038 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14039 FD->dropAttr<IFuncAttr>(); 14040 FD->setInvalidDecl(); 14041 } 14042 14043 // See if this is a redefinition. If 'will have body' is already set, then 14044 // these checks were already performed when it was set. 14045 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 14046 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14047 14048 // If we're skipping the body, we're done. Don't enter the scope. 14049 if (SkipBody && SkipBody->ShouldSkip) 14050 return D; 14051 } 14052 14053 // Mark this function as "will have a body eventually". This lets users to 14054 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14055 // this function. 14056 FD->setWillHaveBody(); 14057 14058 // If we are instantiating a generic lambda call operator, push 14059 // a LambdaScopeInfo onto the function stack. But use the information 14060 // that's already been calculated (ActOnLambdaExpr) to prime the current 14061 // LambdaScopeInfo. 14062 // When the template operator is being specialized, the LambdaScopeInfo, 14063 // has to be properly restored so that tryCaptureVariable doesn't try 14064 // and capture any new variables. In addition when calculating potential 14065 // captures during transformation of nested lambdas, it is necessary to 14066 // have the LSI properly restored. 14067 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14068 assert(inTemplateInstantiation() && 14069 "There should be an active template instantiation on the stack " 14070 "when instantiating a generic lambda!"); 14071 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14072 } else { 14073 // Enter a new function scope 14074 PushFunctionScope(); 14075 } 14076 14077 // Builtin functions cannot be defined. 14078 if (unsigned BuiltinID = FD->getBuiltinID()) { 14079 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14080 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14081 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14082 FD->setInvalidDecl(); 14083 } 14084 } 14085 14086 // The return type of a function definition must be complete 14087 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14088 QualType ResultType = FD->getReturnType(); 14089 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14090 !FD->isInvalidDecl() && 14091 RequireCompleteType(FD->getLocation(), ResultType, 14092 diag::err_func_def_incomplete_result)) 14093 FD->setInvalidDecl(); 14094 14095 if (FnBodyScope) 14096 PushDeclContext(FnBodyScope, FD); 14097 14098 // Check the validity of our function parameters 14099 CheckParmsForFunctionDef(FD->parameters(), 14100 /*CheckParameterNames=*/true); 14101 14102 // Add non-parameter declarations already in the function to the current 14103 // scope. 14104 if (FnBodyScope) { 14105 for (Decl *NPD : FD->decls()) { 14106 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14107 if (!NonParmDecl) 14108 continue; 14109 assert(!isa<ParmVarDecl>(NonParmDecl) && 14110 "parameters should not be in newly created FD yet"); 14111 14112 // If the decl has a name, make it accessible in the current scope. 14113 if (NonParmDecl->getDeclName()) 14114 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14115 14116 // Similarly, dive into enums and fish their constants out, making them 14117 // accessible in this scope. 14118 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14119 for (auto *EI : ED->enumerators()) 14120 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14121 } 14122 } 14123 } 14124 14125 // Introduce our parameters into the function scope 14126 for (auto Param : FD->parameters()) { 14127 Param->setOwningFunction(FD); 14128 14129 // If this has an identifier, add it to the scope stack. 14130 if (Param->getIdentifier() && FnBodyScope) { 14131 CheckShadow(FnBodyScope, Param); 14132 14133 PushOnScopeChains(Param, FnBodyScope); 14134 } 14135 } 14136 14137 // Ensure that the function's exception specification is instantiated. 14138 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14139 ResolveExceptionSpec(D->getLocation(), FPT); 14140 14141 // dllimport cannot be applied to non-inline function definitions. 14142 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14143 !FD->isTemplateInstantiation()) { 14144 assert(!FD->hasAttr<DLLExportAttr>()); 14145 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14146 FD->setInvalidDecl(); 14147 return D; 14148 } 14149 // We want to attach documentation to original Decl (which might be 14150 // a function template). 14151 ActOnDocumentableDecl(D); 14152 if (getCurLexicalContext()->isObjCContainer() && 14153 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14154 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14155 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14156 14157 return D; 14158 } 14159 14160 /// Given the set of return statements within a function body, 14161 /// compute the variables that are subject to the named return value 14162 /// optimization. 14163 /// 14164 /// Each of the variables that is subject to the named return value 14165 /// optimization will be marked as NRVO variables in the AST, and any 14166 /// return statement that has a marked NRVO variable as its NRVO candidate can 14167 /// use the named return value optimization. 14168 /// 14169 /// This function applies a very simplistic algorithm for NRVO: if every return 14170 /// statement in the scope of a variable has the same NRVO candidate, that 14171 /// candidate is an NRVO variable. 14172 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14173 ReturnStmt **Returns = Scope->Returns.data(); 14174 14175 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14176 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14177 if (!NRVOCandidate->isNRVOVariable()) 14178 Returns[I]->setNRVOCandidate(nullptr); 14179 } 14180 } 14181 } 14182 14183 bool Sema::canDelayFunctionBody(const Declarator &D) { 14184 // We can't delay parsing the body of a constexpr function template (yet). 14185 if (D.getDeclSpec().hasConstexprSpecifier()) 14186 return false; 14187 14188 // We can't delay parsing the body of a function template with a deduced 14189 // return type (yet). 14190 if (D.getDeclSpec().hasAutoTypeSpec()) { 14191 // If the placeholder introduces a non-deduced trailing return type, 14192 // we can still delay parsing it. 14193 if (D.getNumTypeObjects()) { 14194 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14195 if (Outer.Kind == DeclaratorChunk::Function && 14196 Outer.Fun.hasTrailingReturnType()) { 14197 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14198 return Ty.isNull() || !Ty->isUndeducedType(); 14199 } 14200 } 14201 return false; 14202 } 14203 14204 return true; 14205 } 14206 14207 bool Sema::canSkipFunctionBody(Decl *D) { 14208 // We cannot skip the body of a function (or function template) which is 14209 // constexpr, since we may need to evaluate its body in order to parse the 14210 // rest of the file. 14211 // We cannot skip the body of a function with an undeduced return type, 14212 // because any callers of that function need to know the type. 14213 if (const FunctionDecl *FD = D->getAsFunction()) { 14214 if (FD->isConstexpr()) 14215 return false; 14216 // We can't simply call Type::isUndeducedType here, because inside template 14217 // auto can be deduced to a dependent type, which is not considered 14218 // "undeduced". 14219 if (FD->getReturnType()->getContainedDeducedType()) 14220 return false; 14221 } 14222 return Consumer.shouldSkipFunctionBody(D); 14223 } 14224 14225 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14226 if (!Decl) 14227 return nullptr; 14228 if (FunctionDecl *FD = Decl->getAsFunction()) 14229 FD->setHasSkippedBody(); 14230 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14231 MD->setHasSkippedBody(); 14232 return Decl; 14233 } 14234 14235 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14236 return ActOnFinishFunctionBody(D, BodyArg, false); 14237 } 14238 14239 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14240 /// body. 14241 class ExitFunctionBodyRAII { 14242 public: 14243 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14244 ~ExitFunctionBodyRAII() { 14245 if (!IsLambda) 14246 S.PopExpressionEvaluationContext(); 14247 } 14248 14249 private: 14250 Sema &S; 14251 bool IsLambda = false; 14252 }; 14253 14254 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14255 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14256 14257 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14258 if (EscapeInfo.count(BD)) 14259 return EscapeInfo[BD]; 14260 14261 bool R = false; 14262 const BlockDecl *CurBD = BD; 14263 14264 do { 14265 R = !CurBD->doesNotEscape(); 14266 if (R) 14267 break; 14268 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14269 } while (CurBD); 14270 14271 return EscapeInfo[BD] = R; 14272 }; 14273 14274 // If the location where 'self' is implicitly retained is inside a escaping 14275 // block, emit a diagnostic. 14276 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14277 S.ImplicitlyRetainedSelfLocs) 14278 if (IsOrNestedInEscapingBlock(P.second)) 14279 S.Diag(P.first, diag::warn_implicitly_retains_self) 14280 << FixItHint::CreateInsertion(P.first, "self->"); 14281 } 14282 14283 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14284 bool IsInstantiation) { 14285 FunctionScopeInfo *FSI = getCurFunction(); 14286 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14287 14288 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14289 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14290 14291 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14292 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14293 14294 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14295 CheckCompletedCoroutineBody(FD, Body); 14296 14297 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14298 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14299 // meant to pop the context added in ActOnStartOfFunctionDef(). 14300 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14301 14302 if (FD) { 14303 FD->setBody(Body); 14304 FD->setWillHaveBody(false); 14305 14306 if (getLangOpts().CPlusPlus14) { 14307 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14308 FD->getReturnType()->isUndeducedType()) { 14309 // If the function has a deduced result type but contains no 'return' 14310 // statements, the result type as written must be exactly 'auto', and 14311 // the deduced result type is 'void'. 14312 if (!FD->getReturnType()->getAs<AutoType>()) { 14313 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14314 << FD->getReturnType(); 14315 FD->setInvalidDecl(); 14316 } else { 14317 // Substitute 'void' for the 'auto' in the type. 14318 TypeLoc ResultType = getReturnTypeLoc(FD); 14319 Context.adjustDeducedFunctionResultType( 14320 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14321 } 14322 } 14323 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14324 // In C++11, we don't use 'auto' deduction rules for lambda call 14325 // operators because we don't support return type deduction. 14326 auto *LSI = getCurLambda(); 14327 if (LSI->HasImplicitReturnType) { 14328 deduceClosureReturnType(*LSI); 14329 14330 // C++11 [expr.prim.lambda]p4: 14331 // [...] if there are no return statements in the compound-statement 14332 // [the deduced type is] the type void 14333 QualType RetType = 14334 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14335 14336 // Update the return type to the deduced type. 14337 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14338 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14339 Proto->getExtProtoInfo())); 14340 } 14341 } 14342 14343 // If the function implicitly returns zero (like 'main') or is naked, 14344 // don't complain about missing return statements. 14345 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14346 WP.disableCheckFallThrough(); 14347 14348 // MSVC permits the use of pure specifier (=0) on function definition, 14349 // defined at class scope, warn about this non-standard construct. 14350 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14351 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14352 14353 if (!FD->isInvalidDecl()) { 14354 // Don't diagnose unused parameters of defaulted or deleted functions. 14355 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14356 DiagnoseUnusedParameters(FD->parameters()); 14357 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14358 FD->getReturnType(), FD); 14359 14360 // If this is a structor, we need a vtable. 14361 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14362 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14363 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14364 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14365 14366 // Try to apply the named return value optimization. We have to check 14367 // if we can do this here because lambdas keep return statements around 14368 // to deduce an implicit return type. 14369 if (FD->getReturnType()->isRecordType() && 14370 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14371 computeNRVO(Body, FSI); 14372 } 14373 14374 // GNU warning -Wmissing-prototypes: 14375 // Warn if a global function is defined without a previous 14376 // prototype declaration. This warning is issued even if the 14377 // definition itself provides a prototype. The aim is to detect 14378 // global functions that fail to be declared in header files. 14379 const FunctionDecl *PossiblePrototype = nullptr; 14380 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14381 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14382 14383 if (PossiblePrototype) { 14384 // We found a declaration that is not a prototype, 14385 // but that could be a zero-parameter prototype 14386 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14387 TypeLoc TL = TI->getTypeLoc(); 14388 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14389 Diag(PossiblePrototype->getLocation(), 14390 diag::note_declaration_not_a_prototype) 14391 << (FD->getNumParams() != 0) 14392 << (FD->getNumParams() == 0 14393 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14394 : FixItHint{}); 14395 } 14396 } else { 14397 // Returns true if the token beginning at this Loc is `const`. 14398 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14399 const LangOptions &LangOpts) { 14400 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14401 if (LocInfo.first.isInvalid()) 14402 return false; 14403 14404 bool Invalid = false; 14405 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14406 if (Invalid) 14407 return false; 14408 14409 if (LocInfo.second > Buffer.size()) 14410 return false; 14411 14412 const char *LexStart = Buffer.data() + LocInfo.second; 14413 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14414 14415 return StartTok.consume_front("const") && 14416 (StartTok.empty() || isWhitespace(StartTok[0]) || 14417 StartTok.startswith("/*") || StartTok.startswith("//")); 14418 }; 14419 14420 auto findBeginLoc = [&]() { 14421 // If the return type has `const` qualifier, we want to insert 14422 // `static` before `const` (and not before the typename). 14423 if ((FD->getReturnType()->isAnyPointerType() && 14424 FD->getReturnType()->getPointeeType().isConstQualified()) || 14425 FD->getReturnType().isConstQualified()) { 14426 // But only do this if we can determine where the `const` is. 14427 14428 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14429 getLangOpts())) 14430 14431 return FD->getBeginLoc(); 14432 } 14433 return FD->getTypeSpecStartLoc(); 14434 }; 14435 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14436 << /* function */ 1 14437 << (FD->getStorageClass() == SC_None 14438 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14439 : FixItHint{}); 14440 } 14441 14442 // GNU warning -Wstrict-prototypes 14443 // Warn if K&R function is defined without a previous declaration. 14444 // This warning is issued only if the definition itself does not provide 14445 // a prototype. Only K&R definitions do not provide a prototype. 14446 if (!FD->hasWrittenPrototype()) { 14447 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14448 TypeLoc TL = TI->getTypeLoc(); 14449 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14450 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14451 } 14452 } 14453 14454 // Warn on CPUDispatch with an actual body. 14455 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14456 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14457 if (!CmpndBody->body_empty()) 14458 Diag(CmpndBody->body_front()->getBeginLoc(), 14459 diag::warn_dispatch_body_ignored); 14460 14461 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14462 const CXXMethodDecl *KeyFunction; 14463 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14464 MD->isVirtual() && 14465 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14466 MD == KeyFunction->getCanonicalDecl()) { 14467 // Update the key-function state if necessary for this ABI. 14468 if (FD->isInlined() && 14469 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14470 Context.setNonKeyFunction(MD); 14471 14472 // If the newly-chosen key function is already defined, then we 14473 // need to mark the vtable as used retroactively. 14474 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14475 const FunctionDecl *Definition; 14476 if (KeyFunction && KeyFunction->isDefined(Definition)) 14477 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14478 } else { 14479 // We just defined they key function; mark the vtable as used. 14480 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14481 } 14482 } 14483 } 14484 14485 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14486 "Function parsing confused"); 14487 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14488 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14489 MD->setBody(Body); 14490 if (!MD->isInvalidDecl()) { 14491 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14492 MD->getReturnType(), MD); 14493 14494 if (Body) 14495 computeNRVO(Body, FSI); 14496 } 14497 if (FSI->ObjCShouldCallSuper) { 14498 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14499 << MD->getSelector().getAsString(); 14500 FSI->ObjCShouldCallSuper = false; 14501 } 14502 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14503 const ObjCMethodDecl *InitMethod = nullptr; 14504 bool isDesignated = 14505 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14506 assert(isDesignated && InitMethod); 14507 (void)isDesignated; 14508 14509 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14510 auto IFace = MD->getClassInterface(); 14511 if (!IFace) 14512 return false; 14513 auto SuperD = IFace->getSuperClass(); 14514 if (!SuperD) 14515 return false; 14516 return SuperD->getIdentifier() == 14517 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14518 }; 14519 // Don't issue this warning for unavailable inits or direct subclasses 14520 // of NSObject. 14521 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14522 Diag(MD->getLocation(), 14523 diag::warn_objc_designated_init_missing_super_call); 14524 Diag(InitMethod->getLocation(), 14525 diag::note_objc_designated_init_marked_here); 14526 } 14527 FSI->ObjCWarnForNoDesignatedInitChain = false; 14528 } 14529 if (FSI->ObjCWarnForNoInitDelegation) { 14530 // Don't issue this warning for unavaialable inits. 14531 if (!MD->isUnavailable()) 14532 Diag(MD->getLocation(), 14533 diag::warn_objc_secondary_init_missing_init_call); 14534 FSI->ObjCWarnForNoInitDelegation = false; 14535 } 14536 14537 diagnoseImplicitlyRetainedSelf(*this); 14538 } else { 14539 // Parsing the function declaration failed in some way. Pop the fake scope 14540 // we pushed on. 14541 PopFunctionScopeInfo(ActivePolicy, dcl); 14542 return nullptr; 14543 } 14544 14545 if (Body && FSI->HasPotentialAvailabilityViolations) 14546 DiagnoseUnguardedAvailabilityViolations(dcl); 14547 14548 assert(!FSI->ObjCShouldCallSuper && 14549 "This should only be set for ObjC methods, which should have been " 14550 "handled in the block above."); 14551 14552 // Verify and clean out per-function state. 14553 if (Body && (!FD || !FD->isDefaulted())) { 14554 // C++ constructors that have function-try-blocks can't have return 14555 // statements in the handlers of that block. (C++ [except.handle]p14) 14556 // Verify this. 14557 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14558 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14559 14560 // Verify that gotos and switch cases don't jump into scopes illegally. 14561 if (FSI->NeedsScopeChecking() && 14562 !PP.isCodeCompletionEnabled()) 14563 DiagnoseInvalidJumps(Body); 14564 14565 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14566 if (!Destructor->getParent()->isDependentType()) 14567 CheckDestructor(Destructor); 14568 14569 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14570 Destructor->getParent()); 14571 } 14572 14573 // If any errors have occurred, clear out any temporaries that may have 14574 // been leftover. This ensures that these temporaries won't be picked up for 14575 // deletion in some later function. 14576 if (hasUncompilableErrorOccurred() || 14577 getDiagnostics().getSuppressAllDiagnostics()) { 14578 DiscardCleanupsInEvaluationContext(); 14579 } 14580 if (!hasUncompilableErrorOccurred() && 14581 !isa<FunctionTemplateDecl>(dcl)) { 14582 // Since the body is valid, issue any analysis-based warnings that are 14583 // enabled. 14584 ActivePolicy = &WP; 14585 } 14586 14587 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14588 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14589 FD->setInvalidDecl(); 14590 14591 if (FD && FD->hasAttr<NakedAttr>()) { 14592 for (const Stmt *S : Body->children()) { 14593 // Allow local register variables without initializer as they don't 14594 // require prologue. 14595 bool RegisterVariables = false; 14596 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14597 for (const auto *Decl : DS->decls()) { 14598 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14599 RegisterVariables = 14600 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14601 if (!RegisterVariables) 14602 break; 14603 } 14604 } 14605 } 14606 if (RegisterVariables) 14607 continue; 14608 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14609 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14610 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14611 FD->setInvalidDecl(); 14612 break; 14613 } 14614 } 14615 } 14616 14617 assert(ExprCleanupObjects.size() == 14618 ExprEvalContexts.back().NumCleanupObjects && 14619 "Leftover temporaries in function"); 14620 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14621 assert(MaybeODRUseExprs.empty() && 14622 "Leftover expressions for odr-use checking"); 14623 } 14624 14625 if (!IsInstantiation) 14626 PopDeclContext(); 14627 14628 PopFunctionScopeInfo(ActivePolicy, dcl); 14629 // If any errors have occurred, clear out any temporaries that may have 14630 // been leftover. This ensures that these temporaries won't be picked up for 14631 // deletion in some later function. 14632 if (hasUncompilableErrorOccurred()) { 14633 DiscardCleanupsInEvaluationContext(); 14634 } 14635 14636 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { 14637 auto ES = getEmissionStatus(FD); 14638 if (ES == Sema::FunctionEmissionStatus::Emitted || 14639 ES == Sema::FunctionEmissionStatus::Unknown) 14640 DeclsToCheckForDeferredDiags.push_back(FD); 14641 } 14642 14643 return dcl; 14644 } 14645 14646 /// When we finish delayed parsing of an attribute, we must attach it to the 14647 /// relevant Decl. 14648 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14649 ParsedAttributes &Attrs) { 14650 // Always attach attributes to the underlying decl. 14651 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14652 D = TD->getTemplatedDecl(); 14653 ProcessDeclAttributeList(S, D, Attrs); 14654 14655 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14656 if (Method->isStatic()) 14657 checkThisInStaticMemberFunctionAttributes(Method); 14658 } 14659 14660 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14661 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14662 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14663 IdentifierInfo &II, Scope *S) { 14664 // Find the scope in which the identifier is injected and the corresponding 14665 // DeclContext. 14666 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14667 // In that case, we inject the declaration into the translation unit scope 14668 // instead. 14669 Scope *BlockScope = S; 14670 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14671 BlockScope = BlockScope->getParent(); 14672 14673 Scope *ContextScope = BlockScope; 14674 while (!ContextScope->getEntity()) 14675 ContextScope = ContextScope->getParent(); 14676 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14677 14678 // Before we produce a declaration for an implicitly defined 14679 // function, see whether there was a locally-scoped declaration of 14680 // this name as a function or variable. If so, use that 14681 // (non-visible) declaration, and complain about it. 14682 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14683 if (ExternCPrev) { 14684 // We still need to inject the function into the enclosing block scope so 14685 // that later (non-call) uses can see it. 14686 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14687 14688 // C89 footnote 38: 14689 // If in fact it is not defined as having type "function returning int", 14690 // the behavior is undefined. 14691 if (!isa<FunctionDecl>(ExternCPrev) || 14692 !Context.typesAreCompatible( 14693 cast<FunctionDecl>(ExternCPrev)->getType(), 14694 Context.getFunctionNoProtoType(Context.IntTy))) { 14695 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14696 << ExternCPrev << !getLangOpts().C99; 14697 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14698 return ExternCPrev; 14699 } 14700 } 14701 14702 // Extension in C99. Legal in C90, but warn about it. 14703 unsigned diag_id; 14704 if (II.getName().startswith("__builtin_")) 14705 diag_id = diag::warn_builtin_unknown; 14706 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14707 else if (getLangOpts().OpenCL) 14708 diag_id = diag::err_opencl_implicit_function_decl; 14709 else if (getLangOpts().C99) 14710 diag_id = diag::ext_implicit_function_decl; 14711 else 14712 diag_id = diag::warn_implicit_function_decl; 14713 Diag(Loc, diag_id) << &II; 14714 14715 // If we found a prior declaration of this function, don't bother building 14716 // another one. We've already pushed that one into scope, so there's nothing 14717 // more to do. 14718 if (ExternCPrev) 14719 return ExternCPrev; 14720 14721 // Because typo correction is expensive, only do it if the implicit 14722 // function declaration is going to be treated as an error. 14723 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14724 TypoCorrection Corrected; 14725 DeclFilterCCC<FunctionDecl> CCC{}; 14726 if (S && (Corrected = 14727 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14728 S, nullptr, CCC, CTK_NonError))) 14729 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14730 /*ErrorRecovery*/false); 14731 } 14732 14733 // Set a Declarator for the implicit definition: int foo(); 14734 const char *Dummy; 14735 AttributeFactory attrFactory; 14736 DeclSpec DS(attrFactory); 14737 unsigned DiagID; 14738 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14739 Context.getPrintingPolicy()); 14740 (void)Error; // Silence warning. 14741 assert(!Error && "Error setting up implicit decl!"); 14742 SourceLocation NoLoc; 14743 Declarator D(DS, DeclaratorContext::BlockContext); 14744 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14745 /*IsAmbiguous=*/false, 14746 /*LParenLoc=*/NoLoc, 14747 /*Params=*/nullptr, 14748 /*NumParams=*/0, 14749 /*EllipsisLoc=*/NoLoc, 14750 /*RParenLoc=*/NoLoc, 14751 /*RefQualifierIsLvalueRef=*/true, 14752 /*RefQualifierLoc=*/NoLoc, 14753 /*MutableLoc=*/NoLoc, EST_None, 14754 /*ESpecRange=*/SourceRange(), 14755 /*Exceptions=*/nullptr, 14756 /*ExceptionRanges=*/nullptr, 14757 /*NumExceptions=*/0, 14758 /*NoexceptExpr=*/nullptr, 14759 /*ExceptionSpecTokens=*/nullptr, 14760 /*DeclsInPrototype=*/None, Loc, 14761 Loc, D), 14762 std::move(DS.getAttributes()), SourceLocation()); 14763 D.SetIdentifier(&II, Loc); 14764 14765 // Insert this function into the enclosing block scope. 14766 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14767 FD->setImplicit(); 14768 14769 AddKnownFunctionAttributes(FD); 14770 14771 return FD; 14772 } 14773 14774 /// If this function is a C++ replaceable global allocation function 14775 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14776 /// adds any function attributes that we know a priori based on the standard. 14777 /// 14778 /// We need to check for duplicate attributes both here and where user-written 14779 /// attributes are applied to declarations. 14780 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14781 FunctionDecl *FD) { 14782 if (FD->isInvalidDecl()) 14783 return; 14784 14785 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14786 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14787 return; 14788 14789 Optional<unsigned> AlignmentParam; 14790 bool IsNothrow = false; 14791 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14792 return; 14793 14794 // C++2a [basic.stc.dynamic.allocation]p4: 14795 // An allocation function that has a non-throwing exception specification 14796 // indicates failure by returning a null pointer value. Any other allocation 14797 // function never returns a null pointer value and indicates failure only by 14798 // throwing an exception [...] 14799 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14800 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14801 14802 // C++2a [basic.stc.dynamic.allocation]p2: 14803 // An allocation function attempts to allocate the requested amount of 14804 // storage. [...] If the request succeeds, the value returned by a 14805 // replaceable allocation function is a [...] pointer value p0 different 14806 // from any previously returned value p1 [...] 14807 // 14808 // However, this particular information is being added in codegen, 14809 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14810 14811 // C++2a [basic.stc.dynamic.allocation]p2: 14812 // An allocation function attempts to allocate the requested amount of 14813 // storage. If it is successful, it returns the address of the start of a 14814 // block of storage whose length in bytes is at least as large as the 14815 // requested size. 14816 if (!FD->hasAttr<AllocSizeAttr>()) { 14817 FD->addAttr(AllocSizeAttr::CreateImplicit( 14818 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14819 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14820 } 14821 14822 // C++2a [basic.stc.dynamic.allocation]p3: 14823 // For an allocation function [...], the pointer returned on a successful 14824 // call shall represent the address of storage that is aligned as follows: 14825 // (3.1) If the allocation function takes an argument of type 14826 // std::align_val_t, the storage will have the alignment 14827 // specified by the value of this argument. 14828 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14829 FD->addAttr(AllocAlignAttr::CreateImplicit( 14830 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14831 } 14832 14833 // FIXME: 14834 // C++2a [basic.stc.dynamic.allocation]p3: 14835 // For an allocation function [...], the pointer returned on a successful 14836 // call shall represent the address of storage that is aligned as follows: 14837 // (3.2) Otherwise, if the allocation function is named operator new[], 14838 // the storage is aligned for any object that does not have 14839 // new-extended alignment ([basic.align]) and is no larger than the 14840 // requested size. 14841 // (3.3) Otherwise, the storage is aligned for any object that does not 14842 // have new-extended alignment and is of the requested size. 14843 } 14844 14845 /// Adds any function attributes that we know a priori based on 14846 /// the declaration of this function. 14847 /// 14848 /// These attributes can apply both to implicitly-declared builtins 14849 /// (like __builtin___printf_chk) or to library-declared functions 14850 /// like NSLog or printf. 14851 /// 14852 /// We need to check for duplicate attributes both here and where user-written 14853 /// attributes are applied to declarations. 14854 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14855 if (FD->isInvalidDecl()) 14856 return; 14857 14858 // If this is a built-in function, map its builtin attributes to 14859 // actual attributes. 14860 if (unsigned BuiltinID = FD->getBuiltinID()) { 14861 // Handle printf-formatting attributes. 14862 unsigned FormatIdx; 14863 bool HasVAListArg; 14864 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14865 if (!FD->hasAttr<FormatAttr>()) { 14866 const char *fmt = "printf"; 14867 unsigned int NumParams = FD->getNumParams(); 14868 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14869 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14870 fmt = "NSString"; 14871 FD->addAttr(FormatAttr::CreateImplicit(Context, 14872 &Context.Idents.get(fmt), 14873 FormatIdx+1, 14874 HasVAListArg ? 0 : FormatIdx+2, 14875 FD->getLocation())); 14876 } 14877 } 14878 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14879 HasVAListArg)) { 14880 if (!FD->hasAttr<FormatAttr>()) 14881 FD->addAttr(FormatAttr::CreateImplicit(Context, 14882 &Context.Idents.get("scanf"), 14883 FormatIdx+1, 14884 HasVAListArg ? 0 : FormatIdx+2, 14885 FD->getLocation())); 14886 } 14887 14888 // Handle automatically recognized callbacks. 14889 SmallVector<int, 4> Encoding; 14890 if (!FD->hasAttr<CallbackAttr>() && 14891 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14892 FD->addAttr(CallbackAttr::CreateImplicit( 14893 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14894 14895 // Mark const if we don't care about errno and that is the only thing 14896 // preventing the function from being const. This allows IRgen to use LLVM 14897 // intrinsics for such functions. 14898 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14899 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14900 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14901 14902 // We make "fma" on some platforms const because we know it does not set 14903 // errno in those environments even though it could set errno based on the 14904 // C standard. 14905 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14906 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14907 !FD->hasAttr<ConstAttr>()) { 14908 switch (BuiltinID) { 14909 case Builtin::BI__builtin_fma: 14910 case Builtin::BI__builtin_fmaf: 14911 case Builtin::BI__builtin_fmal: 14912 case Builtin::BIfma: 14913 case Builtin::BIfmaf: 14914 case Builtin::BIfmal: 14915 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14916 break; 14917 default: 14918 break; 14919 } 14920 } 14921 14922 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14923 !FD->hasAttr<ReturnsTwiceAttr>()) 14924 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14925 FD->getLocation())); 14926 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14927 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14928 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14929 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14930 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14931 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14932 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14933 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14934 // Add the appropriate attribute, depending on the CUDA compilation mode 14935 // and which target the builtin belongs to. For example, during host 14936 // compilation, aux builtins are __device__, while the rest are __host__. 14937 if (getLangOpts().CUDAIsDevice != 14938 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14939 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14940 else 14941 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14942 } 14943 } 14944 14945 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14946 14947 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14948 // throw, add an implicit nothrow attribute to any extern "C" function we come 14949 // across. 14950 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14951 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14952 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14953 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14954 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14955 } 14956 14957 IdentifierInfo *Name = FD->getIdentifier(); 14958 if (!Name) 14959 return; 14960 if ((!getLangOpts().CPlusPlus && 14961 FD->getDeclContext()->isTranslationUnit()) || 14962 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14963 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14964 LinkageSpecDecl::lang_c)) { 14965 // Okay: this could be a libc/libm/Objective-C function we know 14966 // about. 14967 } else 14968 return; 14969 14970 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14971 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14972 // target-specific builtins, perhaps? 14973 if (!FD->hasAttr<FormatAttr>()) 14974 FD->addAttr(FormatAttr::CreateImplicit(Context, 14975 &Context.Idents.get("printf"), 2, 14976 Name->isStr("vasprintf") ? 0 : 3, 14977 FD->getLocation())); 14978 } 14979 14980 if (Name->isStr("__CFStringMakeConstantString")) { 14981 // We already have a __builtin___CFStringMakeConstantString, 14982 // but builds that use -fno-constant-cfstrings don't go through that. 14983 if (!FD->hasAttr<FormatArgAttr>()) 14984 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14985 FD->getLocation())); 14986 } 14987 } 14988 14989 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14990 TypeSourceInfo *TInfo) { 14991 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14992 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14993 14994 if (!TInfo) { 14995 assert(D.isInvalidType() && "no declarator info for valid type"); 14996 TInfo = Context.getTrivialTypeSourceInfo(T); 14997 } 14998 14999 // Scope manipulation handled by caller. 15000 TypedefDecl *NewTD = 15001 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15002 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15003 15004 // Bail out immediately if we have an invalid declaration. 15005 if (D.isInvalidType()) { 15006 NewTD->setInvalidDecl(); 15007 return NewTD; 15008 } 15009 15010 if (D.getDeclSpec().isModulePrivateSpecified()) { 15011 if (CurContext->isFunctionOrMethod()) 15012 Diag(NewTD->getLocation(), diag::err_module_private_local) 15013 << 2 << NewTD 15014 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15015 << FixItHint::CreateRemoval( 15016 D.getDeclSpec().getModulePrivateSpecLoc()); 15017 else 15018 NewTD->setModulePrivate(); 15019 } 15020 15021 // C++ [dcl.typedef]p8: 15022 // If the typedef declaration defines an unnamed class (or 15023 // enum), the first typedef-name declared by the declaration 15024 // to be that class type (or enum type) is used to denote the 15025 // class type (or enum type) for linkage purposes only. 15026 // We need to check whether the type was declared in the declaration. 15027 switch (D.getDeclSpec().getTypeSpecType()) { 15028 case TST_enum: 15029 case TST_struct: 15030 case TST_interface: 15031 case TST_union: 15032 case TST_class: { 15033 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15034 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15035 break; 15036 } 15037 15038 default: 15039 break; 15040 } 15041 15042 return NewTD; 15043 } 15044 15045 /// Check that this is a valid underlying type for an enum declaration. 15046 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15047 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15048 QualType T = TI->getType(); 15049 15050 if (T->isDependentType()) 15051 return false; 15052 15053 // This doesn't use 'isIntegralType' despite the error message mentioning 15054 // integral type because isIntegralType would also allow enum types in C. 15055 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15056 if (BT->isInteger()) 15057 return false; 15058 15059 if (T->isExtIntType()) 15060 return false; 15061 15062 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15063 } 15064 15065 /// Check whether this is a valid redeclaration of a previous enumeration. 15066 /// \return true if the redeclaration was invalid. 15067 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15068 QualType EnumUnderlyingTy, bool IsFixed, 15069 const EnumDecl *Prev) { 15070 if (IsScoped != Prev->isScoped()) { 15071 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15072 << Prev->isScoped(); 15073 Diag(Prev->getLocation(), diag::note_previous_declaration); 15074 return true; 15075 } 15076 15077 if (IsFixed && Prev->isFixed()) { 15078 if (!EnumUnderlyingTy->isDependentType() && 15079 !Prev->getIntegerType()->isDependentType() && 15080 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15081 Prev->getIntegerType())) { 15082 // TODO: Highlight the underlying type of the redeclaration. 15083 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15084 << EnumUnderlyingTy << Prev->getIntegerType(); 15085 Diag(Prev->getLocation(), diag::note_previous_declaration) 15086 << Prev->getIntegerTypeRange(); 15087 return true; 15088 } 15089 } else if (IsFixed != Prev->isFixed()) { 15090 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15091 << Prev->isFixed(); 15092 Diag(Prev->getLocation(), diag::note_previous_declaration); 15093 return true; 15094 } 15095 15096 return false; 15097 } 15098 15099 /// Get diagnostic %select index for tag kind for 15100 /// redeclaration diagnostic message. 15101 /// WARNING: Indexes apply to particular diagnostics only! 15102 /// 15103 /// \returns diagnostic %select index. 15104 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15105 switch (Tag) { 15106 case TTK_Struct: return 0; 15107 case TTK_Interface: return 1; 15108 case TTK_Class: return 2; 15109 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15110 } 15111 } 15112 15113 /// Determine if tag kind is a class-key compatible with 15114 /// class for redeclaration (class, struct, or __interface). 15115 /// 15116 /// \returns true iff the tag kind is compatible. 15117 static bool isClassCompatTagKind(TagTypeKind Tag) 15118 { 15119 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15120 } 15121 15122 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15123 TagTypeKind TTK) { 15124 if (isa<TypedefDecl>(PrevDecl)) 15125 return NTK_Typedef; 15126 else if (isa<TypeAliasDecl>(PrevDecl)) 15127 return NTK_TypeAlias; 15128 else if (isa<ClassTemplateDecl>(PrevDecl)) 15129 return NTK_Template; 15130 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15131 return NTK_TypeAliasTemplate; 15132 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15133 return NTK_TemplateTemplateArgument; 15134 switch (TTK) { 15135 case TTK_Struct: 15136 case TTK_Interface: 15137 case TTK_Class: 15138 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15139 case TTK_Union: 15140 return NTK_NonUnion; 15141 case TTK_Enum: 15142 return NTK_NonEnum; 15143 } 15144 llvm_unreachable("invalid TTK"); 15145 } 15146 15147 /// Determine whether a tag with a given kind is acceptable 15148 /// as a redeclaration of the given tag declaration. 15149 /// 15150 /// \returns true if the new tag kind is acceptable, false otherwise. 15151 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15152 TagTypeKind NewTag, bool isDefinition, 15153 SourceLocation NewTagLoc, 15154 const IdentifierInfo *Name) { 15155 // C++ [dcl.type.elab]p3: 15156 // The class-key or enum keyword present in the 15157 // elaborated-type-specifier shall agree in kind with the 15158 // declaration to which the name in the elaborated-type-specifier 15159 // refers. This rule also applies to the form of 15160 // elaborated-type-specifier that declares a class-name or 15161 // friend class since it can be construed as referring to the 15162 // definition of the class. Thus, in any 15163 // elaborated-type-specifier, the enum keyword shall be used to 15164 // refer to an enumeration (7.2), the union class-key shall be 15165 // used to refer to a union (clause 9), and either the class or 15166 // struct class-key shall be used to refer to a class (clause 9) 15167 // declared using the class or struct class-key. 15168 TagTypeKind OldTag = Previous->getTagKind(); 15169 if (OldTag != NewTag && 15170 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15171 return false; 15172 15173 // Tags are compatible, but we might still want to warn on mismatched tags. 15174 // Non-class tags can't be mismatched at this point. 15175 if (!isClassCompatTagKind(NewTag)) 15176 return true; 15177 15178 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15179 // by our warning analysis. We don't want to warn about mismatches with (eg) 15180 // declarations in system headers that are designed to be specialized, but if 15181 // a user asks us to warn, we should warn if their code contains mismatched 15182 // declarations. 15183 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15184 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15185 Loc); 15186 }; 15187 if (IsIgnoredLoc(NewTagLoc)) 15188 return true; 15189 15190 auto IsIgnored = [&](const TagDecl *Tag) { 15191 return IsIgnoredLoc(Tag->getLocation()); 15192 }; 15193 while (IsIgnored(Previous)) { 15194 Previous = Previous->getPreviousDecl(); 15195 if (!Previous) 15196 return true; 15197 OldTag = Previous->getTagKind(); 15198 } 15199 15200 bool isTemplate = false; 15201 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15202 isTemplate = Record->getDescribedClassTemplate(); 15203 15204 if (inTemplateInstantiation()) { 15205 if (OldTag != NewTag) { 15206 // In a template instantiation, do not offer fix-its for tag mismatches 15207 // since they usually mess up the template instead of fixing the problem. 15208 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15209 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15210 << getRedeclDiagFromTagKind(OldTag); 15211 // FIXME: Note previous location? 15212 } 15213 return true; 15214 } 15215 15216 if (isDefinition) { 15217 // On definitions, check all previous tags and issue a fix-it for each 15218 // one that doesn't match the current tag. 15219 if (Previous->getDefinition()) { 15220 // Don't suggest fix-its for redefinitions. 15221 return true; 15222 } 15223 15224 bool previousMismatch = false; 15225 for (const TagDecl *I : Previous->redecls()) { 15226 if (I->getTagKind() != NewTag) { 15227 // Ignore previous declarations for which the warning was disabled. 15228 if (IsIgnored(I)) 15229 continue; 15230 15231 if (!previousMismatch) { 15232 previousMismatch = true; 15233 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15234 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15235 << getRedeclDiagFromTagKind(I->getTagKind()); 15236 } 15237 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15238 << getRedeclDiagFromTagKind(NewTag) 15239 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15240 TypeWithKeyword::getTagTypeKindName(NewTag)); 15241 } 15242 } 15243 return true; 15244 } 15245 15246 // Identify the prevailing tag kind: this is the kind of the definition (if 15247 // there is a non-ignored definition), or otherwise the kind of the prior 15248 // (non-ignored) declaration. 15249 const TagDecl *PrevDef = Previous->getDefinition(); 15250 if (PrevDef && IsIgnored(PrevDef)) 15251 PrevDef = nullptr; 15252 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15253 if (Redecl->getTagKind() != NewTag) { 15254 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15255 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15256 << getRedeclDiagFromTagKind(OldTag); 15257 Diag(Redecl->getLocation(), diag::note_previous_use); 15258 15259 // If there is a previous definition, suggest a fix-it. 15260 if (PrevDef) { 15261 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15262 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15263 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15264 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15265 } 15266 } 15267 15268 return true; 15269 } 15270 15271 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15272 /// from an outer enclosing namespace or file scope inside a friend declaration. 15273 /// This should provide the commented out code in the following snippet: 15274 /// namespace N { 15275 /// struct X; 15276 /// namespace M { 15277 /// struct Y { friend struct /*N::*/ X; }; 15278 /// } 15279 /// } 15280 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15281 SourceLocation NameLoc) { 15282 // While the decl is in a namespace, do repeated lookup of that name and see 15283 // if we get the same namespace back. If we do not, continue until 15284 // translation unit scope, at which point we have a fully qualified NNS. 15285 SmallVector<IdentifierInfo *, 4> Namespaces; 15286 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15287 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15288 // This tag should be declared in a namespace, which can only be enclosed by 15289 // other namespaces. Bail if there's an anonymous namespace in the chain. 15290 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15291 if (!Namespace || Namespace->isAnonymousNamespace()) 15292 return FixItHint(); 15293 IdentifierInfo *II = Namespace->getIdentifier(); 15294 Namespaces.push_back(II); 15295 NamedDecl *Lookup = SemaRef.LookupSingleName( 15296 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15297 if (Lookup == Namespace) 15298 break; 15299 } 15300 15301 // Once we have all the namespaces, reverse them to go outermost first, and 15302 // build an NNS. 15303 SmallString<64> Insertion; 15304 llvm::raw_svector_ostream OS(Insertion); 15305 if (DC->isTranslationUnit()) 15306 OS << "::"; 15307 std::reverse(Namespaces.begin(), Namespaces.end()); 15308 for (auto *II : Namespaces) 15309 OS << II->getName() << "::"; 15310 return FixItHint::CreateInsertion(NameLoc, Insertion); 15311 } 15312 15313 /// Determine whether a tag originally declared in context \p OldDC can 15314 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15315 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15316 /// using-declaration). 15317 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15318 DeclContext *NewDC) { 15319 OldDC = OldDC->getRedeclContext(); 15320 NewDC = NewDC->getRedeclContext(); 15321 15322 if (OldDC->Equals(NewDC)) 15323 return true; 15324 15325 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15326 // encloses the other). 15327 if (S.getLangOpts().MSVCCompat && 15328 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15329 return true; 15330 15331 return false; 15332 } 15333 15334 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15335 /// former case, Name will be non-null. In the later case, Name will be null. 15336 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15337 /// reference/declaration/definition of a tag. 15338 /// 15339 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15340 /// trailing-type-specifier) other than one in an alias-declaration. 15341 /// 15342 /// \param SkipBody If non-null, will be set to indicate if the caller should 15343 /// skip the definition of this tag and treat it as if it were a declaration. 15344 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15345 SourceLocation KWLoc, CXXScopeSpec &SS, 15346 IdentifierInfo *Name, SourceLocation NameLoc, 15347 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15348 SourceLocation ModulePrivateLoc, 15349 MultiTemplateParamsArg TemplateParameterLists, 15350 bool &OwnedDecl, bool &IsDependent, 15351 SourceLocation ScopedEnumKWLoc, 15352 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15353 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15354 SkipBodyInfo *SkipBody) { 15355 // If this is not a definition, it must have a name. 15356 IdentifierInfo *OrigName = Name; 15357 assert((Name != nullptr || TUK == TUK_Definition) && 15358 "Nameless record must be a definition!"); 15359 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15360 15361 OwnedDecl = false; 15362 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15363 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15364 15365 // FIXME: Check member specializations more carefully. 15366 bool isMemberSpecialization = false; 15367 bool Invalid = false; 15368 15369 // We only need to do this matching if we have template parameters 15370 // or a scope specifier, which also conveniently avoids this work 15371 // for non-C++ cases. 15372 if (TemplateParameterLists.size() > 0 || 15373 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15374 if (TemplateParameterList *TemplateParams = 15375 MatchTemplateParametersToScopeSpecifier( 15376 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15377 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15378 if (Kind == TTK_Enum) { 15379 Diag(KWLoc, diag::err_enum_template); 15380 return nullptr; 15381 } 15382 15383 if (TemplateParams->size() > 0) { 15384 // This is a declaration or definition of a class template (which may 15385 // be a member of another template). 15386 15387 if (Invalid) 15388 return nullptr; 15389 15390 OwnedDecl = false; 15391 DeclResult Result = CheckClassTemplate( 15392 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15393 AS, ModulePrivateLoc, 15394 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15395 TemplateParameterLists.data(), SkipBody); 15396 return Result.get(); 15397 } else { 15398 // The "template<>" header is extraneous. 15399 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15400 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15401 isMemberSpecialization = true; 15402 } 15403 } 15404 15405 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15406 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15407 return nullptr; 15408 } 15409 15410 // Figure out the underlying type if this a enum declaration. We need to do 15411 // this early, because it's needed to detect if this is an incompatible 15412 // redeclaration. 15413 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15414 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15415 15416 if (Kind == TTK_Enum) { 15417 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15418 // No underlying type explicitly specified, or we failed to parse the 15419 // type, default to int. 15420 EnumUnderlying = Context.IntTy.getTypePtr(); 15421 } else if (UnderlyingType.get()) { 15422 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15423 // integral type; any cv-qualification is ignored. 15424 TypeSourceInfo *TI = nullptr; 15425 GetTypeFromParser(UnderlyingType.get(), &TI); 15426 EnumUnderlying = TI; 15427 15428 if (CheckEnumUnderlyingType(TI)) 15429 // Recover by falling back to int. 15430 EnumUnderlying = Context.IntTy.getTypePtr(); 15431 15432 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15433 UPPC_FixedUnderlyingType)) 15434 EnumUnderlying = Context.IntTy.getTypePtr(); 15435 15436 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15437 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15438 // of 'int'. However, if this is an unfixed forward declaration, don't set 15439 // the underlying type unless the user enables -fms-compatibility. This 15440 // makes unfixed forward declared enums incomplete and is more conforming. 15441 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15442 EnumUnderlying = Context.IntTy.getTypePtr(); 15443 } 15444 } 15445 15446 DeclContext *SearchDC = CurContext; 15447 DeclContext *DC = CurContext; 15448 bool isStdBadAlloc = false; 15449 bool isStdAlignValT = false; 15450 15451 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15452 if (TUK == TUK_Friend || TUK == TUK_Reference) 15453 Redecl = NotForRedeclaration; 15454 15455 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15456 /// implemented asks for structural equivalence checking, the returned decl 15457 /// here is passed back to the parser, allowing the tag body to be parsed. 15458 auto createTagFromNewDecl = [&]() -> TagDecl * { 15459 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15460 // If there is an identifier, use the location of the identifier as the 15461 // location of the decl, otherwise use the location of the struct/union 15462 // keyword. 15463 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15464 TagDecl *New = nullptr; 15465 15466 if (Kind == TTK_Enum) { 15467 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15468 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15469 // If this is an undefined enum, bail. 15470 if (TUK != TUK_Definition && !Invalid) 15471 return nullptr; 15472 if (EnumUnderlying) { 15473 EnumDecl *ED = cast<EnumDecl>(New); 15474 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15475 ED->setIntegerTypeSourceInfo(TI); 15476 else 15477 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15478 ED->setPromotionType(ED->getIntegerType()); 15479 } 15480 } else { // struct/union 15481 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15482 nullptr); 15483 } 15484 15485 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15486 // Add alignment attributes if necessary; these attributes are checked 15487 // when the ASTContext lays out the structure. 15488 // 15489 // It is important for implementing the correct semantics that this 15490 // happen here (in ActOnTag). The #pragma pack stack is 15491 // maintained as a result of parser callbacks which can occur at 15492 // many points during the parsing of a struct declaration (because 15493 // the #pragma tokens are effectively skipped over during the 15494 // parsing of the struct). 15495 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15496 AddAlignmentAttributesForRecord(RD); 15497 AddMsStructLayoutForRecord(RD); 15498 } 15499 } 15500 New->setLexicalDeclContext(CurContext); 15501 return New; 15502 }; 15503 15504 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15505 if (Name && SS.isNotEmpty()) { 15506 // We have a nested-name tag ('struct foo::bar'). 15507 15508 // Check for invalid 'foo::'. 15509 if (SS.isInvalid()) { 15510 Name = nullptr; 15511 goto CreateNewDecl; 15512 } 15513 15514 // If this is a friend or a reference to a class in a dependent 15515 // context, don't try to make a decl for it. 15516 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15517 DC = computeDeclContext(SS, false); 15518 if (!DC) { 15519 IsDependent = true; 15520 return nullptr; 15521 } 15522 } else { 15523 DC = computeDeclContext(SS, true); 15524 if (!DC) { 15525 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15526 << SS.getRange(); 15527 return nullptr; 15528 } 15529 } 15530 15531 if (RequireCompleteDeclContext(SS, DC)) 15532 return nullptr; 15533 15534 SearchDC = DC; 15535 // Look-up name inside 'foo::'. 15536 LookupQualifiedName(Previous, DC); 15537 15538 if (Previous.isAmbiguous()) 15539 return nullptr; 15540 15541 if (Previous.empty()) { 15542 // Name lookup did not find anything. However, if the 15543 // nested-name-specifier refers to the current instantiation, 15544 // and that current instantiation has any dependent base 15545 // classes, we might find something at instantiation time: treat 15546 // this as a dependent elaborated-type-specifier. 15547 // But this only makes any sense for reference-like lookups. 15548 if (Previous.wasNotFoundInCurrentInstantiation() && 15549 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15550 IsDependent = true; 15551 return nullptr; 15552 } 15553 15554 // A tag 'foo::bar' must already exist. 15555 Diag(NameLoc, diag::err_not_tag_in_scope) 15556 << Kind << Name << DC << SS.getRange(); 15557 Name = nullptr; 15558 Invalid = true; 15559 goto CreateNewDecl; 15560 } 15561 } else if (Name) { 15562 // C++14 [class.mem]p14: 15563 // If T is the name of a class, then each of the following shall have a 15564 // name different from T: 15565 // -- every member of class T that is itself a type 15566 if (TUK != TUK_Reference && TUK != TUK_Friend && 15567 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15568 return nullptr; 15569 15570 // If this is a named struct, check to see if there was a previous forward 15571 // declaration or definition. 15572 // FIXME: We're looking into outer scopes here, even when we 15573 // shouldn't be. Doing so can result in ambiguities that we 15574 // shouldn't be diagnosing. 15575 LookupName(Previous, S); 15576 15577 // When declaring or defining a tag, ignore ambiguities introduced 15578 // by types using'ed into this scope. 15579 if (Previous.isAmbiguous() && 15580 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15581 LookupResult::Filter F = Previous.makeFilter(); 15582 while (F.hasNext()) { 15583 NamedDecl *ND = F.next(); 15584 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15585 SearchDC->getRedeclContext())) 15586 F.erase(); 15587 } 15588 F.done(); 15589 } 15590 15591 // C++11 [namespace.memdef]p3: 15592 // If the name in a friend declaration is neither qualified nor 15593 // a template-id and the declaration is a function or an 15594 // elaborated-type-specifier, the lookup to determine whether 15595 // the entity has been previously declared shall not consider 15596 // any scopes outside the innermost enclosing namespace. 15597 // 15598 // MSVC doesn't implement the above rule for types, so a friend tag 15599 // declaration may be a redeclaration of a type declared in an enclosing 15600 // scope. They do implement this rule for friend functions. 15601 // 15602 // Does it matter that this should be by scope instead of by 15603 // semantic context? 15604 if (!Previous.empty() && TUK == TUK_Friend) { 15605 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15606 LookupResult::Filter F = Previous.makeFilter(); 15607 bool FriendSawTagOutsideEnclosingNamespace = false; 15608 while (F.hasNext()) { 15609 NamedDecl *ND = F.next(); 15610 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15611 if (DC->isFileContext() && 15612 !EnclosingNS->Encloses(ND->getDeclContext())) { 15613 if (getLangOpts().MSVCCompat) 15614 FriendSawTagOutsideEnclosingNamespace = true; 15615 else 15616 F.erase(); 15617 } 15618 } 15619 F.done(); 15620 15621 // Diagnose this MSVC extension in the easy case where lookup would have 15622 // unambiguously found something outside the enclosing namespace. 15623 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15624 NamedDecl *ND = Previous.getFoundDecl(); 15625 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15626 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15627 } 15628 } 15629 15630 // Note: there used to be some attempt at recovery here. 15631 if (Previous.isAmbiguous()) 15632 return nullptr; 15633 15634 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15635 // FIXME: This makes sure that we ignore the contexts associated 15636 // with C structs, unions, and enums when looking for a matching 15637 // tag declaration or definition. See the similar lookup tweak 15638 // in Sema::LookupName; is there a better way to deal with this? 15639 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15640 SearchDC = SearchDC->getParent(); 15641 } 15642 } 15643 15644 if (Previous.isSingleResult() && 15645 Previous.getFoundDecl()->isTemplateParameter()) { 15646 // Maybe we will complain about the shadowed template parameter. 15647 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15648 // Just pretend that we didn't see the previous declaration. 15649 Previous.clear(); 15650 } 15651 15652 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15653 DC->Equals(getStdNamespace())) { 15654 if (Name->isStr("bad_alloc")) { 15655 // This is a declaration of or a reference to "std::bad_alloc". 15656 isStdBadAlloc = true; 15657 15658 // If std::bad_alloc has been implicitly declared (but made invisible to 15659 // name lookup), fill in this implicit declaration as the previous 15660 // declaration, so that the declarations get chained appropriately. 15661 if (Previous.empty() && StdBadAlloc) 15662 Previous.addDecl(getStdBadAlloc()); 15663 } else if (Name->isStr("align_val_t")) { 15664 isStdAlignValT = true; 15665 if (Previous.empty() && StdAlignValT) 15666 Previous.addDecl(getStdAlignValT()); 15667 } 15668 } 15669 15670 // If we didn't find a previous declaration, and this is a reference 15671 // (or friend reference), move to the correct scope. In C++, we 15672 // also need to do a redeclaration lookup there, just in case 15673 // there's a shadow friend decl. 15674 if (Name && Previous.empty() && 15675 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15676 if (Invalid) goto CreateNewDecl; 15677 assert(SS.isEmpty()); 15678 15679 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15680 // C++ [basic.scope.pdecl]p5: 15681 // -- for an elaborated-type-specifier of the form 15682 // 15683 // class-key identifier 15684 // 15685 // if the elaborated-type-specifier is used in the 15686 // decl-specifier-seq or parameter-declaration-clause of a 15687 // function defined in namespace scope, the identifier is 15688 // declared as a class-name in the namespace that contains 15689 // the declaration; otherwise, except as a friend 15690 // declaration, the identifier is declared in the smallest 15691 // non-class, non-function-prototype scope that contains the 15692 // declaration. 15693 // 15694 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15695 // C structs and unions. 15696 // 15697 // It is an error in C++ to declare (rather than define) an enum 15698 // type, including via an elaborated type specifier. We'll 15699 // diagnose that later; for now, declare the enum in the same 15700 // scope as we would have picked for any other tag type. 15701 // 15702 // GNU C also supports this behavior as part of its incomplete 15703 // enum types extension, while GNU C++ does not. 15704 // 15705 // Find the context where we'll be declaring the tag. 15706 // FIXME: We would like to maintain the current DeclContext as the 15707 // lexical context, 15708 SearchDC = getTagInjectionContext(SearchDC); 15709 15710 // Find the scope where we'll be declaring the tag. 15711 S = getTagInjectionScope(S, getLangOpts()); 15712 } else { 15713 assert(TUK == TUK_Friend); 15714 // C++ [namespace.memdef]p3: 15715 // If a friend declaration in a non-local class first declares a 15716 // class or function, the friend class or function is a member of 15717 // the innermost enclosing namespace. 15718 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15719 } 15720 15721 // In C++, we need to do a redeclaration lookup to properly 15722 // diagnose some problems. 15723 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15724 // hidden declaration so that we don't get ambiguity errors when using a 15725 // type declared by an elaborated-type-specifier. In C that is not correct 15726 // and we should instead merge compatible types found by lookup. 15727 if (getLangOpts().CPlusPlus) { 15728 // FIXME: This can perform qualified lookups into function contexts, 15729 // which are meaningless. 15730 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15731 LookupQualifiedName(Previous, SearchDC); 15732 } else { 15733 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15734 LookupName(Previous, S); 15735 } 15736 } 15737 15738 // If we have a known previous declaration to use, then use it. 15739 if (Previous.empty() && SkipBody && SkipBody->Previous) 15740 Previous.addDecl(SkipBody->Previous); 15741 15742 if (!Previous.empty()) { 15743 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15744 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15745 15746 // It's okay to have a tag decl in the same scope as a typedef 15747 // which hides a tag decl in the same scope. Finding this 15748 // insanity with a redeclaration lookup can only actually happen 15749 // in C++. 15750 // 15751 // This is also okay for elaborated-type-specifiers, which is 15752 // technically forbidden by the current standard but which is 15753 // okay according to the likely resolution of an open issue; 15754 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15755 if (getLangOpts().CPlusPlus) { 15756 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15757 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15758 TagDecl *Tag = TT->getDecl(); 15759 if (Tag->getDeclName() == Name && 15760 Tag->getDeclContext()->getRedeclContext() 15761 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15762 PrevDecl = Tag; 15763 Previous.clear(); 15764 Previous.addDecl(Tag); 15765 Previous.resolveKind(); 15766 } 15767 } 15768 } 15769 } 15770 15771 // If this is a redeclaration of a using shadow declaration, it must 15772 // declare a tag in the same context. In MSVC mode, we allow a 15773 // redefinition if either context is within the other. 15774 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15775 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15776 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15777 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15778 !(OldTag && isAcceptableTagRedeclContext( 15779 *this, OldTag->getDeclContext(), SearchDC))) { 15780 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15781 Diag(Shadow->getTargetDecl()->getLocation(), 15782 diag::note_using_decl_target); 15783 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15784 << 0; 15785 // Recover by ignoring the old declaration. 15786 Previous.clear(); 15787 goto CreateNewDecl; 15788 } 15789 } 15790 15791 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15792 // If this is a use of a previous tag, or if the tag is already declared 15793 // in the same scope (so that the definition/declaration completes or 15794 // rementions the tag), reuse the decl. 15795 if (TUK == TUK_Reference || TUK == TUK_Friend || 15796 isDeclInScope(DirectPrevDecl, SearchDC, S, 15797 SS.isNotEmpty() || isMemberSpecialization)) { 15798 // Make sure that this wasn't declared as an enum and now used as a 15799 // struct or something similar. 15800 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15801 TUK == TUK_Definition, KWLoc, 15802 Name)) { 15803 bool SafeToContinue 15804 = (PrevTagDecl->getTagKind() != TTK_Enum && 15805 Kind != TTK_Enum); 15806 if (SafeToContinue) 15807 Diag(KWLoc, diag::err_use_with_wrong_tag) 15808 << Name 15809 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15810 PrevTagDecl->getKindName()); 15811 else 15812 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15813 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15814 15815 if (SafeToContinue) 15816 Kind = PrevTagDecl->getTagKind(); 15817 else { 15818 // Recover by making this an anonymous redefinition. 15819 Name = nullptr; 15820 Previous.clear(); 15821 Invalid = true; 15822 } 15823 } 15824 15825 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15826 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15827 if (TUK == TUK_Reference || TUK == TUK_Friend) 15828 return PrevTagDecl; 15829 15830 QualType EnumUnderlyingTy; 15831 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15832 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15833 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15834 EnumUnderlyingTy = QualType(T, 0); 15835 15836 // All conflicts with previous declarations are recovered by 15837 // returning the previous declaration, unless this is a definition, 15838 // in which case we want the caller to bail out. 15839 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15840 ScopedEnum, EnumUnderlyingTy, 15841 IsFixed, PrevEnum)) 15842 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15843 } 15844 15845 // C++11 [class.mem]p1: 15846 // A member shall not be declared twice in the member-specification, 15847 // except that a nested class or member class template can be declared 15848 // and then later defined. 15849 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15850 S->isDeclScope(PrevDecl)) { 15851 Diag(NameLoc, diag::ext_member_redeclared); 15852 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15853 } 15854 15855 if (!Invalid) { 15856 // If this is a use, just return the declaration we found, unless 15857 // we have attributes. 15858 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15859 if (!Attrs.empty()) { 15860 // FIXME: Diagnose these attributes. For now, we create a new 15861 // declaration to hold them. 15862 } else if (TUK == TUK_Reference && 15863 (PrevTagDecl->getFriendObjectKind() == 15864 Decl::FOK_Undeclared || 15865 PrevDecl->getOwningModule() != getCurrentModule()) && 15866 SS.isEmpty()) { 15867 // This declaration is a reference to an existing entity, but 15868 // has different visibility from that entity: it either makes 15869 // a friend visible or it makes a type visible in a new module. 15870 // In either case, create a new declaration. We only do this if 15871 // the declaration would have meant the same thing if no prior 15872 // declaration were found, that is, if it was found in the same 15873 // scope where we would have injected a declaration. 15874 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15875 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15876 return PrevTagDecl; 15877 // This is in the injected scope, create a new declaration in 15878 // that scope. 15879 S = getTagInjectionScope(S, getLangOpts()); 15880 } else { 15881 return PrevTagDecl; 15882 } 15883 } 15884 15885 // Diagnose attempts to redefine a tag. 15886 if (TUK == TUK_Definition) { 15887 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15888 // If we're defining a specialization and the previous definition 15889 // is from an implicit instantiation, don't emit an error 15890 // here; we'll catch this in the general case below. 15891 bool IsExplicitSpecializationAfterInstantiation = false; 15892 if (isMemberSpecialization) { 15893 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15894 IsExplicitSpecializationAfterInstantiation = 15895 RD->getTemplateSpecializationKind() != 15896 TSK_ExplicitSpecialization; 15897 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15898 IsExplicitSpecializationAfterInstantiation = 15899 ED->getTemplateSpecializationKind() != 15900 TSK_ExplicitSpecialization; 15901 } 15902 15903 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15904 // not keep more that one definition around (merge them). However, 15905 // ensure the decl passes the structural compatibility check in 15906 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15907 NamedDecl *Hidden = nullptr; 15908 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15909 // There is a definition of this tag, but it is not visible. We 15910 // explicitly make use of C++'s one definition rule here, and 15911 // assume that this definition is identical to the hidden one 15912 // we already have. Make the existing definition visible and 15913 // use it in place of this one. 15914 if (!getLangOpts().CPlusPlus) { 15915 // Postpone making the old definition visible until after we 15916 // complete parsing the new one and do the structural 15917 // comparison. 15918 SkipBody->CheckSameAsPrevious = true; 15919 SkipBody->New = createTagFromNewDecl(); 15920 SkipBody->Previous = Def; 15921 return Def; 15922 } else { 15923 SkipBody->ShouldSkip = true; 15924 SkipBody->Previous = Def; 15925 makeMergedDefinitionVisible(Hidden); 15926 // Carry on and handle it like a normal definition. We'll 15927 // skip starting the definitiion later. 15928 } 15929 } else if (!IsExplicitSpecializationAfterInstantiation) { 15930 // A redeclaration in function prototype scope in C isn't 15931 // visible elsewhere, so merely issue a warning. 15932 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15933 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15934 else 15935 Diag(NameLoc, diag::err_redefinition) << Name; 15936 notePreviousDefinition(Def, 15937 NameLoc.isValid() ? NameLoc : KWLoc); 15938 // If this is a redefinition, recover by making this 15939 // struct be anonymous, which will make any later 15940 // references get the previous definition. 15941 Name = nullptr; 15942 Previous.clear(); 15943 Invalid = true; 15944 } 15945 } else { 15946 // If the type is currently being defined, complain 15947 // about a nested redefinition. 15948 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15949 if (TD->isBeingDefined()) { 15950 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15951 Diag(PrevTagDecl->getLocation(), 15952 diag::note_previous_definition); 15953 Name = nullptr; 15954 Previous.clear(); 15955 Invalid = true; 15956 } 15957 } 15958 15959 // Okay, this is definition of a previously declared or referenced 15960 // tag. We're going to create a new Decl for it. 15961 } 15962 15963 // Okay, we're going to make a redeclaration. If this is some kind 15964 // of reference, make sure we build the redeclaration in the same DC 15965 // as the original, and ignore the current access specifier. 15966 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15967 SearchDC = PrevTagDecl->getDeclContext(); 15968 AS = AS_none; 15969 } 15970 } 15971 // If we get here we have (another) forward declaration or we 15972 // have a definition. Just create a new decl. 15973 15974 } else { 15975 // If we get here, this is a definition of a new tag type in a nested 15976 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15977 // new decl/type. We set PrevDecl to NULL so that the entities 15978 // have distinct types. 15979 Previous.clear(); 15980 } 15981 // If we get here, we're going to create a new Decl. If PrevDecl 15982 // is non-NULL, it's a definition of the tag declared by 15983 // PrevDecl. If it's NULL, we have a new definition. 15984 15985 // Otherwise, PrevDecl is not a tag, but was found with tag 15986 // lookup. This is only actually possible in C++, where a few 15987 // things like templates still live in the tag namespace. 15988 } else { 15989 // Use a better diagnostic if an elaborated-type-specifier 15990 // found the wrong kind of type on the first 15991 // (non-redeclaration) lookup. 15992 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15993 !Previous.isForRedeclaration()) { 15994 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15995 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15996 << Kind; 15997 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15998 Invalid = true; 15999 16000 // Otherwise, only diagnose if the declaration is in scope. 16001 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16002 SS.isNotEmpty() || isMemberSpecialization)) { 16003 // do nothing 16004 16005 // Diagnose implicit declarations introduced by elaborated types. 16006 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16007 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16008 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16009 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16010 Invalid = true; 16011 16012 // Otherwise it's a declaration. Call out a particularly common 16013 // case here. 16014 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16015 unsigned Kind = 0; 16016 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16017 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16018 << Name << Kind << TND->getUnderlyingType(); 16019 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16020 Invalid = true; 16021 16022 // Otherwise, diagnose. 16023 } else { 16024 // The tag name clashes with something else in the target scope, 16025 // issue an error and recover by making this tag be anonymous. 16026 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16027 notePreviousDefinition(PrevDecl, NameLoc); 16028 Name = nullptr; 16029 Invalid = true; 16030 } 16031 16032 // The existing declaration isn't relevant to us; we're in a 16033 // new scope, so clear out the previous declaration. 16034 Previous.clear(); 16035 } 16036 } 16037 16038 CreateNewDecl: 16039 16040 TagDecl *PrevDecl = nullptr; 16041 if (Previous.isSingleResult()) 16042 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16043 16044 // If there is an identifier, use the location of the identifier as the 16045 // location of the decl, otherwise use the location of the struct/union 16046 // keyword. 16047 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16048 16049 // Otherwise, create a new declaration. If there is a previous 16050 // declaration of the same entity, the two will be linked via 16051 // PrevDecl. 16052 TagDecl *New; 16053 16054 if (Kind == TTK_Enum) { 16055 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16056 // enum X { A, B, C } D; D should chain to X. 16057 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16058 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16059 ScopedEnumUsesClassTag, IsFixed); 16060 16061 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16062 StdAlignValT = cast<EnumDecl>(New); 16063 16064 // If this is an undefined enum, warn. 16065 if (TUK != TUK_Definition && !Invalid) { 16066 TagDecl *Def; 16067 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16068 // C++0x: 7.2p2: opaque-enum-declaration. 16069 // Conflicts are diagnosed above. Do nothing. 16070 } 16071 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16072 Diag(Loc, diag::ext_forward_ref_enum_def) 16073 << New; 16074 Diag(Def->getLocation(), diag::note_previous_definition); 16075 } else { 16076 unsigned DiagID = diag::ext_forward_ref_enum; 16077 if (getLangOpts().MSVCCompat) 16078 DiagID = diag::ext_ms_forward_ref_enum; 16079 else if (getLangOpts().CPlusPlus) 16080 DiagID = diag::err_forward_ref_enum; 16081 Diag(Loc, DiagID); 16082 } 16083 } 16084 16085 if (EnumUnderlying) { 16086 EnumDecl *ED = cast<EnumDecl>(New); 16087 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16088 ED->setIntegerTypeSourceInfo(TI); 16089 else 16090 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16091 ED->setPromotionType(ED->getIntegerType()); 16092 assert(ED->isComplete() && "enum with type should be complete"); 16093 } 16094 } else { 16095 // struct/union/class 16096 16097 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16098 // struct X { int A; } D; D should chain to X. 16099 if (getLangOpts().CPlusPlus) { 16100 // FIXME: Look for a way to use RecordDecl for simple structs. 16101 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16102 cast_or_null<CXXRecordDecl>(PrevDecl)); 16103 16104 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16105 StdBadAlloc = cast<CXXRecordDecl>(New); 16106 } else 16107 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16108 cast_or_null<RecordDecl>(PrevDecl)); 16109 } 16110 16111 // C++11 [dcl.type]p3: 16112 // A type-specifier-seq shall not define a class or enumeration [...]. 16113 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16114 TUK == TUK_Definition) { 16115 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16116 << Context.getTagDeclType(New); 16117 Invalid = true; 16118 } 16119 16120 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16121 DC->getDeclKind() == Decl::Enum) { 16122 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16123 << Context.getTagDeclType(New); 16124 Invalid = true; 16125 } 16126 16127 // Maybe add qualifier info. 16128 if (SS.isNotEmpty()) { 16129 if (SS.isSet()) { 16130 // If this is either a declaration or a definition, check the 16131 // nested-name-specifier against the current context. 16132 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16133 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16134 isMemberSpecialization)) 16135 Invalid = true; 16136 16137 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16138 if (TemplateParameterLists.size() > 0) { 16139 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16140 } 16141 } 16142 else 16143 Invalid = true; 16144 } 16145 16146 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16147 // Add alignment attributes if necessary; these attributes are checked when 16148 // the ASTContext lays out the structure. 16149 // 16150 // It is important for implementing the correct semantics that this 16151 // happen here (in ActOnTag). The #pragma pack stack is 16152 // maintained as a result of parser callbacks which can occur at 16153 // many points during the parsing of a struct declaration (because 16154 // the #pragma tokens are effectively skipped over during the 16155 // parsing of the struct). 16156 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16157 AddAlignmentAttributesForRecord(RD); 16158 AddMsStructLayoutForRecord(RD); 16159 } 16160 } 16161 16162 if (ModulePrivateLoc.isValid()) { 16163 if (isMemberSpecialization) 16164 Diag(New->getLocation(), diag::err_module_private_specialization) 16165 << 2 16166 << FixItHint::CreateRemoval(ModulePrivateLoc); 16167 // __module_private__ does not apply to local classes. However, we only 16168 // diagnose this as an error when the declaration specifiers are 16169 // freestanding. Here, we just ignore the __module_private__. 16170 else if (!SearchDC->isFunctionOrMethod()) 16171 New->setModulePrivate(); 16172 } 16173 16174 // If this is a specialization of a member class (of a class template), 16175 // check the specialization. 16176 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16177 Invalid = true; 16178 16179 // If we're declaring or defining a tag in function prototype scope in C, 16180 // note that this type can only be used within the function and add it to 16181 // the list of decls to inject into the function definition scope. 16182 if ((Name || Kind == TTK_Enum) && 16183 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16184 if (getLangOpts().CPlusPlus) { 16185 // C++ [dcl.fct]p6: 16186 // Types shall not be defined in return or parameter types. 16187 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16188 Diag(Loc, diag::err_type_defined_in_param_type) 16189 << Name; 16190 Invalid = true; 16191 } 16192 } else if (!PrevDecl) { 16193 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16194 } 16195 } 16196 16197 if (Invalid) 16198 New->setInvalidDecl(); 16199 16200 // Set the lexical context. If the tag has a C++ scope specifier, the 16201 // lexical context will be different from the semantic context. 16202 New->setLexicalDeclContext(CurContext); 16203 16204 // Mark this as a friend decl if applicable. 16205 // In Microsoft mode, a friend declaration also acts as a forward 16206 // declaration so we always pass true to setObjectOfFriendDecl to make 16207 // the tag name visible. 16208 if (TUK == TUK_Friend) 16209 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16210 16211 // Set the access specifier. 16212 if (!Invalid && SearchDC->isRecord()) 16213 SetMemberAccessSpecifier(New, PrevDecl, AS); 16214 16215 if (PrevDecl) 16216 CheckRedeclarationModuleOwnership(New, PrevDecl); 16217 16218 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16219 New->startDefinition(); 16220 16221 ProcessDeclAttributeList(S, New, Attrs); 16222 AddPragmaAttributes(S, New); 16223 16224 // If this has an identifier, add it to the scope stack. 16225 if (TUK == TUK_Friend) { 16226 // We might be replacing an existing declaration in the lookup tables; 16227 // if so, borrow its access specifier. 16228 if (PrevDecl) 16229 New->setAccess(PrevDecl->getAccess()); 16230 16231 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16232 DC->makeDeclVisibleInContext(New); 16233 if (Name) // can be null along some error paths 16234 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16235 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16236 } else if (Name) { 16237 S = getNonFieldDeclScope(S); 16238 PushOnScopeChains(New, S, true); 16239 } else { 16240 CurContext->addDecl(New); 16241 } 16242 16243 // If this is the C FILE type, notify the AST context. 16244 if (IdentifierInfo *II = New->getIdentifier()) 16245 if (!New->isInvalidDecl() && 16246 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16247 II->isStr("FILE")) 16248 Context.setFILEDecl(New); 16249 16250 if (PrevDecl) 16251 mergeDeclAttributes(New, PrevDecl); 16252 16253 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16254 inferGslOwnerPointerAttribute(CXXRD); 16255 16256 // If there's a #pragma GCC visibility in scope, set the visibility of this 16257 // record. 16258 AddPushedVisibilityAttribute(New); 16259 16260 if (isMemberSpecialization && !New->isInvalidDecl()) 16261 CompleteMemberSpecialization(New, Previous); 16262 16263 OwnedDecl = true; 16264 // In C++, don't return an invalid declaration. We can't recover well from 16265 // the cases where we make the type anonymous. 16266 if (Invalid && getLangOpts().CPlusPlus) { 16267 if (New->isBeingDefined()) 16268 if (auto RD = dyn_cast<RecordDecl>(New)) 16269 RD->completeDefinition(); 16270 return nullptr; 16271 } else if (SkipBody && SkipBody->ShouldSkip) { 16272 return SkipBody->Previous; 16273 } else { 16274 return New; 16275 } 16276 } 16277 16278 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16279 AdjustDeclIfTemplate(TagD); 16280 TagDecl *Tag = cast<TagDecl>(TagD); 16281 16282 // Enter the tag context. 16283 PushDeclContext(S, Tag); 16284 16285 ActOnDocumentableDecl(TagD); 16286 16287 // If there's a #pragma GCC visibility in scope, set the visibility of this 16288 // record. 16289 AddPushedVisibilityAttribute(Tag); 16290 } 16291 16292 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16293 SkipBodyInfo &SkipBody) { 16294 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16295 return false; 16296 16297 // Make the previous decl visible. 16298 makeMergedDefinitionVisible(SkipBody.Previous); 16299 return true; 16300 } 16301 16302 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16303 assert(isa<ObjCContainerDecl>(IDecl) && 16304 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16305 DeclContext *OCD = cast<DeclContext>(IDecl); 16306 assert(OCD->getLexicalParent() == CurContext && 16307 "The next DeclContext should be lexically contained in the current one."); 16308 CurContext = OCD; 16309 return IDecl; 16310 } 16311 16312 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16313 SourceLocation FinalLoc, 16314 bool IsFinalSpelledSealed, 16315 SourceLocation LBraceLoc) { 16316 AdjustDeclIfTemplate(TagD); 16317 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16318 16319 FieldCollector->StartClass(); 16320 16321 if (!Record->getIdentifier()) 16322 return; 16323 16324 if (FinalLoc.isValid()) 16325 Record->addAttr(FinalAttr::Create( 16326 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16327 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16328 16329 // C++ [class]p2: 16330 // [...] The class-name is also inserted into the scope of the 16331 // class itself; this is known as the injected-class-name. For 16332 // purposes of access checking, the injected-class-name is treated 16333 // as if it were a public member name. 16334 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16335 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16336 Record->getLocation(), Record->getIdentifier(), 16337 /*PrevDecl=*/nullptr, 16338 /*DelayTypeCreation=*/true); 16339 Context.getTypeDeclType(InjectedClassName, Record); 16340 InjectedClassName->setImplicit(); 16341 InjectedClassName->setAccess(AS_public); 16342 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16343 InjectedClassName->setDescribedClassTemplate(Template); 16344 PushOnScopeChains(InjectedClassName, S); 16345 assert(InjectedClassName->isInjectedClassName() && 16346 "Broken injected-class-name"); 16347 } 16348 16349 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16350 SourceRange BraceRange) { 16351 AdjustDeclIfTemplate(TagD); 16352 TagDecl *Tag = cast<TagDecl>(TagD); 16353 Tag->setBraceRange(BraceRange); 16354 16355 // Make sure we "complete" the definition even it is invalid. 16356 if (Tag->isBeingDefined()) { 16357 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16358 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16359 RD->completeDefinition(); 16360 } 16361 16362 if (isa<CXXRecordDecl>(Tag)) { 16363 FieldCollector->FinishClass(); 16364 } 16365 16366 // Exit this scope of this tag's definition. 16367 PopDeclContext(); 16368 16369 if (getCurLexicalContext()->isObjCContainer() && 16370 Tag->getDeclContext()->isFileContext()) 16371 Tag->setTopLevelDeclInObjCContainer(); 16372 16373 // Notify the consumer that we've defined a tag. 16374 if (!Tag->isInvalidDecl()) 16375 Consumer.HandleTagDeclDefinition(Tag); 16376 } 16377 16378 void Sema::ActOnObjCContainerFinishDefinition() { 16379 // Exit this scope of this interface definition. 16380 PopDeclContext(); 16381 } 16382 16383 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16384 assert(DC == CurContext && "Mismatch of container contexts"); 16385 OriginalLexicalContext = DC; 16386 ActOnObjCContainerFinishDefinition(); 16387 } 16388 16389 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16390 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16391 OriginalLexicalContext = nullptr; 16392 } 16393 16394 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16395 AdjustDeclIfTemplate(TagD); 16396 TagDecl *Tag = cast<TagDecl>(TagD); 16397 Tag->setInvalidDecl(); 16398 16399 // Make sure we "complete" the definition even it is invalid. 16400 if (Tag->isBeingDefined()) { 16401 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16402 RD->completeDefinition(); 16403 } 16404 16405 // We're undoing ActOnTagStartDefinition here, not 16406 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16407 // the FieldCollector. 16408 16409 PopDeclContext(); 16410 } 16411 16412 // Note that FieldName may be null for anonymous bitfields. 16413 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16414 IdentifierInfo *FieldName, 16415 QualType FieldTy, bool IsMsStruct, 16416 Expr *BitWidth, bool *ZeroWidth) { 16417 assert(BitWidth); 16418 if (BitWidth->containsErrors()) 16419 return ExprError(); 16420 16421 // Default to true; that shouldn't confuse checks for emptiness 16422 if (ZeroWidth) 16423 *ZeroWidth = true; 16424 16425 // C99 6.7.2.1p4 - verify the field type. 16426 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16427 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16428 // Handle incomplete and sizeless types with a specific error. 16429 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16430 diag::err_field_incomplete_or_sizeless)) 16431 return ExprError(); 16432 if (FieldName) 16433 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16434 << FieldName << FieldTy << BitWidth->getSourceRange(); 16435 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16436 << FieldTy << BitWidth->getSourceRange(); 16437 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16438 UPPC_BitFieldWidth)) 16439 return ExprError(); 16440 16441 // If the bit-width is type- or value-dependent, don't try to check 16442 // it now. 16443 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16444 return BitWidth; 16445 16446 llvm::APSInt Value; 16447 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16448 if (ICE.isInvalid()) 16449 return ICE; 16450 BitWidth = ICE.get(); 16451 16452 if (Value != 0 && ZeroWidth) 16453 *ZeroWidth = false; 16454 16455 // Zero-width bitfield is ok for anonymous field. 16456 if (Value == 0 && FieldName) 16457 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16458 16459 if (Value.isSigned() && Value.isNegative()) { 16460 if (FieldName) 16461 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16462 << FieldName << Value.toString(10); 16463 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16464 << Value.toString(10); 16465 } 16466 16467 if (!FieldTy->isDependentType()) { 16468 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16469 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16470 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16471 16472 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16473 // ABI. 16474 bool CStdConstraintViolation = 16475 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16476 bool MSBitfieldViolation = 16477 Value.ugt(TypeStorageSize) && 16478 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16479 if (CStdConstraintViolation || MSBitfieldViolation) { 16480 unsigned DiagWidth = 16481 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16482 if (FieldName) 16483 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16484 << FieldName << (unsigned)Value.getZExtValue() 16485 << !CStdConstraintViolation << DiagWidth; 16486 16487 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16488 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16489 << DiagWidth; 16490 } 16491 16492 // Warn on types where the user might conceivably expect to get all 16493 // specified bits as value bits: that's all integral types other than 16494 // 'bool'. 16495 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16496 if (FieldName) 16497 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16498 << FieldName << (unsigned)Value.getZExtValue() 16499 << (unsigned)TypeWidth; 16500 else 16501 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16502 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16503 } 16504 } 16505 16506 return BitWidth; 16507 } 16508 16509 /// ActOnField - Each field of a C struct/union is passed into this in order 16510 /// to create a FieldDecl object for it. 16511 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16512 Declarator &D, Expr *BitfieldWidth) { 16513 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16514 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16515 /*InitStyle=*/ICIS_NoInit, AS_public); 16516 return Res; 16517 } 16518 16519 /// HandleField - Analyze a field of a C struct or a C++ data member. 16520 /// 16521 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16522 SourceLocation DeclStart, 16523 Declarator &D, Expr *BitWidth, 16524 InClassInitStyle InitStyle, 16525 AccessSpecifier AS) { 16526 if (D.isDecompositionDeclarator()) { 16527 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16528 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16529 << Decomp.getSourceRange(); 16530 return nullptr; 16531 } 16532 16533 IdentifierInfo *II = D.getIdentifier(); 16534 SourceLocation Loc = DeclStart; 16535 if (II) Loc = D.getIdentifierLoc(); 16536 16537 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16538 QualType T = TInfo->getType(); 16539 if (getLangOpts().CPlusPlus) { 16540 CheckExtraCXXDefaultArguments(D); 16541 16542 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16543 UPPC_DataMemberType)) { 16544 D.setInvalidType(); 16545 T = Context.IntTy; 16546 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16547 } 16548 } 16549 16550 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16551 16552 if (D.getDeclSpec().isInlineSpecified()) 16553 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16554 << getLangOpts().CPlusPlus17; 16555 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16556 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16557 diag::err_invalid_thread) 16558 << DeclSpec::getSpecifierName(TSCS); 16559 16560 // Check to see if this name was declared as a member previously 16561 NamedDecl *PrevDecl = nullptr; 16562 LookupResult Previous(*this, II, Loc, LookupMemberName, 16563 ForVisibleRedeclaration); 16564 LookupName(Previous, S); 16565 switch (Previous.getResultKind()) { 16566 case LookupResult::Found: 16567 case LookupResult::FoundUnresolvedValue: 16568 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16569 break; 16570 16571 case LookupResult::FoundOverloaded: 16572 PrevDecl = Previous.getRepresentativeDecl(); 16573 break; 16574 16575 case LookupResult::NotFound: 16576 case LookupResult::NotFoundInCurrentInstantiation: 16577 case LookupResult::Ambiguous: 16578 break; 16579 } 16580 Previous.suppressDiagnostics(); 16581 16582 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16583 // Maybe we will complain about the shadowed template parameter. 16584 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16585 // Just pretend that we didn't see the previous declaration. 16586 PrevDecl = nullptr; 16587 } 16588 16589 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16590 PrevDecl = nullptr; 16591 16592 bool Mutable 16593 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16594 SourceLocation TSSL = D.getBeginLoc(); 16595 FieldDecl *NewFD 16596 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16597 TSSL, AS, PrevDecl, &D); 16598 16599 if (NewFD->isInvalidDecl()) 16600 Record->setInvalidDecl(); 16601 16602 if (D.getDeclSpec().isModulePrivateSpecified()) 16603 NewFD->setModulePrivate(); 16604 16605 if (NewFD->isInvalidDecl() && PrevDecl) { 16606 // Don't introduce NewFD into scope; there's already something 16607 // with the same name in the same scope. 16608 } else if (II) { 16609 PushOnScopeChains(NewFD, S); 16610 } else 16611 Record->addDecl(NewFD); 16612 16613 return NewFD; 16614 } 16615 16616 /// Build a new FieldDecl and check its well-formedness. 16617 /// 16618 /// This routine builds a new FieldDecl given the fields name, type, 16619 /// record, etc. \p PrevDecl should refer to any previous declaration 16620 /// with the same name and in the same scope as the field to be 16621 /// created. 16622 /// 16623 /// \returns a new FieldDecl. 16624 /// 16625 /// \todo The Declarator argument is a hack. It will be removed once 16626 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16627 TypeSourceInfo *TInfo, 16628 RecordDecl *Record, SourceLocation Loc, 16629 bool Mutable, Expr *BitWidth, 16630 InClassInitStyle InitStyle, 16631 SourceLocation TSSL, 16632 AccessSpecifier AS, NamedDecl *PrevDecl, 16633 Declarator *D) { 16634 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16635 bool InvalidDecl = false; 16636 if (D) InvalidDecl = D->isInvalidType(); 16637 16638 // If we receive a broken type, recover by assuming 'int' and 16639 // marking this declaration as invalid. 16640 if (T.isNull() || T->containsErrors()) { 16641 InvalidDecl = true; 16642 T = Context.IntTy; 16643 } 16644 16645 QualType EltTy = Context.getBaseElementType(T); 16646 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16647 if (RequireCompleteSizedType(Loc, EltTy, 16648 diag::err_field_incomplete_or_sizeless)) { 16649 // Fields of incomplete type force their record to be invalid. 16650 Record->setInvalidDecl(); 16651 InvalidDecl = true; 16652 } else { 16653 NamedDecl *Def; 16654 EltTy->isIncompleteType(&Def); 16655 if (Def && Def->isInvalidDecl()) { 16656 Record->setInvalidDecl(); 16657 InvalidDecl = true; 16658 } 16659 } 16660 } 16661 16662 // TR 18037 does not allow fields to be declared with address space 16663 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16664 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16665 Diag(Loc, diag::err_field_with_address_space); 16666 Record->setInvalidDecl(); 16667 InvalidDecl = true; 16668 } 16669 16670 if (LangOpts.OpenCL) { 16671 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16672 // used as structure or union field: image, sampler, event or block types. 16673 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16674 T->isBlockPointerType()) { 16675 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16676 Record->setInvalidDecl(); 16677 InvalidDecl = true; 16678 } 16679 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16680 if (BitWidth) { 16681 Diag(Loc, diag::err_opencl_bitfields); 16682 InvalidDecl = true; 16683 } 16684 } 16685 16686 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16687 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16688 T.hasQualifiers()) { 16689 InvalidDecl = true; 16690 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16691 } 16692 16693 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16694 // than a variably modified type. 16695 if (!InvalidDecl && T->isVariablyModifiedType()) { 16696 bool SizeIsNegative; 16697 llvm::APSInt Oversized; 16698 16699 TypeSourceInfo *FixedTInfo = 16700 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16701 SizeIsNegative, 16702 Oversized); 16703 if (FixedTInfo) { 16704 Diag(Loc, diag::ext_vla_folded_to_constant); 16705 TInfo = FixedTInfo; 16706 T = FixedTInfo->getType(); 16707 } else { 16708 if (SizeIsNegative) 16709 Diag(Loc, diag::err_typecheck_negative_array_size); 16710 else if (Oversized.getBoolValue()) 16711 Diag(Loc, diag::err_array_too_large) 16712 << Oversized.toString(10); 16713 else 16714 Diag(Loc, diag::err_typecheck_field_variable_size); 16715 InvalidDecl = true; 16716 } 16717 } 16718 16719 // Fields can not have abstract class types 16720 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16721 diag::err_abstract_type_in_decl, 16722 AbstractFieldType)) 16723 InvalidDecl = true; 16724 16725 bool ZeroWidth = false; 16726 if (InvalidDecl) 16727 BitWidth = nullptr; 16728 // If this is declared as a bit-field, check the bit-field. 16729 if (BitWidth) { 16730 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16731 &ZeroWidth).get(); 16732 if (!BitWidth) { 16733 InvalidDecl = true; 16734 BitWidth = nullptr; 16735 ZeroWidth = false; 16736 } 16737 } 16738 16739 // Check that 'mutable' is consistent with the type of the declaration. 16740 if (!InvalidDecl && Mutable) { 16741 unsigned DiagID = 0; 16742 if (T->isReferenceType()) 16743 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16744 : diag::err_mutable_reference; 16745 else if (T.isConstQualified()) 16746 DiagID = diag::err_mutable_const; 16747 16748 if (DiagID) { 16749 SourceLocation ErrLoc = Loc; 16750 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16751 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16752 Diag(ErrLoc, DiagID); 16753 if (DiagID != diag::ext_mutable_reference) { 16754 Mutable = false; 16755 InvalidDecl = true; 16756 } 16757 } 16758 } 16759 16760 // C++11 [class.union]p8 (DR1460): 16761 // At most one variant member of a union may have a 16762 // brace-or-equal-initializer. 16763 if (InitStyle != ICIS_NoInit) 16764 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16765 16766 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16767 BitWidth, Mutable, InitStyle); 16768 if (InvalidDecl) 16769 NewFD->setInvalidDecl(); 16770 16771 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16772 Diag(Loc, diag::err_duplicate_member) << II; 16773 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16774 NewFD->setInvalidDecl(); 16775 } 16776 16777 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16778 if (Record->isUnion()) { 16779 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16780 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16781 if (RDecl->getDefinition()) { 16782 // C++ [class.union]p1: An object of a class with a non-trivial 16783 // constructor, a non-trivial copy constructor, a non-trivial 16784 // destructor, or a non-trivial copy assignment operator 16785 // cannot be a member of a union, nor can an array of such 16786 // objects. 16787 if (CheckNontrivialField(NewFD)) 16788 NewFD->setInvalidDecl(); 16789 } 16790 } 16791 16792 // C++ [class.union]p1: If a union contains a member of reference type, 16793 // the program is ill-formed, except when compiling with MSVC extensions 16794 // enabled. 16795 if (EltTy->isReferenceType()) { 16796 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16797 diag::ext_union_member_of_reference_type : 16798 diag::err_union_member_of_reference_type) 16799 << NewFD->getDeclName() << EltTy; 16800 if (!getLangOpts().MicrosoftExt) 16801 NewFD->setInvalidDecl(); 16802 } 16803 } 16804 } 16805 16806 // FIXME: We need to pass in the attributes given an AST 16807 // representation, not a parser representation. 16808 if (D) { 16809 // FIXME: The current scope is almost... but not entirely... correct here. 16810 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16811 16812 if (NewFD->hasAttrs()) 16813 CheckAlignasUnderalignment(NewFD); 16814 } 16815 16816 // In auto-retain/release, infer strong retension for fields of 16817 // retainable type. 16818 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16819 NewFD->setInvalidDecl(); 16820 16821 if (T.isObjCGCWeak()) 16822 Diag(Loc, diag::warn_attribute_weak_on_field); 16823 16824 NewFD->setAccess(AS); 16825 return NewFD; 16826 } 16827 16828 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16829 assert(FD); 16830 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16831 16832 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16833 return false; 16834 16835 QualType EltTy = Context.getBaseElementType(FD->getType()); 16836 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16837 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16838 if (RDecl->getDefinition()) { 16839 // We check for copy constructors before constructors 16840 // because otherwise we'll never get complaints about 16841 // copy constructors. 16842 16843 CXXSpecialMember member = CXXInvalid; 16844 // We're required to check for any non-trivial constructors. Since the 16845 // implicit default constructor is suppressed if there are any 16846 // user-declared constructors, we just need to check that there is a 16847 // trivial default constructor and a trivial copy constructor. (We don't 16848 // worry about move constructors here, since this is a C++98 check.) 16849 if (RDecl->hasNonTrivialCopyConstructor()) 16850 member = CXXCopyConstructor; 16851 else if (!RDecl->hasTrivialDefaultConstructor()) 16852 member = CXXDefaultConstructor; 16853 else if (RDecl->hasNonTrivialCopyAssignment()) 16854 member = CXXCopyAssignment; 16855 else if (RDecl->hasNonTrivialDestructor()) 16856 member = CXXDestructor; 16857 16858 if (member != CXXInvalid) { 16859 if (!getLangOpts().CPlusPlus11 && 16860 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16861 // Objective-C++ ARC: it is an error to have a non-trivial field of 16862 // a union. However, system headers in Objective-C programs 16863 // occasionally have Objective-C lifetime objects within unions, 16864 // and rather than cause the program to fail, we make those 16865 // members unavailable. 16866 SourceLocation Loc = FD->getLocation(); 16867 if (getSourceManager().isInSystemHeader(Loc)) { 16868 if (!FD->hasAttr<UnavailableAttr>()) 16869 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16870 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16871 return false; 16872 } 16873 } 16874 16875 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16876 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16877 diag::err_illegal_union_or_anon_struct_member) 16878 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16879 DiagnoseNontrivial(RDecl, member); 16880 return !getLangOpts().CPlusPlus11; 16881 } 16882 } 16883 } 16884 16885 return false; 16886 } 16887 16888 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16889 /// AST enum value. 16890 static ObjCIvarDecl::AccessControl 16891 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16892 switch (ivarVisibility) { 16893 default: llvm_unreachable("Unknown visitibility kind"); 16894 case tok::objc_private: return ObjCIvarDecl::Private; 16895 case tok::objc_public: return ObjCIvarDecl::Public; 16896 case tok::objc_protected: return ObjCIvarDecl::Protected; 16897 case tok::objc_package: return ObjCIvarDecl::Package; 16898 } 16899 } 16900 16901 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16902 /// in order to create an IvarDecl object for it. 16903 Decl *Sema::ActOnIvar(Scope *S, 16904 SourceLocation DeclStart, 16905 Declarator &D, Expr *BitfieldWidth, 16906 tok::ObjCKeywordKind Visibility) { 16907 16908 IdentifierInfo *II = D.getIdentifier(); 16909 Expr *BitWidth = (Expr*)BitfieldWidth; 16910 SourceLocation Loc = DeclStart; 16911 if (II) Loc = D.getIdentifierLoc(); 16912 16913 // FIXME: Unnamed fields can be handled in various different ways, for 16914 // example, unnamed unions inject all members into the struct namespace! 16915 16916 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16917 QualType T = TInfo->getType(); 16918 16919 if (BitWidth) { 16920 // 6.7.2.1p3, 6.7.2.1p4 16921 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16922 if (!BitWidth) 16923 D.setInvalidType(); 16924 } else { 16925 // Not a bitfield. 16926 16927 // validate II. 16928 16929 } 16930 if (T->isReferenceType()) { 16931 Diag(Loc, diag::err_ivar_reference_type); 16932 D.setInvalidType(); 16933 } 16934 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16935 // than a variably modified type. 16936 else if (T->isVariablyModifiedType()) { 16937 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16938 D.setInvalidType(); 16939 } 16940 16941 // Get the visibility (access control) for this ivar. 16942 ObjCIvarDecl::AccessControl ac = 16943 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16944 : ObjCIvarDecl::None; 16945 // Must set ivar's DeclContext to its enclosing interface. 16946 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16947 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16948 return nullptr; 16949 ObjCContainerDecl *EnclosingContext; 16950 if (ObjCImplementationDecl *IMPDecl = 16951 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16952 if (LangOpts.ObjCRuntime.isFragile()) { 16953 // Case of ivar declared in an implementation. Context is that of its class. 16954 EnclosingContext = IMPDecl->getClassInterface(); 16955 assert(EnclosingContext && "Implementation has no class interface!"); 16956 } 16957 else 16958 EnclosingContext = EnclosingDecl; 16959 } else { 16960 if (ObjCCategoryDecl *CDecl = 16961 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16962 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16963 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16964 return nullptr; 16965 } 16966 } 16967 EnclosingContext = EnclosingDecl; 16968 } 16969 16970 // Construct the decl. 16971 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16972 DeclStart, Loc, II, T, 16973 TInfo, ac, (Expr *)BitfieldWidth); 16974 16975 if (II) { 16976 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16977 ForVisibleRedeclaration); 16978 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16979 && !isa<TagDecl>(PrevDecl)) { 16980 Diag(Loc, diag::err_duplicate_member) << II; 16981 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16982 NewID->setInvalidDecl(); 16983 } 16984 } 16985 16986 // Process attributes attached to the ivar. 16987 ProcessDeclAttributes(S, NewID, D); 16988 16989 if (D.isInvalidType()) 16990 NewID->setInvalidDecl(); 16991 16992 // In ARC, infer 'retaining' for ivars of retainable type. 16993 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16994 NewID->setInvalidDecl(); 16995 16996 if (D.getDeclSpec().isModulePrivateSpecified()) 16997 NewID->setModulePrivate(); 16998 16999 if (II) { 17000 // FIXME: When interfaces are DeclContexts, we'll need to add 17001 // these to the interface. 17002 S->AddDecl(NewID); 17003 IdResolver.AddDecl(NewID); 17004 } 17005 17006 if (LangOpts.ObjCRuntime.isNonFragile() && 17007 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17008 Diag(Loc, diag::warn_ivars_in_interface); 17009 17010 return NewID; 17011 } 17012 17013 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17014 /// class and class extensions. For every class \@interface and class 17015 /// extension \@interface, if the last ivar is a bitfield of any type, 17016 /// then add an implicit `char :0` ivar to the end of that interface. 17017 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17018 SmallVectorImpl<Decl *> &AllIvarDecls) { 17019 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17020 return; 17021 17022 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17023 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17024 17025 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17026 return; 17027 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17028 if (!ID) { 17029 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17030 if (!CD->IsClassExtension()) 17031 return; 17032 } 17033 // No need to add this to end of @implementation. 17034 else 17035 return; 17036 } 17037 // All conditions are met. Add a new bitfield to the tail end of ivars. 17038 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17039 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17040 17041 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17042 DeclLoc, DeclLoc, nullptr, 17043 Context.CharTy, 17044 Context.getTrivialTypeSourceInfo(Context.CharTy, 17045 DeclLoc), 17046 ObjCIvarDecl::Private, BW, 17047 true); 17048 AllIvarDecls.push_back(Ivar); 17049 } 17050 17051 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17052 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17053 SourceLocation RBrac, 17054 const ParsedAttributesView &Attrs) { 17055 assert(EnclosingDecl && "missing record or interface decl"); 17056 17057 // If this is an Objective-C @implementation or category and we have 17058 // new fields here we should reset the layout of the interface since 17059 // it will now change. 17060 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17061 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17062 switch (DC->getKind()) { 17063 default: break; 17064 case Decl::ObjCCategory: 17065 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17066 break; 17067 case Decl::ObjCImplementation: 17068 Context. 17069 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17070 break; 17071 } 17072 } 17073 17074 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17075 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17076 17077 // Start counting up the number of named members; make sure to include 17078 // members of anonymous structs and unions in the total. 17079 unsigned NumNamedMembers = 0; 17080 if (Record) { 17081 for (const auto *I : Record->decls()) { 17082 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17083 if (IFD->getDeclName()) 17084 ++NumNamedMembers; 17085 } 17086 } 17087 17088 // Verify that all the fields are okay. 17089 SmallVector<FieldDecl*, 32> RecFields; 17090 17091 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17092 i != end; ++i) { 17093 FieldDecl *FD = cast<FieldDecl>(*i); 17094 17095 // Get the type for the field. 17096 const Type *FDTy = FD->getType().getTypePtr(); 17097 17098 if (!FD->isAnonymousStructOrUnion()) { 17099 // Remember all fields written by the user. 17100 RecFields.push_back(FD); 17101 } 17102 17103 // If the field is already invalid for some reason, don't emit more 17104 // diagnostics about it. 17105 if (FD->isInvalidDecl()) { 17106 EnclosingDecl->setInvalidDecl(); 17107 continue; 17108 } 17109 17110 // C99 6.7.2.1p2: 17111 // A structure or union shall not contain a member with 17112 // incomplete or function type (hence, a structure shall not 17113 // contain an instance of itself, but may contain a pointer to 17114 // an instance of itself), except that the last member of a 17115 // structure with more than one named member may have incomplete 17116 // array type; such a structure (and any union containing, 17117 // possibly recursively, a member that is such a structure) 17118 // shall not be a member of a structure or an element of an 17119 // array. 17120 bool IsLastField = (i + 1 == Fields.end()); 17121 if (FDTy->isFunctionType()) { 17122 // Field declared as a function. 17123 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17124 << FD->getDeclName(); 17125 FD->setInvalidDecl(); 17126 EnclosingDecl->setInvalidDecl(); 17127 continue; 17128 } else if (FDTy->isIncompleteArrayType() && 17129 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17130 if (Record) { 17131 // Flexible array member. 17132 // Microsoft and g++ is more permissive regarding flexible array. 17133 // It will accept flexible array in union and also 17134 // as the sole element of a struct/class. 17135 unsigned DiagID = 0; 17136 if (!Record->isUnion() && !IsLastField) { 17137 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17138 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17139 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17140 FD->setInvalidDecl(); 17141 EnclosingDecl->setInvalidDecl(); 17142 continue; 17143 } else if (Record->isUnion()) 17144 DiagID = getLangOpts().MicrosoftExt 17145 ? diag::ext_flexible_array_union_ms 17146 : getLangOpts().CPlusPlus 17147 ? diag::ext_flexible_array_union_gnu 17148 : diag::err_flexible_array_union; 17149 else if (NumNamedMembers < 1) 17150 DiagID = getLangOpts().MicrosoftExt 17151 ? diag::ext_flexible_array_empty_aggregate_ms 17152 : getLangOpts().CPlusPlus 17153 ? diag::ext_flexible_array_empty_aggregate_gnu 17154 : diag::err_flexible_array_empty_aggregate; 17155 17156 if (DiagID) 17157 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17158 << Record->getTagKind(); 17159 // While the layout of types that contain virtual bases is not specified 17160 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17161 // virtual bases after the derived members. This would make a flexible 17162 // array member declared at the end of an object not adjacent to the end 17163 // of the type. 17164 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17165 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17166 << FD->getDeclName() << Record->getTagKind(); 17167 if (!getLangOpts().C99) 17168 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17169 << FD->getDeclName() << Record->getTagKind(); 17170 17171 // If the element type has a non-trivial destructor, we would not 17172 // implicitly destroy the elements, so disallow it for now. 17173 // 17174 // FIXME: GCC allows this. We should probably either implicitly delete 17175 // the destructor of the containing class, or just allow this. 17176 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17177 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17178 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17179 << FD->getDeclName() << FD->getType(); 17180 FD->setInvalidDecl(); 17181 EnclosingDecl->setInvalidDecl(); 17182 continue; 17183 } 17184 // Okay, we have a legal flexible array member at the end of the struct. 17185 Record->setHasFlexibleArrayMember(true); 17186 } else { 17187 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17188 // unless they are followed by another ivar. That check is done 17189 // elsewhere, after synthesized ivars are known. 17190 } 17191 } else if (!FDTy->isDependentType() && 17192 RequireCompleteSizedType( 17193 FD->getLocation(), FD->getType(), 17194 diag::err_field_incomplete_or_sizeless)) { 17195 // Incomplete type 17196 FD->setInvalidDecl(); 17197 EnclosingDecl->setInvalidDecl(); 17198 continue; 17199 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17200 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17201 // A type which contains a flexible array member is considered to be a 17202 // flexible array member. 17203 Record->setHasFlexibleArrayMember(true); 17204 if (!Record->isUnion()) { 17205 // If this is a struct/class and this is not the last element, reject 17206 // it. Note that GCC supports variable sized arrays in the middle of 17207 // structures. 17208 if (!IsLastField) 17209 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17210 << FD->getDeclName() << FD->getType(); 17211 else { 17212 // We support flexible arrays at the end of structs in 17213 // other structs as an extension. 17214 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17215 << FD->getDeclName(); 17216 } 17217 } 17218 } 17219 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17220 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17221 diag::err_abstract_type_in_decl, 17222 AbstractIvarType)) { 17223 // Ivars can not have abstract class types 17224 FD->setInvalidDecl(); 17225 } 17226 if (Record && FDTTy->getDecl()->hasObjectMember()) 17227 Record->setHasObjectMember(true); 17228 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17229 Record->setHasVolatileMember(true); 17230 } else if (FDTy->isObjCObjectType()) { 17231 /// A field cannot be an Objective-c object 17232 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17233 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17234 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17235 FD->setType(T); 17236 } else if (Record && Record->isUnion() && 17237 FD->getType().hasNonTrivialObjCLifetime() && 17238 getSourceManager().isInSystemHeader(FD->getLocation()) && 17239 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17240 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17241 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17242 // For backward compatibility, fields of C unions declared in system 17243 // headers that have non-trivial ObjC ownership qualifications are marked 17244 // as unavailable unless the qualifier is explicit and __strong. This can 17245 // break ABI compatibility between programs compiled with ARC and MRR, but 17246 // is a better option than rejecting programs using those unions under 17247 // ARC. 17248 FD->addAttr(UnavailableAttr::CreateImplicit( 17249 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17250 FD->getLocation())); 17251 } else if (getLangOpts().ObjC && 17252 getLangOpts().getGC() != LangOptions::NonGC && Record && 17253 !Record->hasObjectMember()) { 17254 if (FD->getType()->isObjCObjectPointerType() || 17255 FD->getType().isObjCGCStrong()) 17256 Record->setHasObjectMember(true); 17257 else if (Context.getAsArrayType(FD->getType())) { 17258 QualType BaseType = Context.getBaseElementType(FD->getType()); 17259 if (BaseType->isRecordType() && 17260 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17261 Record->setHasObjectMember(true); 17262 else if (BaseType->isObjCObjectPointerType() || 17263 BaseType.isObjCGCStrong()) 17264 Record->setHasObjectMember(true); 17265 } 17266 } 17267 17268 if (Record && !getLangOpts().CPlusPlus && 17269 !shouldIgnoreForRecordTriviality(FD)) { 17270 QualType FT = FD->getType(); 17271 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17272 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17273 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17274 Record->isUnion()) 17275 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17276 } 17277 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17278 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17279 Record->setNonTrivialToPrimitiveCopy(true); 17280 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17281 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17282 } 17283 if (FT.isDestructedType()) { 17284 Record->setNonTrivialToPrimitiveDestroy(true); 17285 Record->setParamDestroyedInCallee(true); 17286 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17287 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17288 } 17289 17290 if (const auto *RT = FT->getAs<RecordType>()) { 17291 if (RT->getDecl()->getArgPassingRestrictions() == 17292 RecordDecl::APK_CanNeverPassInRegs) 17293 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17294 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17295 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17296 } 17297 17298 if (Record && FD->getType().isVolatileQualified()) 17299 Record->setHasVolatileMember(true); 17300 // Keep track of the number of named members. 17301 if (FD->getIdentifier()) 17302 ++NumNamedMembers; 17303 } 17304 17305 // Okay, we successfully defined 'Record'. 17306 if (Record) { 17307 bool Completed = false; 17308 if (CXXRecord) { 17309 if (!CXXRecord->isInvalidDecl()) { 17310 // Set access bits correctly on the directly-declared conversions. 17311 for (CXXRecordDecl::conversion_iterator 17312 I = CXXRecord->conversion_begin(), 17313 E = CXXRecord->conversion_end(); I != E; ++I) 17314 I.setAccess((*I)->getAccess()); 17315 } 17316 17317 // Add any implicitly-declared members to this class. 17318 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17319 17320 if (!CXXRecord->isDependentType()) { 17321 if (!CXXRecord->isInvalidDecl()) { 17322 // If we have virtual base classes, we may end up finding multiple 17323 // final overriders for a given virtual function. Check for this 17324 // problem now. 17325 if (CXXRecord->getNumVBases()) { 17326 CXXFinalOverriderMap FinalOverriders; 17327 CXXRecord->getFinalOverriders(FinalOverriders); 17328 17329 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17330 MEnd = FinalOverriders.end(); 17331 M != MEnd; ++M) { 17332 for (OverridingMethods::iterator SO = M->second.begin(), 17333 SOEnd = M->second.end(); 17334 SO != SOEnd; ++SO) { 17335 assert(SO->second.size() > 0 && 17336 "Virtual function without overriding functions?"); 17337 if (SO->second.size() == 1) 17338 continue; 17339 17340 // C++ [class.virtual]p2: 17341 // In a derived class, if a virtual member function of a base 17342 // class subobject has more than one final overrider the 17343 // program is ill-formed. 17344 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17345 << (const NamedDecl *)M->first << Record; 17346 Diag(M->first->getLocation(), 17347 diag::note_overridden_virtual_function); 17348 for (OverridingMethods::overriding_iterator 17349 OM = SO->second.begin(), 17350 OMEnd = SO->second.end(); 17351 OM != OMEnd; ++OM) 17352 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17353 << (const NamedDecl *)M->first << OM->Method->getParent(); 17354 17355 Record->setInvalidDecl(); 17356 } 17357 } 17358 CXXRecord->completeDefinition(&FinalOverriders); 17359 Completed = true; 17360 } 17361 } 17362 } 17363 } 17364 17365 if (!Completed) 17366 Record->completeDefinition(); 17367 17368 // Handle attributes before checking the layout. 17369 ProcessDeclAttributeList(S, Record, Attrs); 17370 17371 // We may have deferred checking for a deleted destructor. Check now. 17372 if (CXXRecord) { 17373 auto *Dtor = CXXRecord->getDestructor(); 17374 if (Dtor && Dtor->isImplicit() && 17375 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17376 CXXRecord->setImplicitDestructorIsDeleted(); 17377 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17378 } 17379 } 17380 17381 if (Record->hasAttrs()) { 17382 CheckAlignasUnderalignment(Record); 17383 17384 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17385 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17386 IA->getRange(), IA->getBestCase(), 17387 IA->getInheritanceModel()); 17388 } 17389 17390 // Check if the structure/union declaration is a type that can have zero 17391 // size in C. For C this is a language extension, for C++ it may cause 17392 // compatibility problems. 17393 bool CheckForZeroSize; 17394 if (!getLangOpts().CPlusPlus) { 17395 CheckForZeroSize = true; 17396 } else { 17397 // For C++ filter out types that cannot be referenced in C code. 17398 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17399 CheckForZeroSize = 17400 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17401 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17402 CXXRecord->isCLike(); 17403 } 17404 if (CheckForZeroSize) { 17405 bool ZeroSize = true; 17406 bool IsEmpty = true; 17407 unsigned NonBitFields = 0; 17408 for (RecordDecl::field_iterator I = Record->field_begin(), 17409 E = Record->field_end(); 17410 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17411 IsEmpty = false; 17412 if (I->isUnnamedBitfield()) { 17413 if (!I->isZeroLengthBitField(Context)) 17414 ZeroSize = false; 17415 } else { 17416 ++NonBitFields; 17417 QualType FieldType = I->getType(); 17418 if (FieldType->isIncompleteType() || 17419 !Context.getTypeSizeInChars(FieldType).isZero()) 17420 ZeroSize = false; 17421 } 17422 } 17423 17424 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17425 // allowed in C++, but warn if its declaration is inside 17426 // extern "C" block. 17427 if (ZeroSize) { 17428 Diag(RecLoc, getLangOpts().CPlusPlus ? 17429 diag::warn_zero_size_struct_union_in_extern_c : 17430 diag::warn_zero_size_struct_union_compat) 17431 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17432 } 17433 17434 // Structs without named members are extension in C (C99 6.7.2.1p7), 17435 // but are accepted by GCC. 17436 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17437 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17438 diag::ext_no_named_members_in_struct_union) 17439 << Record->isUnion(); 17440 } 17441 } 17442 } else { 17443 ObjCIvarDecl **ClsFields = 17444 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17445 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17446 ID->setEndOfDefinitionLoc(RBrac); 17447 // Add ivar's to class's DeclContext. 17448 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17449 ClsFields[i]->setLexicalDeclContext(ID); 17450 ID->addDecl(ClsFields[i]); 17451 } 17452 // Must enforce the rule that ivars in the base classes may not be 17453 // duplicates. 17454 if (ID->getSuperClass()) 17455 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17456 } else if (ObjCImplementationDecl *IMPDecl = 17457 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17458 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17459 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17460 // Ivar declared in @implementation never belongs to the implementation. 17461 // Only it is in implementation's lexical context. 17462 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17463 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17464 IMPDecl->setIvarLBraceLoc(LBrac); 17465 IMPDecl->setIvarRBraceLoc(RBrac); 17466 } else if (ObjCCategoryDecl *CDecl = 17467 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17468 // case of ivars in class extension; all other cases have been 17469 // reported as errors elsewhere. 17470 // FIXME. Class extension does not have a LocEnd field. 17471 // CDecl->setLocEnd(RBrac); 17472 // Add ivar's to class extension's DeclContext. 17473 // Diagnose redeclaration of private ivars. 17474 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17475 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17476 if (IDecl) { 17477 if (const ObjCIvarDecl *ClsIvar = 17478 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17479 Diag(ClsFields[i]->getLocation(), 17480 diag::err_duplicate_ivar_declaration); 17481 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17482 continue; 17483 } 17484 for (const auto *Ext : IDecl->known_extensions()) { 17485 if (const ObjCIvarDecl *ClsExtIvar 17486 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17487 Diag(ClsFields[i]->getLocation(), 17488 diag::err_duplicate_ivar_declaration); 17489 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17490 continue; 17491 } 17492 } 17493 } 17494 ClsFields[i]->setLexicalDeclContext(CDecl); 17495 CDecl->addDecl(ClsFields[i]); 17496 } 17497 CDecl->setIvarLBraceLoc(LBrac); 17498 CDecl->setIvarRBraceLoc(RBrac); 17499 } 17500 } 17501 } 17502 17503 /// Determine whether the given integral value is representable within 17504 /// the given type T. 17505 static bool isRepresentableIntegerValue(ASTContext &Context, 17506 llvm::APSInt &Value, 17507 QualType T) { 17508 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17509 "Integral type required!"); 17510 unsigned BitWidth = Context.getIntWidth(T); 17511 17512 if (Value.isUnsigned() || Value.isNonNegative()) { 17513 if (T->isSignedIntegerOrEnumerationType()) 17514 --BitWidth; 17515 return Value.getActiveBits() <= BitWidth; 17516 } 17517 return Value.getMinSignedBits() <= BitWidth; 17518 } 17519 17520 // Given an integral type, return the next larger integral type 17521 // (or a NULL type of no such type exists). 17522 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17523 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17524 // enum checking below. 17525 assert((T->isIntegralType(Context) || 17526 T->isEnumeralType()) && "Integral type required!"); 17527 const unsigned NumTypes = 4; 17528 QualType SignedIntegralTypes[NumTypes] = { 17529 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17530 }; 17531 QualType UnsignedIntegralTypes[NumTypes] = { 17532 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17533 Context.UnsignedLongLongTy 17534 }; 17535 17536 unsigned BitWidth = Context.getTypeSize(T); 17537 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17538 : UnsignedIntegralTypes; 17539 for (unsigned I = 0; I != NumTypes; ++I) 17540 if (Context.getTypeSize(Types[I]) > BitWidth) 17541 return Types[I]; 17542 17543 return QualType(); 17544 } 17545 17546 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17547 EnumConstantDecl *LastEnumConst, 17548 SourceLocation IdLoc, 17549 IdentifierInfo *Id, 17550 Expr *Val) { 17551 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17552 llvm::APSInt EnumVal(IntWidth); 17553 QualType EltTy; 17554 17555 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17556 Val = nullptr; 17557 17558 if (Val) 17559 Val = DefaultLvalueConversion(Val).get(); 17560 17561 if (Val) { 17562 if (Enum->isDependentType() || Val->isTypeDependent()) 17563 EltTy = Context.DependentTy; 17564 else { 17565 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17566 // underlying type, but do allow it in all other contexts. 17567 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17568 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17569 // constant-expression in the enumerator-definition shall be a converted 17570 // constant expression of the underlying type. 17571 EltTy = Enum->getIntegerType(); 17572 ExprResult Converted = 17573 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17574 CCEK_Enumerator); 17575 if (Converted.isInvalid()) 17576 Val = nullptr; 17577 else 17578 Val = Converted.get(); 17579 } else if (!Val->isValueDependent() && 17580 !(Val = 17581 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17582 .get())) { 17583 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17584 } else { 17585 if (Enum->isComplete()) { 17586 EltTy = Enum->getIntegerType(); 17587 17588 // In Obj-C and Microsoft mode, require the enumeration value to be 17589 // representable in the underlying type of the enumeration. In C++11, 17590 // we perform a non-narrowing conversion as part of converted constant 17591 // expression checking. 17592 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17593 if (Context.getTargetInfo() 17594 .getTriple() 17595 .isWindowsMSVCEnvironment()) { 17596 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17597 } else { 17598 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17599 } 17600 } 17601 17602 // Cast to the underlying type. 17603 Val = ImpCastExprToType(Val, EltTy, 17604 EltTy->isBooleanType() ? CK_IntegralToBoolean 17605 : CK_IntegralCast) 17606 .get(); 17607 } else if (getLangOpts().CPlusPlus) { 17608 // C++11 [dcl.enum]p5: 17609 // If the underlying type is not fixed, the type of each enumerator 17610 // is the type of its initializing value: 17611 // - If an initializer is specified for an enumerator, the 17612 // initializing value has the same type as the expression. 17613 EltTy = Val->getType(); 17614 } else { 17615 // C99 6.7.2.2p2: 17616 // The expression that defines the value of an enumeration constant 17617 // shall be an integer constant expression that has a value 17618 // representable as an int. 17619 17620 // Complain if the value is not representable in an int. 17621 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17622 Diag(IdLoc, diag::ext_enum_value_not_int) 17623 << EnumVal.toString(10) << Val->getSourceRange() 17624 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17625 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17626 // Force the type of the expression to 'int'. 17627 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17628 } 17629 EltTy = Val->getType(); 17630 } 17631 } 17632 } 17633 } 17634 17635 if (!Val) { 17636 if (Enum->isDependentType()) 17637 EltTy = Context.DependentTy; 17638 else if (!LastEnumConst) { 17639 // C++0x [dcl.enum]p5: 17640 // If the underlying type is not fixed, the type of each enumerator 17641 // is the type of its initializing value: 17642 // - If no initializer is specified for the first enumerator, the 17643 // initializing value has an unspecified integral type. 17644 // 17645 // GCC uses 'int' for its unspecified integral type, as does 17646 // C99 6.7.2.2p3. 17647 if (Enum->isFixed()) { 17648 EltTy = Enum->getIntegerType(); 17649 } 17650 else { 17651 EltTy = Context.IntTy; 17652 } 17653 } else { 17654 // Assign the last value + 1. 17655 EnumVal = LastEnumConst->getInitVal(); 17656 ++EnumVal; 17657 EltTy = LastEnumConst->getType(); 17658 17659 // Check for overflow on increment. 17660 if (EnumVal < LastEnumConst->getInitVal()) { 17661 // C++0x [dcl.enum]p5: 17662 // If the underlying type is not fixed, the type of each enumerator 17663 // is the type of its initializing value: 17664 // 17665 // - Otherwise the type of the initializing value is the same as 17666 // the type of the initializing value of the preceding enumerator 17667 // unless the incremented value is not representable in that type, 17668 // in which case the type is an unspecified integral type 17669 // sufficient to contain the incremented value. If no such type 17670 // exists, the program is ill-formed. 17671 QualType T = getNextLargerIntegralType(Context, EltTy); 17672 if (T.isNull() || Enum->isFixed()) { 17673 // There is no integral type larger enough to represent this 17674 // value. Complain, then allow the value to wrap around. 17675 EnumVal = LastEnumConst->getInitVal(); 17676 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17677 ++EnumVal; 17678 if (Enum->isFixed()) 17679 // When the underlying type is fixed, this is ill-formed. 17680 Diag(IdLoc, diag::err_enumerator_wrapped) 17681 << EnumVal.toString(10) 17682 << EltTy; 17683 else 17684 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17685 << EnumVal.toString(10); 17686 } else { 17687 EltTy = T; 17688 } 17689 17690 // Retrieve the last enumerator's value, extent that type to the 17691 // type that is supposed to be large enough to represent the incremented 17692 // value, then increment. 17693 EnumVal = LastEnumConst->getInitVal(); 17694 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17695 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17696 ++EnumVal; 17697 17698 // If we're not in C++, diagnose the overflow of enumerator values, 17699 // which in C99 means that the enumerator value is not representable in 17700 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17701 // permits enumerator values that are representable in some larger 17702 // integral type. 17703 if (!getLangOpts().CPlusPlus && !T.isNull()) 17704 Diag(IdLoc, diag::warn_enum_value_overflow); 17705 } else if (!getLangOpts().CPlusPlus && 17706 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17707 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17708 Diag(IdLoc, diag::ext_enum_value_not_int) 17709 << EnumVal.toString(10) << 1; 17710 } 17711 } 17712 } 17713 17714 if (!EltTy->isDependentType()) { 17715 // Make the enumerator value match the signedness and size of the 17716 // enumerator's type. 17717 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17718 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17719 } 17720 17721 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17722 Val, EnumVal); 17723 } 17724 17725 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17726 SourceLocation IILoc) { 17727 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17728 !getLangOpts().CPlusPlus) 17729 return SkipBodyInfo(); 17730 17731 // We have an anonymous enum definition. Look up the first enumerator to 17732 // determine if we should merge the definition with an existing one and 17733 // skip the body. 17734 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17735 forRedeclarationInCurContext()); 17736 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17737 if (!PrevECD) 17738 return SkipBodyInfo(); 17739 17740 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17741 NamedDecl *Hidden; 17742 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17743 SkipBodyInfo Skip; 17744 Skip.Previous = Hidden; 17745 return Skip; 17746 } 17747 17748 return SkipBodyInfo(); 17749 } 17750 17751 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17752 SourceLocation IdLoc, IdentifierInfo *Id, 17753 const ParsedAttributesView &Attrs, 17754 SourceLocation EqualLoc, Expr *Val) { 17755 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17756 EnumConstantDecl *LastEnumConst = 17757 cast_or_null<EnumConstantDecl>(lastEnumConst); 17758 17759 // The scope passed in may not be a decl scope. Zip up the scope tree until 17760 // we find one that is. 17761 S = getNonFieldDeclScope(S); 17762 17763 // Verify that there isn't already something declared with this name in this 17764 // scope. 17765 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17766 LookupName(R, S); 17767 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17768 17769 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17770 // Maybe we will complain about the shadowed template parameter. 17771 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17772 // Just pretend that we didn't see the previous declaration. 17773 PrevDecl = nullptr; 17774 } 17775 17776 // C++ [class.mem]p15: 17777 // If T is the name of a class, then each of the following shall have a name 17778 // different from T: 17779 // - every enumerator of every member of class T that is an unscoped 17780 // enumerated type 17781 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17782 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17783 DeclarationNameInfo(Id, IdLoc)); 17784 17785 EnumConstantDecl *New = 17786 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17787 if (!New) 17788 return nullptr; 17789 17790 if (PrevDecl) { 17791 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17792 // Check for other kinds of shadowing not already handled. 17793 CheckShadow(New, PrevDecl, R); 17794 } 17795 17796 // When in C++, we may get a TagDecl with the same name; in this case the 17797 // enum constant will 'hide' the tag. 17798 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17799 "Received TagDecl when not in C++!"); 17800 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17801 if (isa<EnumConstantDecl>(PrevDecl)) 17802 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17803 else 17804 Diag(IdLoc, diag::err_redefinition) << Id; 17805 notePreviousDefinition(PrevDecl, IdLoc); 17806 return nullptr; 17807 } 17808 } 17809 17810 // Process attributes. 17811 ProcessDeclAttributeList(S, New, Attrs); 17812 AddPragmaAttributes(S, New); 17813 17814 // Register this decl in the current scope stack. 17815 New->setAccess(TheEnumDecl->getAccess()); 17816 PushOnScopeChains(New, S); 17817 17818 ActOnDocumentableDecl(New); 17819 17820 return New; 17821 } 17822 17823 // Returns true when the enum initial expression does not trigger the 17824 // duplicate enum warning. A few common cases are exempted as follows: 17825 // Element2 = Element1 17826 // Element2 = Element1 + 1 17827 // Element2 = Element1 - 1 17828 // Where Element2 and Element1 are from the same enum. 17829 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17830 Expr *InitExpr = ECD->getInitExpr(); 17831 if (!InitExpr) 17832 return true; 17833 InitExpr = InitExpr->IgnoreImpCasts(); 17834 17835 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17836 if (!BO->isAdditiveOp()) 17837 return true; 17838 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17839 if (!IL) 17840 return true; 17841 if (IL->getValue() != 1) 17842 return true; 17843 17844 InitExpr = BO->getLHS(); 17845 } 17846 17847 // This checks if the elements are from the same enum. 17848 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17849 if (!DRE) 17850 return true; 17851 17852 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17853 if (!EnumConstant) 17854 return true; 17855 17856 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17857 Enum) 17858 return true; 17859 17860 return false; 17861 } 17862 17863 // Emits a warning when an element is implicitly set a value that 17864 // a previous element has already been set to. 17865 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17866 EnumDecl *Enum, QualType EnumType) { 17867 // Avoid anonymous enums 17868 if (!Enum->getIdentifier()) 17869 return; 17870 17871 // Only check for small enums. 17872 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17873 return; 17874 17875 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17876 return; 17877 17878 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17879 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17880 17881 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17882 17883 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17884 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17885 17886 // Use int64_t as a key to avoid needing special handling for map keys. 17887 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17888 llvm::APSInt Val = D->getInitVal(); 17889 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17890 }; 17891 17892 DuplicatesVector DupVector; 17893 ValueToVectorMap EnumMap; 17894 17895 // Populate the EnumMap with all values represented by enum constants without 17896 // an initializer. 17897 for (auto *Element : Elements) { 17898 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17899 17900 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17901 // this constant. Skip this enum since it may be ill-formed. 17902 if (!ECD) { 17903 return; 17904 } 17905 17906 // Constants with initalizers are handled in the next loop. 17907 if (ECD->getInitExpr()) 17908 continue; 17909 17910 // Duplicate values are handled in the next loop. 17911 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17912 } 17913 17914 if (EnumMap.size() == 0) 17915 return; 17916 17917 // Create vectors for any values that has duplicates. 17918 for (auto *Element : Elements) { 17919 // The last loop returned if any constant was null. 17920 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17921 if (!ValidDuplicateEnum(ECD, Enum)) 17922 continue; 17923 17924 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17925 if (Iter == EnumMap.end()) 17926 continue; 17927 17928 DeclOrVector& Entry = Iter->second; 17929 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17930 // Ensure constants are different. 17931 if (D == ECD) 17932 continue; 17933 17934 // Create new vector and push values onto it. 17935 auto Vec = std::make_unique<ECDVector>(); 17936 Vec->push_back(D); 17937 Vec->push_back(ECD); 17938 17939 // Update entry to point to the duplicates vector. 17940 Entry = Vec.get(); 17941 17942 // Store the vector somewhere we can consult later for quick emission of 17943 // diagnostics. 17944 DupVector.emplace_back(std::move(Vec)); 17945 continue; 17946 } 17947 17948 ECDVector *Vec = Entry.get<ECDVector*>(); 17949 // Make sure constants are not added more than once. 17950 if (*Vec->begin() == ECD) 17951 continue; 17952 17953 Vec->push_back(ECD); 17954 } 17955 17956 // Emit diagnostics. 17957 for (const auto &Vec : DupVector) { 17958 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17959 17960 // Emit warning for one enum constant. 17961 auto *FirstECD = Vec->front(); 17962 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17963 << FirstECD << FirstECD->getInitVal().toString(10) 17964 << FirstECD->getSourceRange(); 17965 17966 // Emit one note for each of the remaining enum constants with 17967 // the same value. 17968 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17969 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17970 << ECD << ECD->getInitVal().toString(10) 17971 << ECD->getSourceRange(); 17972 } 17973 } 17974 17975 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17976 bool AllowMask) const { 17977 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17978 assert(ED->isCompleteDefinition() && "expected enum definition"); 17979 17980 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17981 llvm::APInt &FlagBits = R.first->second; 17982 17983 if (R.second) { 17984 for (auto *E : ED->enumerators()) { 17985 const auto &EVal = E->getInitVal(); 17986 // Only single-bit enumerators introduce new flag values. 17987 if (EVal.isPowerOf2()) 17988 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17989 } 17990 } 17991 17992 // A value is in a flag enum if either its bits are a subset of the enum's 17993 // flag bits (the first condition) or we are allowing masks and the same is 17994 // true of its complement (the second condition). When masks are allowed, we 17995 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17996 // 17997 // While it's true that any value could be used as a mask, the assumption is 17998 // that a mask will have all of the insignificant bits set. Anything else is 17999 // likely a logic error. 18000 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18001 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18002 } 18003 18004 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18005 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18006 const ParsedAttributesView &Attrs) { 18007 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18008 QualType EnumType = Context.getTypeDeclType(Enum); 18009 18010 ProcessDeclAttributeList(S, Enum, Attrs); 18011 18012 if (Enum->isDependentType()) { 18013 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18014 EnumConstantDecl *ECD = 18015 cast_or_null<EnumConstantDecl>(Elements[i]); 18016 if (!ECD) continue; 18017 18018 ECD->setType(EnumType); 18019 } 18020 18021 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18022 return; 18023 } 18024 18025 // TODO: If the result value doesn't fit in an int, it must be a long or long 18026 // long value. ISO C does not support this, but GCC does as an extension, 18027 // emit a warning. 18028 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18029 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18030 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18031 18032 // Verify that all the values are okay, compute the size of the values, and 18033 // reverse the list. 18034 unsigned NumNegativeBits = 0; 18035 unsigned NumPositiveBits = 0; 18036 18037 // Keep track of whether all elements have type int. 18038 bool AllElementsInt = true; 18039 18040 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18041 EnumConstantDecl *ECD = 18042 cast_or_null<EnumConstantDecl>(Elements[i]); 18043 if (!ECD) continue; // Already issued a diagnostic. 18044 18045 const llvm::APSInt &InitVal = ECD->getInitVal(); 18046 18047 // Keep track of the size of positive and negative values. 18048 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18049 NumPositiveBits = std::max(NumPositiveBits, 18050 (unsigned)InitVal.getActiveBits()); 18051 else 18052 NumNegativeBits = std::max(NumNegativeBits, 18053 (unsigned)InitVal.getMinSignedBits()); 18054 18055 // Keep track of whether every enum element has type int (very common). 18056 if (AllElementsInt) 18057 AllElementsInt = ECD->getType() == Context.IntTy; 18058 } 18059 18060 // Figure out the type that should be used for this enum. 18061 QualType BestType; 18062 unsigned BestWidth; 18063 18064 // C++0x N3000 [conv.prom]p3: 18065 // An rvalue of an unscoped enumeration type whose underlying 18066 // type is not fixed can be converted to an rvalue of the first 18067 // of the following types that can represent all the values of 18068 // the enumeration: int, unsigned int, long int, unsigned long 18069 // int, long long int, or unsigned long long int. 18070 // C99 6.4.4.3p2: 18071 // An identifier declared as an enumeration constant has type int. 18072 // The C99 rule is modified by a gcc extension 18073 QualType BestPromotionType; 18074 18075 bool Packed = Enum->hasAttr<PackedAttr>(); 18076 // -fshort-enums is the equivalent to specifying the packed attribute on all 18077 // enum definitions. 18078 if (LangOpts.ShortEnums) 18079 Packed = true; 18080 18081 // If the enum already has a type because it is fixed or dictated by the 18082 // target, promote that type instead of analyzing the enumerators. 18083 if (Enum->isComplete()) { 18084 BestType = Enum->getIntegerType(); 18085 if (BestType->isPromotableIntegerType()) 18086 BestPromotionType = Context.getPromotedIntegerType(BestType); 18087 else 18088 BestPromotionType = BestType; 18089 18090 BestWidth = Context.getIntWidth(BestType); 18091 } 18092 else if (NumNegativeBits) { 18093 // If there is a negative value, figure out the smallest integer type (of 18094 // int/long/longlong) that fits. 18095 // If it's packed, check also if it fits a char or a short. 18096 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18097 BestType = Context.SignedCharTy; 18098 BestWidth = CharWidth; 18099 } else if (Packed && NumNegativeBits <= ShortWidth && 18100 NumPositiveBits < ShortWidth) { 18101 BestType = Context.ShortTy; 18102 BestWidth = ShortWidth; 18103 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18104 BestType = Context.IntTy; 18105 BestWidth = IntWidth; 18106 } else { 18107 BestWidth = Context.getTargetInfo().getLongWidth(); 18108 18109 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18110 BestType = Context.LongTy; 18111 } else { 18112 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18113 18114 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18115 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18116 BestType = Context.LongLongTy; 18117 } 18118 } 18119 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18120 } else { 18121 // If there is no negative value, figure out the smallest type that fits 18122 // all of the enumerator values. 18123 // If it's packed, check also if it fits a char or a short. 18124 if (Packed && NumPositiveBits <= CharWidth) { 18125 BestType = Context.UnsignedCharTy; 18126 BestPromotionType = Context.IntTy; 18127 BestWidth = CharWidth; 18128 } else if (Packed && NumPositiveBits <= ShortWidth) { 18129 BestType = Context.UnsignedShortTy; 18130 BestPromotionType = Context.IntTy; 18131 BestWidth = ShortWidth; 18132 } else if (NumPositiveBits <= IntWidth) { 18133 BestType = Context.UnsignedIntTy; 18134 BestWidth = IntWidth; 18135 BestPromotionType 18136 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18137 ? Context.UnsignedIntTy : Context.IntTy; 18138 } else if (NumPositiveBits <= 18139 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18140 BestType = Context.UnsignedLongTy; 18141 BestPromotionType 18142 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18143 ? Context.UnsignedLongTy : Context.LongTy; 18144 } else { 18145 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18146 assert(NumPositiveBits <= BestWidth && 18147 "How could an initializer get larger than ULL?"); 18148 BestType = Context.UnsignedLongLongTy; 18149 BestPromotionType 18150 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18151 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18152 } 18153 } 18154 18155 // Loop over all of the enumerator constants, changing their types to match 18156 // the type of the enum if needed. 18157 for (auto *D : Elements) { 18158 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18159 if (!ECD) continue; // Already issued a diagnostic. 18160 18161 // Standard C says the enumerators have int type, but we allow, as an 18162 // extension, the enumerators to be larger than int size. If each 18163 // enumerator value fits in an int, type it as an int, otherwise type it the 18164 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18165 // that X has type 'int', not 'unsigned'. 18166 18167 // Determine whether the value fits into an int. 18168 llvm::APSInt InitVal = ECD->getInitVal(); 18169 18170 // If it fits into an integer type, force it. Otherwise force it to match 18171 // the enum decl type. 18172 QualType NewTy; 18173 unsigned NewWidth; 18174 bool NewSign; 18175 if (!getLangOpts().CPlusPlus && 18176 !Enum->isFixed() && 18177 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18178 NewTy = Context.IntTy; 18179 NewWidth = IntWidth; 18180 NewSign = true; 18181 } else if (ECD->getType() == BestType) { 18182 // Already the right type! 18183 if (getLangOpts().CPlusPlus) 18184 // C++ [dcl.enum]p4: Following the closing brace of an 18185 // enum-specifier, each enumerator has the type of its 18186 // enumeration. 18187 ECD->setType(EnumType); 18188 continue; 18189 } else { 18190 NewTy = BestType; 18191 NewWidth = BestWidth; 18192 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18193 } 18194 18195 // Adjust the APSInt value. 18196 InitVal = InitVal.extOrTrunc(NewWidth); 18197 InitVal.setIsSigned(NewSign); 18198 ECD->setInitVal(InitVal); 18199 18200 // Adjust the Expr initializer and type. 18201 if (ECD->getInitExpr() && 18202 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18203 ECD->setInitExpr(ImplicitCastExpr::Create( 18204 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18205 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18206 if (getLangOpts().CPlusPlus) 18207 // C++ [dcl.enum]p4: Following the closing brace of an 18208 // enum-specifier, each enumerator has the type of its 18209 // enumeration. 18210 ECD->setType(EnumType); 18211 else 18212 ECD->setType(NewTy); 18213 } 18214 18215 Enum->completeDefinition(BestType, BestPromotionType, 18216 NumPositiveBits, NumNegativeBits); 18217 18218 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18219 18220 if (Enum->isClosedFlag()) { 18221 for (Decl *D : Elements) { 18222 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18223 if (!ECD) continue; // Already issued a diagnostic. 18224 18225 llvm::APSInt InitVal = ECD->getInitVal(); 18226 if (InitVal != 0 && !InitVal.isPowerOf2() && 18227 !IsValueInFlagEnum(Enum, InitVal, true)) 18228 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18229 << ECD << Enum; 18230 } 18231 } 18232 18233 // Now that the enum type is defined, ensure it's not been underaligned. 18234 if (Enum->hasAttrs()) 18235 CheckAlignasUnderalignment(Enum); 18236 } 18237 18238 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18239 SourceLocation StartLoc, 18240 SourceLocation EndLoc) { 18241 StringLiteral *AsmString = cast<StringLiteral>(expr); 18242 18243 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18244 AsmString, StartLoc, 18245 EndLoc); 18246 CurContext->addDecl(New); 18247 return New; 18248 } 18249 18250 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18251 IdentifierInfo* AliasName, 18252 SourceLocation PragmaLoc, 18253 SourceLocation NameLoc, 18254 SourceLocation AliasNameLoc) { 18255 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18256 LookupOrdinaryName); 18257 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18258 AttributeCommonInfo::AS_Pragma); 18259 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18260 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18261 18262 // If a declaration that: 18263 // 1) declares a function or a variable 18264 // 2) has external linkage 18265 // already exists, add a label attribute to it. 18266 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18267 if (isDeclExternC(PrevDecl)) 18268 PrevDecl->addAttr(Attr); 18269 else 18270 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18271 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18272 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18273 } else 18274 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18275 } 18276 18277 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18278 SourceLocation PragmaLoc, 18279 SourceLocation NameLoc) { 18280 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18281 18282 if (PrevDecl) { 18283 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18284 } else { 18285 (void)WeakUndeclaredIdentifiers.insert( 18286 std::pair<IdentifierInfo*,WeakInfo> 18287 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18288 } 18289 } 18290 18291 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18292 IdentifierInfo* AliasName, 18293 SourceLocation PragmaLoc, 18294 SourceLocation NameLoc, 18295 SourceLocation AliasNameLoc) { 18296 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18297 LookupOrdinaryName); 18298 WeakInfo W = WeakInfo(Name, NameLoc); 18299 18300 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18301 if (!PrevDecl->hasAttr<AliasAttr>()) 18302 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18303 DeclApplyPragmaWeak(TUScope, ND, W); 18304 } else { 18305 (void)WeakUndeclaredIdentifiers.insert( 18306 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18307 } 18308 } 18309 18310 Decl *Sema::getObjCDeclContext() const { 18311 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18312 } 18313 18314 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18315 bool Final) { 18316 // SYCL functions can be template, so we check if they have appropriate 18317 // attribute prior to checking if it is a template. 18318 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18319 return FunctionEmissionStatus::Emitted; 18320 18321 // Templates are emitted when they're instantiated. 18322 if (FD->isDependentContext()) 18323 return FunctionEmissionStatus::TemplateDiscarded; 18324 18325 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18326 if (LangOpts.OpenMPIsDevice) { 18327 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18328 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18329 if (DevTy.hasValue()) { 18330 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18331 OMPES = FunctionEmissionStatus::OMPDiscarded; 18332 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18333 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18334 OMPES = FunctionEmissionStatus::Emitted; 18335 } 18336 } 18337 } else if (LangOpts.OpenMP) { 18338 // In OpenMP 4.5 all the functions are host functions. 18339 if (LangOpts.OpenMP <= 45) { 18340 OMPES = FunctionEmissionStatus::Emitted; 18341 } else { 18342 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18343 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18344 // In OpenMP 5.0 or above, DevTy may be changed later by 18345 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18346 // having no value does not imply host. The emission status will be 18347 // checked again at the end of compilation unit. 18348 if (DevTy.hasValue()) { 18349 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18350 OMPES = FunctionEmissionStatus::OMPDiscarded; 18351 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18352 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18353 OMPES = FunctionEmissionStatus::Emitted; 18354 } else if (Final) 18355 OMPES = FunctionEmissionStatus::Emitted; 18356 } 18357 } 18358 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18359 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18360 return OMPES; 18361 18362 if (LangOpts.CUDA) { 18363 // When compiling for device, host functions are never emitted. Similarly, 18364 // when compiling for host, device and global functions are never emitted. 18365 // (Technically, we do emit a host-side stub for global functions, but this 18366 // doesn't count for our purposes here.) 18367 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18368 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18369 return FunctionEmissionStatus::CUDADiscarded; 18370 if (!LangOpts.CUDAIsDevice && 18371 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18372 return FunctionEmissionStatus::CUDADiscarded; 18373 18374 // Check whether this function is externally visible -- if so, it's 18375 // known-emitted. 18376 // 18377 // We have to check the GVA linkage of the function's *definition* -- if we 18378 // only have a declaration, we don't know whether or not the function will 18379 // be emitted, because (say) the definition could include "inline". 18380 FunctionDecl *Def = FD->getDefinition(); 18381 18382 if (Def && 18383 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18384 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18385 return FunctionEmissionStatus::Emitted; 18386 } 18387 18388 // Otherwise, the function is known-emitted if it's in our set of 18389 // known-emitted functions. 18390 return FunctionEmissionStatus::Unknown; 18391 } 18392 18393 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18394 // Host-side references to a __global__ function refer to the stub, so the 18395 // function itself is never emitted and therefore should not be marked. 18396 // If we have host fn calls kernel fn calls host+device, the HD function 18397 // does not get instantiated on the host. We model this by omitting at the 18398 // call to the kernel from the callgraph. This ensures that, when compiling 18399 // for host, only HD functions actually called from the host get marked as 18400 // known-emitted. 18401 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18402 IdentifyCUDATarget(Callee) == CFT_Global; 18403 } 18404