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/Randstruct.h" 28 #include "clang/AST/StmtCXX.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 37 #include "clang/Sema/CXXFieldCollector.h" 38 #include "clang/Sema/DeclSpec.h" 39 #include "clang/Sema/DelayedDiagnostic.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaInternal.h" 46 #include "clang/Sema/Template.h" 47 #include "llvm/ADT/SmallString.h" 48 #include "llvm/ADT/Triple.h" 49 #include <algorithm> 50 #include <cstring> 51 #include <functional> 52 #include <unordered_map> 53 54 using namespace clang; 55 using namespace sema; 56 57 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 58 if (OwnedType) { 59 Decl *Group[2] = { OwnedType, Ptr }; 60 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 61 } 62 63 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 64 } 65 66 namespace { 67 68 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 69 public: 70 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 71 bool AllowTemplates = false, 72 bool AllowNonTemplates = true) 73 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 74 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 75 WantExpressionKeywords = false; 76 WantCXXNamedCasts = false; 77 WantRemainingKeywords = false; 78 } 79 80 bool ValidateCandidate(const TypoCorrection &candidate) override { 81 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 82 if (!AllowInvalidDecl && ND->isInvalidDecl()) 83 return false; 84 85 if (getAsTypeTemplateDecl(ND)) 86 return AllowTemplates; 87 88 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 89 if (!IsType) 90 return false; 91 92 if (AllowNonTemplates) 93 return true; 94 95 // An injected-class-name of a class template (specialization) is valid 96 // as a template or as a non-template. 97 if (AllowTemplates) { 98 auto *RD = dyn_cast<CXXRecordDecl>(ND); 99 if (!RD || !RD->isInjectedClassName()) 100 return false; 101 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 102 return RD->getDescribedClassTemplate() || 103 isa<ClassTemplateSpecializationDecl>(RD); 104 } 105 106 return false; 107 } 108 109 return !WantClassName && candidate.isKeyword(); 110 } 111 112 std::unique_ptr<CorrectionCandidateCallback> clone() override { 113 return std::make_unique<TypeNameValidatorCCC>(*this); 114 } 115 116 private: 117 bool AllowInvalidDecl; 118 bool WantClassName; 119 bool AllowTemplates; 120 bool AllowNonTemplates; 121 }; 122 123 } // end anonymous namespace 124 125 /// Determine whether the token kind starts a simple-type-specifier. 126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 127 switch (Kind) { 128 // FIXME: Take into account the current language when deciding whether a 129 // token kind is a valid type specifier 130 case tok::kw_short: 131 case tok::kw_long: 132 case tok::kw___int64: 133 case tok::kw___int128: 134 case tok::kw_signed: 135 case tok::kw_unsigned: 136 case tok::kw_void: 137 case tok::kw_char: 138 case tok::kw_int: 139 case tok::kw_half: 140 case tok::kw_float: 141 case tok::kw_double: 142 case tok::kw___bf16: 143 case tok::kw__Float16: 144 case tok::kw___float128: 145 case tok::kw___ibm128: 146 case tok::kw_wchar_t: 147 case tok::kw_bool: 148 case tok::kw___underlying_type: 149 case tok::kw___auto_type: 150 return true; 151 152 case tok::annot_typename: 153 case tok::kw_char16_t: 154 case tok::kw_char32_t: 155 case tok::kw_typeof: 156 case tok::annot_decltype: 157 case tok::kw_decltype: 158 return getLangOpts().CPlusPlus; 159 160 case tok::kw_char8_t: 161 return getLangOpts().Char8; 162 163 default: 164 break; 165 } 166 167 return false; 168 } 169 170 namespace { 171 enum class UnqualifiedTypeNameLookupResult { 172 NotFound, 173 FoundNonType, 174 FoundType 175 }; 176 } // end anonymous namespace 177 178 /// Tries to perform unqualified lookup of the type decls in bases for 179 /// dependent class. 180 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 181 /// type decl, \a FoundType if only type decls are found. 182 static UnqualifiedTypeNameLookupResult 183 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 184 SourceLocation NameLoc, 185 const CXXRecordDecl *RD) { 186 if (!RD->hasDefinition()) 187 return UnqualifiedTypeNameLookupResult::NotFound; 188 // Look for type decls in base classes. 189 UnqualifiedTypeNameLookupResult FoundTypeDecl = 190 UnqualifiedTypeNameLookupResult::NotFound; 191 for (const auto &Base : RD->bases()) { 192 const CXXRecordDecl *BaseRD = nullptr; 193 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 194 BaseRD = BaseTT->getAsCXXRecordDecl(); 195 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 196 // Look for type decls in dependent base classes that have known primary 197 // templates. 198 if (!TST || !TST->isDependentType()) 199 continue; 200 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 201 if (!TD) 202 continue; 203 if (auto *BasePrimaryTemplate = 204 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 205 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 206 BaseRD = BasePrimaryTemplate; 207 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 208 if (const ClassTemplatePartialSpecializationDecl *PS = 209 CTD->findPartialSpecialization(Base.getType())) 210 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 211 BaseRD = PS; 212 } 213 } 214 } 215 if (BaseRD) { 216 for (NamedDecl *ND : BaseRD->lookup(&II)) { 217 if (!isa<TypeDecl>(ND)) 218 return UnqualifiedTypeNameLookupResult::FoundNonType; 219 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 220 } 221 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 222 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 223 case UnqualifiedTypeNameLookupResult::FoundNonType: 224 return UnqualifiedTypeNameLookupResult::FoundNonType; 225 case UnqualifiedTypeNameLookupResult::FoundType: 226 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 227 break; 228 case UnqualifiedTypeNameLookupResult::NotFound: 229 break; 230 } 231 } 232 } 233 } 234 235 return FoundTypeDecl; 236 } 237 238 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 239 const IdentifierInfo &II, 240 SourceLocation NameLoc) { 241 // Lookup in the parent class template context, if any. 242 const CXXRecordDecl *RD = nullptr; 243 UnqualifiedTypeNameLookupResult FoundTypeDecl = 244 UnqualifiedTypeNameLookupResult::NotFound; 245 for (DeclContext *DC = S.CurContext; 246 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 247 DC = DC->getParent()) { 248 // Look for type decls in dependent base classes that have known primary 249 // templates. 250 RD = dyn_cast<CXXRecordDecl>(DC); 251 if (RD && RD->getDescribedClassTemplate()) 252 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 253 } 254 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 255 return nullptr; 256 257 // We found some types in dependent base classes. Recover as if the user 258 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 259 // lookup during template instantiation. 260 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 261 262 ASTContext &Context = S.Context; 263 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 264 cast<Type>(Context.getRecordType(RD))); 265 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 266 267 CXXScopeSpec SS; 268 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 269 270 TypeLocBuilder Builder; 271 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 272 DepTL.setNameLoc(NameLoc); 273 DepTL.setElaboratedKeywordLoc(SourceLocation()); 274 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 275 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 276 } 277 278 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 279 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, 280 SourceLocation NameLoc, 281 bool WantNontrivialTypeSourceInfo = true) { 282 switch (T->getTypeClass()) { 283 case Type::DeducedTemplateSpecialization: 284 case Type::Enum: 285 case Type::InjectedClassName: 286 case Type::Record: 287 case Type::Typedef: 288 case Type::UnresolvedUsing: 289 case Type::Using: 290 break; 291 // These can never be qualified so an ElaboratedType node 292 // would carry no additional meaning. 293 case Type::ObjCInterface: 294 case Type::ObjCTypeParam: 295 case Type::TemplateTypeParm: 296 return ParsedType::make(T); 297 default: 298 llvm_unreachable("Unexpected Type Class"); 299 } 300 301 if (!SS || SS->isEmpty()) 302 return ParsedType::make( 303 S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr)); 304 305 QualType ElTy = S.getElaboratedType(ETK_None, *SS, T); 306 if (!WantNontrivialTypeSourceInfo) 307 return ParsedType::make(ElTy); 308 309 TypeLocBuilder Builder; 310 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 311 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy); 312 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 313 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context)); 314 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy)); 315 } 316 317 /// If the identifier refers to a type name within this scope, 318 /// return the declaration of that type. 319 /// 320 /// This routine performs ordinary name lookup of the identifier II 321 /// within the given scope, with optional C++ scope specifier SS, to 322 /// determine whether the name refers to a type. If so, returns an 323 /// opaque pointer (actually a QualType) corresponding to that 324 /// type. Otherwise, returns NULL. 325 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 326 Scope *S, CXXScopeSpec *SS, 327 bool isClassName, bool HasTrailingDot, 328 ParsedType ObjectTypePtr, 329 bool IsCtorOrDtorName, 330 bool WantNontrivialTypeSourceInfo, 331 bool IsClassTemplateDeductionContext, 332 IdentifierInfo **CorrectedII) { 333 // FIXME: Consider allowing this outside C++1z mode as an extension. 334 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 335 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 336 !isClassName && !HasTrailingDot; 337 338 // Determine where we will perform name lookup. 339 DeclContext *LookupCtx = nullptr; 340 if (ObjectTypePtr) { 341 QualType ObjectType = ObjectTypePtr.get(); 342 if (ObjectType->isRecordType()) 343 LookupCtx = computeDeclContext(ObjectType); 344 } else if (SS && SS->isNotEmpty()) { 345 LookupCtx = computeDeclContext(*SS, false); 346 347 if (!LookupCtx) { 348 if (isDependentScopeSpecifier(*SS)) { 349 // C++ [temp.res]p3: 350 // A qualified-id that refers to a type and in which the 351 // nested-name-specifier depends on a template-parameter (14.6.2) 352 // shall be prefixed by the keyword typename to indicate that the 353 // qualified-id denotes a type, forming an 354 // elaborated-type-specifier (7.1.5.3). 355 // 356 // We therefore do not perform any name lookup if the result would 357 // refer to a member of an unknown specialization. 358 if (!isClassName && !IsCtorOrDtorName) 359 return nullptr; 360 361 // We know from the grammar that this name refers to a type, 362 // so build a dependent node to describe the type. 363 if (WantNontrivialTypeSourceInfo) 364 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 365 366 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 367 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 368 II, NameLoc); 369 return ParsedType::make(T); 370 } 371 372 return nullptr; 373 } 374 375 if (!LookupCtx->isDependentContext() && 376 RequireCompleteDeclContext(*SS, LookupCtx)) 377 return nullptr; 378 } 379 380 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 381 // lookup for class-names. 382 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 383 LookupOrdinaryName; 384 LookupResult Result(*this, &II, NameLoc, Kind); 385 if (LookupCtx) { 386 // Perform "qualified" name lookup into the declaration context we 387 // computed, which is either the type of the base of a member access 388 // expression or the declaration context associated with a prior 389 // nested-name-specifier. 390 LookupQualifiedName(Result, LookupCtx); 391 392 if (ObjectTypePtr && Result.empty()) { 393 // C++ [basic.lookup.classref]p3: 394 // If the unqualified-id is ~type-name, the type-name is looked up 395 // in the context of the entire postfix-expression. If the type T of 396 // the object expression is of a class type C, the type-name is also 397 // looked up in the scope of class C. At least one of the lookups shall 398 // find a name that refers to (possibly cv-qualified) T. 399 LookupName(Result, S); 400 } 401 } else { 402 // Perform unqualified name lookup. 403 LookupName(Result, S); 404 405 // For unqualified lookup in a class template in MSVC mode, look into 406 // dependent base classes where the primary class template is known. 407 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 408 if (ParsedType TypeInBase = 409 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 410 return TypeInBase; 411 } 412 } 413 414 NamedDecl *IIDecl = nullptr; 415 UsingShadowDecl *FoundUsingShadow = nullptr; 416 switch (Result.getResultKind()) { 417 case LookupResult::NotFound: 418 case LookupResult::NotFoundInCurrentInstantiation: 419 if (CorrectedII) { 420 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 421 AllowDeducedTemplate); 422 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 423 S, SS, CCC, CTK_ErrorRecovery); 424 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 425 TemplateTy Template; 426 bool MemberOfUnknownSpecialization; 427 UnqualifiedId TemplateName; 428 TemplateName.setIdentifier(NewII, NameLoc); 429 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 430 CXXScopeSpec NewSS, *NewSSPtr = SS; 431 if (SS && NNS) { 432 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 433 NewSSPtr = &NewSS; 434 } 435 if (Correction && (NNS || NewII != &II) && 436 // Ignore a correction to a template type as the to-be-corrected 437 // identifier is not a template (typo correction for template names 438 // is handled elsewhere). 439 !(getLangOpts().CPlusPlus && NewSSPtr && 440 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 441 Template, MemberOfUnknownSpecialization))) { 442 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 443 isClassName, HasTrailingDot, ObjectTypePtr, 444 IsCtorOrDtorName, 445 WantNontrivialTypeSourceInfo, 446 IsClassTemplateDeductionContext); 447 if (Ty) { 448 diagnoseTypo(Correction, 449 PDiag(diag::err_unknown_type_or_class_name_suggest) 450 << Result.getLookupName() << isClassName); 451 if (SS && NNS) 452 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 453 *CorrectedII = NewII; 454 return Ty; 455 } 456 } 457 } 458 // If typo correction failed or was not performed, fall through 459 LLVM_FALLTHROUGH; 460 case LookupResult::FoundOverloaded: 461 case LookupResult::FoundUnresolvedValue: 462 Result.suppressDiagnostics(); 463 return nullptr; 464 465 case LookupResult::Ambiguous: 466 // Recover from type-hiding ambiguities by hiding the type. We'll 467 // do the lookup again when looking for an object, and we can 468 // diagnose the error then. If we don't do this, then the error 469 // about hiding the type will be immediately followed by an error 470 // that only makes sense if the identifier was treated like a type. 471 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 472 Result.suppressDiagnostics(); 473 return nullptr; 474 } 475 476 // Look to see if we have a type anywhere in the list of results. 477 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 478 Res != ResEnd; ++Res) { 479 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 480 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 481 RealRes) || 482 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 483 if (!IIDecl || 484 // Make the selection of the recovery decl deterministic. 485 RealRes->getLocation() < IIDecl->getLocation()) { 486 IIDecl = RealRes; 487 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); 488 } 489 } 490 } 491 492 if (!IIDecl) { 493 // None of the entities we found is a type, so there is no way 494 // to even assume that the result is a type. In this case, don't 495 // complain about the ambiguity. The parser will either try to 496 // perform this lookup again (e.g., as an object name), which 497 // will produce the ambiguity, or will complain that it expected 498 // a type name. 499 Result.suppressDiagnostics(); 500 return nullptr; 501 } 502 503 // We found a type within the ambiguous lookup; diagnose the 504 // ambiguity and then return that type. This might be the right 505 // answer, or it might not be, but it suppresses any attempt to 506 // perform the name lookup again. 507 break; 508 509 case LookupResult::Found: 510 IIDecl = Result.getFoundDecl(); 511 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); 512 break; 513 } 514 515 assert(IIDecl && "Didn't find decl"); 516 517 QualType T; 518 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 519 // C++ [class.qual]p2: A lookup that would find the injected-class-name 520 // instead names the constructors of the class, except when naming a class. 521 // This is ill-formed when we're not actually forming a ctor or dtor name. 522 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 523 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 524 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 525 FoundRD->isInjectedClassName() && 526 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 527 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 528 << &II << /*Type*/1; 529 530 DiagnoseUseOfDecl(IIDecl, NameLoc); 531 532 T = Context.getTypeDeclType(TD); 533 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 534 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 535 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 536 if (!HasTrailingDot) 537 T = Context.getObjCInterfaceType(IDecl); 538 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. 539 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 540 (void)DiagnoseUseOfDecl(UD, NameLoc); 541 // Recover with 'int' 542 return ParsedType::make(Context.IntTy); 543 } else if (AllowDeducedTemplate) { 544 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { 545 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); 546 TemplateName Template = 547 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 548 T = Context.getDeducedTemplateSpecializationType(Template, QualType(), 549 false); 550 // Don't wrap in a further UsingType. 551 FoundUsingShadow = nullptr; 552 } 553 } 554 555 if (T.isNull()) { 556 // If it's not plausibly a type, suppress diagnostics. 557 Result.suppressDiagnostics(); 558 return nullptr; 559 } 560 561 if (FoundUsingShadow) 562 T = Context.getUsingType(FoundUsingShadow, T); 563 564 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo); 565 } 566 567 // Builds a fake NNS for the given decl context. 568 static NestedNameSpecifier * 569 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 570 for (;; DC = DC->getLookupParent()) { 571 DC = DC->getPrimaryContext(); 572 auto *ND = dyn_cast<NamespaceDecl>(DC); 573 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 574 return NestedNameSpecifier::Create(Context, nullptr, ND); 575 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 576 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 577 RD->getTypeForDecl()); 578 else if (isa<TranslationUnitDecl>(DC)) 579 return NestedNameSpecifier::GlobalSpecifier(Context); 580 } 581 llvm_unreachable("something isn't in TU scope?"); 582 } 583 584 /// Find the parent class with dependent bases of the innermost enclosing method 585 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 586 /// up allowing unqualified dependent type names at class-level, which MSVC 587 /// correctly rejects. 588 static const CXXRecordDecl * 589 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 590 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 591 DC = DC->getPrimaryContext(); 592 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 593 if (MD->getParent()->hasAnyDependentBases()) 594 return MD->getParent(); 595 } 596 return nullptr; 597 } 598 599 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 600 SourceLocation NameLoc, 601 bool IsTemplateTypeArg) { 602 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 603 604 NestedNameSpecifier *NNS = nullptr; 605 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 606 // If we weren't able to parse a default template argument, delay lookup 607 // until instantiation time by making a non-dependent DependentTypeName. We 608 // pretend we saw a NestedNameSpecifier referring to the current scope, and 609 // lookup is retried. 610 // FIXME: This hurts our diagnostic quality, since we get errors like "no 611 // type named 'Foo' in 'current_namespace'" when the user didn't write any 612 // name specifiers. 613 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 614 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 615 } else if (const CXXRecordDecl *RD = 616 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 617 // Build a DependentNameType that will perform lookup into RD at 618 // instantiation time. 619 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 620 RD->getTypeForDecl()); 621 622 // Diagnose that this identifier was undeclared, and retry the lookup during 623 // template instantiation. 624 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 625 << RD; 626 } else { 627 // This is not a situation that we should recover from. 628 return ParsedType(); 629 } 630 631 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 632 633 // Build type location information. We synthesized the qualifier, so we have 634 // to build a fake NestedNameSpecifierLoc. 635 NestedNameSpecifierLocBuilder NNSLocBuilder; 636 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 637 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 638 639 TypeLocBuilder Builder; 640 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 641 DepTL.setNameLoc(NameLoc); 642 DepTL.setElaboratedKeywordLoc(SourceLocation()); 643 DepTL.setQualifierLoc(QualifierLoc); 644 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 645 } 646 647 /// isTagName() - This method is called *for error recovery purposes only* 648 /// to determine if the specified name is a valid tag name ("struct foo"). If 649 /// so, this returns the TST for the tag corresponding to it (TST_enum, 650 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 651 /// cases in C where the user forgot to specify the tag. 652 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 653 // Do a tag name lookup in this scope. 654 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 655 LookupName(R, S, false); 656 R.suppressDiagnostics(); 657 if (R.getResultKind() == LookupResult::Found) 658 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 659 switch (TD->getTagKind()) { 660 case TTK_Struct: return DeclSpec::TST_struct; 661 case TTK_Interface: return DeclSpec::TST_interface; 662 case TTK_Union: return DeclSpec::TST_union; 663 case TTK_Class: return DeclSpec::TST_class; 664 case TTK_Enum: return DeclSpec::TST_enum; 665 } 666 } 667 668 return DeclSpec::TST_unspecified; 669 } 670 671 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 672 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 673 /// then downgrade the missing typename error to a warning. 674 /// This is needed for MSVC compatibility; Example: 675 /// @code 676 /// template<class T> class A { 677 /// public: 678 /// typedef int TYPE; 679 /// }; 680 /// template<class T> class B : public A<T> { 681 /// public: 682 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 683 /// }; 684 /// @endcode 685 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 686 if (CurContext->isRecord()) { 687 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 688 return true; 689 690 const Type *Ty = SS->getScopeRep()->getAsType(); 691 692 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 693 for (const auto &Base : RD->bases()) 694 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 695 return true; 696 return S->isFunctionPrototypeScope(); 697 } 698 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 699 } 700 701 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 702 SourceLocation IILoc, 703 Scope *S, 704 CXXScopeSpec *SS, 705 ParsedType &SuggestedType, 706 bool IsTemplateName) { 707 // Don't report typename errors for editor placeholders. 708 if (II->isEditorPlaceholder()) 709 return; 710 // We don't have anything to suggest (yet). 711 SuggestedType = nullptr; 712 713 // There may have been a typo in the name of the type. Look up typo 714 // results, in case we have something that we can suggest. 715 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 716 /*AllowTemplates=*/IsTemplateName, 717 /*AllowNonTemplates=*/!IsTemplateName); 718 if (TypoCorrection Corrected = 719 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 720 CCC, CTK_ErrorRecovery)) { 721 // FIXME: Support error recovery for the template-name case. 722 bool CanRecover = !IsTemplateName; 723 if (Corrected.isKeyword()) { 724 // We corrected to a keyword. 725 diagnoseTypo(Corrected, 726 PDiag(IsTemplateName ? diag::err_no_template_suggest 727 : diag::err_unknown_typename_suggest) 728 << II); 729 II = Corrected.getCorrectionAsIdentifierInfo(); 730 } else { 731 // We found a similarly-named type or interface; suggest that. 732 if (!SS || !SS->isSet()) { 733 diagnoseTypo(Corrected, 734 PDiag(IsTemplateName ? diag::err_no_template_suggest 735 : diag::err_unknown_typename_suggest) 736 << II, CanRecover); 737 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 738 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 739 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 740 II->getName().equals(CorrectedStr); 741 diagnoseTypo(Corrected, 742 PDiag(IsTemplateName 743 ? diag::err_no_member_template_suggest 744 : diag::err_unknown_nested_typename_suggest) 745 << II << DC << DroppedSpecifier << SS->getRange(), 746 CanRecover); 747 } else { 748 llvm_unreachable("could not have corrected a typo here"); 749 } 750 751 if (!CanRecover) 752 return; 753 754 CXXScopeSpec tmpSS; 755 if (Corrected.getCorrectionSpecifier()) 756 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 757 SourceRange(IILoc)); 758 // FIXME: Support class template argument deduction here. 759 SuggestedType = 760 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 761 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 762 /*IsCtorOrDtorName=*/false, 763 /*WantNontrivialTypeSourceInfo=*/true); 764 } 765 return; 766 } 767 768 if (getLangOpts().CPlusPlus && !IsTemplateName) { 769 // See if II is a class template that the user forgot to pass arguments to. 770 UnqualifiedId Name; 771 Name.setIdentifier(II, IILoc); 772 CXXScopeSpec EmptySS; 773 TemplateTy TemplateResult; 774 bool MemberOfUnknownSpecialization; 775 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 776 Name, nullptr, true, TemplateResult, 777 MemberOfUnknownSpecialization) == TNK_Type_template) { 778 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 779 return; 780 } 781 } 782 783 // FIXME: Should we move the logic that tries to recover from a missing tag 784 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 785 786 if (!SS || (!SS->isSet() && !SS->isInvalid())) 787 Diag(IILoc, IsTemplateName ? diag::err_no_template 788 : diag::err_unknown_typename) 789 << II; 790 else if (DeclContext *DC = computeDeclContext(*SS, false)) 791 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 792 : diag::err_typename_nested_not_found) 793 << II << DC << SS->getRange(); 794 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 795 SuggestedType = 796 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 797 } else if (isDependentScopeSpecifier(*SS)) { 798 unsigned DiagID = diag::err_typename_missing; 799 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 800 DiagID = diag::ext_typename_missing; 801 802 Diag(SS->getRange().getBegin(), DiagID) 803 << SS->getScopeRep() << II->getName() 804 << SourceRange(SS->getRange().getBegin(), IILoc) 805 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 806 SuggestedType = ActOnTypenameType(S, SourceLocation(), 807 *SS, *II, IILoc).get(); 808 } else { 809 assert(SS && SS->isInvalid() && 810 "Invalid scope specifier has already been diagnosed"); 811 } 812 } 813 814 /// Determine whether the given result set contains either a type name 815 /// or 816 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 817 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 818 NextToken.is(tok::less); 819 820 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 821 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 822 return true; 823 824 if (CheckTemplate && isa<TemplateDecl>(*I)) 825 return true; 826 } 827 828 return false; 829 } 830 831 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 832 Scope *S, CXXScopeSpec &SS, 833 IdentifierInfo *&Name, 834 SourceLocation NameLoc) { 835 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 836 SemaRef.LookupParsedName(R, S, &SS); 837 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 838 StringRef FixItTagName; 839 switch (Tag->getTagKind()) { 840 case TTK_Class: 841 FixItTagName = "class "; 842 break; 843 844 case TTK_Enum: 845 FixItTagName = "enum "; 846 break; 847 848 case TTK_Struct: 849 FixItTagName = "struct "; 850 break; 851 852 case TTK_Interface: 853 FixItTagName = "__interface "; 854 break; 855 856 case TTK_Union: 857 FixItTagName = "union "; 858 break; 859 } 860 861 StringRef TagName = FixItTagName.drop_back(); 862 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 863 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 864 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 865 866 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 867 I != IEnd; ++I) 868 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 869 << Name << TagName; 870 871 // Replace lookup results with just the tag decl. 872 Result.clear(Sema::LookupTagName); 873 SemaRef.LookupParsedName(Result, S, &SS); 874 return true; 875 } 876 877 return false; 878 } 879 880 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 881 IdentifierInfo *&Name, 882 SourceLocation NameLoc, 883 const Token &NextToken, 884 CorrectionCandidateCallback *CCC) { 885 DeclarationNameInfo NameInfo(Name, NameLoc); 886 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 887 888 assert(NextToken.isNot(tok::coloncolon) && 889 "parse nested name specifiers before calling ClassifyName"); 890 if (getLangOpts().CPlusPlus && SS.isSet() && 891 isCurrentClassName(*Name, S, &SS)) { 892 // Per [class.qual]p2, this names the constructors of SS, not the 893 // injected-class-name. We don't have a classification for that. 894 // There's not much point caching this result, since the parser 895 // will reject it later. 896 return NameClassification::Unknown(); 897 } 898 899 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 900 LookupParsedName(Result, S, &SS, !CurMethod); 901 902 if (SS.isInvalid()) 903 return NameClassification::Error(); 904 905 // For unqualified lookup in a class template in MSVC mode, look into 906 // dependent base classes where the primary class template is known. 907 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 908 if (ParsedType TypeInBase = 909 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 910 return TypeInBase; 911 } 912 913 // Perform lookup for Objective-C instance variables (including automatically 914 // synthesized instance variables), if we're in an Objective-C method. 915 // FIXME: This lookup really, really needs to be folded in to the normal 916 // unqualified lookup mechanism. 917 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 918 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 919 if (Ivar.isInvalid()) 920 return NameClassification::Error(); 921 if (Ivar.isUsable()) 922 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 923 924 // We defer builtin creation until after ivar lookup inside ObjC methods. 925 if (Result.empty()) 926 LookupBuiltin(Result); 927 } 928 929 bool SecondTry = false; 930 bool IsFilteredTemplateName = false; 931 932 Corrected: 933 switch (Result.getResultKind()) { 934 case LookupResult::NotFound: 935 // If an unqualified-id is followed by a '(', then we have a function 936 // call. 937 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 938 // In C++, this is an ADL-only call. 939 // FIXME: Reference? 940 if (getLangOpts().CPlusPlus) 941 return NameClassification::UndeclaredNonType(); 942 943 // C90 6.3.2.2: 944 // If the expression that precedes the parenthesized argument list in a 945 // function call consists solely of an identifier, and if no 946 // declaration is visible for this identifier, the identifier is 947 // implicitly declared exactly as if, in the innermost block containing 948 // the function call, the declaration 949 // 950 // extern int identifier (); 951 // 952 // appeared. 953 // 954 // We also allow this in C99 as an extension. However, this is not 955 // allowed in all language modes as functions without prototypes may not 956 // be supported. 957 if (getLangOpts().implicitFunctionsAllowed()) { 958 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 959 return NameClassification::NonType(D); 960 } 961 } 962 963 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 964 // In C++20 onwards, this could be an ADL-only call to a function 965 // template, and we're required to assume that this is a template name. 966 // 967 // FIXME: Find a way to still do typo correction in this case. 968 TemplateName Template = 969 Context.getAssumedTemplateName(NameInfo.getName()); 970 return NameClassification::UndeclaredTemplate(Template); 971 } 972 973 // In C, we first see whether there is a tag type by the same name, in 974 // which case it's likely that the user just forgot to write "enum", 975 // "struct", or "union". 976 if (!getLangOpts().CPlusPlus && !SecondTry && 977 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 978 break; 979 } 980 981 // Perform typo correction to determine if there is another name that is 982 // close to this name. 983 if (!SecondTry && CCC) { 984 SecondTry = true; 985 if (TypoCorrection Corrected = 986 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 987 &SS, *CCC, CTK_ErrorRecovery)) { 988 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 989 unsigned QualifiedDiag = diag::err_no_member_suggest; 990 991 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 992 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 993 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 994 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 995 UnqualifiedDiag = diag::err_no_template_suggest; 996 QualifiedDiag = diag::err_no_member_template_suggest; 997 } else if (UnderlyingFirstDecl && 998 (isa<TypeDecl>(UnderlyingFirstDecl) || 999 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 1000 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 1001 UnqualifiedDiag = diag::err_unknown_typename_suggest; 1002 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 1003 } 1004 1005 if (SS.isEmpty()) { 1006 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 1007 } else {// FIXME: is this even reachable? Test it. 1008 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1009 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 1010 Name->getName().equals(CorrectedStr); 1011 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 1012 << Name << computeDeclContext(SS, false) 1013 << DroppedSpecifier << SS.getRange()); 1014 } 1015 1016 // Update the name, so that the caller has the new name. 1017 Name = Corrected.getCorrectionAsIdentifierInfo(); 1018 1019 // Typo correction corrected to a keyword. 1020 if (Corrected.isKeyword()) 1021 return Name; 1022 1023 // Also update the LookupResult... 1024 // FIXME: This should probably go away at some point 1025 Result.clear(); 1026 Result.setLookupName(Corrected.getCorrection()); 1027 if (FirstDecl) 1028 Result.addDecl(FirstDecl); 1029 1030 // If we found an Objective-C instance variable, let 1031 // LookupInObjCMethod build the appropriate expression to 1032 // reference the ivar. 1033 // FIXME: This is a gross hack. 1034 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1035 DeclResult R = 1036 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1037 if (R.isInvalid()) 1038 return NameClassification::Error(); 1039 if (R.isUsable()) 1040 return NameClassification::NonType(Ivar); 1041 } 1042 1043 goto Corrected; 1044 } 1045 } 1046 1047 // We failed to correct; just fall through and let the parser deal with it. 1048 Result.suppressDiagnostics(); 1049 return NameClassification::Unknown(); 1050 1051 case LookupResult::NotFoundInCurrentInstantiation: { 1052 // We performed name lookup into the current instantiation, and there were 1053 // dependent bases, so we treat this result the same way as any other 1054 // dependent nested-name-specifier. 1055 1056 // C++ [temp.res]p2: 1057 // A name used in a template declaration or definition and that is 1058 // dependent on a template-parameter is assumed not to name a type 1059 // unless the applicable name lookup finds a type name or the name is 1060 // qualified by the keyword typename. 1061 // 1062 // FIXME: If the next token is '<', we might want to ask the parser to 1063 // perform some heroics to see if we actually have a 1064 // template-argument-list, which would indicate a missing 'template' 1065 // keyword here. 1066 return NameClassification::DependentNonType(); 1067 } 1068 1069 case LookupResult::Found: 1070 case LookupResult::FoundOverloaded: 1071 case LookupResult::FoundUnresolvedValue: 1072 break; 1073 1074 case LookupResult::Ambiguous: 1075 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1076 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1077 /*AllowDependent=*/false)) { 1078 // C++ [temp.local]p3: 1079 // A lookup that finds an injected-class-name (10.2) can result in an 1080 // ambiguity in certain cases (for example, if it is found in more than 1081 // one base class). If all of the injected-class-names that are found 1082 // refer to specializations of the same class template, and if the name 1083 // is followed by a template-argument-list, the reference refers to the 1084 // class template itself and not a specialization thereof, and is not 1085 // ambiguous. 1086 // 1087 // This filtering can make an ambiguous result into an unambiguous one, 1088 // so try again after filtering out template names. 1089 FilterAcceptableTemplateNames(Result); 1090 if (!Result.isAmbiguous()) { 1091 IsFilteredTemplateName = true; 1092 break; 1093 } 1094 } 1095 1096 // Diagnose the ambiguity and return an error. 1097 return NameClassification::Error(); 1098 } 1099 1100 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1101 (IsFilteredTemplateName || 1102 hasAnyAcceptableTemplateNames( 1103 Result, /*AllowFunctionTemplates=*/true, 1104 /*AllowDependent=*/false, 1105 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1106 getLangOpts().CPlusPlus20))) { 1107 // C++ [temp.names]p3: 1108 // After name lookup (3.4) finds that a name is a template-name or that 1109 // an operator-function-id or a literal- operator-id refers to a set of 1110 // overloaded functions any member of which is a function template if 1111 // this is followed by a <, the < is always taken as the delimiter of a 1112 // template-argument-list and never as the less-than operator. 1113 // C++2a [temp.names]p2: 1114 // A name is also considered to refer to a template if it is an 1115 // unqualified-id followed by a < and name lookup finds either one 1116 // or more functions or finds nothing. 1117 if (!IsFilteredTemplateName) 1118 FilterAcceptableTemplateNames(Result); 1119 1120 bool IsFunctionTemplate; 1121 bool IsVarTemplate; 1122 TemplateName Template; 1123 if (Result.end() - Result.begin() > 1) { 1124 IsFunctionTemplate = true; 1125 Template = Context.getOverloadedTemplateName(Result.begin(), 1126 Result.end()); 1127 } else if (!Result.empty()) { 1128 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1129 *Result.begin(), /*AllowFunctionTemplates=*/true, 1130 /*AllowDependent=*/false)); 1131 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1132 IsVarTemplate = isa<VarTemplateDecl>(TD); 1133 1134 UsingShadowDecl *FoundUsingShadow = 1135 dyn_cast<UsingShadowDecl>(*Result.begin()); 1136 assert(!FoundUsingShadow || 1137 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())); 1138 Template = 1139 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 1140 if (SS.isNotEmpty()) 1141 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1142 /*TemplateKeyword=*/false, 1143 Template); 1144 } else { 1145 // All results were non-template functions. This is a function template 1146 // name. 1147 IsFunctionTemplate = true; 1148 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1149 } 1150 1151 if (IsFunctionTemplate) { 1152 // Function templates always go through overload resolution, at which 1153 // point we'll perform the various checks (e.g., accessibility) we need 1154 // to based on which function we selected. 1155 Result.suppressDiagnostics(); 1156 1157 return NameClassification::FunctionTemplate(Template); 1158 } 1159 1160 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1161 : NameClassification::TypeTemplate(Template); 1162 } 1163 1164 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { 1165 QualType T = Context.getTypeDeclType(Type); 1166 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) 1167 T = Context.getUsingType(USD, T); 1168 return buildNamedType(*this, &SS, T, NameLoc); 1169 }; 1170 1171 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1172 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1173 DiagnoseUseOfDecl(Type, NameLoc); 1174 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1175 return BuildTypeFor(Type, *Result.begin()); 1176 } 1177 1178 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1179 if (!Class) { 1180 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1181 if (ObjCCompatibleAliasDecl *Alias = 1182 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1183 Class = Alias->getClassInterface(); 1184 } 1185 1186 if (Class) { 1187 DiagnoseUseOfDecl(Class, NameLoc); 1188 1189 if (NextToken.is(tok::period)) { 1190 // Interface. <something> is parsed as a property reference expression. 1191 // Just return "unknown" as a fall-through for now. 1192 Result.suppressDiagnostics(); 1193 return NameClassification::Unknown(); 1194 } 1195 1196 QualType T = Context.getObjCInterfaceType(Class); 1197 return ParsedType::make(T); 1198 } 1199 1200 if (isa<ConceptDecl>(FirstDecl)) 1201 return NameClassification::Concept( 1202 TemplateName(cast<TemplateDecl>(FirstDecl))); 1203 1204 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1205 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1206 return NameClassification::Error(); 1207 } 1208 1209 // We can have a type template here if we're classifying a template argument. 1210 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1211 !isa<VarTemplateDecl>(FirstDecl)) 1212 return NameClassification::TypeTemplate( 1213 TemplateName(cast<TemplateDecl>(FirstDecl))); 1214 1215 // Check for a tag type hidden by a non-type decl in a few cases where it 1216 // seems likely a type is wanted instead of the non-type that was found. 1217 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1218 if ((NextToken.is(tok::identifier) || 1219 (NextIsOp && 1220 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1221 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1222 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1223 DiagnoseUseOfDecl(Type, NameLoc); 1224 return BuildTypeFor(Type, *Result.begin()); 1225 } 1226 1227 // If we already know which single declaration is referenced, just annotate 1228 // that declaration directly. Defer resolving even non-overloaded class 1229 // member accesses, as we need to defer certain access checks until we know 1230 // the context. 1231 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1232 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1233 return NameClassification::NonType(Result.getRepresentativeDecl()); 1234 1235 // Otherwise, this is an overload set that we will need to resolve later. 1236 Result.suppressDiagnostics(); 1237 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1238 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1239 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1240 Result.begin(), Result.end())); 1241 } 1242 1243 ExprResult 1244 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1245 SourceLocation NameLoc) { 1246 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1247 CXXScopeSpec SS; 1248 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1249 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1250 } 1251 1252 ExprResult 1253 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1254 IdentifierInfo *Name, 1255 SourceLocation NameLoc, 1256 bool IsAddressOfOperand) { 1257 DeclarationNameInfo NameInfo(Name, NameLoc); 1258 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1259 NameInfo, IsAddressOfOperand, 1260 /*TemplateArgs=*/nullptr); 1261 } 1262 1263 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1264 NamedDecl *Found, 1265 SourceLocation NameLoc, 1266 const Token &NextToken) { 1267 if (getCurMethodDecl() && SS.isEmpty()) 1268 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1269 return BuildIvarRefExpr(S, NameLoc, Ivar); 1270 1271 // Reconstruct the lookup result. 1272 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1273 Result.addDecl(Found); 1274 Result.resolveKind(); 1275 1276 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1277 return BuildDeclarationNameExpr(SS, Result, ADL); 1278 } 1279 1280 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1281 // For an implicit class member access, transform the result into a member 1282 // access expression if necessary. 1283 auto *ULE = cast<UnresolvedLookupExpr>(E); 1284 if ((*ULE->decls_begin())->isCXXClassMember()) { 1285 CXXScopeSpec SS; 1286 SS.Adopt(ULE->getQualifierLoc()); 1287 1288 // Reconstruct the lookup result. 1289 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1290 LookupOrdinaryName); 1291 Result.setNamingClass(ULE->getNamingClass()); 1292 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1293 Result.addDecl(*I, I.getAccess()); 1294 Result.resolveKind(); 1295 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1296 nullptr, S); 1297 } 1298 1299 // Otherwise, this is already in the form we needed, and no further checks 1300 // are necessary. 1301 return ULE; 1302 } 1303 1304 Sema::TemplateNameKindForDiagnostics 1305 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1306 auto *TD = Name.getAsTemplateDecl(); 1307 if (!TD) 1308 return TemplateNameKindForDiagnostics::DependentTemplate; 1309 if (isa<ClassTemplateDecl>(TD)) 1310 return TemplateNameKindForDiagnostics::ClassTemplate; 1311 if (isa<FunctionTemplateDecl>(TD)) 1312 return TemplateNameKindForDiagnostics::FunctionTemplate; 1313 if (isa<VarTemplateDecl>(TD)) 1314 return TemplateNameKindForDiagnostics::VarTemplate; 1315 if (isa<TypeAliasTemplateDecl>(TD)) 1316 return TemplateNameKindForDiagnostics::AliasTemplate; 1317 if (isa<TemplateTemplateParmDecl>(TD)) 1318 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1319 if (isa<ConceptDecl>(TD)) 1320 return TemplateNameKindForDiagnostics::Concept; 1321 return TemplateNameKindForDiagnostics::DependentTemplate; 1322 } 1323 1324 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1325 assert(DC->getLexicalParent() == CurContext && 1326 "The next DeclContext should be lexically contained in the current one."); 1327 CurContext = DC; 1328 S->setEntity(DC); 1329 } 1330 1331 void Sema::PopDeclContext() { 1332 assert(CurContext && "DeclContext imbalance!"); 1333 1334 CurContext = CurContext->getLexicalParent(); 1335 assert(CurContext && "Popped translation unit!"); 1336 } 1337 1338 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1339 Decl *D) { 1340 // Unlike PushDeclContext, the context to which we return is not necessarily 1341 // the containing DC of TD, because the new context will be some pre-existing 1342 // TagDecl definition instead of a fresh one. 1343 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1344 CurContext = cast<TagDecl>(D)->getDefinition(); 1345 assert(CurContext && "skipping definition of undefined tag"); 1346 // Start lookups from the parent of the current context; we don't want to look 1347 // into the pre-existing complete definition. 1348 S->setEntity(CurContext->getLookupParent()); 1349 return Result; 1350 } 1351 1352 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1353 CurContext = static_cast<decltype(CurContext)>(Context); 1354 } 1355 1356 /// EnterDeclaratorContext - Used when we must lookup names in the context 1357 /// of a declarator's nested name specifier. 1358 /// 1359 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1360 // C++0x [basic.lookup.unqual]p13: 1361 // A name used in the definition of a static data member of class 1362 // X (after the qualified-id of the static member) is looked up as 1363 // if the name was used in a member function of X. 1364 // C++0x [basic.lookup.unqual]p14: 1365 // If a variable member of a namespace is defined outside of the 1366 // scope of its namespace then any name used in the definition of 1367 // the variable member (after the declarator-id) is looked up as 1368 // if the definition of the variable member occurred in its 1369 // namespace. 1370 // Both of these imply that we should push a scope whose context 1371 // is the semantic context of the declaration. We can't use 1372 // PushDeclContext here because that context is not necessarily 1373 // lexically contained in the current context. Fortunately, 1374 // the containing scope should have the appropriate information. 1375 1376 assert(!S->getEntity() && "scope already has entity"); 1377 1378 #ifndef NDEBUG 1379 Scope *Ancestor = S->getParent(); 1380 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1381 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1382 #endif 1383 1384 CurContext = DC; 1385 S->setEntity(DC); 1386 1387 if (S->getParent()->isTemplateParamScope()) { 1388 // Also set the corresponding entities for all immediately-enclosing 1389 // template parameter scopes. 1390 EnterTemplatedContext(S->getParent(), DC); 1391 } 1392 } 1393 1394 void Sema::ExitDeclaratorContext(Scope *S) { 1395 assert(S->getEntity() == CurContext && "Context imbalance!"); 1396 1397 // Switch back to the lexical context. The safety of this is 1398 // enforced by an assert in EnterDeclaratorContext. 1399 Scope *Ancestor = S->getParent(); 1400 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1401 CurContext = Ancestor->getEntity(); 1402 1403 // We don't need to do anything with the scope, which is going to 1404 // disappear. 1405 } 1406 1407 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1408 assert(S->isTemplateParamScope() && 1409 "expected to be initializing a template parameter scope"); 1410 1411 // C++20 [temp.local]p7: 1412 // In the definition of a member of a class template that appears outside 1413 // of the class template definition, the name of a member of the class 1414 // template hides the name of a template-parameter of any enclosing class 1415 // templates (but not a template-parameter of the member if the member is a 1416 // class or function template). 1417 // C++20 [temp.local]p9: 1418 // In the definition of a class template or in the definition of a member 1419 // of such a template that appears outside of the template definition, for 1420 // each non-dependent base class (13.8.2.1), if the name of the base class 1421 // or the name of a member of the base class is the same as the name of a 1422 // template-parameter, the base class name or member name hides the 1423 // template-parameter name (6.4.10). 1424 // 1425 // This means that a template parameter scope should be searched immediately 1426 // after searching the DeclContext for which it is a template parameter 1427 // scope. For example, for 1428 // template<typename T> template<typename U> template<typename V> 1429 // void N::A<T>::B<U>::f(...) 1430 // we search V then B<U> (and base classes) then U then A<T> (and base 1431 // classes) then T then N then ::. 1432 unsigned ScopeDepth = getTemplateDepth(S); 1433 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1434 DeclContext *SearchDCAfterScope = DC; 1435 for (; DC; DC = DC->getLookupParent()) { 1436 if (const TemplateParameterList *TPL = 1437 cast<Decl>(DC)->getDescribedTemplateParams()) { 1438 unsigned DCDepth = TPL->getDepth() + 1; 1439 if (DCDepth > ScopeDepth) 1440 continue; 1441 if (ScopeDepth == DCDepth) 1442 SearchDCAfterScope = DC = DC->getLookupParent(); 1443 break; 1444 } 1445 } 1446 S->setLookupEntity(SearchDCAfterScope); 1447 } 1448 } 1449 1450 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1451 // We assume that the caller has already called 1452 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1453 FunctionDecl *FD = D->getAsFunction(); 1454 if (!FD) 1455 return; 1456 1457 // Same implementation as PushDeclContext, but enters the context 1458 // from the lexical parent, rather than the top-level class. 1459 assert(CurContext == FD->getLexicalParent() && 1460 "The next DeclContext should be lexically contained in the current one."); 1461 CurContext = FD; 1462 S->setEntity(CurContext); 1463 1464 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1465 ParmVarDecl *Param = FD->getParamDecl(P); 1466 // If the parameter has an identifier, then add it to the scope 1467 if (Param->getIdentifier()) { 1468 S->AddDecl(Param); 1469 IdResolver.AddDecl(Param); 1470 } 1471 } 1472 } 1473 1474 void Sema::ActOnExitFunctionContext() { 1475 // Same implementation as PopDeclContext, but returns to the lexical parent, 1476 // rather than the top-level class. 1477 assert(CurContext && "DeclContext imbalance!"); 1478 CurContext = CurContext->getLexicalParent(); 1479 assert(CurContext && "Popped translation unit!"); 1480 } 1481 1482 /// Determine whether overloading is allowed for a new function 1483 /// declaration considering prior declarations of the same name. 1484 /// 1485 /// This routine determines whether overloading is possible, not 1486 /// whether a new declaration actually overloads a previous one. 1487 /// It will return true in C++ (where overloads are alway permitted) 1488 /// or, as a C extension, when either the new declaration or a 1489 /// previous one is declared with the 'overloadable' attribute. 1490 static bool AllowOverloadingOfFunction(const LookupResult &Previous, 1491 ASTContext &Context, 1492 const FunctionDecl *New) { 1493 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>()) 1494 return true; 1495 1496 // Multiversion function declarations are not overloads in the 1497 // usual sense of that term, but lookup will report that an 1498 // overload set was found if more than one multiversion function 1499 // declaration is present for the same name. It is therefore 1500 // inadequate to assume that some prior declaration(s) had 1501 // the overloadable attribute; checking is required. Since one 1502 // declaration is permitted to omit the attribute, it is necessary 1503 // to check at least two; hence the 'any_of' check below. Note that 1504 // the overloadable attribute is implicitly added to declarations 1505 // that were required to have it but did not. 1506 if (Previous.getResultKind() == LookupResult::FoundOverloaded) { 1507 return llvm::any_of(Previous, [](const NamedDecl *ND) { 1508 return ND->hasAttr<OverloadableAttr>(); 1509 }); 1510 } else if (Previous.getResultKind() == LookupResult::Found) 1511 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>(); 1512 1513 return false; 1514 } 1515 1516 /// Add this decl to the scope shadowed decl chains. 1517 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1518 // Move up the scope chain until we find the nearest enclosing 1519 // non-transparent context. The declaration will be introduced into this 1520 // scope. 1521 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1522 S = S->getParent(); 1523 1524 // Add scoped declarations into their context, so that they can be 1525 // found later. Declarations without a context won't be inserted 1526 // into any context. 1527 if (AddToContext) 1528 CurContext->addDecl(D); 1529 1530 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1531 // are function-local declarations. 1532 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1533 return; 1534 1535 // Template instantiations should also not be pushed into scope. 1536 if (isa<FunctionDecl>(D) && 1537 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1538 return; 1539 1540 // If this replaces anything in the current scope, 1541 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1542 IEnd = IdResolver.end(); 1543 for (; I != IEnd; ++I) { 1544 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1545 S->RemoveDecl(*I); 1546 IdResolver.RemoveDecl(*I); 1547 1548 // Should only need to replace one decl. 1549 break; 1550 } 1551 } 1552 1553 S->AddDecl(D); 1554 1555 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1556 // Implicitly-generated labels may end up getting generated in an order that 1557 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1558 // the label at the appropriate place in the identifier chain. 1559 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1560 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1561 if (IDC == CurContext) { 1562 if (!S->isDeclScope(*I)) 1563 continue; 1564 } else if (IDC->Encloses(CurContext)) 1565 break; 1566 } 1567 1568 IdResolver.InsertDeclAfter(I, D); 1569 } else { 1570 IdResolver.AddDecl(D); 1571 } 1572 warnOnReservedIdentifier(D); 1573 } 1574 1575 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1576 bool AllowInlineNamespace) { 1577 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1578 } 1579 1580 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1581 DeclContext *TargetDC = DC->getPrimaryContext(); 1582 do { 1583 if (DeclContext *ScopeDC = S->getEntity()) 1584 if (ScopeDC->getPrimaryContext() == TargetDC) 1585 return S; 1586 } while ((S = S->getParent())); 1587 1588 return nullptr; 1589 } 1590 1591 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1592 DeclContext*, 1593 ASTContext&); 1594 1595 /// Filters out lookup results that don't fall within the given scope 1596 /// as determined by isDeclInScope. 1597 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1598 bool ConsiderLinkage, 1599 bool AllowInlineNamespace) { 1600 LookupResult::Filter F = R.makeFilter(); 1601 while (F.hasNext()) { 1602 NamedDecl *D = F.next(); 1603 1604 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1605 continue; 1606 1607 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1608 continue; 1609 1610 F.erase(); 1611 } 1612 1613 F.done(); 1614 } 1615 1616 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1617 /// have compatible owning modules. 1618 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1619 // [module.interface]p7: 1620 // A declaration is attached to a module as follows: 1621 // - If the declaration is a non-dependent friend declaration that nominates a 1622 // function with a declarator-id that is a qualified-id or template-id or that 1623 // nominates a class other than with an elaborated-type-specifier with neither 1624 // a nested-name-specifier nor a simple-template-id, it is attached to the 1625 // module to which the friend is attached ([basic.link]). 1626 if (New->getFriendObjectKind() && 1627 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1628 New->setLocalOwningModule(Old->getOwningModule()); 1629 makeMergedDefinitionVisible(New); 1630 return false; 1631 } 1632 1633 Module *NewM = New->getOwningModule(); 1634 Module *OldM = Old->getOwningModule(); 1635 1636 if (NewM && NewM->isPrivateModule()) 1637 NewM = NewM->Parent; 1638 if (OldM && OldM->isPrivateModule()) 1639 OldM = OldM->Parent; 1640 1641 if (NewM == OldM) 1642 return false; 1643 1644 // Partitions are part of the module, but a partition could import another 1645 // module, so verify that the PMIs agree. 1646 if (NewM && OldM && (NewM->isModulePartition() || OldM->isModulePartition())) 1647 return NewM->getPrimaryModuleInterfaceName() == 1648 OldM->getPrimaryModuleInterfaceName(); 1649 1650 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1651 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1652 if (NewIsModuleInterface || OldIsModuleInterface) { 1653 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1654 // if a declaration of D [...] appears in the purview of a module, all 1655 // other such declarations shall appear in the purview of the same module 1656 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1657 << New 1658 << NewIsModuleInterface 1659 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1660 << OldIsModuleInterface 1661 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1662 Diag(Old->getLocation(), diag::note_previous_declaration); 1663 New->setInvalidDecl(); 1664 return true; 1665 } 1666 1667 return false; 1668 } 1669 1670 // [module.interface]p6: 1671 // A redeclaration of an entity X is implicitly exported if X was introduced by 1672 // an exported declaration; otherwise it shall not be exported. 1673 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { 1674 // [module.interface]p1: 1675 // An export-declaration shall inhabit a namespace scope. 1676 // 1677 // So it is meaningless to talk about redeclaration which is not at namespace 1678 // scope. 1679 if (!New->getLexicalDeclContext() 1680 ->getNonTransparentContext() 1681 ->isFileContext() || 1682 !Old->getLexicalDeclContext() 1683 ->getNonTransparentContext() 1684 ->isFileContext()) 1685 return false; 1686 1687 bool IsNewExported = New->isInExportDeclContext(); 1688 bool IsOldExported = Old->isInExportDeclContext(); 1689 1690 // It should be irrevelant if both of them are not exported. 1691 if (!IsNewExported && !IsOldExported) 1692 return false; 1693 1694 if (IsOldExported) 1695 return false; 1696 1697 assert(IsNewExported); 1698 1699 auto Lk = Old->getFormalLinkage(); 1700 int S = 0; 1701 if (Lk == Linkage::InternalLinkage) 1702 S = 1; 1703 else if (Lk == Linkage::ModuleLinkage) 1704 S = 2; 1705 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S; 1706 Diag(Old->getLocation(), diag::note_previous_declaration); 1707 return true; 1708 } 1709 1710 // A wrapper function for checking the semantic restrictions of 1711 // a redeclaration within a module. 1712 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1713 if (CheckRedeclarationModuleOwnership(New, Old)) 1714 return true; 1715 1716 if (CheckRedeclarationExported(New, Old)) 1717 return true; 1718 1719 return false; 1720 } 1721 1722 static bool isUsingDecl(NamedDecl *D) { 1723 return isa<UsingShadowDecl>(D) || 1724 isa<UnresolvedUsingTypenameDecl>(D) || 1725 isa<UnresolvedUsingValueDecl>(D); 1726 } 1727 1728 /// Removes using shadow declarations from the lookup results. 1729 static void RemoveUsingDecls(LookupResult &R) { 1730 LookupResult::Filter F = R.makeFilter(); 1731 while (F.hasNext()) 1732 if (isUsingDecl(F.next())) 1733 F.erase(); 1734 1735 F.done(); 1736 } 1737 1738 /// Check for this common pattern: 1739 /// @code 1740 /// class S { 1741 /// S(const S&); // DO NOT IMPLEMENT 1742 /// void operator=(const S&); // DO NOT IMPLEMENT 1743 /// }; 1744 /// @endcode 1745 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1746 // FIXME: Should check for private access too but access is set after we get 1747 // the decl here. 1748 if (D->doesThisDeclarationHaveABody()) 1749 return false; 1750 1751 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1752 return CD->isCopyConstructor(); 1753 return D->isCopyAssignmentOperator(); 1754 } 1755 1756 // We need this to handle 1757 // 1758 // typedef struct { 1759 // void *foo() { return 0; } 1760 // } A; 1761 // 1762 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1763 // for example. If 'A', foo will have external linkage. If we have '*A', 1764 // foo will have no linkage. Since we can't know until we get to the end 1765 // of the typedef, this function finds out if D might have non-external linkage. 1766 // Callers should verify at the end of the TU if it D has external linkage or 1767 // not. 1768 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1769 const DeclContext *DC = D->getDeclContext(); 1770 while (!DC->isTranslationUnit()) { 1771 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1772 if (!RD->hasNameForLinkage()) 1773 return true; 1774 } 1775 DC = DC->getParent(); 1776 } 1777 1778 return !D->isExternallyVisible(); 1779 } 1780 1781 // FIXME: This needs to be refactored; some other isInMainFile users want 1782 // these semantics. 1783 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1784 if (S.TUKind != TU_Complete) 1785 return false; 1786 return S.SourceMgr.isInMainFile(Loc); 1787 } 1788 1789 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1790 assert(D); 1791 1792 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1793 return false; 1794 1795 // Ignore all entities declared within templates, and out-of-line definitions 1796 // of members of class templates. 1797 if (D->getDeclContext()->isDependentContext() || 1798 D->getLexicalDeclContext()->isDependentContext()) 1799 return false; 1800 1801 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1802 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1803 return false; 1804 // A non-out-of-line declaration of a member specialization was implicitly 1805 // instantiated; it's the out-of-line declaration that we're interested in. 1806 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1807 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1808 return false; 1809 1810 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1811 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1812 return false; 1813 } else { 1814 // 'static inline' functions are defined in headers; don't warn. 1815 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1816 return false; 1817 } 1818 1819 if (FD->doesThisDeclarationHaveABody() && 1820 Context.DeclMustBeEmitted(FD)) 1821 return false; 1822 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1823 // Constants and utility variables are defined in headers with internal 1824 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1825 // like "inline".) 1826 if (!isMainFileLoc(*this, VD->getLocation())) 1827 return false; 1828 1829 if (Context.DeclMustBeEmitted(VD)) 1830 return false; 1831 1832 if (VD->isStaticDataMember() && 1833 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1834 return false; 1835 if (VD->isStaticDataMember() && 1836 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1837 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1838 return false; 1839 1840 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1841 return false; 1842 } else { 1843 return false; 1844 } 1845 1846 // Only warn for unused decls internal to the translation unit. 1847 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1848 // for inline functions defined in the main source file, for instance. 1849 return mightHaveNonExternalLinkage(D); 1850 } 1851 1852 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1853 if (!D) 1854 return; 1855 1856 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1857 const FunctionDecl *First = FD->getFirstDecl(); 1858 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1859 return; // First should already be in the vector. 1860 } 1861 1862 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1863 const VarDecl *First = VD->getFirstDecl(); 1864 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1865 return; // First should already be in the vector. 1866 } 1867 1868 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1869 UnusedFileScopedDecls.push_back(D); 1870 } 1871 1872 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1873 if (D->isInvalidDecl()) 1874 return false; 1875 1876 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1877 // For a decomposition declaration, warn if none of the bindings are 1878 // referenced, instead of if the variable itself is referenced (which 1879 // it is, by the bindings' expressions). 1880 for (auto *BD : DD->bindings()) 1881 if (BD->isReferenced()) 1882 return false; 1883 } else if (!D->getDeclName()) { 1884 return false; 1885 } else if (D->isReferenced() || D->isUsed()) { 1886 return false; 1887 } 1888 1889 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1890 return false; 1891 1892 if (isa<LabelDecl>(D)) 1893 return true; 1894 1895 // Except for labels, we only care about unused decls that are local to 1896 // functions. 1897 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1898 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1899 // For dependent types, the diagnostic is deferred. 1900 WithinFunction = 1901 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1902 if (!WithinFunction) 1903 return false; 1904 1905 if (isa<TypedefNameDecl>(D)) 1906 return true; 1907 1908 // White-list anything that isn't a local variable. 1909 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1910 return false; 1911 1912 // Types of valid local variables should be complete, so this should succeed. 1913 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1914 1915 const Expr *Init = VD->getInit(); 1916 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init)) 1917 Init = Cleanups->getSubExpr(); 1918 1919 const auto *Ty = VD->getType().getTypePtr(); 1920 1921 // Only look at the outermost level of typedef. 1922 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1923 // Allow anything marked with __attribute__((unused)). 1924 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1925 return false; 1926 } 1927 1928 // Warn for reference variables whose initializtion performs lifetime 1929 // extension. 1930 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) { 1931 if (MTE->getExtendingDecl()) { 1932 Ty = VD->getType().getNonReferenceType().getTypePtr(); 1933 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten(); 1934 } 1935 } 1936 1937 // If we failed to complete the type for some reason, or if the type is 1938 // dependent, don't diagnose the variable. 1939 if (Ty->isIncompleteType() || Ty->isDependentType()) 1940 return false; 1941 1942 // Look at the element type to ensure that the warning behaviour is 1943 // consistent for both scalars and arrays. 1944 Ty = Ty->getBaseElementTypeUnsafe(); 1945 1946 if (const TagType *TT = Ty->getAs<TagType>()) { 1947 const TagDecl *Tag = TT->getDecl(); 1948 if (Tag->hasAttr<UnusedAttr>()) 1949 return false; 1950 1951 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1952 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1953 return false; 1954 1955 if (Init) { 1956 const CXXConstructExpr *Construct = 1957 dyn_cast<CXXConstructExpr>(Init); 1958 if (Construct && !Construct->isElidable()) { 1959 CXXConstructorDecl *CD = Construct->getConstructor(); 1960 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1961 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1962 return false; 1963 } 1964 1965 // Suppress the warning if we don't know how this is constructed, and 1966 // it could possibly be non-trivial constructor. 1967 if (Init->isTypeDependent()) { 1968 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1969 if (!Ctor->isTrivial()) 1970 return false; 1971 } 1972 1973 // Suppress the warning if the constructor is unresolved because 1974 // its arguments are dependent. 1975 if (isa<CXXUnresolvedConstructExpr>(Init)) 1976 return false; 1977 } 1978 } 1979 } 1980 1981 // TODO: __attribute__((unused)) templates? 1982 } 1983 1984 return true; 1985 } 1986 1987 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1988 FixItHint &Hint) { 1989 if (isa<LabelDecl>(D)) { 1990 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1991 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1992 true); 1993 if (AfterColon.isInvalid()) 1994 return; 1995 Hint = FixItHint::CreateRemoval( 1996 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1997 } 1998 } 1999 2000 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 2001 if (D->getTypeForDecl()->isDependentType()) 2002 return; 2003 2004 for (auto *TmpD : D->decls()) { 2005 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 2006 DiagnoseUnusedDecl(T); 2007 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 2008 DiagnoseUnusedNestedTypedefs(R); 2009 } 2010 } 2011 2012 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 2013 /// unless they are marked attr(unused). 2014 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 2015 if (!ShouldDiagnoseUnusedDecl(D)) 2016 return; 2017 2018 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2019 // typedefs can be referenced later on, so the diagnostics are emitted 2020 // at end-of-translation-unit. 2021 UnusedLocalTypedefNameCandidates.insert(TD); 2022 return; 2023 } 2024 2025 FixItHint Hint; 2026 GenerateFixForUnusedDecl(D, Context, Hint); 2027 2028 unsigned DiagID; 2029 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 2030 DiagID = diag::warn_unused_exception_param; 2031 else if (isa<LabelDecl>(D)) 2032 DiagID = diag::warn_unused_label; 2033 else 2034 DiagID = diag::warn_unused_variable; 2035 2036 Diag(D->getLocation(), DiagID) << D << Hint; 2037 } 2038 2039 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 2040 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 2041 // it's not really unused. 2042 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 2043 VD->hasAttr<CleanupAttr>()) 2044 return; 2045 2046 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 2047 2048 if (Ty->isReferenceType() || Ty->isDependentType()) 2049 return; 2050 2051 if (const TagType *TT = Ty->getAs<TagType>()) { 2052 const TagDecl *Tag = TT->getDecl(); 2053 if (Tag->hasAttr<UnusedAttr>()) 2054 return; 2055 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 2056 // mimic gcc's behavior. 2057 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 2058 if (!RD->hasAttr<WarnUnusedAttr>()) 2059 return; 2060 } 2061 } 2062 2063 // Don't warn about __block Objective-C pointer variables, as they might 2064 // be assigned in the block but not used elsewhere for the purpose of lifetime 2065 // extension. 2066 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 2067 return; 2068 2069 // Don't warn about Objective-C pointer variables with precise lifetime 2070 // semantics; they can be used to ensure ARC releases the object at a known 2071 // time, which may mean assignment but no other references. 2072 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) 2073 return; 2074 2075 auto iter = RefsMinusAssignments.find(VD); 2076 if (iter == RefsMinusAssignments.end()) 2077 return; 2078 2079 assert(iter->getSecond() >= 0 && 2080 "Found a negative number of references to a VarDecl"); 2081 if (iter->getSecond() != 0) 2082 return; 2083 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2084 : diag::warn_unused_but_set_variable; 2085 Diag(VD->getLocation(), DiagID) << VD; 2086 } 2087 2088 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 2089 // Verify that we have no forward references left. If so, there was a goto 2090 // or address of a label taken, but no definition of it. Label fwd 2091 // definitions are indicated with a null substmt which is also not a resolved 2092 // MS inline assembly label name. 2093 bool Diagnose = false; 2094 if (L->isMSAsmLabel()) 2095 Diagnose = !L->isResolvedMSAsmLabel(); 2096 else 2097 Diagnose = L->getStmt() == nullptr; 2098 if (Diagnose) 2099 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 2100 } 2101 2102 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2103 S->mergeNRVOIntoParent(); 2104 2105 if (S->decl_empty()) return; 2106 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2107 "Scope shouldn't contain decls!"); 2108 2109 for (auto *TmpD : S->decls()) { 2110 assert(TmpD && "This decl didn't get pushed??"); 2111 2112 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2113 NamedDecl *D = cast<NamedDecl>(TmpD); 2114 2115 // Diagnose unused variables in this scope. 2116 if (!S->hasUnrecoverableErrorOccurred()) { 2117 DiagnoseUnusedDecl(D); 2118 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2119 DiagnoseUnusedNestedTypedefs(RD); 2120 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2121 DiagnoseUnusedButSetDecl(VD); 2122 RefsMinusAssignments.erase(VD); 2123 } 2124 } 2125 2126 if (!D->getDeclName()) continue; 2127 2128 // If this was a forward reference to a label, verify it was defined. 2129 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2130 CheckPoppedLabel(LD, *this); 2131 2132 // Remove this name from our lexical scope, and warn on it if we haven't 2133 // already. 2134 IdResolver.RemoveDecl(D); 2135 auto ShadowI = ShadowingDecls.find(D); 2136 if (ShadowI != ShadowingDecls.end()) { 2137 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2138 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2139 << D << FD << FD->getParent(); 2140 Diag(FD->getLocation(), diag::note_previous_declaration); 2141 } 2142 ShadowingDecls.erase(ShadowI); 2143 } 2144 } 2145 } 2146 2147 /// Look for an Objective-C class in the translation unit. 2148 /// 2149 /// \param Id The name of the Objective-C class we're looking for. If 2150 /// typo-correction fixes this name, the Id will be updated 2151 /// to the fixed name. 2152 /// 2153 /// \param IdLoc The location of the name in the translation unit. 2154 /// 2155 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2156 /// if there is no class with the given name. 2157 /// 2158 /// \returns The declaration of the named Objective-C class, or NULL if the 2159 /// class could not be found. 2160 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2161 SourceLocation IdLoc, 2162 bool DoTypoCorrection) { 2163 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2164 // creation from this context. 2165 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2166 2167 if (!IDecl && DoTypoCorrection) { 2168 // Perform typo correction at the given location, but only if we 2169 // find an Objective-C class name. 2170 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2171 if (TypoCorrection C = 2172 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2173 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2174 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2175 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2176 Id = IDecl->getIdentifier(); 2177 } 2178 } 2179 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2180 // This routine must always return a class definition, if any. 2181 if (Def && Def->getDefinition()) 2182 Def = Def->getDefinition(); 2183 return Def; 2184 } 2185 2186 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2187 /// from S, where a non-field would be declared. This routine copes 2188 /// with the difference between C and C++ scoping rules in structs and 2189 /// unions. For example, the following code is well-formed in C but 2190 /// ill-formed in C++: 2191 /// @code 2192 /// struct S6 { 2193 /// enum { BAR } e; 2194 /// }; 2195 /// 2196 /// void test_S6() { 2197 /// struct S6 a; 2198 /// a.e = BAR; 2199 /// } 2200 /// @endcode 2201 /// For the declaration of BAR, this routine will return a different 2202 /// scope. The scope S will be the scope of the unnamed enumeration 2203 /// within S6. In C++, this routine will return the scope associated 2204 /// with S6, because the enumeration's scope is a transparent 2205 /// context but structures can contain non-field names. In C, this 2206 /// routine will return the translation unit scope, since the 2207 /// enumeration's scope is a transparent context and structures cannot 2208 /// contain non-field names. 2209 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2210 while (((S->getFlags() & Scope::DeclScope) == 0) || 2211 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2212 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2213 S = S->getParent(); 2214 return S; 2215 } 2216 2217 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2218 ASTContext::GetBuiltinTypeError Error) { 2219 switch (Error) { 2220 case ASTContext::GE_None: 2221 return ""; 2222 case ASTContext::GE_Missing_type: 2223 return BuiltinInfo.getHeaderName(ID); 2224 case ASTContext::GE_Missing_stdio: 2225 return "stdio.h"; 2226 case ASTContext::GE_Missing_setjmp: 2227 return "setjmp.h"; 2228 case ASTContext::GE_Missing_ucontext: 2229 return "ucontext.h"; 2230 } 2231 llvm_unreachable("unhandled error kind"); 2232 } 2233 2234 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2235 unsigned ID, SourceLocation Loc) { 2236 DeclContext *Parent = Context.getTranslationUnitDecl(); 2237 2238 if (getLangOpts().CPlusPlus) { 2239 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2240 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2241 CLinkageDecl->setImplicit(); 2242 Parent->addDecl(CLinkageDecl); 2243 Parent = CLinkageDecl; 2244 } 2245 2246 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2247 /*TInfo=*/nullptr, SC_Extern, 2248 getCurFPFeatures().isFPConstrained(), 2249 false, Type->isFunctionProtoType()); 2250 New->setImplicit(); 2251 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2252 2253 // Create Decl objects for each parameter, adding them to the 2254 // FunctionDecl. 2255 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2256 SmallVector<ParmVarDecl *, 16> Params; 2257 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2258 ParmVarDecl *parm = ParmVarDecl::Create( 2259 Context, New, SourceLocation(), SourceLocation(), nullptr, 2260 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2261 parm->setScopeInfo(0, i); 2262 Params.push_back(parm); 2263 } 2264 New->setParams(Params); 2265 } 2266 2267 AddKnownFunctionAttributes(New); 2268 return New; 2269 } 2270 2271 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2272 /// file scope. lazily create a decl for it. ForRedeclaration is true 2273 /// if we're creating this built-in in anticipation of redeclaring the 2274 /// built-in. 2275 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2276 Scope *S, bool ForRedeclaration, 2277 SourceLocation Loc) { 2278 LookupNecessaryTypesForBuiltin(S, ID); 2279 2280 ASTContext::GetBuiltinTypeError Error; 2281 QualType R = Context.GetBuiltinType(ID, Error); 2282 if (Error) { 2283 if (!ForRedeclaration) 2284 return nullptr; 2285 2286 // If we have a builtin without an associated type we should not emit a 2287 // warning when we were not able to find a type for it. 2288 if (Error == ASTContext::GE_Missing_type || 2289 Context.BuiltinInfo.allowTypeMismatch(ID)) 2290 return nullptr; 2291 2292 // If we could not find a type for setjmp it is because the jmp_buf type was 2293 // not defined prior to the setjmp declaration. 2294 if (Error == ASTContext::GE_Missing_setjmp) { 2295 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2296 << Context.BuiltinInfo.getName(ID); 2297 return nullptr; 2298 } 2299 2300 // Generally, we emit a warning that the declaration requires the 2301 // appropriate header. 2302 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2303 << getHeaderName(Context.BuiltinInfo, ID, Error) 2304 << Context.BuiltinInfo.getName(ID); 2305 return nullptr; 2306 } 2307 2308 if (!ForRedeclaration && 2309 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2310 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2311 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99 2312 : diag::ext_implicit_lib_function_decl) 2313 << Context.BuiltinInfo.getName(ID) << R; 2314 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2315 Diag(Loc, diag::note_include_header_or_declare) 2316 << Header << Context.BuiltinInfo.getName(ID); 2317 } 2318 2319 if (R.isNull()) 2320 return nullptr; 2321 2322 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2323 RegisterLocallyScopedExternCDecl(New, S); 2324 2325 // TUScope is the translation-unit scope to insert this function into. 2326 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2327 // relate Scopes to DeclContexts, and probably eliminate CurContext 2328 // entirely, but we're not there yet. 2329 DeclContext *SavedContext = CurContext; 2330 CurContext = New->getDeclContext(); 2331 PushOnScopeChains(New, TUScope); 2332 CurContext = SavedContext; 2333 return New; 2334 } 2335 2336 /// Typedef declarations don't have linkage, but they still denote the same 2337 /// entity if their types are the same. 2338 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2339 /// isSameEntity. 2340 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2341 TypedefNameDecl *Decl, 2342 LookupResult &Previous) { 2343 // This is only interesting when modules are enabled. 2344 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2345 return; 2346 2347 // Empty sets are uninteresting. 2348 if (Previous.empty()) 2349 return; 2350 2351 LookupResult::Filter Filter = Previous.makeFilter(); 2352 while (Filter.hasNext()) { 2353 NamedDecl *Old = Filter.next(); 2354 2355 // Non-hidden declarations are never ignored. 2356 if (S.isVisible(Old)) 2357 continue; 2358 2359 // Declarations of the same entity are not ignored, even if they have 2360 // different linkages. 2361 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2362 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2363 Decl->getUnderlyingType())) 2364 continue; 2365 2366 // If both declarations give a tag declaration a typedef name for linkage 2367 // purposes, then they declare the same entity. 2368 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2369 Decl->getAnonDeclWithTypedefName()) 2370 continue; 2371 } 2372 2373 Filter.erase(); 2374 } 2375 2376 Filter.done(); 2377 } 2378 2379 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2380 QualType OldType; 2381 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2382 OldType = OldTypedef->getUnderlyingType(); 2383 else 2384 OldType = Context.getTypeDeclType(Old); 2385 QualType NewType = New->getUnderlyingType(); 2386 2387 if (NewType->isVariablyModifiedType()) { 2388 // Must not redefine a typedef with a variably-modified type. 2389 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2390 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2391 << Kind << NewType; 2392 if (Old->getLocation().isValid()) 2393 notePreviousDefinition(Old, New->getLocation()); 2394 New->setInvalidDecl(); 2395 return true; 2396 } 2397 2398 if (OldType != NewType && 2399 !OldType->isDependentType() && 2400 !NewType->isDependentType() && 2401 !Context.hasSameType(OldType, NewType)) { 2402 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2403 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2404 << Kind << NewType << OldType; 2405 if (Old->getLocation().isValid()) 2406 notePreviousDefinition(Old, New->getLocation()); 2407 New->setInvalidDecl(); 2408 return true; 2409 } 2410 return false; 2411 } 2412 2413 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2414 /// same name and scope as a previous declaration 'Old'. Figure out 2415 /// how to resolve this situation, merging decls or emitting 2416 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2417 /// 2418 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2419 LookupResult &OldDecls) { 2420 // If the new decl is known invalid already, don't bother doing any 2421 // merging checks. 2422 if (New->isInvalidDecl()) return; 2423 2424 // Allow multiple definitions for ObjC built-in typedefs. 2425 // FIXME: Verify the underlying types are equivalent! 2426 if (getLangOpts().ObjC) { 2427 const IdentifierInfo *TypeID = New->getIdentifier(); 2428 switch (TypeID->getLength()) { 2429 default: break; 2430 case 2: 2431 { 2432 if (!TypeID->isStr("id")) 2433 break; 2434 QualType T = New->getUnderlyingType(); 2435 if (!T->isPointerType()) 2436 break; 2437 if (!T->isVoidPointerType()) { 2438 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2439 if (!PT->isStructureType()) 2440 break; 2441 } 2442 Context.setObjCIdRedefinitionType(T); 2443 // Install the built-in type for 'id', ignoring the current definition. 2444 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2445 return; 2446 } 2447 case 5: 2448 if (!TypeID->isStr("Class")) 2449 break; 2450 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2451 // Install the built-in type for 'Class', ignoring the current definition. 2452 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2453 return; 2454 case 3: 2455 if (!TypeID->isStr("SEL")) 2456 break; 2457 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2458 // Install the built-in type for 'SEL', ignoring the current definition. 2459 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2460 return; 2461 } 2462 // Fall through - the typedef name was not a builtin type. 2463 } 2464 2465 // Verify the old decl was also a type. 2466 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2467 if (!Old) { 2468 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2469 << New->getDeclName(); 2470 2471 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2472 if (OldD->getLocation().isValid()) 2473 notePreviousDefinition(OldD, New->getLocation()); 2474 2475 return New->setInvalidDecl(); 2476 } 2477 2478 // If the old declaration is invalid, just give up here. 2479 if (Old->isInvalidDecl()) 2480 return New->setInvalidDecl(); 2481 2482 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2483 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2484 auto *NewTag = New->getAnonDeclWithTypedefName(); 2485 NamedDecl *Hidden = nullptr; 2486 if (OldTag && NewTag && 2487 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2488 !hasVisibleDefinition(OldTag, &Hidden)) { 2489 // There is a definition of this tag, but it is not visible. Use it 2490 // instead of our tag. 2491 New->setTypeForDecl(OldTD->getTypeForDecl()); 2492 if (OldTD->isModed()) 2493 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2494 OldTD->getUnderlyingType()); 2495 else 2496 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2497 2498 // Make the old tag definition visible. 2499 makeMergedDefinitionVisible(Hidden); 2500 2501 // If this was an unscoped enumeration, yank all of its enumerators 2502 // out of the scope. 2503 if (isa<EnumDecl>(NewTag)) { 2504 Scope *EnumScope = getNonFieldDeclScope(S); 2505 for (auto *D : NewTag->decls()) { 2506 auto *ED = cast<EnumConstantDecl>(D); 2507 assert(EnumScope->isDeclScope(ED)); 2508 EnumScope->RemoveDecl(ED); 2509 IdResolver.RemoveDecl(ED); 2510 ED->getLexicalDeclContext()->removeDecl(ED); 2511 } 2512 } 2513 } 2514 } 2515 2516 // If the typedef types are not identical, reject them in all languages and 2517 // with any extensions enabled. 2518 if (isIncompatibleTypedef(Old, New)) 2519 return; 2520 2521 // The types match. Link up the redeclaration chain and merge attributes if 2522 // the old declaration was a typedef. 2523 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2524 New->setPreviousDecl(Typedef); 2525 mergeDeclAttributes(New, Old); 2526 } 2527 2528 if (getLangOpts().MicrosoftExt) 2529 return; 2530 2531 if (getLangOpts().CPlusPlus) { 2532 // C++ [dcl.typedef]p2: 2533 // In a given non-class scope, a typedef specifier can be used to 2534 // redefine the name of any type declared in that scope to refer 2535 // to the type to which it already refers. 2536 if (!isa<CXXRecordDecl>(CurContext)) 2537 return; 2538 2539 // C++0x [dcl.typedef]p4: 2540 // In a given class scope, a typedef specifier can be used to redefine 2541 // any class-name declared in that scope that is not also a typedef-name 2542 // to refer to the type to which it already refers. 2543 // 2544 // This wording came in via DR424, which was a correction to the 2545 // wording in DR56, which accidentally banned code like: 2546 // 2547 // struct S { 2548 // typedef struct A { } A; 2549 // }; 2550 // 2551 // in the C++03 standard. We implement the C++0x semantics, which 2552 // allow the above but disallow 2553 // 2554 // struct S { 2555 // typedef int I; 2556 // typedef int I; 2557 // }; 2558 // 2559 // since that was the intent of DR56. 2560 if (!isa<TypedefNameDecl>(Old)) 2561 return; 2562 2563 Diag(New->getLocation(), diag::err_redefinition) 2564 << New->getDeclName(); 2565 notePreviousDefinition(Old, New->getLocation()); 2566 return New->setInvalidDecl(); 2567 } 2568 2569 // Modules always permit redefinition of typedefs, as does C11. 2570 if (getLangOpts().Modules || getLangOpts().C11) 2571 return; 2572 2573 // If we have a redefinition of a typedef in C, emit a warning. This warning 2574 // is normally mapped to an error, but can be controlled with 2575 // -Wtypedef-redefinition. If either the original or the redefinition is 2576 // in a system header, don't emit this for compatibility with GCC. 2577 if (getDiagnostics().getSuppressSystemWarnings() && 2578 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2579 (Old->isImplicit() || 2580 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2581 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2582 return; 2583 2584 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2585 << New->getDeclName(); 2586 notePreviousDefinition(Old, New->getLocation()); 2587 } 2588 2589 /// DeclhasAttr - returns true if decl Declaration already has the target 2590 /// attribute. 2591 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2592 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2593 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2594 for (const auto *i : D->attrs()) 2595 if (i->getKind() == A->getKind()) { 2596 if (Ann) { 2597 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2598 return true; 2599 continue; 2600 } 2601 // FIXME: Don't hardcode this check 2602 if (OA && isa<OwnershipAttr>(i)) 2603 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2604 return true; 2605 } 2606 2607 return false; 2608 } 2609 2610 static bool isAttributeTargetADefinition(Decl *D) { 2611 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2612 return VD->isThisDeclarationADefinition(); 2613 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2614 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2615 return true; 2616 } 2617 2618 /// Merge alignment attributes from \p Old to \p New, taking into account the 2619 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2620 /// 2621 /// \return \c true if any attributes were added to \p New. 2622 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2623 // Look for alignas attributes on Old, and pick out whichever attribute 2624 // specifies the strictest alignment requirement. 2625 AlignedAttr *OldAlignasAttr = nullptr; 2626 AlignedAttr *OldStrictestAlignAttr = nullptr; 2627 unsigned OldAlign = 0; 2628 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2629 // FIXME: We have no way of representing inherited dependent alignments 2630 // in a case like: 2631 // template<int A, int B> struct alignas(A) X; 2632 // template<int A, int B> struct alignas(B) X {}; 2633 // For now, we just ignore any alignas attributes which are not on the 2634 // definition in such a case. 2635 if (I->isAlignmentDependent()) 2636 return false; 2637 2638 if (I->isAlignas()) 2639 OldAlignasAttr = I; 2640 2641 unsigned Align = I->getAlignment(S.Context); 2642 if (Align > OldAlign) { 2643 OldAlign = Align; 2644 OldStrictestAlignAttr = I; 2645 } 2646 } 2647 2648 // Look for alignas attributes on New. 2649 AlignedAttr *NewAlignasAttr = nullptr; 2650 unsigned NewAlign = 0; 2651 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2652 if (I->isAlignmentDependent()) 2653 return false; 2654 2655 if (I->isAlignas()) 2656 NewAlignasAttr = I; 2657 2658 unsigned Align = I->getAlignment(S.Context); 2659 if (Align > NewAlign) 2660 NewAlign = Align; 2661 } 2662 2663 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2664 // Both declarations have 'alignas' attributes. We require them to match. 2665 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2666 // fall short. (If two declarations both have alignas, they must both match 2667 // every definition, and so must match each other if there is a definition.) 2668 2669 // If either declaration only contains 'alignas(0)' specifiers, then it 2670 // specifies the natural alignment for the type. 2671 if (OldAlign == 0 || NewAlign == 0) { 2672 QualType Ty; 2673 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2674 Ty = VD->getType(); 2675 else 2676 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2677 2678 if (OldAlign == 0) 2679 OldAlign = S.Context.getTypeAlign(Ty); 2680 if (NewAlign == 0) 2681 NewAlign = S.Context.getTypeAlign(Ty); 2682 } 2683 2684 if (OldAlign != NewAlign) { 2685 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2686 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2687 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2688 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2689 } 2690 } 2691 2692 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2693 // C++11 [dcl.align]p6: 2694 // if any declaration of an entity has an alignment-specifier, 2695 // every defining declaration of that entity shall specify an 2696 // equivalent alignment. 2697 // C11 6.7.5/7: 2698 // If the definition of an object does not have an alignment 2699 // specifier, any other declaration of that object shall also 2700 // have no alignment specifier. 2701 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2702 << OldAlignasAttr; 2703 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2704 << OldAlignasAttr; 2705 } 2706 2707 bool AnyAdded = false; 2708 2709 // Ensure we have an attribute representing the strictest alignment. 2710 if (OldAlign > NewAlign) { 2711 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2712 Clone->setInherited(true); 2713 New->addAttr(Clone); 2714 AnyAdded = true; 2715 } 2716 2717 // Ensure we have an alignas attribute if the old declaration had one. 2718 if (OldAlignasAttr && !NewAlignasAttr && 2719 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2720 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2721 Clone->setInherited(true); 2722 New->addAttr(Clone); 2723 AnyAdded = true; 2724 } 2725 2726 return AnyAdded; 2727 } 2728 2729 #define WANT_DECL_MERGE_LOGIC 2730 #include "clang/Sema/AttrParsedAttrImpl.inc" 2731 #undef WANT_DECL_MERGE_LOGIC 2732 2733 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2734 const InheritableAttr *Attr, 2735 Sema::AvailabilityMergeKind AMK) { 2736 // Diagnose any mutual exclusions between the attribute that we want to add 2737 // and attributes that already exist on the declaration. 2738 if (!DiagnoseMutualExclusions(S, D, Attr)) 2739 return false; 2740 2741 // This function copies an attribute Attr from a previous declaration to the 2742 // new declaration D if the new declaration doesn't itself have that attribute 2743 // yet or if that attribute allows duplicates. 2744 // If you're adding a new attribute that requires logic different from 2745 // "use explicit attribute on decl if present, else use attribute from 2746 // previous decl", for example if the attribute needs to be consistent 2747 // between redeclarations, you need to call a custom merge function here. 2748 InheritableAttr *NewAttr = nullptr; 2749 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2750 NewAttr = S.mergeAvailabilityAttr( 2751 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2752 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2753 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2754 AA->getPriority()); 2755 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2756 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2757 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2758 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2759 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2760 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2761 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2762 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2763 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2764 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2765 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2766 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2767 FA->getFirstArg()); 2768 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2769 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2770 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2771 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2772 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2773 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2774 IA->getInheritanceModel()); 2775 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2776 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2777 &S.Context.Idents.get(AA->getSpelling())); 2778 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2779 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2780 isa<CUDAGlobalAttr>(Attr))) { 2781 // CUDA target attributes are part of function signature for 2782 // overloading purposes and must not be merged. 2783 return false; 2784 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2785 NewAttr = S.mergeMinSizeAttr(D, *MA); 2786 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2787 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2788 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2789 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2790 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2791 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2792 else if (isa<AlignedAttr>(Attr)) 2793 // AlignedAttrs are handled separately, because we need to handle all 2794 // such attributes on a declaration at the same time. 2795 NewAttr = nullptr; 2796 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2797 (AMK == Sema::AMK_Override || 2798 AMK == Sema::AMK_ProtocolImplementation || 2799 AMK == Sema::AMK_OptionalProtocolImplementation)) 2800 NewAttr = nullptr; 2801 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2802 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2803 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2804 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2805 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2806 NewAttr = S.mergeImportNameAttr(D, *INA); 2807 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2808 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2809 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2810 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2811 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2812 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2813 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr)) 2814 NewAttr = 2815 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ()); 2816 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr)) 2817 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType()); 2818 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2819 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2820 2821 if (NewAttr) { 2822 NewAttr->setInherited(true); 2823 D->addAttr(NewAttr); 2824 if (isa<MSInheritanceAttr>(NewAttr)) 2825 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2826 return true; 2827 } 2828 2829 return false; 2830 } 2831 2832 static const NamedDecl *getDefinition(const Decl *D) { 2833 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2834 return TD->getDefinition(); 2835 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2836 const VarDecl *Def = VD->getDefinition(); 2837 if (Def) 2838 return Def; 2839 return VD->getActingDefinition(); 2840 } 2841 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2842 const FunctionDecl *Def = nullptr; 2843 if (FD->isDefined(Def, true)) 2844 return Def; 2845 } 2846 return nullptr; 2847 } 2848 2849 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2850 for (const auto *Attribute : D->attrs()) 2851 if (Attribute->getKind() == Kind) 2852 return true; 2853 return false; 2854 } 2855 2856 /// checkNewAttributesAfterDef - If we already have a definition, check that 2857 /// there are no new attributes in this declaration. 2858 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2859 if (!New->hasAttrs()) 2860 return; 2861 2862 const NamedDecl *Def = getDefinition(Old); 2863 if (!Def || Def == New) 2864 return; 2865 2866 AttrVec &NewAttributes = New->getAttrs(); 2867 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2868 const Attr *NewAttribute = NewAttributes[I]; 2869 2870 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2871 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2872 Sema::SkipBodyInfo SkipBody; 2873 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2874 2875 // If we're skipping this definition, drop the "alias" attribute. 2876 if (SkipBody.ShouldSkip) { 2877 NewAttributes.erase(NewAttributes.begin() + I); 2878 --E; 2879 continue; 2880 } 2881 } else { 2882 VarDecl *VD = cast<VarDecl>(New); 2883 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2884 VarDecl::TentativeDefinition 2885 ? diag::err_alias_after_tentative 2886 : diag::err_redefinition; 2887 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2888 if (Diag == diag::err_redefinition) 2889 S.notePreviousDefinition(Def, VD->getLocation()); 2890 else 2891 S.Diag(Def->getLocation(), diag::note_previous_definition); 2892 VD->setInvalidDecl(); 2893 } 2894 ++I; 2895 continue; 2896 } 2897 2898 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2899 // Tentative definitions are only interesting for the alias check above. 2900 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2901 ++I; 2902 continue; 2903 } 2904 } 2905 2906 if (hasAttribute(Def, NewAttribute->getKind())) { 2907 ++I; 2908 continue; // regular attr merging will take care of validating this. 2909 } 2910 2911 if (isa<C11NoReturnAttr>(NewAttribute)) { 2912 // C's _Noreturn is allowed to be added to a function after it is defined. 2913 ++I; 2914 continue; 2915 } else if (isa<UuidAttr>(NewAttribute)) { 2916 // msvc will allow a subsequent definition to add an uuid to a class 2917 ++I; 2918 continue; 2919 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2920 if (AA->isAlignas()) { 2921 // C++11 [dcl.align]p6: 2922 // if any declaration of an entity has an alignment-specifier, 2923 // every defining declaration of that entity shall specify an 2924 // equivalent alignment. 2925 // C11 6.7.5/7: 2926 // If the definition of an object does not have an alignment 2927 // specifier, any other declaration of that object shall also 2928 // have no alignment specifier. 2929 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2930 << AA; 2931 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2932 << AA; 2933 NewAttributes.erase(NewAttributes.begin() + I); 2934 --E; 2935 continue; 2936 } 2937 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2938 // If there is a C definition followed by a redeclaration with this 2939 // attribute then there are two different definitions. In C++, prefer the 2940 // standard diagnostics. 2941 if (!S.getLangOpts().CPlusPlus) { 2942 S.Diag(NewAttribute->getLocation(), 2943 diag::err_loader_uninitialized_redeclaration); 2944 S.Diag(Def->getLocation(), diag::note_previous_definition); 2945 NewAttributes.erase(NewAttributes.begin() + I); 2946 --E; 2947 continue; 2948 } 2949 } else if (isa<SelectAnyAttr>(NewAttribute) && 2950 cast<VarDecl>(New)->isInline() && 2951 !cast<VarDecl>(New)->isInlineSpecified()) { 2952 // Don't warn about applying selectany to implicitly inline variables. 2953 // Older compilers and language modes would require the use of selectany 2954 // to make such variables inline, and it would have no effect if we 2955 // honored it. 2956 ++I; 2957 continue; 2958 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2959 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2960 // declarations after defintions. 2961 ++I; 2962 continue; 2963 } 2964 2965 S.Diag(NewAttribute->getLocation(), 2966 diag::warn_attribute_precede_definition); 2967 S.Diag(Def->getLocation(), diag::note_previous_definition); 2968 NewAttributes.erase(NewAttributes.begin() + I); 2969 --E; 2970 } 2971 } 2972 2973 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2974 const ConstInitAttr *CIAttr, 2975 bool AttrBeforeInit) { 2976 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2977 2978 // Figure out a good way to write this specifier on the old declaration. 2979 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2980 // enough of the attribute list spelling information to extract that without 2981 // heroics. 2982 std::string SuitableSpelling; 2983 if (S.getLangOpts().CPlusPlus20) 2984 SuitableSpelling = std::string( 2985 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2986 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2987 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2988 InsertLoc, {tok::l_square, tok::l_square, 2989 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2990 S.PP.getIdentifierInfo("require_constant_initialization"), 2991 tok::r_square, tok::r_square})); 2992 if (SuitableSpelling.empty()) 2993 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2994 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2995 S.PP.getIdentifierInfo("require_constant_initialization"), 2996 tok::r_paren, tok::r_paren})); 2997 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2998 SuitableSpelling = "constinit"; 2999 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 3000 SuitableSpelling = "[[clang::require_constant_initialization]]"; 3001 if (SuitableSpelling.empty()) 3002 SuitableSpelling = "__attribute__((require_constant_initialization))"; 3003 SuitableSpelling += " "; 3004 3005 if (AttrBeforeInit) { 3006 // extern constinit int a; 3007 // int a = 0; // error (missing 'constinit'), accepted as extension 3008 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 3009 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 3010 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3011 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 3012 } else { 3013 // int a = 0; 3014 // constinit extern int a; // error (missing 'constinit') 3015 S.Diag(CIAttr->getLocation(), 3016 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 3017 : diag::warn_require_const_init_added_too_late) 3018 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 3019 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 3020 << CIAttr->isConstinit() 3021 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3022 } 3023 } 3024 3025 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 3026 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 3027 AvailabilityMergeKind AMK) { 3028 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 3029 UsedAttr *NewAttr = OldAttr->clone(Context); 3030 NewAttr->setInherited(true); 3031 New->addAttr(NewAttr); 3032 } 3033 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 3034 RetainAttr *NewAttr = OldAttr->clone(Context); 3035 NewAttr->setInherited(true); 3036 New->addAttr(NewAttr); 3037 } 3038 3039 if (!Old->hasAttrs() && !New->hasAttrs()) 3040 return; 3041 3042 // [dcl.constinit]p1: 3043 // If the [constinit] specifier is applied to any declaration of a 3044 // variable, it shall be applied to the initializing declaration. 3045 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 3046 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 3047 if (bool(OldConstInit) != bool(NewConstInit)) { 3048 const auto *OldVD = cast<VarDecl>(Old); 3049 auto *NewVD = cast<VarDecl>(New); 3050 3051 // Find the initializing declaration. Note that we might not have linked 3052 // the new declaration into the redeclaration chain yet. 3053 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 3054 if (!InitDecl && 3055 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 3056 InitDecl = NewVD; 3057 3058 if (InitDecl == NewVD) { 3059 // This is the initializing declaration. If it would inherit 'constinit', 3060 // that's ill-formed. (Note that we do not apply this to the attribute 3061 // form). 3062 if (OldConstInit && OldConstInit->isConstinit()) 3063 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 3064 /*AttrBeforeInit=*/true); 3065 } else if (NewConstInit) { 3066 // This is the first time we've been told that this declaration should 3067 // have a constant initializer. If we already saw the initializing 3068 // declaration, this is too late. 3069 if (InitDecl && InitDecl != NewVD) { 3070 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3071 /*AttrBeforeInit=*/false); 3072 NewVD->dropAttr<ConstInitAttr>(); 3073 } 3074 } 3075 } 3076 3077 // Attributes declared post-definition are currently ignored. 3078 checkNewAttributesAfterDef(*this, New, Old); 3079 3080 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3081 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3082 if (!OldA->isEquivalent(NewA)) { 3083 // This redeclaration changes __asm__ label. 3084 Diag(New->getLocation(), diag::err_different_asm_label); 3085 Diag(OldA->getLocation(), diag::note_previous_declaration); 3086 } 3087 } else if (Old->isUsed()) { 3088 // This redeclaration adds an __asm__ label to a declaration that has 3089 // already been ODR-used. 3090 Diag(New->getLocation(), diag::err_late_asm_label_name) 3091 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3092 } 3093 } 3094 3095 // Re-declaration cannot add abi_tag's. 3096 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3097 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3098 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3099 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3100 Diag(NewAbiTagAttr->getLocation(), 3101 diag::err_new_abi_tag_on_redeclaration) 3102 << NewTag; 3103 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3104 } 3105 } 3106 } else { 3107 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3108 Diag(Old->getLocation(), diag::note_previous_declaration); 3109 } 3110 } 3111 3112 // This redeclaration adds a section attribute. 3113 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3114 if (auto *VD = dyn_cast<VarDecl>(New)) { 3115 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3116 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3117 Diag(Old->getLocation(), diag::note_previous_declaration); 3118 } 3119 } 3120 } 3121 3122 // Redeclaration adds code-seg attribute. 3123 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3124 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3125 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3126 Diag(New->getLocation(), diag::warn_mismatched_section) 3127 << 0 /*codeseg*/; 3128 Diag(Old->getLocation(), diag::note_previous_declaration); 3129 } 3130 3131 if (!Old->hasAttrs()) 3132 return; 3133 3134 bool foundAny = New->hasAttrs(); 3135 3136 // Ensure that any moving of objects within the allocated map is done before 3137 // we process them. 3138 if (!foundAny) New->setAttrs(AttrVec()); 3139 3140 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3141 // Ignore deprecated/unavailable/availability attributes if requested. 3142 AvailabilityMergeKind LocalAMK = AMK_None; 3143 if (isa<DeprecatedAttr>(I) || 3144 isa<UnavailableAttr>(I) || 3145 isa<AvailabilityAttr>(I)) { 3146 switch (AMK) { 3147 case AMK_None: 3148 continue; 3149 3150 case AMK_Redeclaration: 3151 case AMK_Override: 3152 case AMK_ProtocolImplementation: 3153 case AMK_OptionalProtocolImplementation: 3154 LocalAMK = AMK; 3155 break; 3156 } 3157 } 3158 3159 // Already handled. 3160 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3161 continue; 3162 3163 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3164 foundAny = true; 3165 } 3166 3167 if (mergeAlignedAttrs(*this, New, Old)) 3168 foundAny = true; 3169 3170 if (!foundAny) New->dropAttrs(); 3171 } 3172 3173 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3174 /// to the new one. 3175 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3176 const ParmVarDecl *oldDecl, 3177 Sema &S) { 3178 // C++11 [dcl.attr.depend]p2: 3179 // The first declaration of a function shall specify the 3180 // carries_dependency attribute for its declarator-id if any declaration 3181 // of the function specifies the carries_dependency attribute. 3182 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3183 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3184 S.Diag(CDA->getLocation(), 3185 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3186 // Find the first declaration of the parameter. 3187 // FIXME: Should we build redeclaration chains for function parameters? 3188 const FunctionDecl *FirstFD = 3189 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3190 const ParmVarDecl *FirstVD = 3191 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3192 S.Diag(FirstVD->getLocation(), 3193 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3194 } 3195 3196 if (!oldDecl->hasAttrs()) 3197 return; 3198 3199 bool foundAny = newDecl->hasAttrs(); 3200 3201 // Ensure that any moving of objects within the allocated map is 3202 // done before we process them. 3203 if (!foundAny) newDecl->setAttrs(AttrVec()); 3204 3205 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3206 if (!DeclHasAttr(newDecl, I)) { 3207 InheritableAttr *newAttr = 3208 cast<InheritableParamAttr>(I->clone(S.Context)); 3209 newAttr->setInherited(true); 3210 newDecl->addAttr(newAttr); 3211 foundAny = true; 3212 } 3213 } 3214 3215 if (!foundAny) newDecl->dropAttrs(); 3216 } 3217 3218 static bool EquivalentArrayTypes(QualType Old, QualType New, 3219 const ASTContext &Ctx) { 3220 3221 auto NoSizeInfo = [&Ctx](QualType Ty) { 3222 if (Ty->isIncompleteArrayType() || Ty->isPointerType()) 3223 return true; 3224 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty)) 3225 return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star; 3226 return false; 3227 }; 3228 3229 // `type[]` is equivalent to `type *` and `type[*]`. 3230 if (NoSizeInfo(Old) && NoSizeInfo(New)) 3231 return true; 3232 3233 // Don't try to compare VLA sizes, unless one of them has the star modifier. 3234 if (Old->isVariableArrayType() && New->isVariableArrayType()) { 3235 const auto *OldVAT = Ctx.getAsVariableArrayType(Old); 3236 const auto *NewVAT = Ctx.getAsVariableArrayType(New); 3237 if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^ 3238 (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star)) 3239 return false; 3240 return true; 3241 } 3242 3243 // Only compare size, ignore Size modifiers and CVR. 3244 if (Old->isConstantArrayType() && New->isConstantArrayType()) { 3245 return Ctx.getAsConstantArrayType(Old)->getSize() == 3246 Ctx.getAsConstantArrayType(New)->getSize(); 3247 } 3248 3249 // Don't try to compare dependent sized array 3250 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) { 3251 return true; 3252 } 3253 3254 return Old == New; 3255 } 3256 3257 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3258 const ParmVarDecl *OldParam, 3259 Sema &S) { 3260 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3261 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3262 if (*Oldnullability != *Newnullability) { 3263 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3264 << DiagNullabilityKind( 3265 *Newnullability, 3266 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3267 != 0)) 3268 << DiagNullabilityKind( 3269 *Oldnullability, 3270 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3271 != 0)); 3272 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3273 } 3274 } else { 3275 QualType NewT = NewParam->getType(); 3276 NewT = S.Context.getAttributedType( 3277 AttributedType::getNullabilityAttrKind(*Oldnullability), 3278 NewT, NewT); 3279 NewParam->setType(NewT); 3280 } 3281 } 3282 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType()); 3283 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType()); 3284 if (OldParamDT && NewParamDT && 3285 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) { 3286 QualType OldParamOT = OldParamDT->getOriginalType(); 3287 QualType NewParamOT = NewParamDT->getOriginalType(); 3288 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) { 3289 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form) 3290 << NewParam << NewParamOT; 3291 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as) 3292 << OldParamOT; 3293 } 3294 } 3295 } 3296 3297 namespace { 3298 3299 /// Used in MergeFunctionDecl to keep track of function parameters in 3300 /// C. 3301 struct GNUCompatibleParamWarning { 3302 ParmVarDecl *OldParm; 3303 ParmVarDecl *NewParm; 3304 QualType PromotedType; 3305 }; 3306 3307 } // end anonymous namespace 3308 3309 // Determine whether the previous declaration was a definition, implicit 3310 // declaration, or a declaration. 3311 template <typename T> 3312 static std::pair<diag::kind, SourceLocation> 3313 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3314 diag::kind PrevDiag; 3315 SourceLocation OldLocation = Old->getLocation(); 3316 if (Old->isThisDeclarationADefinition()) 3317 PrevDiag = diag::note_previous_definition; 3318 else if (Old->isImplicit()) { 3319 PrevDiag = diag::note_previous_implicit_declaration; 3320 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) { 3321 if (FD->getBuiltinID()) 3322 PrevDiag = diag::note_previous_builtin_declaration; 3323 } 3324 if (OldLocation.isInvalid()) 3325 OldLocation = New->getLocation(); 3326 } else 3327 PrevDiag = diag::note_previous_declaration; 3328 return std::make_pair(PrevDiag, OldLocation); 3329 } 3330 3331 /// canRedefineFunction - checks if a function can be redefined. Currently, 3332 /// only extern inline functions can be redefined, and even then only in 3333 /// GNU89 mode. 3334 static bool canRedefineFunction(const FunctionDecl *FD, 3335 const LangOptions& LangOpts) { 3336 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3337 !LangOpts.CPlusPlus && 3338 FD->isInlineSpecified() && 3339 FD->getStorageClass() == SC_Extern); 3340 } 3341 3342 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3343 const AttributedType *AT = T->getAs<AttributedType>(); 3344 while (AT && !AT->isCallingConv()) 3345 AT = AT->getModifiedType()->getAs<AttributedType>(); 3346 return AT; 3347 } 3348 3349 template <typename T> 3350 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3351 const DeclContext *DC = Old->getDeclContext(); 3352 if (DC->isRecord()) 3353 return false; 3354 3355 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3356 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3357 return true; 3358 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3359 return true; 3360 return false; 3361 } 3362 3363 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3364 static bool isExternC(VarTemplateDecl *) { return false; } 3365 static bool isExternC(FunctionTemplateDecl *) { return false; } 3366 3367 /// Check whether a redeclaration of an entity introduced by a 3368 /// using-declaration is valid, given that we know it's not an overload 3369 /// (nor a hidden tag declaration). 3370 template<typename ExpectedDecl> 3371 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3372 ExpectedDecl *New) { 3373 // C++11 [basic.scope.declarative]p4: 3374 // Given a set of declarations in a single declarative region, each of 3375 // which specifies the same unqualified name, 3376 // -- they shall all refer to the same entity, or all refer to functions 3377 // and function templates; or 3378 // -- exactly one declaration shall declare a class name or enumeration 3379 // name that is not a typedef name and the other declarations shall all 3380 // refer to the same variable or enumerator, or all refer to functions 3381 // and function templates; in this case the class name or enumeration 3382 // name is hidden (3.3.10). 3383 3384 // C++11 [namespace.udecl]p14: 3385 // If a function declaration in namespace scope or block scope has the 3386 // same name and the same parameter-type-list as a function introduced 3387 // by a using-declaration, and the declarations do not declare the same 3388 // function, the program is ill-formed. 3389 3390 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3391 if (Old && 3392 !Old->getDeclContext()->getRedeclContext()->Equals( 3393 New->getDeclContext()->getRedeclContext()) && 3394 !(isExternC(Old) && isExternC(New))) 3395 Old = nullptr; 3396 3397 if (!Old) { 3398 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3399 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3400 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3401 return true; 3402 } 3403 return false; 3404 } 3405 3406 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3407 const FunctionDecl *B) { 3408 assert(A->getNumParams() == B->getNumParams()); 3409 3410 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3411 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3412 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3413 if (AttrA == AttrB) 3414 return true; 3415 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3416 AttrA->isDynamic() == AttrB->isDynamic(); 3417 }; 3418 3419 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3420 } 3421 3422 /// If necessary, adjust the semantic declaration context for a qualified 3423 /// declaration to name the correct inline namespace within the qualifier. 3424 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3425 DeclaratorDecl *OldD) { 3426 // The only case where we need to update the DeclContext is when 3427 // redeclaration lookup for a qualified name finds a declaration 3428 // in an inline namespace within the context named by the qualifier: 3429 // 3430 // inline namespace N { int f(); } 3431 // int ::f(); // Sema DC needs adjusting from :: to N::. 3432 // 3433 // For unqualified declarations, the semantic context *can* change 3434 // along the redeclaration chain (for local extern declarations, 3435 // extern "C" declarations, and friend declarations in particular). 3436 if (!NewD->getQualifier()) 3437 return; 3438 3439 // NewD is probably already in the right context. 3440 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3441 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3442 if (NamedDC->Equals(SemaDC)) 3443 return; 3444 3445 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3446 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3447 "unexpected context for redeclaration"); 3448 3449 auto *LexDC = NewD->getLexicalDeclContext(); 3450 auto FixSemaDC = [=](NamedDecl *D) { 3451 if (!D) 3452 return; 3453 D->setDeclContext(SemaDC); 3454 D->setLexicalDeclContext(LexDC); 3455 }; 3456 3457 FixSemaDC(NewD); 3458 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3459 FixSemaDC(FD->getDescribedFunctionTemplate()); 3460 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3461 FixSemaDC(VD->getDescribedVarTemplate()); 3462 } 3463 3464 /// MergeFunctionDecl - We just parsed a function 'New' from 3465 /// declarator D which has the same name and scope as a previous 3466 /// declaration 'Old'. Figure out how to resolve this situation, 3467 /// merging decls or emitting diagnostics as appropriate. 3468 /// 3469 /// In C++, New and Old must be declarations that are not 3470 /// overloaded. Use IsOverload to determine whether New and Old are 3471 /// overloaded, and to select the Old declaration that New should be 3472 /// merged with. 3473 /// 3474 /// Returns true if there was an error, false otherwise. 3475 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, 3476 bool MergeTypeWithOld, bool NewDeclIsDefn) { 3477 // Verify the old decl was also a function. 3478 FunctionDecl *Old = OldD->getAsFunction(); 3479 if (!Old) { 3480 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3481 if (New->getFriendObjectKind()) { 3482 Diag(New->getLocation(), diag::err_using_decl_friend); 3483 Diag(Shadow->getTargetDecl()->getLocation(), 3484 diag::note_using_decl_target); 3485 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3486 << 0; 3487 return true; 3488 } 3489 3490 // Check whether the two declarations might declare the same function or 3491 // function template. 3492 if (FunctionTemplateDecl *NewTemplate = 3493 New->getDescribedFunctionTemplate()) { 3494 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3495 NewTemplate)) 3496 return true; 3497 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3498 ->getAsFunction(); 3499 } else { 3500 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3501 return true; 3502 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3503 } 3504 } else { 3505 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3506 << New->getDeclName(); 3507 notePreviousDefinition(OldD, New->getLocation()); 3508 return true; 3509 } 3510 } 3511 3512 // If the old declaration was found in an inline namespace and the new 3513 // declaration was qualified, update the DeclContext to match. 3514 adjustDeclContextForDeclaratorDecl(New, Old); 3515 3516 // If the old declaration is invalid, just give up here. 3517 if (Old->isInvalidDecl()) 3518 return true; 3519 3520 // Disallow redeclaration of some builtins. 3521 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3522 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3523 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3524 << Old << Old->getType(); 3525 return true; 3526 } 3527 3528 diag::kind PrevDiag; 3529 SourceLocation OldLocation; 3530 std::tie(PrevDiag, OldLocation) = 3531 getNoteDiagForInvalidRedeclaration(Old, New); 3532 3533 // Don't complain about this if we're in GNU89 mode and the old function 3534 // is an extern inline function. 3535 // Don't complain about specializations. They are not supposed to have 3536 // storage classes. 3537 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3538 New->getStorageClass() == SC_Static && 3539 Old->hasExternalFormalLinkage() && 3540 !New->getTemplateSpecializationInfo() && 3541 !canRedefineFunction(Old, getLangOpts())) { 3542 if (getLangOpts().MicrosoftExt) { 3543 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3544 Diag(OldLocation, PrevDiag); 3545 } else { 3546 Diag(New->getLocation(), diag::err_static_non_static) << New; 3547 Diag(OldLocation, PrevDiag); 3548 return true; 3549 } 3550 } 3551 3552 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3553 if (!Old->hasAttr<InternalLinkageAttr>()) { 3554 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3555 << ILA; 3556 Diag(Old->getLocation(), diag::note_previous_declaration); 3557 New->dropAttr<InternalLinkageAttr>(); 3558 } 3559 3560 if (auto *EA = New->getAttr<ErrorAttr>()) { 3561 if (!Old->hasAttr<ErrorAttr>()) { 3562 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3563 Diag(Old->getLocation(), diag::note_previous_declaration); 3564 New->dropAttr<ErrorAttr>(); 3565 } 3566 } 3567 3568 if (CheckRedeclarationInModule(New, Old)) 3569 return true; 3570 3571 if (!getLangOpts().CPlusPlus) { 3572 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3573 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3574 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3575 << New << OldOvl; 3576 3577 // Try our best to find a decl that actually has the overloadable 3578 // attribute for the note. In most cases (e.g. programs with only one 3579 // broken declaration/definition), this won't matter. 3580 // 3581 // FIXME: We could do this if we juggled some extra state in 3582 // OverloadableAttr, rather than just removing it. 3583 const Decl *DiagOld = Old; 3584 if (OldOvl) { 3585 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3586 const auto *A = D->getAttr<OverloadableAttr>(); 3587 return A && !A->isImplicit(); 3588 }); 3589 // If we've implicitly added *all* of the overloadable attrs to this 3590 // chain, emitting a "previous redecl" note is pointless. 3591 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3592 } 3593 3594 if (DiagOld) 3595 Diag(DiagOld->getLocation(), 3596 diag::note_attribute_overloadable_prev_overload) 3597 << OldOvl; 3598 3599 if (OldOvl) 3600 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3601 else 3602 New->dropAttr<OverloadableAttr>(); 3603 } 3604 } 3605 3606 // If a function is first declared with a calling convention, but is later 3607 // declared or defined without one, all following decls assume the calling 3608 // convention of the first. 3609 // 3610 // It's OK if a function is first declared without a calling convention, 3611 // but is later declared or defined with the default calling convention. 3612 // 3613 // To test if either decl has an explicit calling convention, we look for 3614 // AttributedType sugar nodes on the type as written. If they are missing or 3615 // were canonicalized away, we assume the calling convention was implicit. 3616 // 3617 // Note also that we DO NOT return at this point, because we still have 3618 // other tests to run. 3619 QualType OldQType = Context.getCanonicalType(Old->getType()); 3620 QualType NewQType = Context.getCanonicalType(New->getType()); 3621 const FunctionType *OldType = cast<FunctionType>(OldQType); 3622 const FunctionType *NewType = cast<FunctionType>(NewQType); 3623 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3624 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3625 bool RequiresAdjustment = false; 3626 3627 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3628 FunctionDecl *First = Old->getFirstDecl(); 3629 const FunctionType *FT = 3630 First->getType().getCanonicalType()->castAs<FunctionType>(); 3631 FunctionType::ExtInfo FI = FT->getExtInfo(); 3632 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3633 if (!NewCCExplicit) { 3634 // Inherit the CC from the previous declaration if it was specified 3635 // there but not here. 3636 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3637 RequiresAdjustment = true; 3638 } else if (Old->getBuiltinID()) { 3639 // Builtin attribute isn't propagated to the new one yet at this point, 3640 // so we check if the old one is a builtin. 3641 3642 // Calling Conventions on a Builtin aren't really useful and setting a 3643 // default calling convention and cdecl'ing some builtin redeclarations is 3644 // common, so warn and ignore the calling convention on the redeclaration. 3645 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3646 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3647 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3648 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3649 RequiresAdjustment = true; 3650 } else { 3651 // Calling conventions aren't compatible, so complain. 3652 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3653 Diag(New->getLocation(), diag::err_cconv_change) 3654 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3655 << !FirstCCExplicit 3656 << (!FirstCCExplicit ? "" : 3657 FunctionType::getNameForCallConv(FI.getCC())); 3658 3659 // Put the note on the first decl, since it is the one that matters. 3660 Diag(First->getLocation(), diag::note_previous_declaration); 3661 return true; 3662 } 3663 } 3664 3665 // FIXME: diagnose the other way around? 3666 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3667 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3668 RequiresAdjustment = true; 3669 } 3670 3671 // Merge regparm attribute. 3672 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3673 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3674 if (NewTypeInfo.getHasRegParm()) { 3675 Diag(New->getLocation(), diag::err_regparm_mismatch) 3676 << NewType->getRegParmType() 3677 << OldType->getRegParmType(); 3678 Diag(OldLocation, diag::note_previous_declaration); 3679 return true; 3680 } 3681 3682 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3683 RequiresAdjustment = true; 3684 } 3685 3686 // Merge ns_returns_retained attribute. 3687 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3688 if (NewTypeInfo.getProducesResult()) { 3689 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3690 << "'ns_returns_retained'"; 3691 Diag(OldLocation, diag::note_previous_declaration); 3692 return true; 3693 } 3694 3695 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3696 RequiresAdjustment = true; 3697 } 3698 3699 if (OldTypeInfo.getNoCallerSavedRegs() != 3700 NewTypeInfo.getNoCallerSavedRegs()) { 3701 if (NewTypeInfo.getNoCallerSavedRegs()) { 3702 AnyX86NoCallerSavedRegistersAttr *Attr = 3703 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3704 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3705 Diag(OldLocation, diag::note_previous_declaration); 3706 return true; 3707 } 3708 3709 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3710 RequiresAdjustment = true; 3711 } 3712 3713 if (RequiresAdjustment) { 3714 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3715 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3716 New->setType(QualType(AdjustedType, 0)); 3717 NewQType = Context.getCanonicalType(New->getType()); 3718 } 3719 3720 // If this redeclaration makes the function inline, we may need to add it to 3721 // UndefinedButUsed. 3722 if (!Old->isInlined() && New->isInlined() && 3723 !New->hasAttr<GNUInlineAttr>() && 3724 !getLangOpts().GNUInline && 3725 Old->isUsed(false) && 3726 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3727 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3728 SourceLocation())); 3729 3730 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3731 // about it. 3732 if (New->hasAttr<GNUInlineAttr>() && 3733 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3734 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3735 } 3736 3737 // If pass_object_size params don't match up perfectly, this isn't a valid 3738 // redeclaration. 3739 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3740 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3741 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3742 << New->getDeclName(); 3743 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3744 return true; 3745 } 3746 3747 if (getLangOpts().CPlusPlus) { 3748 // C++1z [over.load]p2 3749 // Certain function declarations cannot be overloaded: 3750 // -- Function declarations that differ only in the return type, 3751 // the exception specification, or both cannot be overloaded. 3752 3753 // Check the exception specifications match. This may recompute the type of 3754 // both Old and New if it resolved exception specifications, so grab the 3755 // types again after this. Because this updates the type, we do this before 3756 // any of the other checks below, which may update the "de facto" NewQType 3757 // but do not necessarily update the type of New. 3758 if (CheckEquivalentExceptionSpec(Old, New)) 3759 return true; 3760 OldQType = Context.getCanonicalType(Old->getType()); 3761 NewQType = Context.getCanonicalType(New->getType()); 3762 3763 // Go back to the type source info to compare the declared return types, 3764 // per C++1y [dcl.type.auto]p13: 3765 // Redeclarations or specializations of a function or function template 3766 // with a declared return type that uses a placeholder type shall also 3767 // use that placeholder, not a deduced type. 3768 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3769 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3770 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3771 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3772 OldDeclaredReturnType)) { 3773 QualType ResQT; 3774 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3775 OldDeclaredReturnType->isObjCObjectPointerType()) 3776 // FIXME: This does the wrong thing for a deduced return type. 3777 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3778 if (ResQT.isNull()) { 3779 if (New->isCXXClassMember() && New->isOutOfLine()) 3780 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3781 << New << New->getReturnTypeSourceRange(); 3782 else 3783 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3784 << New->getReturnTypeSourceRange(); 3785 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3786 << Old->getReturnTypeSourceRange(); 3787 return true; 3788 } 3789 else 3790 NewQType = ResQT; 3791 } 3792 3793 QualType OldReturnType = OldType->getReturnType(); 3794 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3795 if (OldReturnType != NewReturnType) { 3796 // If this function has a deduced return type and has already been 3797 // defined, copy the deduced value from the old declaration. 3798 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3799 if (OldAT && OldAT->isDeduced()) { 3800 QualType DT = OldAT->getDeducedType(); 3801 if (DT.isNull()) { 3802 New->setType(SubstAutoTypeDependent(New->getType())); 3803 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3804 } else { 3805 New->setType(SubstAutoType(New->getType(), DT)); 3806 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3807 } 3808 } 3809 } 3810 3811 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3812 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3813 if (OldMethod && NewMethod) { 3814 // Preserve triviality. 3815 NewMethod->setTrivial(OldMethod->isTrivial()); 3816 3817 // MSVC allows explicit template specialization at class scope: 3818 // 2 CXXMethodDecls referring to the same function will be injected. 3819 // We don't want a redeclaration error. 3820 bool IsClassScopeExplicitSpecialization = 3821 OldMethod->isFunctionTemplateSpecialization() && 3822 NewMethod->isFunctionTemplateSpecialization(); 3823 bool isFriend = NewMethod->getFriendObjectKind(); 3824 3825 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3826 !IsClassScopeExplicitSpecialization) { 3827 // -- Member function declarations with the same name and the 3828 // same parameter types cannot be overloaded if any of them 3829 // is a static member function declaration. 3830 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3831 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3832 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3833 return true; 3834 } 3835 3836 // C++ [class.mem]p1: 3837 // [...] A member shall not be declared twice in the 3838 // member-specification, except that a nested class or member 3839 // class template can be declared and then later defined. 3840 if (!inTemplateInstantiation()) { 3841 unsigned NewDiag; 3842 if (isa<CXXConstructorDecl>(OldMethod)) 3843 NewDiag = diag::err_constructor_redeclared; 3844 else if (isa<CXXDestructorDecl>(NewMethod)) 3845 NewDiag = diag::err_destructor_redeclared; 3846 else if (isa<CXXConversionDecl>(NewMethod)) 3847 NewDiag = diag::err_conv_function_redeclared; 3848 else 3849 NewDiag = diag::err_member_redeclared; 3850 3851 Diag(New->getLocation(), NewDiag); 3852 } else { 3853 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3854 << New << New->getType(); 3855 } 3856 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3857 return true; 3858 3859 // Complain if this is an explicit declaration of a special 3860 // member that was initially declared implicitly. 3861 // 3862 // As an exception, it's okay to befriend such methods in order 3863 // to permit the implicit constructor/destructor/operator calls. 3864 } else if (OldMethod->isImplicit()) { 3865 if (isFriend) { 3866 NewMethod->setImplicit(); 3867 } else { 3868 Diag(NewMethod->getLocation(), 3869 diag::err_definition_of_implicitly_declared_member) 3870 << New << getSpecialMember(OldMethod); 3871 return true; 3872 } 3873 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3874 Diag(NewMethod->getLocation(), 3875 diag::err_definition_of_explicitly_defaulted_member) 3876 << getSpecialMember(OldMethod); 3877 return true; 3878 } 3879 } 3880 3881 // C++11 [dcl.attr.noreturn]p1: 3882 // The first declaration of a function shall specify the noreturn 3883 // attribute if any declaration of that function specifies the noreturn 3884 // attribute. 3885 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3886 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3887 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3888 << NRA; 3889 Diag(Old->getLocation(), diag::note_previous_declaration); 3890 } 3891 3892 // C++11 [dcl.attr.depend]p2: 3893 // The first declaration of a function shall specify the 3894 // carries_dependency attribute for its declarator-id if any declaration 3895 // of the function specifies the carries_dependency attribute. 3896 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3897 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3898 Diag(CDA->getLocation(), 3899 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3900 Diag(Old->getFirstDecl()->getLocation(), 3901 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3902 } 3903 3904 // (C++98 8.3.5p3): 3905 // All declarations for a function shall agree exactly in both the 3906 // return type and the parameter-type-list. 3907 // We also want to respect all the extended bits except noreturn. 3908 3909 // noreturn should now match unless the old type info didn't have it. 3910 QualType OldQTypeForComparison = OldQType; 3911 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3912 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3913 const FunctionType *OldTypeForComparison 3914 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3915 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3916 assert(OldQTypeForComparison.isCanonical()); 3917 } 3918 3919 if (haveIncompatibleLanguageLinkages(Old, New)) { 3920 // As a special case, retain the language linkage from previous 3921 // declarations of a friend function as an extension. 3922 // 3923 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3924 // and is useful because there's otherwise no way to specify language 3925 // linkage within class scope. 3926 // 3927 // Check cautiously as the friend object kind isn't yet complete. 3928 if (New->getFriendObjectKind() != Decl::FOK_None) { 3929 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3930 Diag(OldLocation, PrevDiag); 3931 } else { 3932 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3933 Diag(OldLocation, PrevDiag); 3934 return true; 3935 } 3936 } 3937 3938 // If the function types are compatible, merge the declarations. Ignore the 3939 // exception specifier because it was already checked above in 3940 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3941 // about incompatible types under -fms-compatibility. 3942 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3943 NewQType)) 3944 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3945 3946 // If the types are imprecise (due to dependent constructs in friends or 3947 // local extern declarations), it's OK if they differ. We'll check again 3948 // during instantiation. 3949 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3950 return false; 3951 3952 // Fall through for conflicting redeclarations and redefinitions. 3953 } 3954 3955 // C: Function types need to be compatible, not identical. This handles 3956 // duplicate function decls like "void f(int); void f(enum X);" properly. 3957 if (!getLangOpts().CPlusPlus) { 3958 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other 3959 // type is specified by a function definition that contains a (possibly 3960 // empty) identifier list, both shall agree in the number of parameters 3961 // and the type of each parameter shall be compatible with the type that 3962 // results from the application of default argument promotions to the 3963 // type of the corresponding identifier. ... 3964 // This cannot be handled by ASTContext::typesAreCompatible() because that 3965 // doesn't know whether the function type is for a definition or not when 3966 // eventually calling ASTContext::mergeFunctionTypes(). The only situation 3967 // we need to cover here is that the number of arguments agree as the 3968 // default argument promotion rules were already checked by 3969 // ASTContext::typesAreCompatible(). 3970 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn && 3971 Old->getNumParams() != New->getNumParams()) { 3972 if (Old->hasInheritedPrototype()) 3973 Old = Old->getCanonicalDecl(); 3974 Diag(New->getLocation(), diag::err_conflicting_types) << New; 3975 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 3976 return true; 3977 } 3978 3979 // If we are merging two functions where only one of them has a prototype, 3980 // we may have enough information to decide to issue a diagnostic that the 3981 // function without a protoype will change behavior in C2x. This handles 3982 // cases like: 3983 // void i(); void i(int j); 3984 // void i(int j); void i(); 3985 // void i(); void i(int j) {} 3986 // See ActOnFinishFunctionBody() for other cases of the behavior change 3987 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 3988 // type without a prototype. 3989 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && 3990 !New->isImplicit() && !Old->isImplicit()) { 3991 const FunctionDecl *WithProto, *WithoutProto; 3992 if (New->hasWrittenPrototype()) { 3993 WithProto = New; 3994 WithoutProto = Old; 3995 } else { 3996 WithProto = Old; 3997 WithoutProto = New; 3998 } 3999 4000 if (WithProto->getNumParams() != 0) { 4001 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) { 4002 // The one without the prototype will be changing behavior in C2x, so 4003 // warn about that one so long as it's a user-visible declaration. 4004 bool IsWithoutProtoADef = false, IsWithProtoADef = false; 4005 if (WithoutProto == New) 4006 IsWithoutProtoADef = NewDeclIsDefn; 4007 else 4008 IsWithProtoADef = NewDeclIsDefn; 4009 Diag(WithoutProto->getLocation(), 4010 diag::warn_non_prototype_changes_behavior) 4011 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1) 4012 << (WithoutProto == Old) << IsWithProtoADef; 4013 4014 // The reason the one without the prototype will be changing behavior 4015 // is because of the one with the prototype, so note that so long as 4016 // it's a user-visible declaration. There is one exception to this: 4017 // when the new declaration is a definition without a prototype, the 4018 // old declaration with a prototype is not the cause of the issue, 4019 // and that does not need to be noted because the one with a 4020 // prototype will not change behavior in C2x. 4021 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() && 4022 !IsWithoutProtoADef) 4023 Diag(WithProto->getLocation(), diag::note_conflicting_prototype); 4024 } 4025 } 4026 } 4027 4028 if (Context.typesAreCompatible(OldQType, NewQType)) { 4029 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 4030 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 4031 const FunctionProtoType *OldProto = nullptr; 4032 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 4033 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 4034 // The old declaration provided a function prototype, but the 4035 // new declaration does not. Merge in the prototype. 4036 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 4037 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 4038 NewQType = 4039 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 4040 OldProto->getExtProtoInfo()); 4041 New->setType(NewQType); 4042 New->setHasInheritedPrototype(); 4043 4044 // Synthesize parameters with the same types. 4045 SmallVector<ParmVarDecl *, 16> Params; 4046 for (const auto &ParamType : OldProto->param_types()) { 4047 ParmVarDecl *Param = ParmVarDecl::Create( 4048 Context, New, SourceLocation(), SourceLocation(), nullptr, 4049 ParamType, /*TInfo=*/nullptr, SC_None, nullptr); 4050 Param->setScopeInfo(0, Params.size()); 4051 Param->setImplicit(); 4052 Params.push_back(Param); 4053 } 4054 4055 New->setParams(Params); 4056 } 4057 4058 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4059 } 4060 } 4061 4062 // Check if the function types are compatible when pointer size address 4063 // spaces are ignored. 4064 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 4065 return false; 4066 4067 // GNU C permits a K&R definition to follow a prototype declaration 4068 // if the declared types of the parameters in the K&R definition 4069 // match the types in the prototype declaration, even when the 4070 // promoted types of the parameters from the K&R definition differ 4071 // from the types in the prototype. GCC then keeps the types from 4072 // the prototype. 4073 // 4074 // If a variadic prototype is followed by a non-variadic K&R definition, 4075 // the K&R definition becomes variadic. This is sort of an edge case, but 4076 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 4077 // C99 6.9.1p8. 4078 if (!getLangOpts().CPlusPlus && 4079 Old->hasPrototype() && !New->hasPrototype() && 4080 New->getType()->getAs<FunctionProtoType>() && 4081 Old->getNumParams() == New->getNumParams()) { 4082 SmallVector<QualType, 16> ArgTypes; 4083 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 4084 const FunctionProtoType *OldProto 4085 = Old->getType()->getAs<FunctionProtoType>(); 4086 const FunctionProtoType *NewProto 4087 = New->getType()->getAs<FunctionProtoType>(); 4088 4089 // Determine whether this is the GNU C extension. 4090 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 4091 NewProto->getReturnType()); 4092 bool LooseCompatible = !MergedReturn.isNull(); 4093 for (unsigned Idx = 0, End = Old->getNumParams(); 4094 LooseCompatible && Idx != End; ++Idx) { 4095 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 4096 ParmVarDecl *NewParm = New->getParamDecl(Idx); 4097 if (Context.typesAreCompatible(OldParm->getType(), 4098 NewProto->getParamType(Idx))) { 4099 ArgTypes.push_back(NewParm->getType()); 4100 } else if (Context.typesAreCompatible(OldParm->getType(), 4101 NewParm->getType(), 4102 /*CompareUnqualified=*/true)) { 4103 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 4104 NewProto->getParamType(Idx) }; 4105 Warnings.push_back(Warn); 4106 ArgTypes.push_back(NewParm->getType()); 4107 } else 4108 LooseCompatible = false; 4109 } 4110 4111 if (LooseCompatible) { 4112 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 4113 Diag(Warnings[Warn].NewParm->getLocation(), 4114 diag::ext_param_promoted_not_compatible_with_prototype) 4115 << Warnings[Warn].PromotedType 4116 << Warnings[Warn].OldParm->getType(); 4117 if (Warnings[Warn].OldParm->getLocation().isValid()) 4118 Diag(Warnings[Warn].OldParm->getLocation(), 4119 diag::note_previous_declaration); 4120 } 4121 4122 if (MergeTypeWithOld) 4123 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 4124 OldProto->getExtProtoInfo())); 4125 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4126 } 4127 4128 // Fall through to diagnose conflicting types. 4129 } 4130 4131 // A function that has already been declared has been redeclared or 4132 // defined with a different type; show an appropriate diagnostic. 4133 4134 // If the previous declaration was an implicitly-generated builtin 4135 // declaration, then at the very least we should use a specialized note. 4136 unsigned BuiltinID; 4137 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 4138 // If it's actually a library-defined builtin function like 'malloc' 4139 // or 'printf', just warn about the incompatible redeclaration. 4140 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4141 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 4142 Diag(OldLocation, diag::note_previous_builtin_declaration) 4143 << Old << Old->getType(); 4144 return false; 4145 } 4146 4147 PrevDiag = diag::note_previous_builtin_declaration; 4148 } 4149 4150 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 4151 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4152 return true; 4153 } 4154 4155 /// Completes the merge of two function declarations that are 4156 /// known to be compatible. 4157 /// 4158 /// This routine handles the merging of attributes and other 4159 /// properties of function declarations from the old declaration to 4160 /// the new declaration, once we know that New is in fact a 4161 /// redeclaration of Old. 4162 /// 4163 /// \returns false 4164 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 4165 Scope *S, bool MergeTypeWithOld) { 4166 // Merge the attributes 4167 mergeDeclAttributes(New, Old); 4168 4169 // Merge "pure" flag. 4170 if (Old->isPure()) 4171 New->setPure(); 4172 4173 // Merge "used" flag. 4174 if (Old->getMostRecentDecl()->isUsed(false)) 4175 New->setIsUsed(); 4176 4177 // Merge attributes from the parameters. These can mismatch with K&R 4178 // declarations. 4179 if (New->getNumParams() == Old->getNumParams()) 4180 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 4181 ParmVarDecl *NewParam = New->getParamDecl(i); 4182 ParmVarDecl *OldParam = Old->getParamDecl(i); 4183 mergeParamDeclAttributes(NewParam, OldParam, *this); 4184 mergeParamDeclTypes(NewParam, OldParam, *this); 4185 } 4186 4187 if (getLangOpts().CPlusPlus) 4188 return MergeCXXFunctionDecl(New, Old, S); 4189 4190 // Merge the function types so the we get the composite types for the return 4191 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 4192 // was visible. 4193 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 4194 if (!Merged.isNull() && MergeTypeWithOld) 4195 New->setType(Merged); 4196 4197 return false; 4198 } 4199 4200 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4201 ObjCMethodDecl *oldMethod) { 4202 // Merge the attributes, including deprecated/unavailable 4203 AvailabilityMergeKind MergeKind = 4204 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4205 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4206 : AMK_ProtocolImplementation) 4207 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4208 : AMK_Override; 4209 4210 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4211 4212 // Merge attributes from the parameters. 4213 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4214 oe = oldMethod->param_end(); 4215 for (ObjCMethodDecl::param_iterator 4216 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4217 ni != ne && oi != oe; ++ni, ++oi) 4218 mergeParamDeclAttributes(*ni, *oi, *this); 4219 4220 CheckObjCMethodOverride(newMethod, oldMethod); 4221 } 4222 4223 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4224 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4225 4226 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4227 ? diag::err_redefinition_different_type 4228 : diag::err_redeclaration_different_type) 4229 << New->getDeclName() << New->getType() << Old->getType(); 4230 4231 diag::kind PrevDiag; 4232 SourceLocation OldLocation; 4233 std::tie(PrevDiag, OldLocation) 4234 = getNoteDiagForInvalidRedeclaration(Old, New); 4235 S.Diag(OldLocation, PrevDiag); 4236 New->setInvalidDecl(); 4237 } 4238 4239 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4240 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4241 /// emitting diagnostics as appropriate. 4242 /// 4243 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4244 /// to here in AddInitializerToDecl. We can't check them before the initializer 4245 /// is attached. 4246 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4247 bool MergeTypeWithOld) { 4248 if (New->isInvalidDecl() || Old->isInvalidDecl()) 4249 return; 4250 4251 QualType MergedT; 4252 if (getLangOpts().CPlusPlus) { 4253 if (New->getType()->isUndeducedType()) { 4254 // We don't know what the new type is until the initializer is attached. 4255 return; 4256 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4257 // These could still be something that needs exception specs checked. 4258 return MergeVarDeclExceptionSpecs(New, Old); 4259 } 4260 // C++ [basic.link]p10: 4261 // [...] the types specified by all declarations referring to a given 4262 // object or function shall be identical, except that declarations for an 4263 // array object can specify array types that differ by the presence or 4264 // absence of a major array bound (8.3.4). 4265 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4266 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4267 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4268 4269 // We are merging a variable declaration New into Old. If it has an array 4270 // bound, and that bound differs from Old's bound, we should diagnose the 4271 // mismatch. 4272 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4273 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4274 PrevVD = PrevVD->getPreviousDecl()) { 4275 QualType PrevVDTy = PrevVD->getType(); 4276 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4277 continue; 4278 4279 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4280 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4281 } 4282 } 4283 4284 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4285 if (Context.hasSameType(OldArray->getElementType(), 4286 NewArray->getElementType())) 4287 MergedT = New->getType(); 4288 } 4289 // FIXME: Check visibility. New is hidden but has a complete type. If New 4290 // has no array bound, it should not inherit one from Old, if Old is not 4291 // visible. 4292 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4293 if (Context.hasSameType(OldArray->getElementType(), 4294 NewArray->getElementType())) 4295 MergedT = Old->getType(); 4296 } 4297 } 4298 else if (New->getType()->isObjCObjectPointerType() && 4299 Old->getType()->isObjCObjectPointerType()) { 4300 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4301 Old->getType()); 4302 } 4303 } else { 4304 // C 6.2.7p2: 4305 // All declarations that refer to the same object or function shall have 4306 // compatible type. 4307 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4308 } 4309 if (MergedT.isNull()) { 4310 // It's OK if we couldn't merge types if either type is dependent, for a 4311 // block-scope variable. In other cases (static data members of class 4312 // templates, variable templates, ...), we require the types to be 4313 // equivalent. 4314 // FIXME: The C++ standard doesn't say anything about this. 4315 if ((New->getType()->isDependentType() || 4316 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4317 // If the old type was dependent, we can't merge with it, so the new type 4318 // becomes dependent for now. We'll reproduce the original type when we 4319 // instantiate the TypeSourceInfo for the variable. 4320 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4321 New->setType(Context.DependentTy); 4322 return; 4323 } 4324 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4325 } 4326 4327 // Don't actually update the type on the new declaration if the old 4328 // declaration was an extern declaration in a different scope. 4329 if (MergeTypeWithOld) 4330 New->setType(MergedT); 4331 } 4332 4333 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4334 LookupResult &Previous) { 4335 // C11 6.2.7p4: 4336 // For an identifier with internal or external linkage declared 4337 // in a scope in which a prior declaration of that identifier is 4338 // visible, if the prior declaration specifies internal or 4339 // external linkage, the type of the identifier at the later 4340 // declaration becomes the composite type. 4341 // 4342 // If the variable isn't visible, we do not merge with its type. 4343 if (Previous.isShadowed()) 4344 return false; 4345 4346 if (S.getLangOpts().CPlusPlus) { 4347 // C++11 [dcl.array]p3: 4348 // If there is a preceding declaration of the entity in the same 4349 // scope in which the bound was specified, an omitted array bound 4350 // is taken to be the same as in that earlier declaration. 4351 return NewVD->isPreviousDeclInSameBlockScope() || 4352 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4353 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4354 } else { 4355 // If the old declaration was function-local, don't merge with its 4356 // type unless we're in the same function. 4357 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4358 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4359 } 4360 } 4361 4362 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4363 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4364 /// situation, merging decls or emitting diagnostics as appropriate. 4365 /// 4366 /// Tentative definition rules (C99 6.9.2p2) are checked by 4367 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4368 /// definitions here, since the initializer hasn't been attached. 4369 /// 4370 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4371 // If the new decl is already invalid, don't do any other checking. 4372 if (New->isInvalidDecl()) 4373 return; 4374 4375 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4376 return; 4377 4378 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4379 4380 // Verify the old decl was also a variable or variable template. 4381 VarDecl *Old = nullptr; 4382 VarTemplateDecl *OldTemplate = nullptr; 4383 if (Previous.isSingleResult()) { 4384 if (NewTemplate) { 4385 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4386 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4387 4388 if (auto *Shadow = 4389 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4390 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4391 return New->setInvalidDecl(); 4392 } else { 4393 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4394 4395 if (auto *Shadow = 4396 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4397 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4398 return New->setInvalidDecl(); 4399 } 4400 } 4401 if (!Old) { 4402 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4403 << New->getDeclName(); 4404 notePreviousDefinition(Previous.getRepresentativeDecl(), 4405 New->getLocation()); 4406 return New->setInvalidDecl(); 4407 } 4408 4409 // If the old declaration was found in an inline namespace and the new 4410 // declaration was qualified, update the DeclContext to match. 4411 adjustDeclContextForDeclaratorDecl(New, Old); 4412 4413 // Ensure the template parameters are compatible. 4414 if (NewTemplate && 4415 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4416 OldTemplate->getTemplateParameters(), 4417 /*Complain=*/true, TPL_TemplateMatch)) 4418 return New->setInvalidDecl(); 4419 4420 // C++ [class.mem]p1: 4421 // A member shall not be declared twice in the member-specification [...] 4422 // 4423 // Here, we need only consider static data members. 4424 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4425 Diag(New->getLocation(), diag::err_duplicate_member) 4426 << New->getIdentifier(); 4427 Diag(Old->getLocation(), diag::note_previous_declaration); 4428 New->setInvalidDecl(); 4429 } 4430 4431 mergeDeclAttributes(New, Old); 4432 // Warn if an already-declared variable is made a weak_import in a subsequent 4433 // declaration 4434 if (New->hasAttr<WeakImportAttr>() && 4435 Old->getStorageClass() == SC_None && 4436 !Old->hasAttr<WeakImportAttr>()) { 4437 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4438 Diag(Old->getLocation(), diag::note_previous_declaration); 4439 // Remove weak_import attribute on new declaration. 4440 New->dropAttr<WeakImportAttr>(); 4441 } 4442 4443 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4444 if (!Old->hasAttr<InternalLinkageAttr>()) { 4445 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4446 << ILA; 4447 Diag(Old->getLocation(), diag::note_previous_declaration); 4448 New->dropAttr<InternalLinkageAttr>(); 4449 } 4450 4451 // Merge the types. 4452 VarDecl *MostRecent = Old->getMostRecentDecl(); 4453 if (MostRecent != Old) { 4454 MergeVarDeclTypes(New, MostRecent, 4455 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4456 if (New->isInvalidDecl()) 4457 return; 4458 } 4459 4460 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4461 if (New->isInvalidDecl()) 4462 return; 4463 4464 diag::kind PrevDiag; 4465 SourceLocation OldLocation; 4466 std::tie(PrevDiag, OldLocation) = 4467 getNoteDiagForInvalidRedeclaration(Old, New); 4468 4469 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4470 if (New->getStorageClass() == SC_Static && 4471 !New->isStaticDataMember() && 4472 Old->hasExternalFormalLinkage()) { 4473 if (getLangOpts().MicrosoftExt) { 4474 Diag(New->getLocation(), diag::ext_static_non_static) 4475 << New->getDeclName(); 4476 Diag(OldLocation, PrevDiag); 4477 } else { 4478 Diag(New->getLocation(), diag::err_static_non_static) 4479 << New->getDeclName(); 4480 Diag(OldLocation, PrevDiag); 4481 return New->setInvalidDecl(); 4482 } 4483 } 4484 // C99 6.2.2p4: 4485 // For an identifier declared with the storage-class specifier 4486 // extern in a scope in which a prior declaration of that 4487 // identifier is visible,23) if the prior declaration specifies 4488 // internal or external linkage, the linkage of the identifier at 4489 // the later declaration is the same as the linkage specified at 4490 // the prior declaration. If no prior declaration is visible, or 4491 // if the prior declaration specifies no linkage, then the 4492 // identifier has external linkage. 4493 if (New->hasExternalStorage() && Old->hasLinkage()) 4494 /* Okay */; 4495 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4496 !New->isStaticDataMember() && 4497 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4498 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4499 Diag(OldLocation, PrevDiag); 4500 return New->setInvalidDecl(); 4501 } 4502 4503 // Check if extern is followed by non-extern and vice-versa. 4504 if (New->hasExternalStorage() && 4505 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4506 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4507 Diag(OldLocation, PrevDiag); 4508 return New->setInvalidDecl(); 4509 } 4510 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4511 !New->hasExternalStorage()) { 4512 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4513 Diag(OldLocation, PrevDiag); 4514 return New->setInvalidDecl(); 4515 } 4516 4517 if (CheckRedeclarationInModule(New, Old)) 4518 return; 4519 4520 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4521 4522 // FIXME: The test for external storage here seems wrong? We still 4523 // need to check for mismatches. 4524 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4525 // Don't complain about out-of-line definitions of static members. 4526 !(Old->getLexicalDeclContext()->isRecord() && 4527 !New->getLexicalDeclContext()->isRecord())) { 4528 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4529 Diag(OldLocation, PrevDiag); 4530 return New->setInvalidDecl(); 4531 } 4532 4533 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4534 if (VarDecl *Def = Old->getDefinition()) { 4535 // C++1z [dcl.fcn.spec]p4: 4536 // If the definition of a variable appears in a translation unit before 4537 // its first declaration as inline, the program is ill-formed. 4538 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4539 Diag(Def->getLocation(), diag::note_previous_definition); 4540 } 4541 } 4542 4543 // If this redeclaration makes the variable inline, we may need to add it to 4544 // UndefinedButUsed. 4545 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4546 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4547 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4548 SourceLocation())); 4549 4550 if (New->getTLSKind() != Old->getTLSKind()) { 4551 if (!Old->getTLSKind()) { 4552 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4553 Diag(OldLocation, PrevDiag); 4554 } else if (!New->getTLSKind()) { 4555 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4556 Diag(OldLocation, PrevDiag); 4557 } else { 4558 // Do not allow redeclaration to change the variable between requiring 4559 // static and dynamic initialization. 4560 // FIXME: GCC allows this, but uses the TLS keyword on the first 4561 // declaration to determine the kind. Do we need to be compatible here? 4562 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4563 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4564 Diag(OldLocation, PrevDiag); 4565 } 4566 } 4567 4568 // C++ doesn't have tentative definitions, so go right ahead and check here. 4569 if (getLangOpts().CPlusPlus) { 4570 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4571 Old->getCanonicalDecl()->isConstexpr()) { 4572 // This definition won't be a definition any more once it's been merged. 4573 Diag(New->getLocation(), 4574 diag::warn_deprecated_redundant_constexpr_static_def); 4575 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) { 4576 VarDecl *Def = Old->getDefinition(); 4577 if (Def && checkVarDeclRedefinition(Def, New)) 4578 return; 4579 } 4580 } 4581 4582 if (haveIncompatibleLanguageLinkages(Old, New)) { 4583 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4584 Diag(OldLocation, PrevDiag); 4585 New->setInvalidDecl(); 4586 return; 4587 } 4588 4589 // Merge "used" flag. 4590 if (Old->getMostRecentDecl()->isUsed(false)) 4591 New->setIsUsed(); 4592 4593 // Keep a chain of previous declarations. 4594 New->setPreviousDecl(Old); 4595 if (NewTemplate) 4596 NewTemplate->setPreviousDecl(OldTemplate); 4597 4598 // Inherit access appropriately. 4599 New->setAccess(Old->getAccess()); 4600 if (NewTemplate) 4601 NewTemplate->setAccess(New->getAccess()); 4602 4603 if (Old->isInline()) 4604 New->setImplicitlyInline(); 4605 } 4606 4607 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4608 SourceManager &SrcMgr = getSourceManager(); 4609 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4610 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4611 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4612 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4613 auto &HSI = PP.getHeaderSearchInfo(); 4614 StringRef HdrFilename = 4615 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4616 4617 auto noteFromModuleOrInclude = [&](Module *Mod, 4618 SourceLocation IncLoc) -> bool { 4619 // Redefinition errors with modules are common with non modular mapped 4620 // headers, example: a non-modular header H in module A that also gets 4621 // included directly in a TU. Pointing twice to the same header/definition 4622 // is confusing, try to get better diagnostics when modules is on. 4623 if (IncLoc.isValid()) { 4624 if (Mod) { 4625 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4626 << HdrFilename.str() << Mod->getFullModuleName(); 4627 if (!Mod->DefinitionLoc.isInvalid()) 4628 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4629 << Mod->getFullModuleName(); 4630 } else { 4631 Diag(IncLoc, diag::note_redefinition_include_same_file) 4632 << HdrFilename.str(); 4633 } 4634 return true; 4635 } 4636 4637 return false; 4638 }; 4639 4640 // Is it the same file and same offset? Provide more information on why 4641 // this leads to a redefinition error. 4642 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4643 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4644 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4645 bool EmittedDiag = 4646 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4647 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4648 4649 // If the header has no guards, emit a note suggesting one. 4650 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4651 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4652 4653 if (EmittedDiag) 4654 return; 4655 } 4656 4657 // Redefinition coming from different files or couldn't do better above. 4658 if (Old->getLocation().isValid()) 4659 Diag(Old->getLocation(), diag::note_previous_definition); 4660 } 4661 4662 /// We've just determined that \p Old and \p New both appear to be definitions 4663 /// of the same variable. Either diagnose or fix the problem. 4664 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4665 if (!hasVisibleDefinition(Old) && 4666 (New->getFormalLinkage() == InternalLinkage || 4667 New->isInline() || 4668 New->getDescribedVarTemplate() || 4669 New->getNumTemplateParameterLists() || 4670 New->getDeclContext()->isDependentContext())) { 4671 // The previous definition is hidden, and multiple definitions are 4672 // permitted (in separate TUs). Demote this to a declaration. 4673 New->demoteThisDefinitionToDeclaration(); 4674 4675 // Make the canonical definition visible. 4676 if (auto *OldTD = Old->getDescribedVarTemplate()) 4677 makeMergedDefinitionVisible(OldTD); 4678 makeMergedDefinitionVisible(Old); 4679 return false; 4680 } else { 4681 Diag(New->getLocation(), diag::err_redefinition) << New; 4682 notePreviousDefinition(Old, New->getLocation()); 4683 New->setInvalidDecl(); 4684 return true; 4685 } 4686 } 4687 4688 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4689 /// no declarator (e.g. "struct foo;") is parsed. 4690 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 4691 DeclSpec &DS, 4692 const ParsedAttributesView &DeclAttrs, 4693 RecordDecl *&AnonRecord) { 4694 return ParsedFreeStandingDeclSpec( 4695 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord); 4696 } 4697 4698 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4699 // disambiguate entities defined in different scopes. 4700 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4701 // compatibility. 4702 // We will pick our mangling number depending on which version of MSVC is being 4703 // targeted. 4704 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4705 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4706 ? S->getMSCurManglingNumber() 4707 : S->getMSLastManglingNumber(); 4708 } 4709 4710 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4711 if (!Context.getLangOpts().CPlusPlus) 4712 return; 4713 4714 if (isa<CXXRecordDecl>(Tag->getParent())) { 4715 // If this tag is the direct child of a class, number it if 4716 // it is anonymous. 4717 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4718 return; 4719 MangleNumberingContext &MCtx = 4720 Context.getManglingNumberContext(Tag->getParent()); 4721 Context.setManglingNumber( 4722 Tag, MCtx.getManglingNumber( 4723 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4724 return; 4725 } 4726 4727 // If this tag isn't a direct child of a class, number it if it is local. 4728 MangleNumberingContext *MCtx; 4729 Decl *ManglingContextDecl; 4730 std::tie(MCtx, ManglingContextDecl) = 4731 getCurrentMangleNumberContext(Tag->getDeclContext()); 4732 if (MCtx) { 4733 Context.setManglingNumber( 4734 Tag, MCtx->getManglingNumber( 4735 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4736 } 4737 } 4738 4739 namespace { 4740 struct NonCLikeKind { 4741 enum { 4742 None, 4743 BaseClass, 4744 DefaultMemberInit, 4745 Lambda, 4746 Friend, 4747 OtherMember, 4748 Invalid, 4749 } Kind = None; 4750 SourceRange Range; 4751 4752 explicit operator bool() { return Kind != None; } 4753 }; 4754 } 4755 4756 /// Determine whether a class is C-like, according to the rules of C++ 4757 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4758 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4759 if (RD->isInvalidDecl()) 4760 return {NonCLikeKind::Invalid, {}}; 4761 4762 // C++ [dcl.typedef]p9: [P1766R1] 4763 // An unnamed class with a typedef name for linkage purposes shall not 4764 // 4765 // -- have any base classes 4766 if (RD->getNumBases()) 4767 return {NonCLikeKind::BaseClass, 4768 SourceRange(RD->bases_begin()->getBeginLoc(), 4769 RD->bases_end()[-1].getEndLoc())}; 4770 bool Invalid = false; 4771 for (Decl *D : RD->decls()) { 4772 // Don't complain about things we already diagnosed. 4773 if (D->isInvalidDecl()) { 4774 Invalid = true; 4775 continue; 4776 } 4777 4778 // -- have any [...] default member initializers 4779 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4780 if (FD->hasInClassInitializer()) { 4781 auto *Init = FD->getInClassInitializer(); 4782 return {NonCLikeKind::DefaultMemberInit, 4783 Init ? Init->getSourceRange() : D->getSourceRange()}; 4784 } 4785 continue; 4786 } 4787 4788 // FIXME: We don't allow friend declarations. This violates the wording of 4789 // P1766, but not the intent. 4790 if (isa<FriendDecl>(D)) 4791 return {NonCLikeKind::Friend, D->getSourceRange()}; 4792 4793 // -- declare any members other than non-static data members, member 4794 // enumerations, or member classes, 4795 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4796 isa<EnumDecl>(D)) 4797 continue; 4798 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4799 if (!MemberRD) { 4800 if (D->isImplicit()) 4801 continue; 4802 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4803 } 4804 4805 // -- contain a lambda-expression, 4806 if (MemberRD->isLambda()) 4807 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4808 4809 // and all member classes shall also satisfy these requirements 4810 // (recursively). 4811 if (MemberRD->isThisDeclarationADefinition()) { 4812 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4813 return Kind; 4814 } 4815 } 4816 4817 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4818 } 4819 4820 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4821 TypedefNameDecl *NewTD) { 4822 if (TagFromDeclSpec->isInvalidDecl()) 4823 return; 4824 4825 // Do nothing if the tag already has a name for linkage purposes. 4826 if (TagFromDeclSpec->hasNameForLinkage()) 4827 return; 4828 4829 // A well-formed anonymous tag must always be a TUK_Definition. 4830 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4831 4832 // The type must match the tag exactly; no qualifiers allowed. 4833 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4834 Context.getTagDeclType(TagFromDeclSpec))) { 4835 if (getLangOpts().CPlusPlus) 4836 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4837 return; 4838 } 4839 4840 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4841 // An unnamed class with a typedef name for linkage purposes shall [be 4842 // C-like]. 4843 // 4844 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4845 // shouldn't happen, but there are constructs that the language rule doesn't 4846 // disallow for which we can't reasonably avoid computing linkage early. 4847 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4848 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4849 : NonCLikeKind(); 4850 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4851 if (NonCLike || ChangesLinkage) { 4852 if (NonCLike.Kind == NonCLikeKind::Invalid) 4853 return; 4854 4855 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4856 if (ChangesLinkage) { 4857 // If the linkage changes, we can't accept this as an extension. 4858 if (NonCLike.Kind == NonCLikeKind::None) 4859 DiagID = diag::err_typedef_changes_linkage; 4860 else 4861 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4862 } 4863 4864 SourceLocation FixitLoc = 4865 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4866 llvm::SmallString<40> TextToInsert; 4867 TextToInsert += ' '; 4868 TextToInsert += NewTD->getIdentifier()->getName(); 4869 4870 Diag(FixitLoc, DiagID) 4871 << isa<TypeAliasDecl>(NewTD) 4872 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4873 if (NonCLike.Kind != NonCLikeKind::None) { 4874 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4875 << NonCLike.Kind - 1 << NonCLike.Range; 4876 } 4877 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4878 << NewTD << isa<TypeAliasDecl>(NewTD); 4879 4880 if (ChangesLinkage) 4881 return; 4882 } 4883 4884 // Otherwise, set this as the anon-decl typedef for the tag. 4885 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4886 } 4887 4888 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4889 switch (T) { 4890 case DeclSpec::TST_class: 4891 return 0; 4892 case DeclSpec::TST_struct: 4893 return 1; 4894 case DeclSpec::TST_interface: 4895 return 2; 4896 case DeclSpec::TST_union: 4897 return 3; 4898 case DeclSpec::TST_enum: 4899 return 4; 4900 default: 4901 llvm_unreachable("unexpected type specifier"); 4902 } 4903 } 4904 4905 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4906 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4907 /// parameters to cope with template friend declarations. 4908 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 4909 DeclSpec &DS, 4910 const ParsedAttributesView &DeclAttrs, 4911 MultiTemplateParamsArg TemplateParams, 4912 bool IsExplicitInstantiation, 4913 RecordDecl *&AnonRecord) { 4914 Decl *TagD = nullptr; 4915 TagDecl *Tag = nullptr; 4916 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4917 DS.getTypeSpecType() == DeclSpec::TST_struct || 4918 DS.getTypeSpecType() == DeclSpec::TST_interface || 4919 DS.getTypeSpecType() == DeclSpec::TST_union || 4920 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4921 TagD = DS.getRepAsDecl(); 4922 4923 if (!TagD) // We probably had an error 4924 return nullptr; 4925 4926 // Note that the above type specs guarantee that the 4927 // type rep is a Decl, whereas in many of the others 4928 // it's a Type. 4929 if (isa<TagDecl>(TagD)) 4930 Tag = cast<TagDecl>(TagD); 4931 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4932 Tag = CTD->getTemplatedDecl(); 4933 } 4934 4935 if (Tag) { 4936 handleTagNumbering(Tag, S); 4937 Tag->setFreeStanding(); 4938 if (Tag->isInvalidDecl()) 4939 return Tag; 4940 } 4941 4942 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4943 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4944 // or incomplete types shall not be restrict-qualified." 4945 if (TypeQuals & DeclSpec::TQ_restrict) 4946 Diag(DS.getRestrictSpecLoc(), 4947 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4948 << DS.getSourceRange(); 4949 } 4950 4951 if (DS.isInlineSpecified()) 4952 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4953 << getLangOpts().CPlusPlus17; 4954 4955 if (DS.hasConstexprSpecifier()) { 4956 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4957 // and definitions of functions and variables. 4958 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4959 // the declaration of a function or function template 4960 if (Tag) 4961 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4962 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4963 << static_cast<int>(DS.getConstexprSpecifier()); 4964 else 4965 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4966 << static_cast<int>(DS.getConstexprSpecifier()); 4967 // Don't emit warnings after this error. 4968 return TagD; 4969 } 4970 4971 DiagnoseFunctionSpecifiers(DS); 4972 4973 if (DS.isFriendSpecified()) { 4974 // If we're dealing with a decl but not a TagDecl, assume that 4975 // whatever routines created it handled the friendship aspect. 4976 if (TagD && !Tag) 4977 return nullptr; 4978 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4979 } 4980 4981 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4982 bool IsExplicitSpecialization = 4983 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4984 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4985 !IsExplicitInstantiation && !IsExplicitSpecialization && 4986 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4987 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4988 // nested-name-specifier unless it is an explicit instantiation 4989 // or an explicit specialization. 4990 // 4991 // FIXME: We allow class template partial specializations here too, per the 4992 // obvious intent of DR1819. 4993 // 4994 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4995 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4996 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4997 return nullptr; 4998 } 4999 5000 // Track whether this decl-specifier declares anything. 5001 bool DeclaresAnything = true; 5002 5003 // Handle anonymous struct definitions. 5004 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 5005 if (!Record->getDeclName() && Record->isCompleteDefinition() && 5006 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 5007 if (getLangOpts().CPlusPlus || 5008 Record->getDeclContext()->isRecord()) { 5009 // If CurContext is a DeclContext that can contain statements, 5010 // RecursiveASTVisitor won't visit the decls that 5011 // BuildAnonymousStructOrUnion() will put into CurContext. 5012 // Also store them here so that they can be part of the 5013 // DeclStmt that gets created in this case. 5014 // FIXME: Also return the IndirectFieldDecls created by 5015 // BuildAnonymousStructOr union, for the same reason? 5016 if (CurContext->isFunctionOrMethod()) 5017 AnonRecord = Record; 5018 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 5019 Context.getPrintingPolicy()); 5020 } 5021 5022 DeclaresAnything = false; 5023 } 5024 } 5025 5026 // C11 6.7.2.1p2: 5027 // A struct-declaration that does not declare an anonymous structure or 5028 // anonymous union shall contain a struct-declarator-list. 5029 // 5030 // This rule also existed in C89 and C99; the grammar for struct-declaration 5031 // did not permit a struct-declaration without a struct-declarator-list. 5032 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 5033 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 5034 // Check for Microsoft C extension: anonymous struct/union member. 5035 // Handle 2 kinds of anonymous struct/union: 5036 // struct STRUCT; 5037 // union UNION; 5038 // and 5039 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 5040 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 5041 if ((Tag && Tag->getDeclName()) || 5042 DS.getTypeSpecType() == DeclSpec::TST_typename) { 5043 RecordDecl *Record = nullptr; 5044 if (Tag) 5045 Record = dyn_cast<RecordDecl>(Tag); 5046 else if (const RecordType *RT = 5047 DS.getRepAsType().get()->getAsStructureType()) 5048 Record = RT->getDecl(); 5049 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 5050 Record = UT->getDecl(); 5051 5052 if (Record && getLangOpts().MicrosoftExt) { 5053 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 5054 << Record->isUnion() << DS.getSourceRange(); 5055 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 5056 } 5057 5058 DeclaresAnything = false; 5059 } 5060 } 5061 5062 // Skip all the checks below if we have a type error. 5063 if (DS.getTypeSpecType() == DeclSpec::TST_error || 5064 (TagD && TagD->isInvalidDecl())) 5065 return TagD; 5066 5067 if (getLangOpts().CPlusPlus && 5068 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 5069 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 5070 if (Enum->enumerator_begin() == Enum->enumerator_end() && 5071 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 5072 DeclaresAnything = false; 5073 5074 if (!DS.isMissingDeclaratorOk()) { 5075 // Customize diagnostic for a typedef missing a name. 5076 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 5077 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 5078 << DS.getSourceRange(); 5079 else 5080 DeclaresAnything = false; 5081 } 5082 5083 if (DS.isModulePrivateSpecified() && 5084 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 5085 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 5086 << Tag->getTagKind() 5087 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 5088 5089 ActOnDocumentableDecl(TagD); 5090 5091 // C 6.7/2: 5092 // A declaration [...] shall declare at least a declarator [...], a tag, 5093 // or the members of an enumeration. 5094 // C++ [dcl.dcl]p3: 5095 // [If there are no declarators], and except for the declaration of an 5096 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5097 // names into the program, or shall redeclare a name introduced by a 5098 // previous declaration. 5099 if (!DeclaresAnything) { 5100 // In C, we allow this as a (popular) extension / bug. Don't bother 5101 // producing further diagnostics for redundant qualifiers after this. 5102 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 5103 ? diag::err_no_declarators 5104 : diag::ext_no_declarators) 5105 << DS.getSourceRange(); 5106 return TagD; 5107 } 5108 5109 // C++ [dcl.stc]p1: 5110 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 5111 // init-declarator-list of the declaration shall not be empty. 5112 // C++ [dcl.fct.spec]p1: 5113 // If a cv-qualifier appears in a decl-specifier-seq, the 5114 // init-declarator-list of the declaration shall not be empty. 5115 // 5116 // Spurious qualifiers here appear to be valid in C. 5117 unsigned DiagID = diag::warn_standalone_specifier; 5118 if (getLangOpts().CPlusPlus) 5119 DiagID = diag::ext_standalone_specifier; 5120 5121 // Note that a linkage-specification sets a storage class, but 5122 // 'extern "C" struct foo;' is actually valid and not theoretically 5123 // useless. 5124 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5125 if (SCS == DeclSpec::SCS_mutable) 5126 // Since mutable is not a viable storage class specifier in C, there is 5127 // no reason to treat it as an extension. Instead, diagnose as an error. 5128 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 5129 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 5130 Diag(DS.getStorageClassSpecLoc(), DiagID) 5131 << DeclSpec::getSpecifierName(SCS); 5132 } 5133 5134 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 5135 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 5136 << DeclSpec::getSpecifierName(TSCS); 5137 if (DS.getTypeQualifiers()) { 5138 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5139 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 5140 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5141 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 5142 // Restrict is covered above. 5143 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5144 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 5145 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5146 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 5147 } 5148 5149 // Warn about ignored type attributes, for example: 5150 // __attribute__((aligned)) struct A; 5151 // Attributes should be placed after tag to apply to type declaration. 5152 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) { 5153 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 5154 if (TypeSpecType == DeclSpec::TST_class || 5155 TypeSpecType == DeclSpec::TST_struct || 5156 TypeSpecType == DeclSpec::TST_interface || 5157 TypeSpecType == DeclSpec::TST_union || 5158 TypeSpecType == DeclSpec::TST_enum) { 5159 for (const ParsedAttr &AL : DS.getAttributes()) 5160 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 5161 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 5162 for (const ParsedAttr &AL : DeclAttrs) 5163 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 5164 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 5165 } 5166 } 5167 5168 return TagD; 5169 } 5170 5171 /// We are trying to inject an anonymous member into the given scope; 5172 /// check if there's an existing declaration that can't be overloaded. 5173 /// 5174 /// \return true if this is a forbidden redeclaration 5175 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 5176 Scope *S, 5177 DeclContext *Owner, 5178 DeclarationName Name, 5179 SourceLocation NameLoc, 5180 bool IsUnion) { 5181 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 5182 Sema::ForVisibleRedeclaration); 5183 if (!SemaRef.LookupName(R, S)) return false; 5184 5185 // Pick a representative declaration. 5186 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 5187 assert(PrevDecl && "Expected a non-null Decl"); 5188 5189 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 5190 return false; 5191 5192 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 5193 << IsUnion << Name; 5194 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5195 5196 return true; 5197 } 5198 5199 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 5200 /// anonymous struct or union AnonRecord into the owning context Owner 5201 /// and scope S. This routine will be invoked just after we realize 5202 /// that an unnamed union or struct is actually an anonymous union or 5203 /// struct, e.g., 5204 /// 5205 /// @code 5206 /// union { 5207 /// int i; 5208 /// float f; 5209 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5210 /// // f into the surrounding scope.x 5211 /// @endcode 5212 /// 5213 /// This routine is recursive, injecting the names of nested anonymous 5214 /// structs/unions into the owning context and scope as well. 5215 static bool 5216 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5217 RecordDecl *AnonRecord, AccessSpecifier AS, 5218 SmallVectorImpl<NamedDecl *> &Chaining) { 5219 bool Invalid = false; 5220 5221 // Look every FieldDecl and IndirectFieldDecl with a name. 5222 for (auto *D : AnonRecord->decls()) { 5223 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5224 cast<NamedDecl>(D)->getDeclName()) { 5225 ValueDecl *VD = cast<ValueDecl>(D); 5226 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5227 VD->getLocation(), 5228 AnonRecord->isUnion())) { 5229 // C++ [class.union]p2: 5230 // The names of the members of an anonymous union shall be 5231 // distinct from the names of any other entity in the 5232 // scope in which the anonymous union is declared. 5233 Invalid = true; 5234 } else { 5235 // C++ [class.union]p2: 5236 // For the purpose of name lookup, after the anonymous union 5237 // definition, the members of the anonymous union are 5238 // considered to have been defined in the scope in which the 5239 // anonymous union is declared. 5240 unsigned OldChainingSize = Chaining.size(); 5241 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5242 Chaining.append(IF->chain_begin(), IF->chain_end()); 5243 else 5244 Chaining.push_back(VD); 5245 5246 assert(Chaining.size() >= 2); 5247 NamedDecl **NamedChain = 5248 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5249 for (unsigned i = 0; i < Chaining.size(); i++) 5250 NamedChain[i] = Chaining[i]; 5251 5252 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5253 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5254 VD->getType(), {NamedChain, Chaining.size()}); 5255 5256 for (const auto *Attr : VD->attrs()) 5257 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5258 5259 IndirectField->setAccess(AS); 5260 IndirectField->setImplicit(); 5261 SemaRef.PushOnScopeChains(IndirectField, S); 5262 5263 // That includes picking up the appropriate access specifier. 5264 if (AS != AS_none) IndirectField->setAccess(AS); 5265 5266 Chaining.resize(OldChainingSize); 5267 } 5268 } 5269 } 5270 5271 return Invalid; 5272 } 5273 5274 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5275 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5276 /// illegal input values are mapped to SC_None. 5277 static StorageClass 5278 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5279 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5280 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5281 "Parser allowed 'typedef' as storage class VarDecl."); 5282 switch (StorageClassSpec) { 5283 case DeclSpec::SCS_unspecified: return SC_None; 5284 case DeclSpec::SCS_extern: 5285 if (DS.isExternInLinkageSpec()) 5286 return SC_None; 5287 return SC_Extern; 5288 case DeclSpec::SCS_static: return SC_Static; 5289 case DeclSpec::SCS_auto: return SC_Auto; 5290 case DeclSpec::SCS_register: return SC_Register; 5291 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5292 // Illegal SCSs map to None: error reporting is up to the caller. 5293 case DeclSpec::SCS_mutable: // Fall through. 5294 case DeclSpec::SCS_typedef: return SC_None; 5295 } 5296 llvm_unreachable("unknown storage class specifier"); 5297 } 5298 5299 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5300 assert(Record->hasInClassInitializer()); 5301 5302 for (const auto *I : Record->decls()) { 5303 const auto *FD = dyn_cast<FieldDecl>(I); 5304 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5305 FD = IFD->getAnonField(); 5306 if (FD && FD->hasInClassInitializer()) 5307 return FD->getLocation(); 5308 } 5309 5310 llvm_unreachable("couldn't find in-class initializer"); 5311 } 5312 5313 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5314 SourceLocation DefaultInitLoc) { 5315 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5316 return; 5317 5318 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5319 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5320 } 5321 5322 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5323 CXXRecordDecl *AnonUnion) { 5324 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5325 return; 5326 5327 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5328 } 5329 5330 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5331 /// anonymous structure or union. Anonymous unions are a C++ feature 5332 /// (C++ [class.union]) and a C11 feature; anonymous structures 5333 /// are a C11 feature and GNU C++ extension. 5334 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5335 AccessSpecifier AS, 5336 RecordDecl *Record, 5337 const PrintingPolicy &Policy) { 5338 DeclContext *Owner = Record->getDeclContext(); 5339 5340 // Diagnose whether this anonymous struct/union is an extension. 5341 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5342 Diag(Record->getLocation(), diag::ext_anonymous_union); 5343 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5344 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5345 else if (!Record->isUnion() && !getLangOpts().C11) 5346 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5347 5348 // C and C++ require different kinds of checks for anonymous 5349 // structs/unions. 5350 bool Invalid = false; 5351 if (getLangOpts().CPlusPlus) { 5352 const char *PrevSpec = nullptr; 5353 if (Record->isUnion()) { 5354 // C++ [class.union]p6: 5355 // C++17 [class.union.anon]p2: 5356 // Anonymous unions declared in a named namespace or in the 5357 // global namespace shall be declared static. 5358 unsigned DiagID; 5359 DeclContext *OwnerScope = Owner->getRedeclContext(); 5360 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5361 (OwnerScope->isTranslationUnit() || 5362 (OwnerScope->isNamespace() && 5363 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5364 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5365 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5366 5367 // Recover by adding 'static'. 5368 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5369 PrevSpec, DiagID, Policy); 5370 } 5371 // C++ [class.union]p6: 5372 // A storage class is not allowed in a declaration of an 5373 // anonymous union in a class scope. 5374 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5375 isa<RecordDecl>(Owner)) { 5376 Diag(DS.getStorageClassSpecLoc(), 5377 diag::err_anonymous_union_with_storage_spec) 5378 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5379 5380 // Recover by removing the storage specifier. 5381 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5382 SourceLocation(), 5383 PrevSpec, DiagID, Context.getPrintingPolicy()); 5384 } 5385 } 5386 5387 // Ignore const/volatile/restrict qualifiers. 5388 if (DS.getTypeQualifiers()) { 5389 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5390 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5391 << Record->isUnion() << "const" 5392 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5393 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5394 Diag(DS.getVolatileSpecLoc(), 5395 diag::ext_anonymous_struct_union_qualified) 5396 << Record->isUnion() << "volatile" 5397 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5398 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5399 Diag(DS.getRestrictSpecLoc(), 5400 diag::ext_anonymous_struct_union_qualified) 5401 << Record->isUnion() << "restrict" 5402 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5403 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5404 Diag(DS.getAtomicSpecLoc(), 5405 diag::ext_anonymous_struct_union_qualified) 5406 << Record->isUnion() << "_Atomic" 5407 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5408 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5409 Diag(DS.getUnalignedSpecLoc(), 5410 diag::ext_anonymous_struct_union_qualified) 5411 << Record->isUnion() << "__unaligned" 5412 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5413 5414 DS.ClearTypeQualifiers(); 5415 } 5416 5417 // C++ [class.union]p2: 5418 // The member-specification of an anonymous union shall only 5419 // define non-static data members. [Note: nested types and 5420 // functions cannot be declared within an anonymous union. ] 5421 for (auto *Mem : Record->decls()) { 5422 // Ignore invalid declarations; we already diagnosed them. 5423 if (Mem->isInvalidDecl()) 5424 continue; 5425 5426 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5427 // C++ [class.union]p3: 5428 // An anonymous union shall not have private or protected 5429 // members (clause 11). 5430 assert(FD->getAccess() != AS_none); 5431 if (FD->getAccess() != AS_public) { 5432 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5433 << Record->isUnion() << (FD->getAccess() == AS_protected); 5434 Invalid = true; 5435 } 5436 5437 // C++ [class.union]p1 5438 // An object of a class with a non-trivial constructor, a non-trivial 5439 // copy constructor, a non-trivial destructor, or a non-trivial copy 5440 // assignment operator cannot be a member of a union, nor can an 5441 // array of such objects. 5442 if (CheckNontrivialField(FD)) 5443 Invalid = true; 5444 } else if (Mem->isImplicit()) { 5445 // Any implicit members are fine. 5446 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5447 // This is a type that showed up in an 5448 // elaborated-type-specifier inside the anonymous struct or 5449 // union, but which actually declares a type outside of the 5450 // anonymous struct or union. It's okay. 5451 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5452 if (!MemRecord->isAnonymousStructOrUnion() && 5453 MemRecord->getDeclName()) { 5454 // Visual C++ allows type definition in anonymous struct or union. 5455 if (getLangOpts().MicrosoftExt) 5456 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5457 << Record->isUnion(); 5458 else { 5459 // This is a nested type declaration. 5460 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5461 << Record->isUnion(); 5462 Invalid = true; 5463 } 5464 } else { 5465 // This is an anonymous type definition within another anonymous type. 5466 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5467 // not part of standard C++. 5468 Diag(MemRecord->getLocation(), 5469 diag::ext_anonymous_record_with_anonymous_type) 5470 << Record->isUnion(); 5471 } 5472 } else if (isa<AccessSpecDecl>(Mem)) { 5473 // Any access specifier is fine. 5474 } else if (isa<StaticAssertDecl>(Mem)) { 5475 // In C++1z, static_assert declarations are also fine. 5476 } else { 5477 // We have something that isn't a non-static data 5478 // member. Complain about it. 5479 unsigned DK = diag::err_anonymous_record_bad_member; 5480 if (isa<TypeDecl>(Mem)) 5481 DK = diag::err_anonymous_record_with_type; 5482 else if (isa<FunctionDecl>(Mem)) 5483 DK = diag::err_anonymous_record_with_function; 5484 else if (isa<VarDecl>(Mem)) 5485 DK = diag::err_anonymous_record_with_static; 5486 5487 // Visual C++ allows type definition in anonymous struct or union. 5488 if (getLangOpts().MicrosoftExt && 5489 DK == diag::err_anonymous_record_with_type) 5490 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5491 << Record->isUnion(); 5492 else { 5493 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5494 Invalid = true; 5495 } 5496 } 5497 } 5498 5499 // C++11 [class.union]p8 (DR1460): 5500 // At most one variant member of a union may have a 5501 // brace-or-equal-initializer. 5502 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5503 Owner->isRecord()) 5504 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5505 cast<CXXRecordDecl>(Record)); 5506 } 5507 5508 if (!Record->isUnion() && !Owner->isRecord()) { 5509 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5510 << getLangOpts().CPlusPlus; 5511 Invalid = true; 5512 } 5513 5514 // C++ [dcl.dcl]p3: 5515 // [If there are no declarators], and except for the declaration of an 5516 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5517 // names into the program 5518 // C++ [class.mem]p2: 5519 // each such member-declaration shall either declare at least one member 5520 // name of the class or declare at least one unnamed bit-field 5521 // 5522 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5523 if (getLangOpts().CPlusPlus && Record->field_empty()) 5524 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5525 5526 // Mock up a declarator. 5527 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member); 5528 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5529 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5530 5531 // Create a declaration for this anonymous struct/union. 5532 NamedDecl *Anon = nullptr; 5533 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5534 Anon = FieldDecl::Create( 5535 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5536 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5537 /*BitWidth=*/nullptr, /*Mutable=*/false, 5538 /*InitStyle=*/ICIS_NoInit); 5539 Anon->setAccess(AS); 5540 ProcessDeclAttributes(S, Anon, Dc); 5541 5542 if (getLangOpts().CPlusPlus) 5543 FieldCollector->Add(cast<FieldDecl>(Anon)); 5544 } else { 5545 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5546 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5547 if (SCSpec == DeclSpec::SCS_mutable) { 5548 // mutable can only appear on non-static class members, so it's always 5549 // an error here 5550 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5551 Invalid = true; 5552 SC = SC_None; 5553 } 5554 5555 assert(DS.getAttributes().empty() && "No attribute expected"); 5556 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5557 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5558 Context.getTypeDeclType(Record), TInfo, SC); 5559 5560 // Default-initialize the implicit variable. This initialization will be 5561 // trivial in almost all cases, except if a union member has an in-class 5562 // initializer: 5563 // union { int n = 0; }; 5564 ActOnUninitializedDecl(Anon); 5565 } 5566 Anon->setImplicit(); 5567 5568 // Mark this as an anonymous struct/union type. 5569 Record->setAnonymousStructOrUnion(true); 5570 5571 // Add the anonymous struct/union object to the current 5572 // context. We'll be referencing this object when we refer to one of 5573 // its members. 5574 Owner->addDecl(Anon); 5575 5576 // Inject the members of the anonymous struct/union into the owning 5577 // context and into the identifier resolver chain for name lookup 5578 // purposes. 5579 SmallVector<NamedDecl*, 2> Chain; 5580 Chain.push_back(Anon); 5581 5582 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5583 Invalid = true; 5584 5585 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5586 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5587 MangleNumberingContext *MCtx; 5588 Decl *ManglingContextDecl; 5589 std::tie(MCtx, ManglingContextDecl) = 5590 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5591 if (MCtx) { 5592 Context.setManglingNumber( 5593 NewVD, MCtx->getManglingNumber( 5594 NewVD, getMSManglingNumber(getLangOpts(), S))); 5595 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5596 } 5597 } 5598 } 5599 5600 if (Invalid) 5601 Anon->setInvalidDecl(); 5602 5603 return Anon; 5604 } 5605 5606 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5607 /// Microsoft C anonymous structure. 5608 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5609 /// Example: 5610 /// 5611 /// struct A { int a; }; 5612 /// struct B { struct A; int b; }; 5613 /// 5614 /// void foo() { 5615 /// B var; 5616 /// var.a = 3; 5617 /// } 5618 /// 5619 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5620 RecordDecl *Record) { 5621 assert(Record && "expected a record!"); 5622 5623 // Mock up a declarator. 5624 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName); 5625 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5626 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5627 5628 auto *ParentDecl = cast<RecordDecl>(CurContext); 5629 QualType RecTy = Context.getTypeDeclType(Record); 5630 5631 // Create a declaration for this anonymous struct. 5632 NamedDecl *Anon = 5633 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5634 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5635 /*BitWidth=*/nullptr, /*Mutable=*/false, 5636 /*InitStyle=*/ICIS_NoInit); 5637 Anon->setImplicit(); 5638 5639 // Add the anonymous struct object to the current context. 5640 CurContext->addDecl(Anon); 5641 5642 // Inject the members of the anonymous struct into the current 5643 // context and into the identifier resolver chain for name lookup 5644 // purposes. 5645 SmallVector<NamedDecl*, 2> Chain; 5646 Chain.push_back(Anon); 5647 5648 RecordDecl *RecordDef = Record->getDefinition(); 5649 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5650 diag::err_field_incomplete_or_sizeless) || 5651 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5652 AS_none, Chain)) { 5653 Anon->setInvalidDecl(); 5654 ParentDecl->setInvalidDecl(); 5655 } 5656 5657 return Anon; 5658 } 5659 5660 /// GetNameForDeclarator - Determine the full declaration name for the 5661 /// given Declarator. 5662 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5663 return GetNameFromUnqualifiedId(D.getName()); 5664 } 5665 5666 /// Retrieves the declaration name from a parsed unqualified-id. 5667 DeclarationNameInfo 5668 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5669 DeclarationNameInfo NameInfo; 5670 NameInfo.setLoc(Name.StartLocation); 5671 5672 switch (Name.getKind()) { 5673 5674 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5675 case UnqualifiedIdKind::IK_Identifier: 5676 NameInfo.setName(Name.Identifier); 5677 return NameInfo; 5678 5679 case UnqualifiedIdKind::IK_DeductionGuideName: { 5680 // C++ [temp.deduct.guide]p3: 5681 // The simple-template-id shall name a class template specialization. 5682 // The template-name shall be the same identifier as the template-name 5683 // of the simple-template-id. 5684 // These together intend to imply that the template-name shall name a 5685 // class template. 5686 // FIXME: template<typename T> struct X {}; 5687 // template<typename T> using Y = X<T>; 5688 // Y(int) -> Y<int>; 5689 // satisfies these rules but does not name a class template. 5690 TemplateName TN = Name.TemplateName.get().get(); 5691 auto *Template = TN.getAsTemplateDecl(); 5692 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5693 Diag(Name.StartLocation, 5694 diag::err_deduction_guide_name_not_class_template) 5695 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5696 if (Template) 5697 Diag(Template->getLocation(), diag::note_template_decl_here); 5698 return DeclarationNameInfo(); 5699 } 5700 5701 NameInfo.setName( 5702 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5703 return NameInfo; 5704 } 5705 5706 case UnqualifiedIdKind::IK_OperatorFunctionId: 5707 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5708 Name.OperatorFunctionId.Operator)); 5709 NameInfo.setCXXOperatorNameRange(SourceRange( 5710 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5711 return NameInfo; 5712 5713 case UnqualifiedIdKind::IK_LiteralOperatorId: 5714 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5715 Name.Identifier)); 5716 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5717 return NameInfo; 5718 5719 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5720 TypeSourceInfo *TInfo; 5721 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5722 if (Ty.isNull()) 5723 return DeclarationNameInfo(); 5724 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5725 Context.getCanonicalType(Ty))); 5726 NameInfo.setNamedTypeInfo(TInfo); 5727 return NameInfo; 5728 } 5729 5730 case UnqualifiedIdKind::IK_ConstructorName: { 5731 TypeSourceInfo *TInfo; 5732 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5733 if (Ty.isNull()) 5734 return DeclarationNameInfo(); 5735 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5736 Context.getCanonicalType(Ty))); 5737 NameInfo.setNamedTypeInfo(TInfo); 5738 return NameInfo; 5739 } 5740 5741 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5742 // In well-formed code, we can only have a constructor 5743 // template-id that refers to the current context, so go there 5744 // to find the actual type being constructed. 5745 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5746 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5747 return DeclarationNameInfo(); 5748 5749 // Determine the type of the class being constructed. 5750 QualType CurClassType = Context.getTypeDeclType(CurClass); 5751 5752 // FIXME: Check two things: that the template-id names the same type as 5753 // CurClassType, and that the template-id does not occur when the name 5754 // was qualified. 5755 5756 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5757 Context.getCanonicalType(CurClassType))); 5758 // FIXME: should we retrieve TypeSourceInfo? 5759 NameInfo.setNamedTypeInfo(nullptr); 5760 return NameInfo; 5761 } 5762 5763 case UnqualifiedIdKind::IK_DestructorName: { 5764 TypeSourceInfo *TInfo; 5765 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5766 if (Ty.isNull()) 5767 return DeclarationNameInfo(); 5768 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5769 Context.getCanonicalType(Ty))); 5770 NameInfo.setNamedTypeInfo(TInfo); 5771 return NameInfo; 5772 } 5773 5774 case UnqualifiedIdKind::IK_TemplateId: { 5775 TemplateName TName = Name.TemplateId->Template.get(); 5776 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5777 return Context.getNameForTemplate(TName, TNameLoc); 5778 } 5779 5780 } // switch (Name.getKind()) 5781 5782 llvm_unreachable("Unknown name kind"); 5783 } 5784 5785 static QualType getCoreType(QualType Ty) { 5786 do { 5787 if (Ty->isPointerType() || Ty->isReferenceType()) 5788 Ty = Ty->getPointeeType(); 5789 else if (Ty->isArrayType()) 5790 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5791 else 5792 return Ty.withoutLocalFastQualifiers(); 5793 } while (true); 5794 } 5795 5796 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5797 /// and Definition have "nearly" matching parameters. This heuristic is 5798 /// used to improve diagnostics in the case where an out-of-line function 5799 /// definition doesn't match any declaration within the class or namespace. 5800 /// Also sets Params to the list of indices to the parameters that differ 5801 /// between the declaration and the definition. If hasSimilarParameters 5802 /// returns true and Params is empty, then all of the parameters match. 5803 static bool hasSimilarParameters(ASTContext &Context, 5804 FunctionDecl *Declaration, 5805 FunctionDecl *Definition, 5806 SmallVectorImpl<unsigned> &Params) { 5807 Params.clear(); 5808 if (Declaration->param_size() != Definition->param_size()) 5809 return false; 5810 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5811 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5812 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5813 5814 // The parameter types are identical 5815 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5816 continue; 5817 5818 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5819 QualType DefParamBaseTy = getCoreType(DefParamTy); 5820 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5821 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5822 5823 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5824 (DeclTyName && DeclTyName == DefTyName)) 5825 Params.push_back(Idx); 5826 else // The two parameters aren't even close 5827 return false; 5828 } 5829 5830 return true; 5831 } 5832 5833 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given 5834 /// declarator needs to be rebuilt in the current instantiation. 5835 /// Any bits of declarator which appear before the name are valid for 5836 /// consideration here. That's specifically the type in the decl spec 5837 /// and the base type in any member-pointer chunks. 5838 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5839 DeclarationName Name) { 5840 // The types we specifically need to rebuild are: 5841 // - typenames, typeofs, and decltypes 5842 // - types which will become injected class names 5843 // Of course, we also need to rebuild any type referencing such a 5844 // type. It's safest to just say "dependent", but we call out a 5845 // few cases here. 5846 5847 DeclSpec &DS = D.getMutableDeclSpec(); 5848 switch (DS.getTypeSpecType()) { 5849 case DeclSpec::TST_typename: 5850 case DeclSpec::TST_typeofType: 5851 case DeclSpec::TST_underlyingType: 5852 case DeclSpec::TST_atomic: { 5853 // Grab the type from the parser. 5854 TypeSourceInfo *TSI = nullptr; 5855 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5856 if (T.isNull() || !T->isInstantiationDependentType()) break; 5857 5858 // Make sure there's a type source info. This isn't really much 5859 // of a waste; most dependent types should have type source info 5860 // attached already. 5861 if (!TSI) 5862 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5863 5864 // Rebuild the type in the current instantiation. 5865 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5866 if (!TSI) return true; 5867 5868 // Store the new type back in the decl spec. 5869 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5870 DS.UpdateTypeRep(LocType); 5871 break; 5872 } 5873 5874 case DeclSpec::TST_decltype: 5875 case DeclSpec::TST_typeofExpr: { 5876 Expr *E = DS.getRepAsExpr(); 5877 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5878 if (Result.isInvalid()) return true; 5879 DS.UpdateExprRep(Result.get()); 5880 break; 5881 } 5882 5883 default: 5884 // Nothing to do for these decl specs. 5885 break; 5886 } 5887 5888 // It doesn't matter what order we do this in. 5889 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5890 DeclaratorChunk &Chunk = D.getTypeObject(I); 5891 5892 // The only type information in the declarator which can come 5893 // before the declaration name is the base type of a member 5894 // pointer. 5895 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5896 continue; 5897 5898 // Rebuild the scope specifier in-place. 5899 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5900 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5901 return true; 5902 } 5903 5904 return false; 5905 } 5906 5907 /// Returns true if the declaration is declared in a system header or from a 5908 /// system macro. 5909 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { 5910 return SM.isInSystemHeader(D->getLocation()) || 5911 SM.isInSystemMacro(D->getLocation()); 5912 } 5913 5914 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5915 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5916 // of system decl. 5917 if (D->getPreviousDecl() || D->isImplicit()) 5918 return; 5919 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5920 if (Status != ReservedIdentifierStatus::NotReserved && 5921 !isFromSystemHeader(Context.getSourceManager(), D)) { 5922 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5923 << D << static_cast<int>(Status); 5924 } 5925 } 5926 5927 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5928 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5929 5930 // Check if we are in an `omp begin/end declare variant` scope. Handle this 5931 // declaration only if the `bind_to_declaration` extension is set. 5932 SmallVector<FunctionDecl *, 4> Bases; 5933 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 5934 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty:: 5935 implementation_extension_bind_to_declaration)) 5936 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 5937 S, D, MultiTemplateParamsArg(), Bases); 5938 5939 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5940 5941 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5942 Dcl && Dcl->getDeclContext()->isFileContext()) 5943 Dcl->setTopLevelDeclInObjCContainer(); 5944 5945 if (!Bases.empty()) 5946 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 5947 5948 return Dcl; 5949 } 5950 5951 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5952 /// If T is the name of a class, then each of the following shall have a 5953 /// name different from T: 5954 /// - every static data member of class T; 5955 /// - every member function of class T 5956 /// - every member of class T that is itself a type; 5957 /// \returns true if the declaration name violates these rules. 5958 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5959 DeclarationNameInfo NameInfo) { 5960 DeclarationName Name = NameInfo.getName(); 5961 5962 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5963 while (Record && Record->isAnonymousStructOrUnion()) 5964 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5965 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5966 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5967 return true; 5968 } 5969 5970 return false; 5971 } 5972 5973 /// Diagnose a declaration whose declarator-id has the given 5974 /// nested-name-specifier. 5975 /// 5976 /// \param SS The nested-name-specifier of the declarator-id. 5977 /// 5978 /// \param DC The declaration context to which the nested-name-specifier 5979 /// resolves. 5980 /// 5981 /// \param Name The name of the entity being declared. 5982 /// 5983 /// \param Loc The location of the name of the entity being declared. 5984 /// 5985 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5986 /// we're declaring an explicit / partial specialization / instantiation. 5987 /// 5988 /// \returns true if we cannot safely recover from this error, false otherwise. 5989 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5990 DeclarationName Name, 5991 SourceLocation Loc, bool IsTemplateId) { 5992 DeclContext *Cur = CurContext; 5993 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5994 Cur = Cur->getParent(); 5995 5996 // If the user provided a superfluous scope specifier that refers back to the 5997 // class in which the entity is already declared, diagnose and ignore it. 5998 // 5999 // class X { 6000 // void X::f(); 6001 // }; 6002 // 6003 // Note, it was once ill-formed to give redundant qualification in all 6004 // contexts, but that rule was removed by DR482. 6005 if (Cur->Equals(DC)) { 6006 if (Cur->isRecord()) { 6007 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 6008 : diag::err_member_extra_qualification) 6009 << Name << FixItHint::CreateRemoval(SS.getRange()); 6010 SS.clear(); 6011 } else { 6012 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 6013 } 6014 return false; 6015 } 6016 6017 // Check whether the qualifying scope encloses the scope of the original 6018 // declaration. For a template-id, we perform the checks in 6019 // CheckTemplateSpecializationScope. 6020 if (!Cur->Encloses(DC) && !IsTemplateId) { 6021 if (Cur->isRecord()) 6022 Diag(Loc, diag::err_member_qualification) 6023 << Name << SS.getRange(); 6024 else if (isa<TranslationUnitDecl>(DC)) 6025 Diag(Loc, diag::err_invalid_declarator_global_scope) 6026 << Name << SS.getRange(); 6027 else if (isa<FunctionDecl>(Cur)) 6028 Diag(Loc, diag::err_invalid_declarator_in_function) 6029 << Name << SS.getRange(); 6030 else if (isa<BlockDecl>(Cur)) 6031 Diag(Loc, diag::err_invalid_declarator_in_block) 6032 << Name << SS.getRange(); 6033 else if (isa<ExportDecl>(Cur)) { 6034 if (!isa<NamespaceDecl>(DC)) 6035 Diag(Loc, diag::err_export_non_namespace_scope_name) 6036 << Name << SS.getRange(); 6037 else 6038 // The cases that DC is not NamespaceDecl should be handled in 6039 // CheckRedeclarationExported. 6040 return false; 6041 } else 6042 Diag(Loc, diag::err_invalid_declarator_scope) 6043 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 6044 6045 return true; 6046 } 6047 6048 if (Cur->isRecord()) { 6049 // Cannot qualify members within a class. 6050 Diag(Loc, diag::err_member_qualification) 6051 << Name << SS.getRange(); 6052 SS.clear(); 6053 6054 // C++ constructors and destructors with incorrect scopes can break 6055 // our AST invariants by having the wrong underlying types. If 6056 // that's the case, then drop this declaration entirely. 6057 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 6058 Name.getNameKind() == DeclarationName::CXXDestructorName) && 6059 !Context.hasSameType(Name.getCXXNameType(), 6060 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 6061 return true; 6062 6063 return false; 6064 } 6065 6066 // C++11 [dcl.meaning]p1: 6067 // [...] "The nested-name-specifier of the qualified declarator-id shall 6068 // not begin with a decltype-specifer" 6069 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 6070 while (SpecLoc.getPrefix()) 6071 SpecLoc = SpecLoc.getPrefix(); 6072 if (isa_and_nonnull<DecltypeType>( 6073 SpecLoc.getNestedNameSpecifier()->getAsType())) 6074 Diag(Loc, diag::err_decltype_in_declarator) 6075 << SpecLoc.getTypeLoc().getSourceRange(); 6076 6077 return false; 6078 } 6079 6080 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 6081 MultiTemplateParamsArg TemplateParamLists) { 6082 // TODO: consider using NameInfo for diagnostic. 6083 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6084 DeclarationName Name = NameInfo.getName(); 6085 6086 // All of these full declarators require an identifier. If it doesn't have 6087 // one, the ParsedFreeStandingDeclSpec action should be used. 6088 if (D.isDecompositionDeclarator()) { 6089 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 6090 } else if (!Name) { 6091 if (!D.isInvalidType()) // Reject this if we think it is valid. 6092 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 6093 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 6094 return nullptr; 6095 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 6096 return nullptr; 6097 6098 // The scope passed in may not be a decl scope. Zip up the scope tree until 6099 // we find one that is. 6100 while ((S->getFlags() & Scope::DeclScope) == 0 || 6101 (S->getFlags() & Scope::TemplateParamScope) != 0) 6102 S = S->getParent(); 6103 6104 DeclContext *DC = CurContext; 6105 if (D.getCXXScopeSpec().isInvalid()) 6106 D.setInvalidType(); 6107 else if (D.getCXXScopeSpec().isSet()) { 6108 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 6109 UPPC_DeclarationQualifier)) 6110 return nullptr; 6111 6112 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 6113 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 6114 if (!DC || isa<EnumDecl>(DC)) { 6115 // If we could not compute the declaration context, it's because the 6116 // declaration context is dependent but does not refer to a class, 6117 // class template, or class template partial specialization. Complain 6118 // and return early, to avoid the coming semantic disaster. 6119 Diag(D.getIdentifierLoc(), 6120 diag::err_template_qualified_declarator_no_match) 6121 << D.getCXXScopeSpec().getScopeRep() 6122 << D.getCXXScopeSpec().getRange(); 6123 return nullptr; 6124 } 6125 bool IsDependentContext = DC->isDependentContext(); 6126 6127 if (!IsDependentContext && 6128 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 6129 return nullptr; 6130 6131 // If a class is incomplete, do not parse entities inside it. 6132 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 6133 Diag(D.getIdentifierLoc(), 6134 diag::err_member_def_undefined_record) 6135 << Name << DC << D.getCXXScopeSpec().getRange(); 6136 return nullptr; 6137 } 6138 if (!D.getDeclSpec().isFriendSpecified()) { 6139 if (diagnoseQualifiedDeclaration( 6140 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 6141 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 6142 if (DC->isRecord()) 6143 return nullptr; 6144 6145 D.setInvalidType(); 6146 } 6147 } 6148 6149 // Check whether we need to rebuild the type of the given 6150 // declaration in the current instantiation. 6151 if (EnteringContext && IsDependentContext && 6152 TemplateParamLists.size() != 0) { 6153 ContextRAII SavedContext(*this, DC); 6154 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 6155 D.setInvalidType(); 6156 } 6157 } 6158 6159 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6160 QualType R = TInfo->getType(); 6161 6162 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6163 UPPC_DeclarationType)) 6164 D.setInvalidType(); 6165 6166 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6167 forRedeclarationInCurContext()); 6168 6169 // See if this is a redefinition of a variable in the same scope. 6170 if (!D.getCXXScopeSpec().isSet()) { 6171 bool IsLinkageLookup = false; 6172 bool CreateBuiltins = false; 6173 6174 // If the declaration we're planning to build will be a function 6175 // or object with linkage, then look for another declaration with 6176 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 6177 // 6178 // If the declaration we're planning to build will be declared with 6179 // external linkage in the translation unit, create any builtin with 6180 // the same name. 6181 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 6182 /* Do nothing*/; 6183 else if (CurContext->isFunctionOrMethod() && 6184 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 6185 R->isFunctionType())) { 6186 IsLinkageLookup = true; 6187 CreateBuiltins = 6188 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 6189 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 6190 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 6191 CreateBuiltins = true; 6192 6193 if (IsLinkageLookup) { 6194 Previous.clear(LookupRedeclarationWithLinkage); 6195 Previous.setRedeclarationKind(ForExternalRedeclaration); 6196 } 6197 6198 LookupName(Previous, S, CreateBuiltins); 6199 } else { // Something like "int foo::x;" 6200 LookupQualifiedName(Previous, DC); 6201 6202 // C++ [dcl.meaning]p1: 6203 // When the declarator-id is qualified, the declaration shall refer to a 6204 // previously declared member of the class or namespace to which the 6205 // qualifier refers (or, in the case of a namespace, of an element of the 6206 // inline namespace set of that namespace (7.3.1)) or to a specialization 6207 // thereof; [...] 6208 // 6209 // Note that we already checked the context above, and that we do not have 6210 // enough information to make sure that Previous contains the declaration 6211 // we want to match. For example, given: 6212 // 6213 // class X { 6214 // void f(); 6215 // void f(float); 6216 // }; 6217 // 6218 // void X::f(int) { } // ill-formed 6219 // 6220 // In this case, Previous will point to the overload set 6221 // containing the two f's declared in X, but neither of them 6222 // matches. 6223 6224 // C++ [dcl.meaning]p1: 6225 // [...] the member shall not merely have been introduced by a 6226 // using-declaration in the scope of the class or namespace nominated by 6227 // the nested-name-specifier of the declarator-id. 6228 RemoveUsingDecls(Previous); 6229 } 6230 6231 if (Previous.isSingleResult() && 6232 Previous.getFoundDecl()->isTemplateParameter()) { 6233 // Maybe we will complain about the shadowed template parameter. 6234 if (!D.isInvalidType()) 6235 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 6236 Previous.getFoundDecl()); 6237 6238 // Just pretend that we didn't see the previous declaration. 6239 Previous.clear(); 6240 } 6241 6242 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6243 // Forget that the previous declaration is the injected-class-name. 6244 Previous.clear(); 6245 6246 // In C++, the previous declaration we find might be a tag type 6247 // (class or enum). In this case, the new declaration will hide the 6248 // tag type. Note that this applies to functions, function templates, and 6249 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6250 if (Previous.isSingleTagDecl() && 6251 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6252 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6253 Previous.clear(); 6254 6255 // Check that there are no default arguments other than in the parameters 6256 // of a function declaration (C++ only). 6257 if (getLangOpts().CPlusPlus) 6258 CheckExtraCXXDefaultArguments(D); 6259 6260 NamedDecl *New; 6261 6262 bool AddToScope = true; 6263 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6264 if (TemplateParamLists.size()) { 6265 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6266 return nullptr; 6267 } 6268 6269 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6270 } else if (R->isFunctionType()) { 6271 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6272 TemplateParamLists, 6273 AddToScope); 6274 } else { 6275 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6276 AddToScope); 6277 } 6278 6279 if (!New) 6280 return nullptr; 6281 6282 // If this has an identifier and is not a function template specialization, 6283 // add it to the scope stack. 6284 if (New->getDeclName() && AddToScope) 6285 PushOnScopeChains(New, S); 6286 6287 if (isInOpenMPDeclareTargetContext()) 6288 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6289 6290 return New; 6291 } 6292 6293 /// Helper method to turn variable array types into constant array 6294 /// types in certain situations which would otherwise be errors (for 6295 /// GCC compatibility). 6296 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6297 ASTContext &Context, 6298 bool &SizeIsNegative, 6299 llvm::APSInt &Oversized) { 6300 // This method tries to turn a variable array into a constant 6301 // array even when the size isn't an ICE. This is necessary 6302 // for compatibility with code that depends on gcc's buggy 6303 // constant expression folding, like struct {char x[(int)(char*)2];} 6304 SizeIsNegative = false; 6305 Oversized = 0; 6306 6307 if (T->isDependentType()) 6308 return QualType(); 6309 6310 QualifierCollector Qs; 6311 const Type *Ty = Qs.strip(T); 6312 6313 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6314 QualType Pointee = PTy->getPointeeType(); 6315 QualType FixedType = 6316 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6317 Oversized); 6318 if (FixedType.isNull()) return FixedType; 6319 FixedType = Context.getPointerType(FixedType); 6320 return Qs.apply(Context, FixedType); 6321 } 6322 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6323 QualType Inner = PTy->getInnerType(); 6324 QualType FixedType = 6325 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6326 Oversized); 6327 if (FixedType.isNull()) return FixedType; 6328 FixedType = Context.getParenType(FixedType); 6329 return Qs.apply(Context, FixedType); 6330 } 6331 6332 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6333 if (!VLATy) 6334 return QualType(); 6335 6336 QualType ElemTy = VLATy->getElementType(); 6337 if (ElemTy->isVariablyModifiedType()) { 6338 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6339 SizeIsNegative, Oversized); 6340 if (ElemTy.isNull()) 6341 return QualType(); 6342 } 6343 6344 Expr::EvalResult Result; 6345 if (!VLATy->getSizeExpr() || 6346 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6347 return QualType(); 6348 6349 llvm::APSInt Res = Result.Val.getInt(); 6350 6351 // Check whether the array size is negative. 6352 if (Res.isSigned() && Res.isNegative()) { 6353 SizeIsNegative = true; 6354 return QualType(); 6355 } 6356 6357 // Check whether the array is too large to be addressed. 6358 unsigned ActiveSizeBits = 6359 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6360 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6361 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6362 : Res.getActiveBits(); 6363 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6364 Oversized = Res; 6365 return QualType(); 6366 } 6367 6368 QualType FoldedArrayType = Context.getConstantArrayType( 6369 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6370 return Qs.apply(Context, FoldedArrayType); 6371 } 6372 6373 static void 6374 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6375 SrcTL = SrcTL.getUnqualifiedLoc(); 6376 DstTL = DstTL.getUnqualifiedLoc(); 6377 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6378 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6379 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6380 DstPTL.getPointeeLoc()); 6381 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6382 return; 6383 } 6384 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6385 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6386 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6387 DstPTL.getInnerLoc()); 6388 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6389 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6390 return; 6391 } 6392 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6393 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6394 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6395 TypeLoc DstElemTL = DstATL.getElementLoc(); 6396 if (VariableArrayTypeLoc SrcElemATL = 6397 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6398 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6399 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6400 } else { 6401 DstElemTL.initializeFullCopy(SrcElemTL); 6402 } 6403 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6404 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6405 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6406 } 6407 6408 /// Helper method to turn variable array types into constant array 6409 /// types in certain situations which would otherwise be errors (for 6410 /// GCC compatibility). 6411 static TypeSourceInfo* 6412 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6413 ASTContext &Context, 6414 bool &SizeIsNegative, 6415 llvm::APSInt &Oversized) { 6416 QualType FixedTy 6417 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6418 SizeIsNegative, Oversized); 6419 if (FixedTy.isNull()) 6420 return nullptr; 6421 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6422 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6423 FixedTInfo->getTypeLoc()); 6424 return FixedTInfo; 6425 } 6426 6427 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6428 /// true if we were successful. 6429 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6430 QualType &T, SourceLocation Loc, 6431 unsigned FailedFoldDiagID) { 6432 bool SizeIsNegative; 6433 llvm::APSInt Oversized; 6434 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6435 TInfo, Context, SizeIsNegative, Oversized); 6436 if (FixedTInfo) { 6437 Diag(Loc, diag::ext_vla_folded_to_constant); 6438 TInfo = FixedTInfo; 6439 T = FixedTInfo->getType(); 6440 return true; 6441 } 6442 6443 if (SizeIsNegative) 6444 Diag(Loc, diag::err_typecheck_negative_array_size); 6445 else if (Oversized.getBoolValue()) 6446 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6447 else if (FailedFoldDiagID) 6448 Diag(Loc, FailedFoldDiagID); 6449 return false; 6450 } 6451 6452 /// Register the given locally-scoped extern "C" declaration so 6453 /// that it can be found later for redeclarations. We include any extern "C" 6454 /// declaration that is not visible in the translation unit here, not just 6455 /// function-scope declarations. 6456 void 6457 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6458 if (!getLangOpts().CPlusPlus && 6459 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6460 // Don't need to track declarations in the TU in C. 6461 return; 6462 6463 // Note that we have a locally-scoped external with this name. 6464 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6465 } 6466 6467 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6468 // FIXME: We can have multiple results via __attribute__((overloadable)). 6469 auto Result = Context.getExternCContextDecl()->lookup(Name); 6470 return Result.empty() ? nullptr : *Result.begin(); 6471 } 6472 6473 /// Diagnose function specifiers on a declaration of an identifier that 6474 /// does not identify a function. 6475 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6476 // FIXME: We should probably indicate the identifier in question to avoid 6477 // confusion for constructs like "virtual int a(), b;" 6478 if (DS.isVirtualSpecified()) 6479 Diag(DS.getVirtualSpecLoc(), 6480 diag::err_virtual_non_function); 6481 6482 if (DS.hasExplicitSpecifier()) 6483 Diag(DS.getExplicitSpecLoc(), 6484 diag::err_explicit_non_function); 6485 6486 if (DS.isNoreturnSpecified()) 6487 Diag(DS.getNoreturnSpecLoc(), 6488 diag::err_noreturn_non_function); 6489 } 6490 6491 NamedDecl* 6492 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6493 TypeSourceInfo *TInfo, LookupResult &Previous) { 6494 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6495 if (D.getCXXScopeSpec().isSet()) { 6496 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6497 << D.getCXXScopeSpec().getRange(); 6498 D.setInvalidType(); 6499 // Pretend we didn't see the scope specifier. 6500 DC = CurContext; 6501 Previous.clear(); 6502 } 6503 6504 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6505 6506 if (D.getDeclSpec().isInlineSpecified()) 6507 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6508 << getLangOpts().CPlusPlus17; 6509 if (D.getDeclSpec().hasConstexprSpecifier()) 6510 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6511 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6512 6513 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6514 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6515 Diag(D.getName().StartLocation, 6516 diag::err_deduction_guide_invalid_specifier) 6517 << "typedef"; 6518 else 6519 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6520 << D.getName().getSourceRange(); 6521 return nullptr; 6522 } 6523 6524 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6525 if (!NewTD) return nullptr; 6526 6527 // Handle attributes prior to checking for duplicates in MergeVarDecl 6528 ProcessDeclAttributes(S, NewTD, D); 6529 6530 CheckTypedefForVariablyModifiedType(S, NewTD); 6531 6532 bool Redeclaration = D.isRedeclaration(); 6533 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6534 D.setRedeclaration(Redeclaration); 6535 return ND; 6536 } 6537 6538 void 6539 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6540 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6541 // then it shall have block scope. 6542 // Note that variably modified types must be fixed before merging the decl so 6543 // that redeclarations will match. 6544 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6545 QualType T = TInfo->getType(); 6546 if (T->isVariablyModifiedType()) { 6547 setFunctionHasBranchProtectedScope(); 6548 6549 if (S->getFnParent() == nullptr) { 6550 bool SizeIsNegative; 6551 llvm::APSInt Oversized; 6552 TypeSourceInfo *FixedTInfo = 6553 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6554 SizeIsNegative, 6555 Oversized); 6556 if (FixedTInfo) { 6557 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6558 NewTD->setTypeSourceInfo(FixedTInfo); 6559 } else { 6560 if (SizeIsNegative) 6561 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6562 else if (T->isVariableArrayType()) 6563 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6564 else if (Oversized.getBoolValue()) 6565 Diag(NewTD->getLocation(), diag::err_array_too_large) 6566 << toString(Oversized, 10); 6567 else 6568 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6569 NewTD->setInvalidDecl(); 6570 } 6571 } 6572 } 6573 } 6574 6575 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6576 /// declares a typedef-name, either using the 'typedef' type specifier or via 6577 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6578 NamedDecl* 6579 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6580 LookupResult &Previous, bool &Redeclaration) { 6581 6582 // Find the shadowed declaration before filtering for scope. 6583 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6584 6585 // Merge the decl with the existing one if appropriate. If the decl is 6586 // in an outer scope, it isn't the same thing. 6587 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6588 /*AllowInlineNamespace*/false); 6589 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6590 if (!Previous.empty()) { 6591 Redeclaration = true; 6592 MergeTypedefNameDecl(S, NewTD, Previous); 6593 } else { 6594 inferGslPointerAttribute(NewTD); 6595 } 6596 6597 if (ShadowedDecl && !Redeclaration) 6598 CheckShadow(NewTD, ShadowedDecl, Previous); 6599 6600 // If this is the C FILE type, notify the AST context. 6601 if (IdentifierInfo *II = NewTD->getIdentifier()) 6602 if (!NewTD->isInvalidDecl() && 6603 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6604 if (II->isStr("FILE")) 6605 Context.setFILEDecl(NewTD); 6606 else if (II->isStr("jmp_buf")) 6607 Context.setjmp_bufDecl(NewTD); 6608 else if (II->isStr("sigjmp_buf")) 6609 Context.setsigjmp_bufDecl(NewTD); 6610 else if (II->isStr("ucontext_t")) 6611 Context.setucontext_tDecl(NewTD); 6612 } 6613 6614 return NewTD; 6615 } 6616 6617 /// Determines whether the given declaration is an out-of-scope 6618 /// previous declaration. 6619 /// 6620 /// This routine should be invoked when name lookup has found a 6621 /// previous declaration (PrevDecl) that is not in the scope where a 6622 /// new declaration by the same name is being introduced. If the new 6623 /// declaration occurs in a local scope, previous declarations with 6624 /// linkage may still be considered previous declarations (C99 6625 /// 6.2.2p4-5, C++ [basic.link]p6). 6626 /// 6627 /// \param PrevDecl the previous declaration found by name 6628 /// lookup 6629 /// 6630 /// \param DC the context in which the new declaration is being 6631 /// declared. 6632 /// 6633 /// \returns true if PrevDecl is an out-of-scope previous declaration 6634 /// for a new delcaration with the same name. 6635 static bool 6636 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6637 ASTContext &Context) { 6638 if (!PrevDecl) 6639 return false; 6640 6641 if (!PrevDecl->hasLinkage()) 6642 return false; 6643 6644 if (Context.getLangOpts().CPlusPlus) { 6645 // C++ [basic.link]p6: 6646 // If there is a visible declaration of an entity with linkage 6647 // having the same name and type, ignoring entities declared 6648 // outside the innermost enclosing namespace scope, the block 6649 // scope declaration declares that same entity and receives the 6650 // linkage of the previous declaration. 6651 DeclContext *OuterContext = DC->getRedeclContext(); 6652 if (!OuterContext->isFunctionOrMethod()) 6653 // This rule only applies to block-scope declarations. 6654 return false; 6655 6656 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6657 if (PrevOuterContext->isRecord()) 6658 // We found a member function: ignore it. 6659 return false; 6660 6661 // Find the innermost enclosing namespace for the new and 6662 // previous declarations. 6663 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6664 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6665 6666 // The previous declaration is in a different namespace, so it 6667 // isn't the same function. 6668 if (!OuterContext->Equals(PrevOuterContext)) 6669 return false; 6670 } 6671 6672 return true; 6673 } 6674 6675 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6676 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6677 if (!SS.isSet()) return; 6678 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6679 } 6680 6681 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6682 QualType type = decl->getType(); 6683 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6684 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6685 // Various kinds of declaration aren't allowed to be __autoreleasing. 6686 unsigned kind = -1U; 6687 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6688 if (var->hasAttr<BlocksAttr>()) 6689 kind = 0; // __block 6690 else if (!var->hasLocalStorage()) 6691 kind = 1; // global 6692 } else if (isa<ObjCIvarDecl>(decl)) { 6693 kind = 3; // ivar 6694 } else if (isa<FieldDecl>(decl)) { 6695 kind = 2; // field 6696 } 6697 6698 if (kind != -1U) { 6699 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6700 << kind; 6701 } 6702 } else if (lifetime == Qualifiers::OCL_None) { 6703 // Try to infer lifetime. 6704 if (!type->isObjCLifetimeType()) 6705 return false; 6706 6707 lifetime = type->getObjCARCImplicitLifetime(); 6708 type = Context.getLifetimeQualifiedType(type, lifetime); 6709 decl->setType(type); 6710 } 6711 6712 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6713 // Thread-local variables cannot have lifetime. 6714 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6715 var->getTLSKind()) { 6716 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6717 << var->getType(); 6718 return true; 6719 } 6720 } 6721 6722 return false; 6723 } 6724 6725 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6726 if (Decl->getType().hasAddressSpace()) 6727 return; 6728 if (Decl->getType()->isDependentType()) 6729 return; 6730 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6731 QualType Type = Var->getType(); 6732 if (Type->isSamplerT() || Type->isVoidType()) 6733 return; 6734 LangAS ImplAS = LangAS::opencl_private; 6735 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6736 // __opencl_c_program_scope_global_variables feature, the address space 6737 // for a variable at program scope or a static or extern variable inside 6738 // a function are inferred to be __global. 6739 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6740 Var->hasGlobalStorage()) 6741 ImplAS = LangAS::opencl_global; 6742 // If the original type from a decayed type is an array type and that array 6743 // type has no address space yet, deduce it now. 6744 if (auto DT = dyn_cast<DecayedType>(Type)) { 6745 auto OrigTy = DT->getOriginalType(); 6746 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6747 // Add the address space to the original array type and then propagate 6748 // that to the element type through `getAsArrayType`. 6749 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6750 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6751 // Re-generate the decayed type. 6752 Type = Context.getDecayedType(OrigTy); 6753 } 6754 } 6755 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6756 // Apply any qualifiers (including address space) from the array type to 6757 // the element type. This implements C99 6.7.3p8: "If the specification of 6758 // an array type includes any type qualifiers, the element type is so 6759 // qualified, not the array type." 6760 if (Type->isArrayType()) 6761 Type = QualType(Context.getAsArrayType(Type), 0); 6762 Decl->setType(Type); 6763 } 6764 } 6765 6766 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6767 // Ensure that an auto decl is deduced otherwise the checks below might cache 6768 // the wrong linkage. 6769 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6770 6771 // 'weak' only applies to declarations with external linkage. 6772 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6773 if (!ND.isExternallyVisible()) { 6774 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6775 ND.dropAttr<WeakAttr>(); 6776 } 6777 } 6778 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6779 if (ND.isExternallyVisible()) { 6780 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6781 ND.dropAttr<WeakRefAttr>(); 6782 ND.dropAttr<AliasAttr>(); 6783 } 6784 } 6785 6786 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6787 if (VD->hasInit()) { 6788 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6789 assert(VD->isThisDeclarationADefinition() && 6790 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6791 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6792 VD->dropAttr<AliasAttr>(); 6793 } 6794 } 6795 } 6796 6797 // 'selectany' only applies to externally visible variable declarations. 6798 // It does not apply to functions. 6799 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6800 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6801 S.Diag(Attr->getLocation(), 6802 diag::err_attribute_selectany_non_extern_data); 6803 ND.dropAttr<SelectAnyAttr>(); 6804 } 6805 } 6806 6807 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6808 auto *VD = dyn_cast<VarDecl>(&ND); 6809 bool IsAnonymousNS = false; 6810 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6811 if (VD) { 6812 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6813 while (NS && !IsAnonymousNS) { 6814 IsAnonymousNS = NS->isAnonymousNamespace(); 6815 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6816 } 6817 } 6818 // dll attributes require external linkage. Static locals may have external 6819 // linkage but still cannot be explicitly imported or exported. 6820 // In Microsoft mode, a variable defined in anonymous namespace must have 6821 // external linkage in order to be exported. 6822 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6823 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6824 (!AnonNSInMicrosoftMode && 6825 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6826 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6827 << &ND << Attr; 6828 ND.setInvalidDecl(); 6829 } 6830 } 6831 6832 // Check the attributes on the function type, if any. 6833 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6834 // Don't declare this variable in the second operand of the for-statement; 6835 // GCC miscompiles that by ending its lifetime before evaluating the 6836 // third operand. See gcc.gnu.org/PR86769. 6837 AttributedTypeLoc ATL; 6838 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6839 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6840 TL = ATL.getModifiedLoc()) { 6841 // The [[lifetimebound]] attribute can be applied to the implicit object 6842 // parameter of a non-static member function (other than a ctor or dtor) 6843 // by applying it to the function type. 6844 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6845 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6846 if (!MD || MD->isStatic()) { 6847 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6848 << !MD << A->getRange(); 6849 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6850 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6851 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6852 } 6853 } 6854 } 6855 } 6856 } 6857 6858 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6859 NamedDecl *NewDecl, 6860 bool IsSpecialization, 6861 bool IsDefinition) { 6862 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6863 return; 6864 6865 bool IsTemplate = false; 6866 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6867 OldDecl = OldTD->getTemplatedDecl(); 6868 IsTemplate = true; 6869 if (!IsSpecialization) 6870 IsDefinition = false; 6871 } 6872 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6873 NewDecl = NewTD->getTemplatedDecl(); 6874 IsTemplate = true; 6875 } 6876 6877 if (!OldDecl || !NewDecl) 6878 return; 6879 6880 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6881 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6882 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6883 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6884 6885 // dllimport and dllexport are inheritable attributes so we have to exclude 6886 // inherited attribute instances. 6887 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6888 (NewExportAttr && !NewExportAttr->isInherited()); 6889 6890 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6891 // the only exception being explicit specializations. 6892 // Implicitly generated declarations are also excluded for now because there 6893 // is no other way to switch these to use dllimport or dllexport. 6894 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6895 6896 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6897 // Allow with a warning for free functions and global variables. 6898 bool JustWarn = false; 6899 if (!OldDecl->isCXXClassMember()) { 6900 auto *VD = dyn_cast<VarDecl>(OldDecl); 6901 if (VD && !VD->getDescribedVarTemplate()) 6902 JustWarn = true; 6903 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6904 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6905 JustWarn = true; 6906 } 6907 6908 // We cannot change a declaration that's been used because IR has already 6909 // been emitted. Dllimported functions will still work though (modulo 6910 // address equality) as they can use the thunk. 6911 if (OldDecl->isUsed()) 6912 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6913 JustWarn = false; 6914 6915 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6916 : diag::err_attribute_dll_redeclaration; 6917 S.Diag(NewDecl->getLocation(), DiagID) 6918 << NewDecl 6919 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6920 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6921 if (!JustWarn) { 6922 NewDecl->setInvalidDecl(); 6923 return; 6924 } 6925 } 6926 6927 // A redeclaration is not allowed to drop a dllimport attribute, the only 6928 // exceptions being inline function definitions (except for function 6929 // templates), local extern declarations, qualified friend declarations or 6930 // special MSVC extension: in the last case, the declaration is treated as if 6931 // it were marked dllexport. 6932 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6933 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6934 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6935 // Ignore static data because out-of-line definitions are diagnosed 6936 // separately. 6937 IsStaticDataMember = VD->isStaticDataMember(); 6938 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6939 VarDecl::DeclarationOnly; 6940 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6941 IsInline = FD->isInlined(); 6942 IsQualifiedFriend = FD->getQualifier() && 6943 FD->getFriendObjectKind() == Decl::FOK_Declared; 6944 } 6945 6946 if (OldImportAttr && !HasNewAttr && 6947 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6948 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6949 if (IsMicrosoftABI && IsDefinition) { 6950 S.Diag(NewDecl->getLocation(), 6951 diag::warn_redeclaration_without_import_attribute) 6952 << NewDecl; 6953 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6954 NewDecl->dropAttr<DLLImportAttr>(); 6955 NewDecl->addAttr( 6956 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6957 } else { 6958 S.Diag(NewDecl->getLocation(), 6959 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6960 << NewDecl << OldImportAttr; 6961 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6962 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6963 OldDecl->dropAttr<DLLImportAttr>(); 6964 NewDecl->dropAttr<DLLImportAttr>(); 6965 } 6966 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6967 // In MinGW, seeing a function declared inline drops the dllimport 6968 // attribute. 6969 OldDecl->dropAttr<DLLImportAttr>(); 6970 NewDecl->dropAttr<DLLImportAttr>(); 6971 S.Diag(NewDecl->getLocation(), 6972 diag::warn_dllimport_dropped_from_inline_function) 6973 << NewDecl << OldImportAttr; 6974 } 6975 6976 // A specialization of a class template member function is processed here 6977 // since it's a redeclaration. If the parent class is dllexport, the 6978 // specialization inherits that attribute. This doesn't happen automatically 6979 // since the parent class isn't instantiated until later. 6980 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6981 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6982 !NewImportAttr && !NewExportAttr) { 6983 if (const DLLExportAttr *ParentExportAttr = 6984 MD->getParent()->getAttr<DLLExportAttr>()) { 6985 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6986 NewAttr->setInherited(true); 6987 NewDecl->addAttr(NewAttr); 6988 } 6989 } 6990 } 6991 } 6992 6993 /// Given that we are within the definition of the given function, 6994 /// will that definition behave like C99's 'inline', where the 6995 /// definition is discarded except for optimization purposes? 6996 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6997 // Try to avoid calling GetGVALinkageForFunction. 6998 6999 // All cases of this require the 'inline' keyword. 7000 if (!FD->isInlined()) return false; 7001 7002 // This is only possible in C++ with the gnu_inline attribute. 7003 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 7004 return false; 7005 7006 // Okay, go ahead and call the relatively-more-expensive function. 7007 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 7008 } 7009 7010 /// Determine whether a variable is extern "C" prior to attaching 7011 /// an initializer. We can't just call isExternC() here, because that 7012 /// will also compute and cache whether the declaration is externally 7013 /// visible, which might change when we attach the initializer. 7014 /// 7015 /// This can only be used if the declaration is known to not be a 7016 /// redeclaration of an internal linkage declaration. 7017 /// 7018 /// For instance: 7019 /// 7020 /// auto x = []{}; 7021 /// 7022 /// Attaching the initializer here makes this declaration not externally 7023 /// visible, because its type has internal linkage. 7024 /// 7025 /// FIXME: This is a hack. 7026 template<typename T> 7027 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 7028 if (S.getLangOpts().CPlusPlus) { 7029 // In C++, the overloadable attribute negates the effects of extern "C". 7030 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 7031 return false; 7032 7033 // So do CUDA's host/device attributes. 7034 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 7035 D->template hasAttr<CUDAHostAttr>())) 7036 return false; 7037 } 7038 return D->isExternC(); 7039 } 7040 7041 static bool shouldConsiderLinkage(const VarDecl *VD) { 7042 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 7043 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 7044 isa<OMPDeclareMapperDecl>(DC)) 7045 return VD->hasExternalStorage(); 7046 if (DC->isFileContext()) 7047 return true; 7048 if (DC->isRecord()) 7049 return false; 7050 if (isa<RequiresExprBodyDecl>(DC)) 7051 return false; 7052 llvm_unreachable("Unexpected context"); 7053 } 7054 7055 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 7056 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 7057 if (DC->isFileContext() || DC->isFunctionOrMethod() || 7058 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 7059 return true; 7060 if (DC->isRecord()) 7061 return false; 7062 llvm_unreachable("Unexpected context"); 7063 } 7064 7065 static bool hasParsedAttr(Scope *S, const Declarator &PD, 7066 ParsedAttr::Kind Kind) { 7067 // Check decl attributes on the DeclSpec. 7068 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 7069 return true; 7070 7071 // Walk the declarator structure, checking decl attributes that were in a type 7072 // position to the decl itself. 7073 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 7074 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 7075 return true; 7076 } 7077 7078 // Finally, check attributes on the decl itself. 7079 return PD.getAttributes().hasAttribute(Kind) || 7080 PD.getDeclarationAttributes().hasAttribute(Kind); 7081 } 7082 7083 /// Adjust the \c DeclContext for a function or variable that might be a 7084 /// function-local external declaration. 7085 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 7086 if (!DC->isFunctionOrMethod()) 7087 return false; 7088 7089 // If this is a local extern function or variable declared within a function 7090 // template, don't add it into the enclosing namespace scope until it is 7091 // instantiated; it might have a dependent type right now. 7092 if (DC->isDependentContext()) 7093 return true; 7094 7095 // C++11 [basic.link]p7: 7096 // When a block scope declaration of an entity with linkage is not found to 7097 // refer to some other declaration, then that entity is a member of the 7098 // innermost enclosing namespace. 7099 // 7100 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 7101 // semantically-enclosing namespace, not a lexically-enclosing one. 7102 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 7103 DC = DC->getParent(); 7104 return true; 7105 } 7106 7107 /// Returns true if given declaration has external C language linkage. 7108 static bool isDeclExternC(const Decl *D) { 7109 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 7110 return FD->isExternC(); 7111 if (const auto *VD = dyn_cast<VarDecl>(D)) 7112 return VD->isExternC(); 7113 7114 llvm_unreachable("Unknown type of decl!"); 7115 } 7116 7117 /// Returns true if there hasn't been any invalid type diagnosed. 7118 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 7119 DeclContext *DC = NewVD->getDeclContext(); 7120 QualType R = NewVD->getType(); 7121 7122 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 7123 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 7124 // argument. 7125 if (R->isImageType() || R->isPipeType()) { 7126 Se.Diag(NewVD->getLocation(), 7127 diag::err_opencl_type_can_only_be_used_as_function_parameter) 7128 << R; 7129 NewVD->setInvalidDecl(); 7130 return false; 7131 } 7132 7133 // OpenCL v1.2 s6.9.r: 7134 // The event type cannot be used to declare a program scope variable. 7135 // OpenCL v2.0 s6.9.q: 7136 // The clk_event_t and reserve_id_t types cannot be declared in program 7137 // scope. 7138 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 7139 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 7140 Se.Diag(NewVD->getLocation(), 7141 diag::err_invalid_type_for_program_scope_var) 7142 << R; 7143 NewVD->setInvalidDecl(); 7144 return false; 7145 } 7146 } 7147 7148 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 7149 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 7150 Se.getLangOpts())) { 7151 QualType NR = R.getCanonicalType(); 7152 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 7153 NR->isReferenceType()) { 7154 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 7155 NR->isFunctionReferenceType()) { 7156 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 7157 << NR->isReferenceType(); 7158 NewVD->setInvalidDecl(); 7159 return false; 7160 } 7161 NR = NR->getPointeeType(); 7162 } 7163 } 7164 7165 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 7166 Se.getLangOpts())) { 7167 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 7168 // half array type (unless the cl_khr_fp16 extension is enabled). 7169 if (Se.Context.getBaseElementType(R)->isHalfType()) { 7170 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 7171 NewVD->setInvalidDecl(); 7172 return false; 7173 } 7174 } 7175 7176 // OpenCL v1.2 s6.9.r: 7177 // The event type cannot be used with the __local, __constant and __global 7178 // address space qualifiers. 7179 if (R->isEventT()) { 7180 if (R.getAddressSpace() != LangAS::opencl_private) { 7181 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 7182 NewVD->setInvalidDecl(); 7183 return false; 7184 } 7185 } 7186 7187 if (R->isSamplerT()) { 7188 // OpenCL v1.2 s6.9.b p4: 7189 // The sampler type cannot be used with the __local and __global address 7190 // space qualifiers. 7191 if (R.getAddressSpace() == LangAS::opencl_local || 7192 R.getAddressSpace() == LangAS::opencl_global) { 7193 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 7194 NewVD->setInvalidDecl(); 7195 } 7196 7197 // OpenCL v1.2 s6.12.14.1: 7198 // A global sampler must be declared with either the constant address 7199 // space qualifier or with the const qualifier. 7200 if (DC->isTranslationUnit() && 7201 !(R.getAddressSpace() == LangAS::opencl_constant || 7202 R.isConstQualified())) { 7203 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 7204 NewVD->setInvalidDecl(); 7205 } 7206 if (NewVD->isInvalidDecl()) 7207 return false; 7208 } 7209 7210 return true; 7211 } 7212 7213 template <typename AttrTy> 7214 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 7215 const TypedefNameDecl *TND = TT->getDecl(); 7216 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 7217 AttrTy *Clone = Attribute->clone(S.Context); 7218 Clone->setInherited(true); 7219 D->addAttr(Clone); 7220 } 7221 } 7222 7223 NamedDecl *Sema::ActOnVariableDeclarator( 7224 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7225 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7226 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7227 QualType R = TInfo->getType(); 7228 DeclarationName Name = GetNameForDeclarator(D).getName(); 7229 7230 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7231 7232 if (D.isDecompositionDeclarator()) { 7233 // Take the name of the first declarator as our name for diagnostic 7234 // purposes. 7235 auto &Decomp = D.getDecompositionDeclarator(); 7236 if (!Decomp.bindings().empty()) { 7237 II = Decomp.bindings()[0].Name; 7238 Name = II; 7239 } 7240 } else if (!II) { 7241 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7242 return nullptr; 7243 } 7244 7245 7246 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7247 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7248 7249 // dllimport globals without explicit storage class are treated as extern. We 7250 // have to change the storage class this early to get the right DeclContext. 7251 if (SC == SC_None && !DC->isRecord() && 7252 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7253 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7254 SC = SC_Extern; 7255 7256 DeclContext *OriginalDC = DC; 7257 bool IsLocalExternDecl = SC == SC_Extern && 7258 adjustContextForLocalExternDecl(DC); 7259 7260 if (SCSpec == DeclSpec::SCS_mutable) { 7261 // mutable can only appear on non-static class members, so it's always 7262 // an error here 7263 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7264 D.setInvalidType(); 7265 SC = SC_None; 7266 } 7267 7268 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7269 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7270 D.getDeclSpec().getStorageClassSpecLoc())) { 7271 // In C++11, the 'register' storage class specifier is deprecated. 7272 // Suppress the warning in system macros, it's used in macros in some 7273 // popular C system headers, such as in glibc's htonl() macro. 7274 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7275 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7276 : diag::warn_deprecated_register) 7277 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7278 } 7279 7280 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7281 7282 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7283 // C99 6.9p2: The storage-class specifiers auto and register shall not 7284 // appear in the declaration specifiers in an external declaration. 7285 // Global Register+Asm is a GNU extension we support. 7286 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7287 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7288 D.setInvalidType(); 7289 } 7290 } 7291 7292 // If this variable has a VLA type and an initializer, try to 7293 // fold to a constant-sized type. This is otherwise invalid. 7294 if (D.hasInitializer() && R->isVariableArrayType()) 7295 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7296 /*DiagID=*/0); 7297 7298 bool IsMemberSpecialization = false; 7299 bool IsVariableTemplateSpecialization = false; 7300 bool IsPartialSpecialization = false; 7301 bool IsVariableTemplate = false; 7302 VarDecl *NewVD = nullptr; 7303 VarTemplateDecl *NewTemplate = nullptr; 7304 TemplateParameterList *TemplateParams = nullptr; 7305 if (!getLangOpts().CPlusPlus) { 7306 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7307 II, R, TInfo, SC); 7308 7309 if (R->getContainedDeducedType()) 7310 ParsingInitForAutoVars.insert(NewVD); 7311 7312 if (D.isInvalidType()) 7313 NewVD->setInvalidDecl(); 7314 7315 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7316 NewVD->hasLocalStorage()) 7317 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7318 NTCUC_AutoVar, NTCUK_Destruct); 7319 } else { 7320 bool Invalid = false; 7321 7322 if (DC->isRecord() && !CurContext->isRecord()) { 7323 // This is an out-of-line definition of a static data member. 7324 switch (SC) { 7325 case SC_None: 7326 break; 7327 case SC_Static: 7328 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7329 diag::err_static_out_of_line) 7330 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7331 break; 7332 case SC_Auto: 7333 case SC_Register: 7334 case SC_Extern: 7335 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7336 // to names of variables declared in a block or to function parameters. 7337 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7338 // of class members 7339 7340 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7341 diag::err_storage_class_for_static_member) 7342 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7343 break; 7344 case SC_PrivateExtern: 7345 llvm_unreachable("C storage class in c++!"); 7346 } 7347 } 7348 7349 if (SC == SC_Static && CurContext->isRecord()) { 7350 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7351 // Walk up the enclosing DeclContexts to check for any that are 7352 // incompatible with static data members. 7353 const DeclContext *FunctionOrMethod = nullptr; 7354 const CXXRecordDecl *AnonStruct = nullptr; 7355 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7356 if (Ctxt->isFunctionOrMethod()) { 7357 FunctionOrMethod = Ctxt; 7358 break; 7359 } 7360 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7361 if (ParentDecl && !ParentDecl->getDeclName()) { 7362 AnonStruct = ParentDecl; 7363 break; 7364 } 7365 } 7366 if (FunctionOrMethod) { 7367 // C++ [class.static.data]p5: A local class shall not have static data 7368 // members. 7369 Diag(D.getIdentifierLoc(), 7370 diag::err_static_data_member_not_allowed_in_local_class) 7371 << Name << RD->getDeclName() << RD->getTagKind(); 7372 } else if (AnonStruct) { 7373 // C++ [class.static.data]p4: Unnamed classes and classes contained 7374 // directly or indirectly within unnamed classes shall not contain 7375 // static data members. 7376 Diag(D.getIdentifierLoc(), 7377 diag::err_static_data_member_not_allowed_in_anon_struct) 7378 << Name << AnonStruct->getTagKind(); 7379 Invalid = true; 7380 } else if (RD->isUnion()) { 7381 // C++98 [class.union]p1: If a union contains a static data member, 7382 // the program is ill-formed. C++11 drops this restriction. 7383 Diag(D.getIdentifierLoc(), 7384 getLangOpts().CPlusPlus11 7385 ? diag::warn_cxx98_compat_static_data_member_in_union 7386 : diag::ext_static_data_member_in_union) << Name; 7387 } 7388 } 7389 } 7390 7391 // Match up the template parameter lists with the scope specifier, then 7392 // determine whether we have a template or a template specialization. 7393 bool InvalidScope = false; 7394 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7395 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7396 D.getCXXScopeSpec(), 7397 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7398 ? D.getName().TemplateId 7399 : nullptr, 7400 TemplateParamLists, 7401 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7402 Invalid |= InvalidScope; 7403 7404 if (TemplateParams) { 7405 if (!TemplateParams->size() && 7406 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7407 // There is an extraneous 'template<>' for this variable. Complain 7408 // about it, but allow the declaration of the variable. 7409 Diag(TemplateParams->getTemplateLoc(), 7410 diag::err_template_variable_noparams) 7411 << II 7412 << SourceRange(TemplateParams->getTemplateLoc(), 7413 TemplateParams->getRAngleLoc()); 7414 TemplateParams = nullptr; 7415 } else { 7416 // Check that we can declare a template here. 7417 if (CheckTemplateDeclScope(S, TemplateParams)) 7418 return nullptr; 7419 7420 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7421 // This is an explicit specialization or a partial specialization. 7422 IsVariableTemplateSpecialization = true; 7423 IsPartialSpecialization = TemplateParams->size() > 0; 7424 } else { // if (TemplateParams->size() > 0) 7425 // This is a template declaration. 7426 IsVariableTemplate = true; 7427 7428 // Only C++1y supports variable templates (N3651). 7429 Diag(D.getIdentifierLoc(), 7430 getLangOpts().CPlusPlus14 7431 ? diag::warn_cxx11_compat_variable_template 7432 : diag::ext_variable_template); 7433 } 7434 } 7435 } else { 7436 // Check that we can declare a member specialization here. 7437 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7438 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7439 return nullptr; 7440 assert((Invalid || 7441 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7442 "should have a 'template<>' for this decl"); 7443 } 7444 7445 if (IsVariableTemplateSpecialization) { 7446 SourceLocation TemplateKWLoc = 7447 TemplateParamLists.size() > 0 7448 ? TemplateParamLists[0]->getTemplateLoc() 7449 : SourceLocation(); 7450 DeclResult Res = ActOnVarTemplateSpecialization( 7451 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7452 IsPartialSpecialization); 7453 if (Res.isInvalid()) 7454 return nullptr; 7455 NewVD = cast<VarDecl>(Res.get()); 7456 AddToScope = false; 7457 } else if (D.isDecompositionDeclarator()) { 7458 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7459 D.getIdentifierLoc(), R, TInfo, SC, 7460 Bindings); 7461 } else 7462 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7463 D.getIdentifierLoc(), II, R, TInfo, SC); 7464 7465 // If this is supposed to be a variable template, create it as such. 7466 if (IsVariableTemplate) { 7467 NewTemplate = 7468 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7469 TemplateParams, NewVD); 7470 NewVD->setDescribedVarTemplate(NewTemplate); 7471 } 7472 7473 // If this decl has an auto type in need of deduction, make a note of the 7474 // Decl so we can diagnose uses of it in its own initializer. 7475 if (R->getContainedDeducedType()) 7476 ParsingInitForAutoVars.insert(NewVD); 7477 7478 if (D.isInvalidType() || Invalid) { 7479 NewVD->setInvalidDecl(); 7480 if (NewTemplate) 7481 NewTemplate->setInvalidDecl(); 7482 } 7483 7484 SetNestedNameSpecifier(*this, NewVD, D); 7485 7486 // If we have any template parameter lists that don't directly belong to 7487 // the variable (matching the scope specifier), store them. 7488 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7489 if (TemplateParamLists.size() > VDTemplateParamLists) 7490 NewVD->setTemplateParameterListsInfo( 7491 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7492 } 7493 7494 if (D.getDeclSpec().isInlineSpecified()) { 7495 if (!getLangOpts().CPlusPlus) { 7496 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7497 << 0; 7498 } else if (CurContext->isFunctionOrMethod()) { 7499 // 'inline' is not allowed on block scope variable declaration. 7500 Diag(D.getDeclSpec().getInlineSpecLoc(), 7501 diag::err_inline_declaration_block_scope) << Name 7502 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7503 } else { 7504 Diag(D.getDeclSpec().getInlineSpecLoc(), 7505 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7506 : diag::ext_inline_variable); 7507 NewVD->setInlineSpecified(); 7508 } 7509 } 7510 7511 // Set the lexical context. If the declarator has a C++ scope specifier, the 7512 // lexical context will be different from the semantic context. 7513 NewVD->setLexicalDeclContext(CurContext); 7514 if (NewTemplate) 7515 NewTemplate->setLexicalDeclContext(CurContext); 7516 7517 if (IsLocalExternDecl) { 7518 if (D.isDecompositionDeclarator()) 7519 for (auto *B : Bindings) 7520 B->setLocalExternDecl(); 7521 else 7522 NewVD->setLocalExternDecl(); 7523 } 7524 7525 bool EmitTLSUnsupportedError = false; 7526 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7527 // C++11 [dcl.stc]p4: 7528 // When thread_local is applied to a variable of block scope the 7529 // storage-class-specifier static is implied if it does not appear 7530 // explicitly. 7531 // Core issue: 'static' is not implied if the variable is declared 7532 // 'extern'. 7533 if (NewVD->hasLocalStorage() && 7534 (SCSpec != DeclSpec::SCS_unspecified || 7535 TSCS != DeclSpec::TSCS_thread_local || 7536 !DC->isFunctionOrMethod())) 7537 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7538 diag::err_thread_non_global) 7539 << DeclSpec::getSpecifierName(TSCS); 7540 else if (!Context.getTargetInfo().isTLSSupported()) { 7541 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7542 getLangOpts().SYCLIsDevice) { 7543 // Postpone error emission until we've collected attributes required to 7544 // figure out whether it's a host or device variable and whether the 7545 // error should be ignored. 7546 EmitTLSUnsupportedError = true; 7547 // We still need to mark the variable as TLS so it shows up in AST with 7548 // proper storage class for other tools to use even if we're not going 7549 // to emit any code for it. 7550 NewVD->setTSCSpec(TSCS); 7551 } else 7552 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7553 diag::err_thread_unsupported); 7554 } else 7555 NewVD->setTSCSpec(TSCS); 7556 } 7557 7558 switch (D.getDeclSpec().getConstexprSpecifier()) { 7559 case ConstexprSpecKind::Unspecified: 7560 break; 7561 7562 case ConstexprSpecKind::Consteval: 7563 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7564 diag::err_constexpr_wrong_decl_kind) 7565 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7566 LLVM_FALLTHROUGH; 7567 7568 case ConstexprSpecKind::Constexpr: 7569 NewVD->setConstexpr(true); 7570 // C++1z [dcl.spec.constexpr]p1: 7571 // A static data member declared with the constexpr specifier is 7572 // implicitly an inline variable. 7573 if (NewVD->isStaticDataMember() && 7574 (getLangOpts().CPlusPlus17 || 7575 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7576 NewVD->setImplicitlyInline(); 7577 break; 7578 7579 case ConstexprSpecKind::Constinit: 7580 if (!NewVD->hasGlobalStorage()) 7581 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7582 diag::err_constinit_local_variable); 7583 else 7584 NewVD->addAttr(ConstInitAttr::Create( 7585 Context, D.getDeclSpec().getConstexprSpecLoc(), 7586 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7587 break; 7588 } 7589 7590 // C99 6.7.4p3 7591 // An inline definition of a function with external linkage shall 7592 // not contain a definition of a modifiable object with static or 7593 // thread storage duration... 7594 // We only apply this when the function is required to be defined 7595 // elsewhere, i.e. when the function is not 'extern inline'. Note 7596 // that a local variable with thread storage duration still has to 7597 // be marked 'static'. Also note that it's possible to get these 7598 // semantics in C++ using __attribute__((gnu_inline)). 7599 if (SC == SC_Static && S->getFnParent() != nullptr && 7600 !NewVD->getType().isConstQualified()) { 7601 FunctionDecl *CurFD = getCurFunctionDecl(); 7602 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7603 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7604 diag::warn_static_local_in_extern_inline); 7605 MaybeSuggestAddingStaticToDecl(CurFD); 7606 } 7607 } 7608 7609 if (D.getDeclSpec().isModulePrivateSpecified()) { 7610 if (IsVariableTemplateSpecialization) 7611 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7612 << (IsPartialSpecialization ? 1 : 0) 7613 << FixItHint::CreateRemoval( 7614 D.getDeclSpec().getModulePrivateSpecLoc()); 7615 else if (IsMemberSpecialization) 7616 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7617 << 2 7618 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7619 else if (NewVD->hasLocalStorage()) 7620 Diag(NewVD->getLocation(), diag::err_module_private_local) 7621 << 0 << NewVD 7622 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7623 << FixItHint::CreateRemoval( 7624 D.getDeclSpec().getModulePrivateSpecLoc()); 7625 else { 7626 NewVD->setModulePrivate(); 7627 if (NewTemplate) 7628 NewTemplate->setModulePrivate(); 7629 for (auto *B : Bindings) 7630 B->setModulePrivate(); 7631 } 7632 } 7633 7634 if (getLangOpts().OpenCL) { 7635 deduceOpenCLAddressSpace(NewVD); 7636 7637 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7638 if (TSC != TSCS_unspecified) { 7639 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7640 diag::err_opencl_unknown_type_specifier) 7641 << getLangOpts().getOpenCLVersionString() 7642 << DeclSpec::getSpecifierName(TSC) << 1; 7643 NewVD->setInvalidDecl(); 7644 } 7645 } 7646 7647 // Handle attributes prior to checking for duplicates in MergeVarDecl 7648 ProcessDeclAttributes(S, NewVD, D); 7649 7650 // FIXME: This is probably the wrong location to be doing this and we should 7651 // probably be doing this for more attributes (especially for function 7652 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7653 // the code to copy attributes would be generated by TableGen. 7654 if (R->isFunctionPointerType()) 7655 if (const auto *TT = R->getAs<TypedefType>()) 7656 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7657 7658 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7659 getLangOpts().SYCLIsDevice) { 7660 if (EmitTLSUnsupportedError && 7661 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7662 (getLangOpts().OpenMPIsDevice && 7663 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7664 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7665 diag::err_thread_unsupported); 7666 7667 if (EmitTLSUnsupportedError && 7668 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7669 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7670 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7671 // storage [duration]." 7672 if (SC == SC_None && S->getFnParent() != nullptr && 7673 (NewVD->hasAttr<CUDASharedAttr>() || 7674 NewVD->hasAttr<CUDAConstantAttr>())) { 7675 NewVD->setStorageClass(SC_Static); 7676 } 7677 } 7678 7679 // Ensure that dllimport globals without explicit storage class are treated as 7680 // extern. The storage class is set above using parsed attributes. Now we can 7681 // check the VarDecl itself. 7682 assert(!NewVD->hasAttr<DLLImportAttr>() || 7683 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7684 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7685 7686 // In auto-retain/release, infer strong retension for variables of 7687 // retainable type. 7688 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7689 NewVD->setInvalidDecl(); 7690 7691 // Handle GNU asm-label extension (encoded as an attribute). 7692 if (Expr *E = (Expr*)D.getAsmLabel()) { 7693 // The parser guarantees this is a string. 7694 StringLiteral *SE = cast<StringLiteral>(E); 7695 StringRef Label = SE->getString(); 7696 if (S->getFnParent() != nullptr) { 7697 switch (SC) { 7698 case SC_None: 7699 case SC_Auto: 7700 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7701 break; 7702 case SC_Register: 7703 // Local Named register 7704 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7705 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7706 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7707 break; 7708 case SC_Static: 7709 case SC_Extern: 7710 case SC_PrivateExtern: 7711 break; 7712 } 7713 } else if (SC == SC_Register) { 7714 // Global Named register 7715 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7716 const auto &TI = Context.getTargetInfo(); 7717 bool HasSizeMismatch; 7718 7719 if (!TI.isValidGCCRegisterName(Label)) 7720 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7721 else if (!TI.validateGlobalRegisterVariable(Label, 7722 Context.getTypeSize(R), 7723 HasSizeMismatch)) 7724 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7725 else if (HasSizeMismatch) 7726 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7727 } 7728 7729 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7730 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7731 NewVD->setInvalidDecl(true); 7732 } 7733 } 7734 7735 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7736 /*IsLiteralLabel=*/true, 7737 SE->getStrTokenLoc(0))); 7738 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7739 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7740 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7741 if (I != ExtnameUndeclaredIdentifiers.end()) { 7742 if (isDeclExternC(NewVD)) { 7743 NewVD->addAttr(I->second); 7744 ExtnameUndeclaredIdentifiers.erase(I); 7745 } else 7746 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7747 << /*Variable*/1 << NewVD; 7748 } 7749 } 7750 7751 // Find the shadowed declaration before filtering for scope. 7752 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7753 ? getShadowedDeclaration(NewVD, Previous) 7754 : nullptr; 7755 7756 // Don't consider existing declarations that are in a different 7757 // scope and are out-of-semantic-context declarations (if the new 7758 // declaration has linkage). 7759 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7760 D.getCXXScopeSpec().isNotEmpty() || 7761 IsMemberSpecialization || 7762 IsVariableTemplateSpecialization); 7763 7764 // Check whether the previous declaration is in the same block scope. This 7765 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7766 if (getLangOpts().CPlusPlus && 7767 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7768 NewVD->setPreviousDeclInSameBlockScope( 7769 Previous.isSingleResult() && !Previous.isShadowed() && 7770 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7771 7772 if (!getLangOpts().CPlusPlus) { 7773 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7774 } else { 7775 // If this is an explicit specialization of a static data member, check it. 7776 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7777 CheckMemberSpecialization(NewVD, Previous)) 7778 NewVD->setInvalidDecl(); 7779 7780 // Merge the decl with the existing one if appropriate. 7781 if (!Previous.empty()) { 7782 if (Previous.isSingleResult() && 7783 isa<FieldDecl>(Previous.getFoundDecl()) && 7784 D.getCXXScopeSpec().isSet()) { 7785 // The user tried to define a non-static data member 7786 // out-of-line (C++ [dcl.meaning]p1). 7787 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7788 << D.getCXXScopeSpec().getRange(); 7789 Previous.clear(); 7790 NewVD->setInvalidDecl(); 7791 } 7792 } else if (D.getCXXScopeSpec().isSet()) { 7793 // No previous declaration in the qualifying scope. 7794 Diag(D.getIdentifierLoc(), diag::err_no_member) 7795 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7796 << D.getCXXScopeSpec().getRange(); 7797 NewVD->setInvalidDecl(); 7798 } 7799 7800 if (!IsVariableTemplateSpecialization) 7801 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7802 7803 if (NewTemplate) { 7804 VarTemplateDecl *PrevVarTemplate = 7805 NewVD->getPreviousDecl() 7806 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7807 : nullptr; 7808 7809 // Check the template parameter list of this declaration, possibly 7810 // merging in the template parameter list from the previous variable 7811 // template declaration. 7812 if (CheckTemplateParameterList( 7813 TemplateParams, 7814 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7815 : nullptr, 7816 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7817 DC->isDependentContext()) 7818 ? TPC_ClassTemplateMember 7819 : TPC_VarTemplate)) 7820 NewVD->setInvalidDecl(); 7821 7822 // If we are providing an explicit specialization of a static variable 7823 // template, make a note of that. 7824 if (PrevVarTemplate && 7825 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7826 PrevVarTemplate->setMemberSpecialization(); 7827 } 7828 } 7829 7830 // Diagnose shadowed variables iff this isn't a redeclaration. 7831 if (ShadowedDecl && !D.isRedeclaration()) 7832 CheckShadow(NewVD, ShadowedDecl, Previous); 7833 7834 ProcessPragmaWeak(S, NewVD); 7835 7836 // If this is the first declaration of an extern C variable, update 7837 // the map of such variables. 7838 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7839 isIncompleteDeclExternC(*this, NewVD)) 7840 RegisterLocallyScopedExternCDecl(NewVD, S); 7841 7842 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7843 MangleNumberingContext *MCtx; 7844 Decl *ManglingContextDecl; 7845 std::tie(MCtx, ManglingContextDecl) = 7846 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7847 if (MCtx) { 7848 Context.setManglingNumber( 7849 NewVD, MCtx->getManglingNumber( 7850 NewVD, getMSManglingNumber(getLangOpts(), S))); 7851 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7852 } 7853 } 7854 7855 // Special handling of variable named 'main'. 7856 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7857 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7858 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7859 7860 // C++ [basic.start.main]p3 7861 // A program that declares a variable main at global scope is ill-formed. 7862 if (getLangOpts().CPlusPlus) 7863 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7864 7865 // In C, and external-linkage variable named main results in undefined 7866 // behavior. 7867 else if (NewVD->hasExternalFormalLinkage()) 7868 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7869 } 7870 7871 if (D.isRedeclaration() && !Previous.empty()) { 7872 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7873 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7874 D.isFunctionDefinition()); 7875 } 7876 7877 if (NewTemplate) { 7878 if (NewVD->isInvalidDecl()) 7879 NewTemplate->setInvalidDecl(); 7880 ActOnDocumentableDecl(NewTemplate); 7881 return NewTemplate; 7882 } 7883 7884 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7885 CompleteMemberSpecialization(NewVD, Previous); 7886 7887 return NewVD; 7888 } 7889 7890 /// Enum describing the %select options in diag::warn_decl_shadow. 7891 enum ShadowedDeclKind { 7892 SDK_Local, 7893 SDK_Global, 7894 SDK_StaticMember, 7895 SDK_Field, 7896 SDK_Typedef, 7897 SDK_Using, 7898 SDK_StructuredBinding 7899 }; 7900 7901 /// Determine what kind of declaration we're shadowing. 7902 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7903 const DeclContext *OldDC) { 7904 if (isa<TypeAliasDecl>(ShadowedDecl)) 7905 return SDK_Using; 7906 else if (isa<TypedefDecl>(ShadowedDecl)) 7907 return SDK_Typedef; 7908 else if (isa<BindingDecl>(ShadowedDecl)) 7909 return SDK_StructuredBinding; 7910 else if (isa<RecordDecl>(OldDC)) 7911 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7912 7913 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7914 } 7915 7916 /// Return the location of the capture if the given lambda captures the given 7917 /// variable \p VD, or an invalid source location otherwise. 7918 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7919 const VarDecl *VD) { 7920 for (const Capture &Capture : LSI->Captures) { 7921 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7922 return Capture.getLocation(); 7923 } 7924 return SourceLocation(); 7925 } 7926 7927 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7928 const LookupResult &R) { 7929 // Only diagnose if we're shadowing an unambiguous field or variable. 7930 if (R.getResultKind() != LookupResult::Found) 7931 return false; 7932 7933 // Return false if warning is ignored. 7934 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7935 } 7936 7937 /// Return the declaration shadowed by the given variable \p D, or null 7938 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7939 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7940 const LookupResult &R) { 7941 if (!shouldWarnIfShadowedDecl(Diags, R)) 7942 return nullptr; 7943 7944 // Don't diagnose declarations at file scope. 7945 if (D->hasGlobalStorage()) 7946 return nullptr; 7947 7948 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7949 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7950 : nullptr; 7951 } 7952 7953 /// Return the declaration shadowed by the given typedef \p D, or null 7954 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7955 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7956 const LookupResult &R) { 7957 // Don't warn if typedef declaration is part of a class 7958 if (D->getDeclContext()->isRecord()) 7959 return nullptr; 7960 7961 if (!shouldWarnIfShadowedDecl(Diags, R)) 7962 return nullptr; 7963 7964 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7965 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7966 } 7967 7968 /// Return the declaration shadowed by the given variable \p D, or null 7969 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7970 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7971 const LookupResult &R) { 7972 if (!shouldWarnIfShadowedDecl(Diags, R)) 7973 return nullptr; 7974 7975 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7976 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7977 : nullptr; 7978 } 7979 7980 /// Diagnose variable or built-in function shadowing. Implements 7981 /// -Wshadow. 7982 /// 7983 /// This method is called whenever a VarDecl is added to a "useful" 7984 /// scope. 7985 /// 7986 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7987 /// \param R the lookup of the name 7988 /// 7989 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7990 const LookupResult &R) { 7991 DeclContext *NewDC = D->getDeclContext(); 7992 7993 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7994 // Fields are not shadowed by variables in C++ static methods. 7995 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7996 if (MD->isStatic()) 7997 return; 7998 7999 // Fields shadowed by constructor parameters are a special case. Usually 8000 // the constructor initializes the field with the parameter. 8001 if (isa<CXXConstructorDecl>(NewDC)) 8002 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 8003 // Remember that this was shadowed so we can either warn about its 8004 // modification or its existence depending on warning settings. 8005 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 8006 return; 8007 } 8008 } 8009 8010 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 8011 if (shadowedVar->isExternC()) { 8012 // For shadowing external vars, make sure that we point to the global 8013 // declaration, not a locally scoped extern declaration. 8014 for (auto I : shadowedVar->redecls()) 8015 if (I->isFileVarDecl()) { 8016 ShadowedDecl = I; 8017 break; 8018 } 8019 } 8020 8021 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 8022 8023 unsigned WarningDiag = diag::warn_decl_shadow; 8024 SourceLocation CaptureLoc; 8025 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 8026 isa<CXXMethodDecl>(NewDC)) { 8027 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 8028 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 8029 if (RD->getLambdaCaptureDefault() == LCD_None) { 8030 // Try to avoid warnings for lambdas with an explicit capture list. 8031 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 8032 // Warn only when the lambda captures the shadowed decl explicitly. 8033 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 8034 if (CaptureLoc.isInvalid()) 8035 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 8036 } else { 8037 // Remember that this was shadowed so we can avoid the warning if the 8038 // shadowed decl isn't captured and the warning settings allow it. 8039 cast<LambdaScopeInfo>(getCurFunction()) 8040 ->ShadowingDecls.push_back( 8041 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 8042 return; 8043 } 8044 } 8045 8046 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 8047 // A variable can't shadow a local variable in an enclosing scope, if 8048 // they are separated by a non-capturing declaration context. 8049 for (DeclContext *ParentDC = NewDC; 8050 ParentDC && !ParentDC->Equals(OldDC); 8051 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 8052 // Only block literals, captured statements, and lambda expressions 8053 // can capture; other scopes don't. 8054 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 8055 !isLambdaCallOperator(ParentDC)) { 8056 return; 8057 } 8058 } 8059 } 8060 } 8061 } 8062 8063 // Only warn about certain kinds of shadowing for class members. 8064 if (NewDC && NewDC->isRecord()) { 8065 // In particular, don't warn about shadowing non-class members. 8066 if (!OldDC->isRecord()) 8067 return; 8068 8069 // TODO: should we warn about static data members shadowing 8070 // static data members from base classes? 8071 8072 // TODO: don't diagnose for inaccessible shadowed members. 8073 // This is hard to do perfectly because we might friend the 8074 // shadowing context, but that's just a false negative. 8075 } 8076 8077 8078 DeclarationName Name = R.getLookupName(); 8079 8080 // Emit warning and note. 8081 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 8082 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 8083 if (!CaptureLoc.isInvalid()) 8084 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8085 << Name << /*explicitly*/ 1; 8086 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8087 } 8088 8089 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 8090 /// when these variables are captured by the lambda. 8091 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 8092 for (const auto &Shadow : LSI->ShadowingDecls) { 8093 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 8094 // Try to avoid the warning when the shadowed decl isn't captured. 8095 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 8096 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8097 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 8098 ? diag::warn_decl_shadow_uncaptured_local 8099 : diag::warn_decl_shadow) 8100 << Shadow.VD->getDeclName() 8101 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8102 if (!CaptureLoc.isInvalid()) 8103 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8104 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 8105 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8106 } 8107 } 8108 8109 /// Check -Wshadow without the advantage of a previous lookup. 8110 void Sema::CheckShadow(Scope *S, VarDecl *D) { 8111 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 8112 return; 8113 8114 LookupResult R(*this, D->getDeclName(), D->getLocation(), 8115 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 8116 LookupName(R, S); 8117 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 8118 CheckShadow(D, ShadowedDecl, R); 8119 } 8120 8121 /// Check if 'E', which is an expression that is about to be modified, refers 8122 /// to a constructor parameter that shadows a field. 8123 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 8124 // Quickly ignore expressions that can't be shadowing ctor parameters. 8125 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 8126 return; 8127 E = E->IgnoreParenImpCasts(); 8128 auto *DRE = dyn_cast<DeclRefExpr>(E); 8129 if (!DRE) 8130 return; 8131 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 8132 auto I = ShadowingDecls.find(D); 8133 if (I == ShadowingDecls.end()) 8134 return; 8135 const NamedDecl *ShadowedDecl = I->second; 8136 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8137 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 8138 Diag(D->getLocation(), diag::note_var_declared_here) << D; 8139 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8140 8141 // Avoid issuing multiple warnings about the same decl. 8142 ShadowingDecls.erase(I); 8143 } 8144 8145 /// Check for conflict between this global or extern "C" declaration and 8146 /// previous global or extern "C" declarations. This is only used in C++. 8147 template<typename T> 8148 static bool checkGlobalOrExternCConflict( 8149 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 8150 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 8151 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 8152 8153 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 8154 // The common case: this global doesn't conflict with any extern "C" 8155 // declaration. 8156 return false; 8157 } 8158 8159 if (Prev) { 8160 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 8161 // Both the old and new declarations have C language linkage. This is a 8162 // redeclaration. 8163 Previous.clear(); 8164 Previous.addDecl(Prev); 8165 return true; 8166 } 8167 8168 // This is a global, non-extern "C" declaration, and there is a previous 8169 // non-global extern "C" declaration. Diagnose if this is a variable 8170 // declaration. 8171 if (!isa<VarDecl>(ND)) 8172 return false; 8173 } else { 8174 // The declaration is extern "C". Check for any declaration in the 8175 // translation unit which might conflict. 8176 if (IsGlobal) { 8177 // We have already performed the lookup into the translation unit. 8178 IsGlobal = false; 8179 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8180 I != E; ++I) { 8181 if (isa<VarDecl>(*I)) { 8182 Prev = *I; 8183 break; 8184 } 8185 } 8186 } else { 8187 DeclContext::lookup_result R = 8188 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 8189 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 8190 I != E; ++I) { 8191 if (isa<VarDecl>(*I)) { 8192 Prev = *I; 8193 break; 8194 } 8195 // FIXME: If we have any other entity with this name in global scope, 8196 // the declaration is ill-formed, but that is a defect: it breaks the 8197 // 'stat' hack, for instance. Only variables can have mangled name 8198 // clashes with extern "C" declarations, so only they deserve a 8199 // diagnostic. 8200 } 8201 } 8202 8203 if (!Prev) 8204 return false; 8205 } 8206 8207 // Use the first declaration's location to ensure we point at something which 8208 // is lexically inside an extern "C" linkage-spec. 8209 assert(Prev && "should have found a previous declaration to diagnose"); 8210 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 8211 Prev = FD->getFirstDecl(); 8212 else 8213 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 8214 8215 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 8216 << IsGlobal << ND; 8217 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 8218 << IsGlobal; 8219 return false; 8220 } 8221 8222 /// Apply special rules for handling extern "C" declarations. Returns \c true 8223 /// if we have found that this is a redeclaration of some prior entity. 8224 /// 8225 /// Per C++ [dcl.link]p6: 8226 /// Two declarations [for a function or variable] with C language linkage 8227 /// with the same name that appear in different scopes refer to the same 8228 /// [entity]. An entity with C language linkage shall not be declared with 8229 /// the same name as an entity in global scope. 8230 template<typename T> 8231 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8232 LookupResult &Previous) { 8233 if (!S.getLangOpts().CPlusPlus) { 8234 // In C, when declaring a global variable, look for a corresponding 'extern' 8235 // variable declared in function scope. We don't need this in C++, because 8236 // we find local extern decls in the surrounding file-scope DeclContext. 8237 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8238 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8239 Previous.clear(); 8240 Previous.addDecl(Prev); 8241 return true; 8242 } 8243 } 8244 return false; 8245 } 8246 8247 // A declaration in the translation unit can conflict with an extern "C" 8248 // declaration. 8249 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8250 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8251 8252 // An extern "C" declaration can conflict with a declaration in the 8253 // translation unit or can be a redeclaration of an extern "C" declaration 8254 // in another scope. 8255 if (isIncompleteDeclExternC(S,ND)) 8256 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8257 8258 // Neither global nor extern "C": nothing to do. 8259 return false; 8260 } 8261 8262 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8263 // If the decl is already known invalid, don't check it. 8264 if (NewVD->isInvalidDecl()) 8265 return; 8266 8267 QualType T = NewVD->getType(); 8268 8269 // Defer checking an 'auto' type until its initializer is attached. 8270 if (T->isUndeducedType()) 8271 return; 8272 8273 if (NewVD->hasAttrs()) 8274 CheckAlignasUnderalignment(NewVD); 8275 8276 if (T->isObjCObjectType()) { 8277 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8278 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8279 T = Context.getObjCObjectPointerType(T); 8280 NewVD->setType(T); 8281 } 8282 8283 // Emit an error if an address space was applied to decl with local storage. 8284 // This includes arrays of objects with address space qualifiers, but not 8285 // automatic variables that point to other address spaces. 8286 // ISO/IEC TR 18037 S5.1.2 8287 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8288 T.getAddressSpace() != LangAS::Default) { 8289 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8290 NewVD->setInvalidDecl(); 8291 return; 8292 } 8293 8294 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8295 // scope. 8296 if (getLangOpts().OpenCLVersion == 120 && 8297 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8298 getLangOpts()) && 8299 NewVD->isStaticLocal()) { 8300 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8301 NewVD->setInvalidDecl(); 8302 return; 8303 } 8304 8305 if (getLangOpts().OpenCL) { 8306 if (!diagnoseOpenCLTypes(*this, NewVD)) 8307 return; 8308 8309 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8310 if (NewVD->hasAttr<BlocksAttr>()) { 8311 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8312 return; 8313 } 8314 8315 if (T->isBlockPointerType()) { 8316 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8317 // can't use 'extern' storage class. 8318 if (!T.isConstQualified()) { 8319 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8320 << 0 /*const*/; 8321 NewVD->setInvalidDecl(); 8322 return; 8323 } 8324 if (NewVD->hasExternalStorage()) { 8325 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8326 NewVD->setInvalidDecl(); 8327 return; 8328 } 8329 } 8330 8331 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8332 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8333 NewVD->hasExternalStorage()) { 8334 if (!T->isSamplerT() && !T->isDependentType() && 8335 !(T.getAddressSpace() == LangAS::opencl_constant || 8336 (T.getAddressSpace() == LangAS::opencl_global && 8337 getOpenCLOptions().areProgramScopeVariablesSupported( 8338 getLangOpts())))) { 8339 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8340 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8341 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8342 << Scope << "global or constant"; 8343 else 8344 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8345 << Scope << "constant"; 8346 NewVD->setInvalidDecl(); 8347 return; 8348 } 8349 } else { 8350 if (T.getAddressSpace() == LangAS::opencl_global) { 8351 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8352 << 1 /*is any function*/ << "global"; 8353 NewVD->setInvalidDecl(); 8354 return; 8355 } 8356 if (T.getAddressSpace() == LangAS::opencl_constant || 8357 T.getAddressSpace() == LangAS::opencl_local) { 8358 FunctionDecl *FD = getCurFunctionDecl(); 8359 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8360 // in functions. 8361 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8362 if (T.getAddressSpace() == LangAS::opencl_constant) 8363 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8364 << 0 /*non-kernel only*/ << "constant"; 8365 else 8366 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8367 << 0 /*non-kernel only*/ << "local"; 8368 NewVD->setInvalidDecl(); 8369 return; 8370 } 8371 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8372 // in the outermost scope of a kernel function. 8373 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8374 if (!getCurScope()->isFunctionScope()) { 8375 if (T.getAddressSpace() == LangAS::opencl_constant) 8376 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8377 << "constant"; 8378 else 8379 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8380 << "local"; 8381 NewVD->setInvalidDecl(); 8382 return; 8383 } 8384 } 8385 } else if (T.getAddressSpace() != LangAS::opencl_private && 8386 // If we are parsing a template we didn't deduce an addr 8387 // space yet. 8388 T.getAddressSpace() != LangAS::Default) { 8389 // Do not allow other address spaces on automatic variable. 8390 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8391 NewVD->setInvalidDecl(); 8392 return; 8393 } 8394 } 8395 } 8396 8397 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8398 && !NewVD->hasAttr<BlocksAttr>()) { 8399 if (getLangOpts().getGC() != LangOptions::NonGC) 8400 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8401 else { 8402 assert(!getLangOpts().ObjCAutoRefCount); 8403 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8404 } 8405 } 8406 8407 bool isVM = T->isVariablyModifiedType(); 8408 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8409 NewVD->hasAttr<BlocksAttr>()) 8410 setFunctionHasBranchProtectedScope(); 8411 8412 if ((isVM && NewVD->hasLinkage()) || 8413 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8414 bool SizeIsNegative; 8415 llvm::APSInt Oversized; 8416 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8417 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8418 QualType FixedT; 8419 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8420 FixedT = FixedTInfo->getType(); 8421 else if (FixedTInfo) { 8422 // Type and type-as-written are canonically different. We need to fix up 8423 // both types separately. 8424 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8425 Oversized); 8426 } 8427 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8428 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8429 // FIXME: This won't give the correct result for 8430 // int a[10][n]; 8431 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8432 8433 if (NewVD->isFileVarDecl()) 8434 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8435 << SizeRange; 8436 else if (NewVD->isStaticLocal()) 8437 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8438 << SizeRange; 8439 else 8440 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8441 << SizeRange; 8442 NewVD->setInvalidDecl(); 8443 return; 8444 } 8445 8446 if (!FixedTInfo) { 8447 if (NewVD->isFileVarDecl()) 8448 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8449 else 8450 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8451 NewVD->setInvalidDecl(); 8452 return; 8453 } 8454 8455 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8456 NewVD->setType(FixedT); 8457 NewVD->setTypeSourceInfo(FixedTInfo); 8458 } 8459 8460 if (T->isVoidType()) { 8461 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8462 // of objects and functions. 8463 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8464 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8465 << T; 8466 NewVD->setInvalidDecl(); 8467 return; 8468 } 8469 } 8470 8471 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8472 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8473 NewVD->setInvalidDecl(); 8474 return; 8475 } 8476 8477 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8478 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8479 NewVD->setInvalidDecl(); 8480 return; 8481 } 8482 8483 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8484 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8485 NewVD->setInvalidDecl(); 8486 return; 8487 } 8488 8489 if (NewVD->isConstexpr() && !T->isDependentType() && 8490 RequireLiteralType(NewVD->getLocation(), T, 8491 diag::err_constexpr_var_non_literal)) { 8492 NewVD->setInvalidDecl(); 8493 return; 8494 } 8495 8496 // PPC MMA non-pointer types are not allowed as non-local variable types. 8497 if (Context.getTargetInfo().getTriple().isPPC64() && 8498 !NewVD->isLocalVarDecl() && 8499 CheckPPCMMAType(T, NewVD->getLocation())) { 8500 NewVD->setInvalidDecl(); 8501 return; 8502 } 8503 } 8504 8505 /// Perform semantic checking on a newly-created variable 8506 /// declaration. 8507 /// 8508 /// This routine performs all of the type-checking required for a 8509 /// variable declaration once it has been built. It is used both to 8510 /// check variables after they have been parsed and their declarators 8511 /// have been translated into a declaration, and to check variables 8512 /// that have been instantiated from a template. 8513 /// 8514 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8515 /// 8516 /// Returns true if the variable declaration is a redeclaration. 8517 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8518 CheckVariableDeclarationType(NewVD); 8519 8520 // If the decl is already known invalid, don't check it. 8521 if (NewVD->isInvalidDecl()) 8522 return false; 8523 8524 // If we did not find anything by this name, look for a non-visible 8525 // extern "C" declaration with the same name. 8526 if (Previous.empty() && 8527 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8528 Previous.setShadowed(); 8529 8530 if (!Previous.empty()) { 8531 MergeVarDecl(NewVD, Previous); 8532 return true; 8533 } 8534 return false; 8535 } 8536 8537 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8538 /// and if so, check that it's a valid override and remember it. 8539 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8540 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8541 8542 // Look for methods in base classes that this method might override. 8543 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8544 /*DetectVirtual=*/false); 8545 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8546 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8547 DeclarationName Name = MD->getDeclName(); 8548 8549 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8550 // We really want to find the base class destructor here. 8551 QualType T = Context.getTypeDeclType(BaseRecord); 8552 CanQualType CT = Context.getCanonicalType(T); 8553 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8554 } 8555 8556 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8557 CXXMethodDecl *BaseMD = 8558 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8559 if (!BaseMD || !BaseMD->isVirtual() || 8560 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8561 /*ConsiderCudaAttrs=*/true, 8562 // C++2a [class.virtual]p2 does not consider requires 8563 // clauses when overriding. 8564 /*ConsiderRequiresClauses=*/false)) 8565 continue; 8566 8567 if (Overridden.insert(BaseMD).second) { 8568 MD->addOverriddenMethod(BaseMD); 8569 CheckOverridingFunctionReturnType(MD, BaseMD); 8570 CheckOverridingFunctionAttributes(MD, BaseMD); 8571 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8572 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8573 } 8574 8575 // A method can only override one function from each base class. We 8576 // don't track indirectly overridden methods from bases of bases. 8577 return true; 8578 } 8579 8580 return false; 8581 }; 8582 8583 DC->lookupInBases(VisitBase, Paths); 8584 return !Overridden.empty(); 8585 } 8586 8587 namespace { 8588 // Struct for holding all of the extra arguments needed by 8589 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8590 struct ActOnFDArgs { 8591 Scope *S; 8592 Declarator &D; 8593 MultiTemplateParamsArg TemplateParamLists; 8594 bool AddToScope; 8595 }; 8596 } // end anonymous namespace 8597 8598 namespace { 8599 8600 // Callback to only accept typo corrections that have a non-zero edit distance. 8601 // Also only accept corrections that have the same parent decl. 8602 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8603 public: 8604 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8605 CXXRecordDecl *Parent) 8606 : Context(Context), OriginalFD(TypoFD), 8607 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8608 8609 bool ValidateCandidate(const TypoCorrection &candidate) override { 8610 if (candidate.getEditDistance() == 0) 8611 return false; 8612 8613 SmallVector<unsigned, 1> MismatchedParams; 8614 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8615 CDeclEnd = candidate.end(); 8616 CDecl != CDeclEnd; ++CDecl) { 8617 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8618 8619 if (FD && !FD->hasBody() && 8620 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8621 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8622 CXXRecordDecl *Parent = MD->getParent(); 8623 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8624 return true; 8625 } else if (!ExpectedParent) { 8626 return true; 8627 } 8628 } 8629 } 8630 8631 return false; 8632 } 8633 8634 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8635 return std::make_unique<DifferentNameValidatorCCC>(*this); 8636 } 8637 8638 private: 8639 ASTContext &Context; 8640 FunctionDecl *OriginalFD; 8641 CXXRecordDecl *ExpectedParent; 8642 }; 8643 8644 } // end anonymous namespace 8645 8646 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8647 TypoCorrectedFunctionDefinitions.insert(F); 8648 } 8649 8650 /// Generate diagnostics for an invalid function redeclaration. 8651 /// 8652 /// This routine handles generating the diagnostic messages for an invalid 8653 /// function redeclaration, including finding possible similar declarations 8654 /// or performing typo correction if there are no previous declarations with 8655 /// the same name. 8656 /// 8657 /// Returns a NamedDecl iff typo correction was performed and substituting in 8658 /// the new declaration name does not cause new errors. 8659 static NamedDecl *DiagnoseInvalidRedeclaration( 8660 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8661 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8662 DeclarationName Name = NewFD->getDeclName(); 8663 DeclContext *NewDC = NewFD->getDeclContext(); 8664 SmallVector<unsigned, 1> MismatchedParams; 8665 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8666 TypoCorrection Correction; 8667 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8668 unsigned DiagMsg = 8669 IsLocalFriend ? diag::err_no_matching_local_friend : 8670 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8671 diag::err_member_decl_does_not_match; 8672 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8673 IsLocalFriend ? Sema::LookupLocalFriendName 8674 : Sema::LookupOrdinaryName, 8675 Sema::ForVisibleRedeclaration); 8676 8677 NewFD->setInvalidDecl(); 8678 if (IsLocalFriend) 8679 SemaRef.LookupName(Prev, S); 8680 else 8681 SemaRef.LookupQualifiedName(Prev, NewDC); 8682 assert(!Prev.isAmbiguous() && 8683 "Cannot have an ambiguity in previous-declaration lookup"); 8684 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8685 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8686 MD ? MD->getParent() : nullptr); 8687 if (!Prev.empty()) { 8688 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8689 Func != FuncEnd; ++Func) { 8690 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8691 if (FD && 8692 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8693 // Add 1 to the index so that 0 can mean the mismatch didn't 8694 // involve a parameter 8695 unsigned ParamNum = 8696 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8697 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8698 } 8699 } 8700 // If the qualified name lookup yielded nothing, try typo correction 8701 } else if ((Correction = SemaRef.CorrectTypo( 8702 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8703 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8704 IsLocalFriend ? nullptr : NewDC))) { 8705 // Set up everything for the call to ActOnFunctionDeclarator 8706 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8707 ExtraArgs.D.getIdentifierLoc()); 8708 Previous.clear(); 8709 Previous.setLookupName(Correction.getCorrection()); 8710 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8711 CDeclEnd = Correction.end(); 8712 CDecl != CDeclEnd; ++CDecl) { 8713 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8714 if (FD && !FD->hasBody() && 8715 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8716 Previous.addDecl(FD); 8717 } 8718 } 8719 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8720 8721 NamedDecl *Result; 8722 // Retry building the function declaration with the new previous 8723 // declarations, and with errors suppressed. 8724 { 8725 // Trap errors. 8726 Sema::SFINAETrap Trap(SemaRef); 8727 8728 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8729 // pieces need to verify the typo-corrected C++ declaration and hopefully 8730 // eliminate the need for the parameter pack ExtraArgs. 8731 Result = SemaRef.ActOnFunctionDeclarator( 8732 ExtraArgs.S, ExtraArgs.D, 8733 Correction.getCorrectionDecl()->getDeclContext(), 8734 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8735 ExtraArgs.AddToScope); 8736 8737 if (Trap.hasErrorOccurred()) 8738 Result = nullptr; 8739 } 8740 8741 if (Result) { 8742 // Determine which correction we picked. 8743 Decl *Canonical = Result->getCanonicalDecl(); 8744 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8745 I != E; ++I) 8746 if ((*I)->getCanonicalDecl() == Canonical) 8747 Correction.setCorrectionDecl(*I); 8748 8749 // Let Sema know about the correction. 8750 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8751 SemaRef.diagnoseTypo( 8752 Correction, 8753 SemaRef.PDiag(IsLocalFriend 8754 ? diag::err_no_matching_local_friend_suggest 8755 : diag::err_member_decl_does_not_match_suggest) 8756 << Name << NewDC << IsDefinition); 8757 return Result; 8758 } 8759 8760 // Pretend the typo correction never occurred 8761 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8762 ExtraArgs.D.getIdentifierLoc()); 8763 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8764 Previous.clear(); 8765 Previous.setLookupName(Name); 8766 } 8767 8768 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8769 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8770 8771 bool NewFDisConst = false; 8772 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8773 NewFDisConst = NewMD->isConst(); 8774 8775 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8776 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8777 NearMatch != NearMatchEnd; ++NearMatch) { 8778 FunctionDecl *FD = NearMatch->first; 8779 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8780 bool FDisConst = MD && MD->isConst(); 8781 bool IsMember = MD || !IsLocalFriend; 8782 8783 // FIXME: These notes are poorly worded for the local friend case. 8784 if (unsigned Idx = NearMatch->second) { 8785 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8786 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8787 if (Loc.isInvalid()) Loc = FD->getLocation(); 8788 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8789 : diag::note_local_decl_close_param_match) 8790 << Idx << FDParam->getType() 8791 << NewFD->getParamDecl(Idx - 1)->getType(); 8792 } else if (FDisConst != NewFDisConst) { 8793 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8794 << NewFDisConst << FD->getSourceRange().getEnd() 8795 << (NewFDisConst 8796 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 8797 .getConstQualifierLoc()) 8798 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 8799 .getRParenLoc() 8800 .getLocWithOffset(1), 8801 " const")); 8802 } else 8803 SemaRef.Diag(FD->getLocation(), 8804 IsMember ? diag::note_member_def_close_match 8805 : diag::note_local_decl_close_match); 8806 } 8807 return nullptr; 8808 } 8809 8810 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8811 switch (D.getDeclSpec().getStorageClassSpec()) { 8812 default: llvm_unreachable("Unknown storage class!"); 8813 case DeclSpec::SCS_auto: 8814 case DeclSpec::SCS_register: 8815 case DeclSpec::SCS_mutable: 8816 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8817 diag::err_typecheck_sclass_func); 8818 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8819 D.setInvalidType(); 8820 break; 8821 case DeclSpec::SCS_unspecified: break; 8822 case DeclSpec::SCS_extern: 8823 if (D.getDeclSpec().isExternInLinkageSpec()) 8824 return SC_None; 8825 return SC_Extern; 8826 case DeclSpec::SCS_static: { 8827 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8828 // C99 6.7.1p5: 8829 // The declaration of an identifier for a function that has 8830 // block scope shall have no explicit storage-class specifier 8831 // other than extern 8832 // See also (C++ [dcl.stc]p4). 8833 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8834 diag::err_static_block_func); 8835 break; 8836 } else 8837 return SC_Static; 8838 } 8839 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8840 } 8841 8842 // No explicit storage class has already been returned 8843 return SC_None; 8844 } 8845 8846 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8847 DeclContext *DC, QualType &R, 8848 TypeSourceInfo *TInfo, 8849 StorageClass SC, 8850 bool &IsVirtualOkay) { 8851 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8852 DeclarationName Name = NameInfo.getName(); 8853 8854 FunctionDecl *NewFD = nullptr; 8855 bool isInline = D.getDeclSpec().isInlineSpecified(); 8856 8857 if (!SemaRef.getLangOpts().CPlusPlus) { 8858 // Determine whether the function was written with a prototype. This is 8859 // true when: 8860 // - there is a prototype in the declarator, or 8861 // - the type R of the function is some kind of typedef or other non- 8862 // attributed reference to a type name (which eventually refers to a 8863 // function type). Note, we can't always look at the adjusted type to 8864 // check this case because attributes may cause a non-function 8865 // declarator to still have a function type. e.g., 8866 // typedef void func(int a); 8867 // __attribute__((noreturn)) func other_func; // This has a prototype 8868 bool HasPrototype = 8869 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8870 (D.getDeclSpec().isTypeRep() && 8871 D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) || 8872 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8873 assert( 8874 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && 8875 "Strict prototypes are required"); 8876 8877 NewFD = FunctionDecl::Create( 8878 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8879 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8880 ConstexprSpecKind::Unspecified, 8881 /*TrailingRequiresClause=*/nullptr); 8882 if (D.isInvalidType()) 8883 NewFD->setInvalidDecl(); 8884 8885 return NewFD; 8886 } 8887 8888 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8889 8890 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8891 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8892 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8893 diag::err_constexpr_wrong_decl_kind) 8894 << static_cast<int>(ConstexprKind); 8895 ConstexprKind = ConstexprSpecKind::Unspecified; 8896 D.getMutableDeclSpec().ClearConstexprSpec(); 8897 } 8898 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8899 8900 // Check that the return type is not an abstract class type. 8901 // For record types, this is done by the AbstractClassUsageDiagnoser once 8902 // the class has been completely parsed. 8903 if (!DC->isRecord() && 8904 SemaRef.RequireNonAbstractType( 8905 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8906 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8907 D.setInvalidType(); 8908 8909 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8910 // This is a C++ constructor declaration. 8911 assert(DC->isRecord() && 8912 "Constructors can only be declared in a member context"); 8913 8914 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8915 return CXXConstructorDecl::Create( 8916 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8917 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8918 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8919 InheritedConstructor(), TrailingRequiresClause); 8920 8921 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8922 // This is a C++ destructor declaration. 8923 if (DC->isRecord()) { 8924 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8925 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8926 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8927 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8928 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8929 /*isImplicitlyDeclared=*/false, ConstexprKind, 8930 TrailingRequiresClause); 8931 // User defined destructors start as not selected if the class definition is still 8932 // not done. 8933 if (Record->isBeingDefined()) 8934 NewDD->setIneligibleOrNotSelected(true); 8935 8936 // If the destructor needs an implicit exception specification, set it 8937 // now. FIXME: It'd be nice to be able to create the right type to start 8938 // with, but the type needs to reference the destructor declaration. 8939 if (SemaRef.getLangOpts().CPlusPlus11) 8940 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8941 8942 IsVirtualOkay = true; 8943 return NewDD; 8944 8945 } else { 8946 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8947 D.setInvalidType(); 8948 8949 // Create a FunctionDecl to satisfy the function definition parsing 8950 // code path. 8951 return FunctionDecl::Create( 8952 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8953 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8954 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8955 } 8956 8957 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8958 if (!DC->isRecord()) { 8959 SemaRef.Diag(D.getIdentifierLoc(), 8960 diag::err_conv_function_not_member); 8961 return nullptr; 8962 } 8963 8964 SemaRef.CheckConversionDeclarator(D, R, SC); 8965 if (D.isInvalidType()) 8966 return nullptr; 8967 8968 IsVirtualOkay = true; 8969 return CXXConversionDecl::Create( 8970 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8971 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8972 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8973 TrailingRequiresClause); 8974 8975 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8976 if (TrailingRequiresClause) 8977 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8978 diag::err_trailing_requires_clause_on_deduction_guide) 8979 << TrailingRequiresClause->getSourceRange(); 8980 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8981 8982 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8983 ExplicitSpecifier, NameInfo, R, TInfo, 8984 D.getEndLoc()); 8985 } else if (DC->isRecord()) { 8986 // If the name of the function is the same as the name of the record, 8987 // then this must be an invalid constructor that has a return type. 8988 // (The parser checks for a return type and makes the declarator a 8989 // constructor if it has no return type). 8990 if (Name.getAsIdentifierInfo() && 8991 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8992 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8993 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8994 << SourceRange(D.getIdentifierLoc()); 8995 return nullptr; 8996 } 8997 8998 // This is a C++ method declaration. 8999 CXXMethodDecl *Ret = CXXMethodDecl::Create( 9000 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9001 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9002 ConstexprKind, SourceLocation(), TrailingRequiresClause); 9003 IsVirtualOkay = !Ret->isStatic(); 9004 return Ret; 9005 } else { 9006 bool isFriend = 9007 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 9008 if (!isFriend && SemaRef.CurContext->isRecord()) 9009 return nullptr; 9010 9011 // Determine whether the function was written with a 9012 // prototype. This true when: 9013 // - we're in C++ (where every function has a prototype), 9014 return FunctionDecl::Create( 9015 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9016 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9017 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 9018 } 9019 } 9020 9021 enum OpenCLParamType { 9022 ValidKernelParam, 9023 PtrPtrKernelParam, 9024 PtrKernelParam, 9025 InvalidAddrSpacePtrKernelParam, 9026 InvalidKernelParam, 9027 RecordKernelParam 9028 }; 9029 9030 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 9031 // Size dependent types are just typedefs to normal integer types 9032 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 9033 // integers other than by their names. 9034 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 9035 9036 // Remove typedefs one by one until we reach a typedef 9037 // for a size dependent type. 9038 QualType DesugaredTy = Ty; 9039 do { 9040 ArrayRef<StringRef> Names(SizeTypeNames); 9041 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 9042 if (Names.end() != Match) 9043 return true; 9044 9045 Ty = DesugaredTy; 9046 DesugaredTy = Ty.getSingleStepDesugaredType(C); 9047 } while (DesugaredTy != Ty); 9048 9049 return false; 9050 } 9051 9052 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 9053 if (PT->isDependentType()) 9054 return InvalidKernelParam; 9055 9056 if (PT->isPointerType() || PT->isReferenceType()) { 9057 QualType PointeeType = PT->getPointeeType(); 9058 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 9059 PointeeType.getAddressSpace() == LangAS::opencl_private || 9060 PointeeType.getAddressSpace() == LangAS::Default) 9061 return InvalidAddrSpacePtrKernelParam; 9062 9063 if (PointeeType->isPointerType()) { 9064 // This is a pointer to pointer parameter. 9065 // Recursively check inner type. 9066 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 9067 if (ParamKind == InvalidAddrSpacePtrKernelParam || 9068 ParamKind == InvalidKernelParam) 9069 return ParamKind; 9070 9071 return PtrPtrKernelParam; 9072 } 9073 9074 // C++ for OpenCL v1.0 s2.4: 9075 // Moreover the types used in parameters of the kernel functions must be: 9076 // Standard layout types for pointer parameters. The same applies to 9077 // reference if an implementation supports them in kernel parameters. 9078 if (S.getLangOpts().OpenCLCPlusPlus && 9079 !S.getOpenCLOptions().isAvailableOption( 9080 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9081 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 9082 !PointeeType->isStandardLayoutType()) 9083 return InvalidKernelParam; 9084 9085 return PtrKernelParam; 9086 } 9087 9088 // OpenCL v1.2 s6.9.k: 9089 // Arguments to kernel functions in a program cannot be declared with the 9090 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9091 // uintptr_t or a struct and/or union that contain fields declared to be one 9092 // of these built-in scalar types. 9093 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 9094 return InvalidKernelParam; 9095 9096 if (PT->isImageType()) 9097 return PtrKernelParam; 9098 9099 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 9100 return InvalidKernelParam; 9101 9102 // OpenCL extension spec v1.2 s9.5: 9103 // This extension adds support for half scalar and vector types as built-in 9104 // types that can be used for arithmetic operations, conversions etc. 9105 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 9106 PT->isHalfType()) 9107 return InvalidKernelParam; 9108 9109 // Look into an array argument to check if it has a forbidden type. 9110 if (PT->isArrayType()) { 9111 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 9112 // Call ourself to check an underlying type of an array. Since the 9113 // getPointeeOrArrayElementType returns an innermost type which is not an 9114 // array, this recursive call only happens once. 9115 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 9116 } 9117 9118 // C++ for OpenCL v1.0 s2.4: 9119 // Moreover the types used in parameters of the kernel functions must be: 9120 // Trivial and standard-layout types C++17 [basic.types] (plain old data 9121 // types) for parameters passed by value; 9122 if (S.getLangOpts().OpenCLCPlusPlus && 9123 !S.getOpenCLOptions().isAvailableOption( 9124 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9125 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 9126 return InvalidKernelParam; 9127 9128 if (PT->isRecordType()) 9129 return RecordKernelParam; 9130 9131 return ValidKernelParam; 9132 } 9133 9134 static void checkIsValidOpenCLKernelParameter( 9135 Sema &S, 9136 Declarator &D, 9137 ParmVarDecl *Param, 9138 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 9139 QualType PT = Param->getType(); 9140 9141 // Cache the valid types we encounter to avoid rechecking structs that are 9142 // used again 9143 if (ValidTypes.count(PT.getTypePtr())) 9144 return; 9145 9146 switch (getOpenCLKernelParameterType(S, PT)) { 9147 case PtrPtrKernelParam: 9148 // OpenCL v3.0 s6.11.a: 9149 // A kernel function argument cannot be declared as a pointer to a pointer 9150 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 9151 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 9152 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 9153 D.setInvalidType(); 9154 return; 9155 } 9156 9157 ValidTypes.insert(PT.getTypePtr()); 9158 return; 9159 9160 case InvalidAddrSpacePtrKernelParam: 9161 // OpenCL v1.0 s6.5: 9162 // __kernel function arguments declared to be a pointer of a type can point 9163 // to one of the following address spaces only : __global, __local or 9164 // __constant. 9165 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 9166 D.setInvalidType(); 9167 return; 9168 9169 // OpenCL v1.2 s6.9.k: 9170 // Arguments to kernel functions in a program cannot be declared with the 9171 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9172 // uintptr_t or a struct and/or union that contain fields declared to be 9173 // one of these built-in scalar types. 9174 9175 case InvalidKernelParam: 9176 // OpenCL v1.2 s6.8 n: 9177 // A kernel function argument cannot be declared 9178 // of event_t type. 9179 // Do not diagnose half type since it is diagnosed as invalid argument 9180 // type for any function elsewhere. 9181 if (!PT->isHalfType()) { 9182 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9183 9184 // Explain what typedefs are involved. 9185 const TypedefType *Typedef = nullptr; 9186 while ((Typedef = PT->getAs<TypedefType>())) { 9187 SourceLocation Loc = Typedef->getDecl()->getLocation(); 9188 // SourceLocation may be invalid for a built-in type. 9189 if (Loc.isValid()) 9190 S.Diag(Loc, diag::note_entity_declared_at) << PT; 9191 PT = Typedef->desugar(); 9192 } 9193 } 9194 9195 D.setInvalidType(); 9196 return; 9197 9198 case PtrKernelParam: 9199 case ValidKernelParam: 9200 ValidTypes.insert(PT.getTypePtr()); 9201 return; 9202 9203 case RecordKernelParam: 9204 break; 9205 } 9206 9207 // Track nested structs we will inspect 9208 SmallVector<const Decl *, 4> VisitStack; 9209 9210 // Track where we are in the nested structs. Items will migrate from 9211 // VisitStack to HistoryStack as we do the DFS for bad field. 9212 SmallVector<const FieldDecl *, 4> HistoryStack; 9213 HistoryStack.push_back(nullptr); 9214 9215 // At this point we already handled everything except of a RecordType or 9216 // an ArrayType of a RecordType. 9217 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9218 const RecordType *RecTy = 9219 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9220 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9221 9222 VisitStack.push_back(RecTy->getDecl()); 9223 assert(VisitStack.back() && "First decl null?"); 9224 9225 do { 9226 const Decl *Next = VisitStack.pop_back_val(); 9227 if (!Next) { 9228 assert(!HistoryStack.empty()); 9229 // Found a marker, we have gone up a level 9230 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9231 ValidTypes.insert(Hist->getType().getTypePtr()); 9232 9233 continue; 9234 } 9235 9236 // Adds everything except the original parameter declaration (which is not a 9237 // field itself) to the history stack. 9238 const RecordDecl *RD; 9239 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9240 HistoryStack.push_back(Field); 9241 9242 QualType FieldTy = Field->getType(); 9243 // Other field types (known to be valid or invalid) are handled while we 9244 // walk around RecordDecl::fields(). 9245 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9246 "Unexpected type."); 9247 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9248 9249 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9250 } else { 9251 RD = cast<RecordDecl>(Next); 9252 } 9253 9254 // Add a null marker so we know when we've gone back up a level 9255 VisitStack.push_back(nullptr); 9256 9257 for (const auto *FD : RD->fields()) { 9258 QualType QT = FD->getType(); 9259 9260 if (ValidTypes.count(QT.getTypePtr())) 9261 continue; 9262 9263 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9264 if (ParamType == ValidKernelParam) 9265 continue; 9266 9267 if (ParamType == RecordKernelParam) { 9268 VisitStack.push_back(FD); 9269 continue; 9270 } 9271 9272 // OpenCL v1.2 s6.9.p: 9273 // Arguments to kernel functions that are declared to be a struct or union 9274 // do not allow OpenCL objects to be passed as elements of the struct or 9275 // union. 9276 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9277 ParamType == InvalidAddrSpacePtrKernelParam) { 9278 S.Diag(Param->getLocation(), 9279 diag::err_record_with_pointers_kernel_param) 9280 << PT->isUnionType() 9281 << PT; 9282 } else { 9283 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9284 } 9285 9286 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9287 << OrigRecDecl->getDeclName(); 9288 9289 // We have an error, now let's go back up through history and show where 9290 // the offending field came from 9291 for (ArrayRef<const FieldDecl *>::const_iterator 9292 I = HistoryStack.begin() + 1, 9293 E = HistoryStack.end(); 9294 I != E; ++I) { 9295 const FieldDecl *OuterField = *I; 9296 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9297 << OuterField->getType(); 9298 } 9299 9300 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9301 << QT->isPointerType() 9302 << QT; 9303 D.setInvalidType(); 9304 return; 9305 } 9306 } while (!VisitStack.empty()); 9307 } 9308 9309 /// Find the DeclContext in which a tag is implicitly declared if we see an 9310 /// elaborated type specifier in the specified context, and lookup finds 9311 /// nothing. 9312 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9313 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9314 DC = DC->getParent(); 9315 return DC; 9316 } 9317 9318 /// Find the Scope in which a tag is implicitly declared if we see an 9319 /// elaborated type specifier in the specified context, and lookup finds 9320 /// nothing. 9321 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9322 while (S->isClassScope() || 9323 (LangOpts.CPlusPlus && 9324 S->isFunctionPrototypeScope()) || 9325 ((S->getFlags() & Scope::DeclScope) == 0) || 9326 (S->getEntity() && S->getEntity()->isTransparentContext())) 9327 S = S->getParent(); 9328 return S; 9329 } 9330 9331 /// Determine whether a declaration matches a known function in namespace std. 9332 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, 9333 unsigned BuiltinID) { 9334 switch (BuiltinID) { 9335 case Builtin::BI__GetExceptionInfo: 9336 // No type checking whatsoever. 9337 return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); 9338 9339 case Builtin::BIaddressof: 9340 case Builtin::BI__addressof: 9341 case Builtin::BIforward: 9342 case Builtin::BImove: 9343 case Builtin::BImove_if_noexcept: 9344 case Builtin::BIas_const: { 9345 // Ensure that we don't treat the algorithm 9346 // OutputIt std::move(InputIt, InputIt, OutputIt) 9347 // as the builtin std::move. 9348 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 9349 return FPT->getNumParams() == 1 && !FPT->isVariadic(); 9350 } 9351 9352 default: 9353 return false; 9354 } 9355 } 9356 9357 NamedDecl* 9358 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9359 TypeSourceInfo *TInfo, LookupResult &Previous, 9360 MultiTemplateParamsArg TemplateParamListsRef, 9361 bool &AddToScope) { 9362 QualType R = TInfo->getType(); 9363 9364 assert(R->isFunctionType()); 9365 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9366 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9367 9368 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9369 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9370 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9371 if (!TemplateParamLists.empty() && 9372 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9373 TemplateParamLists.back() = Invented; 9374 else 9375 TemplateParamLists.push_back(Invented); 9376 } 9377 9378 // TODO: consider using NameInfo for diagnostic. 9379 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9380 DeclarationName Name = NameInfo.getName(); 9381 StorageClass SC = getFunctionStorageClass(*this, D); 9382 9383 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9384 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9385 diag::err_invalid_thread) 9386 << DeclSpec::getSpecifierName(TSCS); 9387 9388 if (D.isFirstDeclarationOfMember()) 9389 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9390 D.getIdentifierLoc()); 9391 9392 bool isFriend = false; 9393 FunctionTemplateDecl *FunctionTemplate = nullptr; 9394 bool isMemberSpecialization = false; 9395 bool isFunctionTemplateSpecialization = false; 9396 9397 bool isDependentClassScopeExplicitSpecialization = false; 9398 bool HasExplicitTemplateArgs = false; 9399 TemplateArgumentListInfo TemplateArgs; 9400 9401 bool isVirtualOkay = false; 9402 9403 DeclContext *OriginalDC = DC; 9404 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9405 9406 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9407 isVirtualOkay); 9408 if (!NewFD) return nullptr; 9409 9410 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9411 NewFD->setTopLevelDeclInObjCContainer(); 9412 9413 // Set the lexical context. If this is a function-scope declaration, or has a 9414 // C++ scope specifier, or is the object of a friend declaration, the lexical 9415 // context will be different from the semantic context. 9416 NewFD->setLexicalDeclContext(CurContext); 9417 9418 if (IsLocalExternDecl) 9419 NewFD->setLocalExternDecl(); 9420 9421 if (getLangOpts().CPlusPlus) { 9422 bool isInline = D.getDeclSpec().isInlineSpecified(); 9423 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9424 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9425 isFriend = D.getDeclSpec().isFriendSpecified(); 9426 if (isFriend && !isInline && D.isFunctionDefinition()) { 9427 // C++ [class.friend]p5 9428 // A function can be defined in a friend declaration of a 9429 // class . . . . Such a function is implicitly inline. 9430 NewFD->setImplicitlyInline(); 9431 } 9432 9433 // If this is a method defined in an __interface, and is not a constructor 9434 // or an overloaded operator, then set the pure flag (isVirtual will already 9435 // return true). 9436 if (const CXXRecordDecl *Parent = 9437 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9438 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9439 NewFD->setPure(true); 9440 9441 // C++ [class.union]p2 9442 // A union can have member functions, but not virtual functions. 9443 if (isVirtual && Parent->isUnion()) { 9444 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9445 NewFD->setInvalidDecl(); 9446 } 9447 if ((Parent->isClass() || Parent->isStruct()) && 9448 Parent->hasAttr<SYCLSpecialClassAttr>() && 9449 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9450 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9451 if (auto *Def = Parent->getDefinition()) 9452 Def->setInitMethod(true); 9453 } 9454 } 9455 9456 SetNestedNameSpecifier(*this, NewFD, D); 9457 isMemberSpecialization = false; 9458 isFunctionTemplateSpecialization = false; 9459 if (D.isInvalidType()) 9460 NewFD->setInvalidDecl(); 9461 9462 // Match up the template parameter lists with the scope specifier, then 9463 // determine whether we have a template or a template specialization. 9464 bool Invalid = false; 9465 TemplateParameterList *TemplateParams = 9466 MatchTemplateParametersToScopeSpecifier( 9467 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9468 D.getCXXScopeSpec(), 9469 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9470 ? D.getName().TemplateId 9471 : nullptr, 9472 TemplateParamLists, isFriend, isMemberSpecialization, 9473 Invalid); 9474 if (TemplateParams) { 9475 // Check that we can declare a template here. 9476 if (CheckTemplateDeclScope(S, TemplateParams)) 9477 NewFD->setInvalidDecl(); 9478 9479 if (TemplateParams->size() > 0) { 9480 // This is a function template 9481 9482 // A destructor cannot be a template. 9483 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9484 Diag(NewFD->getLocation(), diag::err_destructor_template); 9485 NewFD->setInvalidDecl(); 9486 } 9487 9488 // If we're adding a template to a dependent context, we may need to 9489 // rebuilding some of the types used within the template parameter list, 9490 // now that we know what the current instantiation is. 9491 if (DC->isDependentContext()) { 9492 ContextRAII SavedContext(*this, DC); 9493 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9494 Invalid = true; 9495 } 9496 9497 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9498 NewFD->getLocation(), 9499 Name, TemplateParams, 9500 NewFD); 9501 FunctionTemplate->setLexicalDeclContext(CurContext); 9502 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9503 9504 // For source fidelity, store the other template param lists. 9505 if (TemplateParamLists.size() > 1) { 9506 NewFD->setTemplateParameterListsInfo(Context, 9507 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9508 .drop_back(1)); 9509 } 9510 } else { 9511 // This is a function template specialization. 9512 isFunctionTemplateSpecialization = true; 9513 // For source fidelity, store all the template param lists. 9514 if (TemplateParamLists.size() > 0) 9515 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9516 9517 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9518 if (isFriend) { 9519 // We want to remove the "template<>", found here. 9520 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9521 9522 // If we remove the template<> and the name is not a 9523 // template-id, we're actually silently creating a problem: 9524 // the friend declaration will refer to an untemplated decl, 9525 // and clearly the user wants a template specialization. So 9526 // we need to insert '<>' after the name. 9527 SourceLocation InsertLoc; 9528 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9529 InsertLoc = D.getName().getSourceRange().getEnd(); 9530 InsertLoc = getLocForEndOfToken(InsertLoc); 9531 } 9532 9533 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9534 << Name << RemoveRange 9535 << FixItHint::CreateRemoval(RemoveRange) 9536 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9537 Invalid = true; 9538 } 9539 } 9540 } else { 9541 // Check that we can declare a template here. 9542 if (!TemplateParamLists.empty() && isMemberSpecialization && 9543 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9544 NewFD->setInvalidDecl(); 9545 9546 // All template param lists were matched against the scope specifier: 9547 // this is NOT (an explicit specialization of) a template. 9548 if (TemplateParamLists.size() > 0) 9549 // For source fidelity, store all the template param lists. 9550 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9551 } 9552 9553 if (Invalid) { 9554 NewFD->setInvalidDecl(); 9555 if (FunctionTemplate) 9556 FunctionTemplate->setInvalidDecl(); 9557 } 9558 9559 // C++ [dcl.fct.spec]p5: 9560 // The virtual specifier shall only be used in declarations of 9561 // nonstatic class member functions that appear within a 9562 // member-specification of a class declaration; see 10.3. 9563 // 9564 if (isVirtual && !NewFD->isInvalidDecl()) { 9565 if (!isVirtualOkay) { 9566 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9567 diag::err_virtual_non_function); 9568 } else if (!CurContext->isRecord()) { 9569 // 'virtual' was specified outside of the class. 9570 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9571 diag::err_virtual_out_of_class) 9572 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9573 } else if (NewFD->getDescribedFunctionTemplate()) { 9574 // C++ [temp.mem]p3: 9575 // A member function template shall not be virtual. 9576 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9577 diag::err_virtual_member_function_template) 9578 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9579 } else { 9580 // Okay: Add virtual to the method. 9581 NewFD->setVirtualAsWritten(true); 9582 } 9583 9584 if (getLangOpts().CPlusPlus14 && 9585 NewFD->getReturnType()->isUndeducedType()) 9586 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9587 } 9588 9589 if (getLangOpts().CPlusPlus14 && 9590 (NewFD->isDependentContext() || 9591 (isFriend && CurContext->isDependentContext())) && 9592 NewFD->getReturnType()->isUndeducedType()) { 9593 // If the function template is referenced directly (for instance, as a 9594 // member of the current instantiation), pretend it has a dependent type. 9595 // This is not really justified by the standard, but is the only sane 9596 // thing to do. 9597 // FIXME: For a friend function, we have not marked the function as being 9598 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9599 const FunctionProtoType *FPT = 9600 NewFD->getType()->castAs<FunctionProtoType>(); 9601 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9602 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9603 FPT->getExtProtoInfo())); 9604 } 9605 9606 // C++ [dcl.fct.spec]p3: 9607 // The inline specifier shall not appear on a block scope function 9608 // declaration. 9609 if (isInline && !NewFD->isInvalidDecl()) { 9610 if (CurContext->isFunctionOrMethod()) { 9611 // 'inline' is not allowed on block scope function declaration. 9612 Diag(D.getDeclSpec().getInlineSpecLoc(), 9613 diag::err_inline_declaration_block_scope) << Name 9614 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9615 } 9616 } 9617 9618 // C++ [dcl.fct.spec]p6: 9619 // The explicit specifier shall be used only in the declaration of a 9620 // constructor or conversion function within its class definition; 9621 // see 12.3.1 and 12.3.2. 9622 if (hasExplicit && !NewFD->isInvalidDecl() && 9623 !isa<CXXDeductionGuideDecl>(NewFD)) { 9624 if (!CurContext->isRecord()) { 9625 // 'explicit' was specified outside of the class. 9626 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9627 diag::err_explicit_out_of_class) 9628 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9629 } else if (!isa<CXXConstructorDecl>(NewFD) && 9630 !isa<CXXConversionDecl>(NewFD)) { 9631 // 'explicit' was specified on a function that wasn't a constructor 9632 // or conversion function. 9633 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9634 diag::err_explicit_non_ctor_or_conv_function) 9635 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9636 } 9637 } 9638 9639 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9640 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9641 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9642 // are implicitly inline. 9643 NewFD->setImplicitlyInline(); 9644 9645 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9646 // be either constructors or to return a literal type. Therefore, 9647 // destructors cannot be declared constexpr. 9648 if (isa<CXXDestructorDecl>(NewFD) && 9649 (!getLangOpts().CPlusPlus20 || 9650 ConstexprKind == ConstexprSpecKind::Consteval)) { 9651 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9652 << static_cast<int>(ConstexprKind); 9653 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9654 ? ConstexprSpecKind::Unspecified 9655 : ConstexprSpecKind::Constexpr); 9656 } 9657 // C++20 [dcl.constexpr]p2: An allocation function, or a 9658 // deallocation function shall not be declared with the consteval 9659 // specifier. 9660 if (ConstexprKind == ConstexprSpecKind::Consteval && 9661 (NewFD->getOverloadedOperator() == OO_New || 9662 NewFD->getOverloadedOperator() == OO_Array_New || 9663 NewFD->getOverloadedOperator() == OO_Delete || 9664 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9665 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9666 diag::err_invalid_consteval_decl_kind) 9667 << NewFD; 9668 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9669 } 9670 } 9671 9672 // If __module_private__ was specified, mark the function accordingly. 9673 if (D.getDeclSpec().isModulePrivateSpecified()) { 9674 if (isFunctionTemplateSpecialization) { 9675 SourceLocation ModulePrivateLoc 9676 = D.getDeclSpec().getModulePrivateSpecLoc(); 9677 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9678 << 0 9679 << FixItHint::CreateRemoval(ModulePrivateLoc); 9680 } else { 9681 NewFD->setModulePrivate(); 9682 if (FunctionTemplate) 9683 FunctionTemplate->setModulePrivate(); 9684 } 9685 } 9686 9687 if (isFriend) { 9688 if (FunctionTemplate) { 9689 FunctionTemplate->setObjectOfFriendDecl(); 9690 FunctionTemplate->setAccess(AS_public); 9691 } 9692 NewFD->setObjectOfFriendDecl(); 9693 NewFD->setAccess(AS_public); 9694 } 9695 9696 // If a function is defined as defaulted or deleted, mark it as such now. 9697 // We'll do the relevant checks on defaulted / deleted functions later. 9698 switch (D.getFunctionDefinitionKind()) { 9699 case FunctionDefinitionKind::Declaration: 9700 case FunctionDefinitionKind::Definition: 9701 break; 9702 9703 case FunctionDefinitionKind::Defaulted: 9704 NewFD->setDefaulted(); 9705 break; 9706 9707 case FunctionDefinitionKind::Deleted: 9708 NewFD->setDeletedAsWritten(); 9709 break; 9710 } 9711 9712 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9713 D.isFunctionDefinition()) { 9714 // C++ [class.mfct]p2: 9715 // A member function may be defined (8.4) in its class definition, in 9716 // which case it is an inline member function (7.1.2) 9717 NewFD->setImplicitlyInline(); 9718 } 9719 9720 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9721 !CurContext->isRecord()) { 9722 // C++ [class.static]p1: 9723 // A data or function member of a class may be declared static 9724 // in a class definition, in which case it is a static member of 9725 // the class. 9726 9727 // Complain about the 'static' specifier if it's on an out-of-line 9728 // member function definition. 9729 9730 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9731 // member function template declaration and class member template 9732 // declaration (MSVC versions before 2015), warn about this. 9733 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9734 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9735 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9736 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9737 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9738 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9739 } 9740 9741 // C++11 [except.spec]p15: 9742 // A deallocation function with no exception-specification is treated 9743 // as if it were specified with noexcept(true). 9744 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9745 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9746 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9747 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9748 NewFD->setType(Context.getFunctionType( 9749 FPT->getReturnType(), FPT->getParamTypes(), 9750 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9751 } 9752 9753 // Filter out previous declarations that don't match the scope. 9754 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9755 D.getCXXScopeSpec().isNotEmpty() || 9756 isMemberSpecialization || 9757 isFunctionTemplateSpecialization); 9758 9759 // Handle GNU asm-label extension (encoded as an attribute). 9760 if (Expr *E = (Expr*) D.getAsmLabel()) { 9761 // The parser guarantees this is a string. 9762 StringLiteral *SE = cast<StringLiteral>(E); 9763 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9764 /*IsLiteralLabel=*/true, 9765 SE->getStrTokenLoc(0))); 9766 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9767 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9768 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9769 if (I != ExtnameUndeclaredIdentifiers.end()) { 9770 if (isDeclExternC(NewFD)) { 9771 NewFD->addAttr(I->second); 9772 ExtnameUndeclaredIdentifiers.erase(I); 9773 } else 9774 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9775 << /*Variable*/0 << NewFD; 9776 } 9777 } 9778 9779 // Copy the parameter declarations from the declarator D to the function 9780 // declaration NewFD, if they are available. First scavenge them into Params. 9781 SmallVector<ParmVarDecl*, 16> Params; 9782 unsigned FTIIdx; 9783 if (D.isFunctionDeclarator(FTIIdx)) { 9784 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9785 9786 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9787 // function that takes no arguments, not a function that takes a 9788 // single void argument. 9789 // We let through "const void" here because Sema::GetTypeForDeclarator 9790 // already checks for that case. 9791 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9792 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9793 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9794 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9795 Param->setDeclContext(NewFD); 9796 Params.push_back(Param); 9797 9798 if (Param->isInvalidDecl()) 9799 NewFD->setInvalidDecl(); 9800 } 9801 } 9802 9803 if (!getLangOpts().CPlusPlus) { 9804 // In C, find all the tag declarations from the prototype and move them 9805 // into the function DeclContext. Remove them from the surrounding tag 9806 // injection context of the function, which is typically but not always 9807 // the TU. 9808 DeclContext *PrototypeTagContext = 9809 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9810 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9811 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9812 9813 // We don't want to reparent enumerators. Look at their parent enum 9814 // instead. 9815 if (!TD) { 9816 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9817 TD = cast<EnumDecl>(ECD->getDeclContext()); 9818 } 9819 if (!TD) 9820 continue; 9821 DeclContext *TagDC = TD->getLexicalDeclContext(); 9822 if (!TagDC->containsDecl(TD)) 9823 continue; 9824 TagDC->removeDecl(TD); 9825 TD->setDeclContext(NewFD); 9826 NewFD->addDecl(TD); 9827 9828 // Preserve the lexical DeclContext if it is not the surrounding tag 9829 // injection context of the FD. In this example, the semantic context of 9830 // E will be f and the lexical context will be S, while both the 9831 // semantic and lexical contexts of S will be f: 9832 // void f(struct S { enum E { a } f; } s); 9833 if (TagDC != PrototypeTagContext) 9834 TD->setLexicalDeclContext(TagDC); 9835 } 9836 } 9837 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9838 // When we're declaring a function with a typedef, typeof, etc as in the 9839 // following example, we'll need to synthesize (unnamed) 9840 // parameters for use in the declaration. 9841 // 9842 // @code 9843 // typedef void fn(int); 9844 // fn f; 9845 // @endcode 9846 9847 // Synthesize a parameter for each argument type. 9848 for (const auto &AI : FT->param_types()) { 9849 ParmVarDecl *Param = 9850 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9851 Param->setScopeInfo(0, Params.size()); 9852 Params.push_back(Param); 9853 } 9854 } else { 9855 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9856 "Should not need args for typedef of non-prototype fn"); 9857 } 9858 9859 // Finally, we know we have the right number of parameters, install them. 9860 NewFD->setParams(Params); 9861 9862 if (D.getDeclSpec().isNoreturnSpecified()) 9863 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9864 D.getDeclSpec().getNoreturnSpecLoc(), 9865 AttributeCommonInfo::AS_Keyword)); 9866 9867 // Functions returning a variably modified type violate C99 6.7.5.2p2 9868 // because all functions have linkage. 9869 if (!NewFD->isInvalidDecl() && 9870 NewFD->getReturnType()->isVariablyModifiedType()) { 9871 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9872 NewFD->setInvalidDecl(); 9873 } 9874 9875 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9876 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9877 !NewFD->hasAttr<SectionAttr>()) 9878 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9879 Context, PragmaClangTextSection.SectionName, 9880 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9881 9882 // Apply an implicit SectionAttr if #pragma code_seg is active. 9883 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9884 !NewFD->hasAttr<SectionAttr>()) { 9885 NewFD->addAttr(SectionAttr::CreateImplicit( 9886 Context, CodeSegStack.CurrentValue->getString(), 9887 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9888 SectionAttr::Declspec_allocate)); 9889 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9890 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9891 ASTContext::PSF_Read, 9892 NewFD)) 9893 NewFD->dropAttr<SectionAttr>(); 9894 } 9895 9896 // Apply an implicit CodeSegAttr from class declspec or 9897 // apply an implicit SectionAttr from #pragma code_seg if active. 9898 if (!NewFD->hasAttr<CodeSegAttr>()) { 9899 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9900 D.isFunctionDefinition())) { 9901 NewFD->addAttr(SAttr); 9902 } 9903 } 9904 9905 // Handle attributes. 9906 ProcessDeclAttributes(S, NewFD, D); 9907 9908 if (getLangOpts().OpenCL) { 9909 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9910 // type declaration will generate a compilation error. 9911 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9912 if (AddressSpace != LangAS::Default) { 9913 Diag(NewFD->getLocation(), 9914 diag::err_opencl_return_value_with_address_space); 9915 NewFD->setInvalidDecl(); 9916 } 9917 } 9918 9919 if (!getLangOpts().CPlusPlus) { 9920 // Perform semantic checking on the function declaration. 9921 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9922 CheckMain(NewFD, D.getDeclSpec()); 9923 9924 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9925 CheckMSVCRTEntryPoint(NewFD); 9926 9927 if (!NewFD->isInvalidDecl()) 9928 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9929 isMemberSpecialization, 9930 D.isFunctionDefinition())); 9931 else if (!Previous.empty()) 9932 // Recover gracefully from an invalid redeclaration. 9933 D.setRedeclaration(true); 9934 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9935 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9936 "previous declaration set still overloaded"); 9937 9938 // Diagnose no-prototype function declarations with calling conventions that 9939 // don't support variadic calls. Only do this in C and do it after merging 9940 // possibly prototyped redeclarations. 9941 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9942 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9943 CallingConv CC = FT->getExtInfo().getCC(); 9944 if (!supportsVariadicCall(CC)) { 9945 // Windows system headers sometimes accidentally use stdcall without 9946 // (void) parameters, so we relax this to a warning. 9947 int DiagID = 9948 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9949 Diag(NewFD->getLocation(), DiagID) 9950 << FunctionType::getNameForCallConv(CC); 9951 } 9952 } 9953 9954 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9955 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9956 checkNonTrivialCUnion(NewFD->getReturnType(), 9957 NewFD->getReturnTypeSourceRange().getBegin(), 9958 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9959 } else { 9960 // C++11 [replacement.functions]p3: 9961 // The program's definitions shall not be specified as inline. 9962 // 9963 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9964 // 9965 // Suppress the diagnostic if the function is __attribute__((used)), since 9966 // that forces an external definition to be emitted. 9967 if (D.getDeclSpec().isInlineSpecified() && 9968 NewFD->isReplaceableGlobalAllocationFunction() && 9969 !NewFD->hasAttr<UsedAttr>()) 9970 Diag(D.getDeclSpec().getInlineSpecLoc(), 9971 diag::ext_operator_new_delete_declared_inline) 9972 << NewFD->getDeclName(); 9973 9974 // If the declarator is a template-id, translate the parser's template 9975 // argument list into our AST format. 9976 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9977 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9978 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9979 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9980 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9981 TemplateId->NumArgs); 9982 translateTemplateArguments(TemplateArgsPtr, 9983 TemplateArgs); 9984 9985 HasExplicitTemplateArgs = true; 9986 9987 if (NewFD->isInvalidDecl()) { 9988 HasExplicitTemplateArgs = false; 9989 } else if (FunctionTemplate) { 9990 // Function template with explicit template arguments. 9991 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9992 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9993 9994 HasExplicitTemplateArgs = false; 9995 } else { 9996 assert((isFunctionTemplateSpecialization || 9997 D.getDeclSpec().isFriendSpecified()) && 9998 "should have a 'template<>' for this decl"); 9999 // "friend void foo<>(int);" is an implicit specialization decl. 10000 isFunctionTemplateSpecialization = true; 10001 } 10002 } else if (isFriend && isFunctionTemplateSpecialization) { 10003 // This combination is only possible in a recovery case; the user 10004 // wrote something like: 10005 // template <> friend void foo(int); 10006 // which we're recovering from as if the user had written: 10007 // friend void foo<>(int); 10008 // Go ahead and fake up a template id. 10009 HasExplicitTemplateArgs = true; 10010 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 10011 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 10012 } 10013 10014 // We do not add HD attributes to specializations here because 10015 // they may have different constexpr-ness compared to their 10016 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 10017 // may end up with different effective targets. Instead, a 10018 // specialization inherits its target attributes from its template 10019 // in the CheckFunctionTemplateSpecialization() call below. 10020 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 10021 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 10022 10023 // If it's a friend (and only if it's a friend), it's possible 10024 // that either the specialized function type or the specialized 10025 // template is dependent, and therefore matching will fail. In 10026 // this case, don't check the specialization yet. 10027 if (isFunctionTemplateSpecialization && isFriend && 10028 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 10029 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 10030 TemplateArgs.arguments()))) { 10031 assert(HasExplicitTemplateArgs && 10032 "friend function specialization without template args"); 10033 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 10034 Previous)) 10035 NewFD->setInvalidDecl(); 10036 } else if (isFunctionTemplateSpecialization) { 10037 if (CurContext->isDependentContext() && CurContext->isRecord() 10038 && !isFriend) { 10039 isDependentClassScopeExplicitSpecialization = true; 10040 } else if (!NewFD->isInvalidDecl() && 10041 CheckFunctionTemplateSpecialization( 10042 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 10043 Previous)) 10044 NewFD->setInvalidDecl(); 10045 10046 // C++ [dcl.stc]p1: 10047 // A storage-class-specifier shall not be specified in an explicit 10048 // specialization (14.7.3) 10049 FunctionTemplateSpecializationInfo *Info = 10050 NewFD->getTemplateSpecializationInfo(); 10051 if (Info && SC != SC_None) { 10052 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 10053 Diag(NewFD->getLocation(), 10054 diag::err_explicit_specialization_inconsistent_storage_class) 10055 << SC 10056 << FixItHint::CreateRemoval( 10057 D.getDeclSpec().getStorageClassSpecLoc()); 10058 10059 else 10060 Diag(NewFD->getLocation(), 10061 diag::ext_explicit_specialization_storage_class) 10062 << FixItHint::CreateRemoval( 10063 D.getDeclSpec().getStorageClassSpecLoc()); 10064 } 10065 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 10066 if (CheckMemberSpecialization(NewFD, Previous)) 10067 NewFD->setInvalidDecl(); 10068 } 10069 10070 // Perform semantic checking on the function declaration. 10071 if (!isDependentClassScopeExplicitSpecialization) { 10072 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10073 CheckMain(NewFD, D.getDeclSpec()); 10074 10075 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10076 CheckMSVCRTEntryPoint(NewFD); 10077 10078 if (!NewFD->isInvalidDecl()) 10079 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10080 isMemberSpecialization, 10081 D.isFunctionDefinition())); 10082 else if (!Previous.empty()) 10083 // Recover gracefully from an invalid redeclaration. 10084 D.setRedeclaration(true); 10085 } 10086 10087 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 10088 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10089 "previous declaration set still overloaded"); 10090 10091 NamedDecl *PrincipalDecl = (FunctionTemplate 10092 ? cast<NamedDecl>(FunctionTemplate) 10093 : NewFD); 10094 10095 if (isFriend && NewFD->getPreviousDecl()) { 10096 AccessSpecifier Access = AS_public; 10097 if (!NewFD->isInvalidDecl()) 10098 Access = NewFD->getPreviousDecl()->getAccess(); 10099 10100 NewFD->setAccess(Access); 10101 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 10102 } 10103 10104 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 10105 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 10106 PrincipalDecl->setNonMemberOperator(); 10107 10108 // If we have a function template, check the template parameter 10109 // list. This will check and merge default template arguments. 10110 if (FunctionTemplate) { 10111 FunctionTemplateDecl *PrevTemplate = 10112 FunctionTemplate->getPreviousDecl(); 10113 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 10114 PrevTemplate ? PrevTemplate->getTemplateParameters() 10115 : nullptr, 10116 D.getDeclSpec().isFriendSpecified() 10117 ? (D.isFunctionDefinition() 10118 ? TPC_FriendFunctionTemplateDefinition 10119 : TPC_FriendFunctionTemplate) 10120 : (D.getCXXScopeSpec().isSet() && 10121 DC && DC->isRecord() && 10122 DC->isDependentContext()) 10123 ? TPC_ClassTemplateMember 10124 : TPC_FunctionTemplate); 10125 } 10126 10127 if (NewFD->isInvalidDecl()) { 10128 // Ignore all the rest of this. 10129 } else if (!D.isRedeclaration()) { 10130 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 10131 AddToScope }; 10132 // Fake up an access specifier if it's supposed to be a class member. 10133 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 10134 NewFD->setAccess(AS_public); 10135 10136 // Qualified decls generally require a previous declaration. 10137 if (D.getCXXScopeSpec().isSet()) { 10138 // ...with the major exception of templated-scope or 10139 // dependent-scope friend declarations. 10140 10141 // TODO: we currently also suppress this check in dependent 10142 // contexts because (1) the parameter depth will be off when 10143 // matching friend templates and (2) we might actually be 10144 // selecting a friend based on a dependent factor. But there 10145 // are situations where these conditions don't apply and we 10146 // can actually do this check immediately. 10147 // 10148 // Unless the scope is dependent, it's always an error if qualified 10149 // redeclaration lookup found nothing at all. Diagnose that now; 10150 // nothing will diagnose that error later. 10151 if (isFriend && 10152 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 10153 (!Previous.empty() && CurContext->isDependentContext()))) { 10154 // ignore these 10155 } else if (NewFD->isCPUDispatchMultiVersion() || 10156 NewFD->isCPUSpecificMultiVersion()) { 10157 // ignore this, we allow the redeclaration behavior here to create new 10158 // versions of the function. 10159 } else { 10160 // The user tried to provide an out-of-line definition for a 10161 // function that is a member of a class or namespace, but there 10162 // was no such member function declared (C++ [class.mfct]p2, 10163 // C++ [namespace.memdef]p2). For example: 10164 // 10165 // class X { 10166 // void f() const; 10167 // }; 10168 // 10169 // void X::f() { } // ill-formed 10170 // 10171 // Complain about this problem, and attempt to suggest close 10172 // matches (e.g., those that differ only in cv-qualifiers and 10173 // whether the parameter types are references). 10174 10175 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10176 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 10177 AddToScope = ExtraArgs.AddToScope; 10178 return Result; 10179 } 10180 } 10181 10182 // Unqualified local friend declarations are required to resolve 10183 // to something. 10184 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 10185 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10186 *this, Previous, NewFD, ExtraArgs, true, S)) { 10187 AddToScope = ExtraArgs.AddToScope; 10188 return Result; 10189 } 10190 } 10191 } else if (!D.isFunctionDefinition() && 10192 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 10193 !isFriend && !isFunctionTemplateSpecialization && 10194 !isMemberSpecialization) { 10195 // An out-of-line member function declaration must also be a 10196 // definition (C++ [class.mfct]p2). 10197 // Note that this is not the case for explicit specializations of 10198 // function templates or member functions of class templates, per 10199 // C++ [temp.expl.spec]p2. We also allow these declarations as an 10200 // extension for compatibility with old SWIG code which likes to 10201 // generate them. 10202 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 10203 << D.getCXXScopeSpec().getRange(); 10204 } 10205 } 10206 10207 // If this is the first declaration of a library builtin function, add 10208 // attributes as appropriate. 10209 if (!D.isRedeclaration()) { 10210 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 10211 if (unsigned BuiltinID = II->getBuiltinID()) { 10212 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID); 10213 if (!InStdNamespace && 10214 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 10215 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 10216 // Validate the type matches unless this builtin is specified as 10217 // matching regardless of its declared type. 10218 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 10219 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10220 } else { 10221 ASTContext::GetBuiltinTypeError Error; 10222 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10223 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 10224 10225 if (!Error && !BuiltinType.isNull() && 10226 Context.hasSameFunctionTypeIgnoringExceptionSpec( 10227 NewFD->getType(), BuiltinType)) 10228 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10229 } 10230 } 10231 } else if (InStdNamespace && NewFD->isInStdNamespace() && 10232 isStdBuiltin(Context, NewFD, BuiltinID)) { 10233 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10234 } 10235 } 10236 } 10237 } 10238 10239 ProcessPragmaWeak(S, NewFD); 10240 checkAttributesAfterMerging(*this, *NewFD); 10241 10242 AddKnownFunctionAttributes(NewFD); 10243 10244 if (NewFD->hasAttr<OverloadableAttr>() && 10245 !NewFD->getType()->getAs<FunctionProtoType>()) { 10246 Diag(NewFD->getLocation(), 10247 diag::err_attribute_overloadable_no_prototype) 10248 << NewFD; 10249 10250 // Turn this into a variadic function with no parameters. 10251 const auto *FT = NewFD->getType()->castAs<FunctionType>(); 10252 FunctionProtoType::ExtProtoInfo EPI( 10253 Context.getDefaultCallingConvention(true, false)); 10254 EPI.Variadic = true; 10255 EPI.ExtInfo = FT->getExtInfo(); 10256 10257 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 10258 NewFD->setType(R); 10259 } 10260 10261 // If there's a #pragma GCC visibility in scope, and this isn't a class 10262 // member, set the visibility of this function. 10263 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10264 AddPushedVisibilityAttribute(NewFD); 10265 10266 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10267 // marking the function. 10268 AddCFAuditedAttribute(NewFD); 10269 10270 // If this is a function definition, check if we have to apply any 10271 // attributes (i.e. optnone and no_builtin) due to a pragma. 10272 if (D.isFunctionDefinition()) { 10273 AddRangeBasedOptnone(NewFD); 10274 AddImplicitMSFunctionNoBuiltinAttr(NewFD); 10275 AddSectionMSAllocText(NewFD); 10276 ModifyFnAttributesMSPragmaOptimize(NewFD); 10277 } 10278 10279 // If this is the first declaration of an extern C variable, update 10280 // the map of such variables. 10281 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10282 isIncompleteDeclExternC(*this, NewFD)) 10283 RegisterLocallyScopedExternCDecl(NewFD, S); 10284 10285 // Set this FunctionDecl's range up to the right paren. 10286 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10287 10288 if (D.isRedeclaration() && !Previous.empty()) { 10289 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10290 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10291 isMemberSpecialization || 10292 isFunctionTemplateSpecialization, 10293 D.isFunctionDefinition()); 10294 } 10295 10296 if (getLangOpts().CUDA) { 10297 IdentifierInfo *II = NewFD->getIdentifier(); 10298 if (II && II->isStr(getCudaConfigureFuncName()) && 10299 !NewFD->isInvalidDecl() && 10300 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10301 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10302 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10303 << getCudaConfigureFuncName(); 10304 Context.setcudaConfigureCallDecl(NewFD); 10305 } 10306 10307 // Variadic functions, other than a *declaration* of printf, are not allowed 10308 // in device-side CUDA code, unless someone passed 10309 // -fcuda-allow-variadic-functions. 10310 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10311 (NewFD->hasAttr<CUDADeviceAttr>() || 10312 NewFD->hasAttr<CUDAGlobalAttr>()) && 10313 !(II && II->isStr("printf") && NewFD->isExternC() && 10314 !D.isFunctionDefinition())) { 10315 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10316 } 10317 } 10318 10319 MarkUnusedFileScopedDecl(NewFD); 10320 10321 10322 10323 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10324 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10325 if (SC == SC_Static) { 10326 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10327 D.setInvalidType(); 10328 } 10329 10330 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10331 if (!NewFD->getReturnType()->isVoidType()) { 10332 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10333 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10334 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10335 : FixItHint()); 10336 D.setInvalidType(); 10337 } 10338 10339 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10340 for (auto Param : NewFD->parameters()) 10341 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10342 10343 if (getLangOpts().OpenCLCPlusPlus) { 10344 if (DC->isRecord()) { 10345 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10346 D.setInvalidType(); 10347 } 10348 if (FunctionTemplate) { 10349 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10350 D.setInvalidType(); 10351 } 10352 } 10353 } 10354 10355 if (getLangOpts().CPlusPlus) { 10356 if (FunctionTemplate) { 10357 if (NewFD->isInvalidDecl()) 10358 FunctionTemplate->setInvalidDecl(); 10359 return FunctionTemplate; 10360 } 10361 10362 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10363 CompleteMemberSpecialization(NewFD, Previous); 10364 } 10365 10366 for (const ParmVarDecl *Param : NewFD->parameters()) { 10367 QualType PT = Param->getType(); 10368 10369 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10370 // types. 10371 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10372 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10373 QualType ElemTy = PipeTy->getElementType(); 10374 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10375 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10376 D.setInvalidType(); 10377 } 10378 } 10379 } 10380 } 10381 10382 // Here we have an function template explicit specialization at class scope. 10383 // The actual specialization will be postponed to template instatiation 10384 // time via the ClassScopeFunctionSpecializationDecl node. 10385 if (isDependentClassScopeExplicitSpecialization) { 10386 ClassScopeFunctionSpecializationDecl *NewSpec = 10387 ClassScopeFunctionSpecializationDecl::Create( 10388 Context, CurContext, NewFD->getLocation(), 10389 cast<CXXMethodDecl>(NewFD), 10390 HasExplicitTemplateArgs, TemplateArgs); 10391 CurContext->addDecl(NewSpec); 10392 AddToScope = false; 10393 } 10394 10395 // Diagnose availability attributes. Availability cannot be used on functions 10396 // that are run during load/unload. 10397 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10398 if (NewFD->hasAttr<ConstructorAttr>()) { 10399 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10400 << 1; 10401 NewFD->dropAttr<AvailabilityAttr>(); 10402 } 10403 if (NewFD->hasAttr<DestructorAttr>()) { 10404 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10405 << 2; 10406 NewFD->dropAttr<AvailabilityAttr>(); 10407 } 10408 } 10409 10410 // Diagnose no_builtin attribute on function declaration that are not a 10411 // definition. 10412 // FIXME: We should really be doing this in 10413 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10414 // the FunctionDecl and at this point of the code 10415 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10416 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10417 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10418 switch (D.getFunctionDefinitionKind()) { 10419 case FunctionDefinitionKind::Defaulted: 10420 case FunctionDefinitionKind::Deleted: 10421 Diag(NBA->getLocation(), 10422 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10423 << NBA->getSpelling(); 10424 break; 10425 case FunctionDefinitionKind::Declaration: 10426 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10427 << NBA->getSpelling(); 10428 break; 10429 case FunctionDefinitionKind::Definition: 10430 break; 10431 } 10432 10433 return NewFD; 10434 } 10435 10436 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10437 /// when __declspec(code_seg) "is applied to a class, all member functions of 10438 /// the class and nested classes -- this includes compiler-generated special 10439 /// member functions -- are put in the specified segment." 10440 /// The actual behavior is a little more complicated. The Microsoft compiler 10441 /// won't check outer classes if there is an active value from #pragma code_seg. 10442 /// The CodeSeg is always applied from the direct parent but only from outer 10443 /// classes when the #pragma code_seg stack is empty. See: 10444 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10445 /// available since MS has removed the page. 10446 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10447 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10448 if (!Method) 10449 return nullptr; 10450 const CXXRecordDecl *Parent = Method->getParent(); 10451 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10452 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10453 NewAttr->setImplicit(true); 10454 return NewAttr; 10455 } 10456 10457 // The Microsoft compiler won't check outer classes for the CodeSeg 10458 // when the #pragma code_seg stack is active. 10459 if (S.CodeSegStack.CurrentValue) 10460 return nullptr; 10461 10462 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10463 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10464 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10465 NewAttr->setImplicit(true); 10466 return NewAttr; 10467 } 10468 } 10469 return nullptr; 10470 } 10471 10472 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10473 /// containing class. Otherwise it will return implicit SectionAttr if the 10474 /// function is a definition and there is an active value on CodeSegStack 10475 /// (from the current #pragma code-seg value). 10476 /// 10477 /// \param FD Function being declared. 10478 /// \param IsDefinition Whether it is a definition or just a declarartion. 10479 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10480 /// nullptr if no attribute should be added. 10481 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10482 bool IsDefinition) { 10483 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10484 return A; 10485 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10486 CodeSegStack.CurrentValue) 10487 return SectionAttr::CreateImplicit( 10488 getASTContext(), CodeSegStack.CurrentValue->getString(), 10489 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10490 SectionAttr::Declspec_allocate); 10491 return nullptr; 10492 } 10493 10494 /// Determines if we can perform a correct type check for \p D as a 10495 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10496 /// best-effort check. 10497 /// 10498 /// \param NewD The new declaration. 10499 /// \param OldD The old declaration. 10500 /// \param NewT The portion of the type of the new declaration to check. 10501 /// \param OldT The portion of the type of the old declaration to check. 10502 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10503 QualType NewT, QualType OldT) { 10504 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10505 return true; 10506 10507 // For dependently-typed local extern declarations and friends, we can't 10508 // perform a correct type check in general until instantiation: 10509 // 10510 // int f(); 10511 // template<typename T> void g() { T f(); } 10512 // 10513 // (valid if g() is only instantiated with T = int). 10514 if (NewT->isDependentType() && 10515 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10516 return false; 10517 10518 // Similarly, if the previous declaration was a dependent local extern 10519 // declaration, we don't really know its type yet. 10520 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10521 return false; 10522 10523 return true; 10524 } 10525 10526 /// Checks if the new declaration declared in dependent context must be 10527 /// put in the same redeclaration chain as the specified declaration. 10528 /// 10529 /// \param D Declaration that is checked. 10530 /// \param PrevDecl Previous declaration found with proper lookup method for the 10531 /// same declaration name. 10532 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10533 /// belongs to. 10534 /// 10535 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10536 if (!D->getLexicalDeclContext()->isDependentContext()) 10537 return true; 10538 10539 // Don't chain dependent friend function definitions until instantiation, to 10540 // permit cases like 10541 // 10542 // void func(); 10543 // template<typename T> class C1 { friend void func() {} }; 10544 // template<typename T> class C2 { friend void func() {} }; 10545 // 10546 // ... which is valid if only one of C1 and C2 is ever instantiated. 10547 // 10548 // FIXME: This need only apply to function definitions. For now, we proxy 10549 // this by checking for a file-scope function. We do not want this to apply 10550 // to friend declarations nominating member functions, because that gets in 10551 // the way of access checks. 10552 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10553 return false; 10554 10555 auto *VD = dyn_cast<ValueDecl>(D); 10556 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10557 return !VD || !PrevVD || 10558 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10559 PrevVD->getType()); 10560 } 10561 10562 /// Check the target attribute of the function for MultiVersion 10563 /// validity. 10564 /// 10565 /// Returns true if there was an error, false otherwise. 10566 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10567 const auto *TA = FD->getAttr<TargetAttr>(); 10568 assert(TA && "MultiVersion Candidate requires a target attribute"); 10569 ParsedTargetAttr ParseInfo = TA->parse(); 10570 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10571 enum ErrType { Feature = 0, Architecture = 1 }; 10572 10573 if (!ParseInfo.Architecture.empty() && 10574 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10575 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10576 << Architecture << ParseInfo.Architecture; 10577 return true; 10578 } 10579 10580 for (const auto &Feat : ParseInfo.Features) { 10581 auto BareFeat = StringRef{Feat}.substr(1); 10582 if (Feat[0] == '-') { 10583 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10584 << Feature << ("no-" + BareFeat).str(); 10585 return true; 10586 } 10587 10588 if (!TargetInfo.validateCpuSupports(BareFeat) || 10589 !TargetInfo.isValidFeatureName(BareFeat)) { 10590 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10591 << Feature << BareFeat; 10592 return true; 10593 } 10594 } 10595 return false; 10596 } 10597 10598 // Provide a white-list of attributes that are allowed to be combined with 10599 // multiversion functions. 10600 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10601 MultiVersionKind MVKind) { 10602 // Note: this list/diagnosis must match the list in 10603 // checkMultiversionAttributesAllSame. 10604 switch (Kind) { 10605 default: 10606 return false; 10607 case attr::Used: 10608 return MVKind == MultiVersionKind::Target; 10609 case attr::NonNull: 10610 case attr::NoThrow: 10611 return true; 10612 } 10613 } 10614 10615 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10616 const FunctionDecl *FD, 10617 const FunctionDecl *CausedFD, 10618 MultiVersionKind MVKind) { 10619 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 10620 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10621 << static_cast<unsigned>(MVKind) << A; 10622 if (CausedFD) 10623 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10624 return true; 10625 }; 10626 10627 for (const Attr *A : FD->attrs()) { 10628 switch (A->getKind()) { 10629 case attr::CPUDispatch: 10630 case attr::CPUSpecific: 10631 if (MVKind != MultiVersionKind::CPUDispatch && 10632 MVKind != MultiVersionKind::CPUSpecific) 10633 return Diagnose(S, A); 10634 break; 10635 case attr::Target: 10636 if (MVKind != MultiVersionKind::Target) 10637 return Diagnose(S, A); 10638 break; 10639 case attr::TargetClones: 10640 if (MVKind != MultiVersionKind::TargetClones) 10641 return Diagnose(S, A); 10642 break; 10643 default: 10644 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 10645 return Diagnose(S, A); 10646 break; 10647 } 10648 } 10649 return false; 10650 } 10651 10652 bool Sema::areMultiversionVariantFunctionsCompatible( 10653 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10654 const PartialDiagnostic &NoProtoDiagID, 10655 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10656 const PartialDiagnosticAt &NoSupportDiagIDAt, 10657 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10658 bool ConstexprSupported, bool CLinkageMayDiffer) { 10659 enum DoesntSupport { 10660 FuncTemplates = 0, 10661 VirtFuncs = 1, 10662 DeducedReturn = 2, 10663 Constructors = 3, 10664 Destructors = 4, 10665 DeletedFuncs = 5, 10666 DefaultedFuncs = 6, 10667 ConstexprFuncs = 7, 10668 ConstevalFuncs = 8, 10669 Lambda = 9, 10670 }; 10671 enum Different { 10672 CallingConv = 0, 10673 ReturnType = 1, 10674 ConstexprSpec = 2, 10675 InlineSpec = 3, 10676 Linkage = 4, 10677 LanguageLinkage = 5, 10678 }; 10679 10680 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10681 !OldFD->getType()->getAs<FunctionProtoType>()) { 10682 Diag(OldFD->getLocation(), NoProtoDiagID); 10683 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10684 return true; 10685 } 10686 10687 if (NoProtoDiagID.getDiagID() != 0 && 10688 !NewFD->getType()->getAs<FunctionProtoType>()) 10689 return Diag(NewFD->getLocation(), NoProtoDiagID); 10690 10691 if (!TemplatesSupported && 10692 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10693 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10694 << FuncTemplates; 10695 10696 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10697 if (NewCXXFD->isVirtual()) 10698 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10699 << VirtFuncs; 10700 10701 if (isa<CXXConstructorDecl>(NewCXXFD)) 10702 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10703 << Constructors; 10704 10705 if (isa<CXXDestructorDecl>(NewCXXFD)) 10706 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10707 << Destructors; 10708 } 10709 10710 if (NewFD->isDeleted()) 10711 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10712 << DeletedFuncs; 10713 10714 if (NewFD->isDefaulted()) 10715 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10716 << DefaultedFuncs; 10717 10718 if (!ConstexprSupported && NewFD->isConstexpr()) 10719 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10720 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10721 10722 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10723 const auto *NewType = cast<FunctionType>(NewQType); 10724 QualType NewReturnType = NewType->getReturnType(); 10725 10726 if (NewReturnType->isUndeducedType()) 10727 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10728 << DeducedReturn; 10729 10730 // Ensure the return type is identical. 10731 if (OldFD) { 10732 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10733 const auto *OldType = cast<FunctionType>(OldQType); 10734 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10735 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10736 10737 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10738 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10739 10740 QualType OldReturnType = OldType->getReturnType(); 10741 10742 if (OldReturnType != NewReturnType) 10743 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10744 10745 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10746 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10747 10748 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10749 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10750 10751 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10752 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10753 10754 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10755 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10756 10757 if (CheckEquivalentExceptionSpec( 10758 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10759 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10760 return true; 10761 } 10762 return false; 10763 } 10764 10765 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10766 const FunctionDecl *NewFD, 10767 bool CausesMV, 10768 MultiVersionKind MVKind) { 10769 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10770 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10771 if (OldFD) 10772 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10773 return true; 10774 } 10775 10776 bool IsCPUSpecificCPUDispatchMVKind = 10777 MVKind == MultiVersionKind::CPUDispatch || 10778 MVKind == MultiVersionKind::CPUSpecific; 10779 10780 if (CausesMV && OldFD && 10781 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 10782 return true; 10783 10784 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 10785 return true; 10786 10787 // Only allow transition to MultiVersion if it hasn't been used. 10788 if (OldFD && CausesMV && OldFD->isUsed(false)) 10789 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10790 10791 return S.areMultiversionVariantFunctionsCompatible( 10792 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10793 PartialDiagnosticAt(NewFD->getLocation(), 10794 S.PDiag(diag::note_multiversioning_caused_here)), 10795 PartialDiagnosticAt(NewFD->getLocation(), 10796 S.PDiag(diag::err_multiversion_doesnt_support) 10797 << static_cast<unsigned>(MVKind)), 10798 PartialDiagnosticAt(NewFD->getLocation(), 10799 S.PDiag(diag::err_multiversion_diff)), 10800 /*TemplatesSupported=*/false, 10801 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 10802 /*CLinkageMayDiffer=*/false); 10803 } 10804 10805 /// Check the validity of a multiversion function declaration that is the 10806 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10807 /// 10808 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10809 /// 10810 /// Returns true if there was an error, false otherwise. 10811 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10812 MultiVersionKind MVKind, 10813 const TargetAttr *TA) { 10814 assert(MVKind != MultiVersionKind::None && 10815 "Function lacks multiversion attribute"); 10816 10817 // Target only causes MV if it is default, otherwise this is a normal 10818 // function. 10819 if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion()) 10820 return false; 10821 10822 if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10823 FD->setInvalidDecl(); 10824 return true; 10825 } 10826 10827 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 10828 FD->setInvalidDecl(); 10829 return true; 10830 } 10831 10832 FD->setIsMultiVersion(); 10833 return false; 10834 } 10835 10836 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10837 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10838 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10839 return true; 10840 } 10841 10842 return false; 10843 } 10844 10845 static bool CheckTargetCausesMultiVersioning( 10846 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10847 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { 10848 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10849 ParsedTargetAttr NewParsed = NewTA->parse(); 10850 // Sort order doesn't matter, it just needs to be consistent. 10851 llvm::sort(NewParsed.Features); 10852 10853 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10854 // to change, this is a simple redeclaration. 10855 if (!NewTA->isDefaultVersion() && 10856 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10857 return false; 10858 10859 // Otherwise, this decl causes MultiVersioning. 10860 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10861 MultiVersionKind::Target)) { 10862 NewFD->setInvalidDecl(); 10863 return true; 10864 } 10865 10866 if (CheckMultiVersionValue(S, NewFD)) { 10867 NewFD->setInvalidDecl(); 10868 return true; 10869 } 10870 10871 // If this is 'default', permit the forward declaration. 10872 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10873 Redeclaration = true; 10874 OldDecl = OldFD; 10875 OldFD->setIsMultiVersion(); 10876 NewFD->setIsMultiVersion(); 10877 return false; 10878 } 10879 10880 if (CheckMultiVersionValue(S, OldFD)) { 10881 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10882 NewFD->setInvalidDecl(); 10883 return true; 10884 } 10885 10886 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10887 10888 if (OldParsed == NewParsed) { 10889 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10890 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10891 NewFD->setInvalidDecl(); 10892 return true; 10893 } 10894 10895 for (const auto *FD : OldFD->redecls()) { 10896 const auto *CurTA = FD->getAttr<TargetAttr>(); 10897 // We allow forward declarations before ANY multiversioning attributes, but 10898 // nothing after the fact. 10899 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10900 (!CurTA || CurTA->isInherited())) { 10901 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10902 << 0; 10903 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10904 NewFD->setInvalidDecl(); 10905 return true; 10906 } 10907 } 10908 10909 OldFD->setIsMultiVersion(); 10910 NewFD->setIsMultiVersion(); 10911 Redeclaration = false; 10912 OldDecl = nullptr; 10913 Previous.clear(); 10914 return false; 10915 } 10916 10917 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 10918 MultiVersionKind New) { 10919 if (Old == New || Old == MultiVersionKind::None || 10920 New == MultiVersionKind::None) 10921 return true; 10922 10923 return (Old == MultiVersionKind::CPUDispatch && 10924 New == MultiVersionKind::CPUSpecific) || 10925 (Old == MultiVersionKind::CPUSpecific && 10926 New == MultiVersionKind::CPUDispatch); 10927 } 10928 10929 /// Check the validity of a new function declaration being added to an existing 10930 /// multiversioned declaration collection. 10931 static bool CheckMultiVersionAdditionalDecl( 10932 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10933 MultiVersionKind NewMVKind, const TargetAttr *NewTA, 10934 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10935 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 10936 LookupResult &Previous) { 10937 10938 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 10939 // Disallow mixing of multiversioning types. 10940 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { 10941 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10942 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10943 NewFD->setInvalidDecl(); 10944 return true; 10945 } 10946 10947 ParsedTargetAttr NewParsed; 10948 if (NewTA) { 10949 NewParsed = NewTA->parse(); 10950 llvm::sort(NewParsed.Features); 10951 } 10952 10953 bool UseMemberUsingDeclRules = 10954 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10955 10956 bool MayNeedOverloadableChecks = 10957 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 10958 10959 // Next, check ALL non-overloads to see if this is a redeclaration of a 10960 // previous member of the MultiVersion set. 10961 for (NamedDecl *ND : Previous) { 10962 FunctionDecl *CurFD = ND->getAsFunction(); 10963 if (!CurFD) 10964 continue; 10965 if (MayNeedOverloadableChecks && 10966 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10967 continue; 10968 10969 switch (NewMVKind) { 10970 case MultiVersionKind::None: 10971 assert(OldMVKind == MultiVersionKind::TargetClones && 10972 "Only target_clones can be omitted in subsequent declarations"); 10973 break; 10974 case MultiVersionKind::Target: { 10975 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10976 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10977 NewFD->setIsMultiVersion(); 10978 Redeclaration = true; 10979 OldDecl = ND; 10980 return false; 10981 } 10982 10983 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10984 if (CurParsed == NewParsed) { 10985 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10986 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10987 NewFD->setInvalidDecl(); 10988 return true; 10989 } 10990 break; 10991 } 10992 case MultiVersionKind::TargetClones: { 10993 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 10994 Redeclaration = true; 10995 OldDecl = CurFD; 10996 NewFD->setIsMultiVersion(); 10997 10998 if (CurClones && NewClones && 10999 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 11000 !std::equal(CurClones->featuresStrs_begin(), 11001 CurClones->featuresStrs_end(), 11002 NewClones->featuresStrs_begin()))) { 11003 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 11004 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11005 NewFD->setInvalidDecl(); 11006 return true; 11007 } 11008 11009 return false; 11010 } 11011 case MultiVersionKind::CPUSpecific: 11012 case MultiVersionKind::CPUDispatch: { 11013 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 11014 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 11015 // Handle CPUDispatch/CPUSpecific versions. 11016 // Only 1 CPUDispatch function is allowed, this will make it go through 11017 // the redeclaration errors. 11018 if (NewMVKind == MultiVersionKind::CPUDispatch && 11019 CurFD->hasAttr<CPUDispatchAttr>()) { 11020 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 11021 std::equal( 11022 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 11023 NewCPUDisp->cpus_begin(), 11024 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11025 return Cur->getName() == New->getName(); 11026 })) { 11027 NewFD->setIsMultiVersion(); 11028 Redeclaration = true; 11029 OldDecl = ND; 11030 return false; 11031 } 11032 11033 // If the declarations don't match, this is an error condition. 11034 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 11035 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11036 NewFD->setInvalidDecl(); 11037 return true; 11038 } 11039 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 11040 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 11041 std::equal( 11042 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 11043 NewCPUSpec->cpus_begin(), 11044 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11045 return Cur->getName() == New->getName(); 11046 })) { 11047 NewFD->setIsMultiVersion(); 11048 Redeclaration = true; 11049 OldDecl = ND; 11050 return false; 11051 } 11052 11053 // Only 1 version of CPUSpecific is allowed for each CPU. 11054 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 11055 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 11056 if (CurII == NewII) { 11057 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 11058 << NewII; 11059 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11060 NewFD->setInvalidDecl(); 11061 return true; 11062 } 11063 } 11064 } 11065 } 11066 break; 11067 } 11068 } 11069 } 11070 11071 // Else, this is simply a non-redecl case. Checking the 'value' is only 11072 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 11073 // handled in the attribute adding step. 11074 if (NewMVKind == MultiVersionKind::Target && 11075 CheckMultiVersionValue(S, NewFD)) { 11076 NewFD->setInvalidDecl(); 11077 return true; 11078 } 11079 11080 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 11081 !OldFD->isMultiVersion(), NewMVKind)) { 11082 NewFD->setInvalidDecl(); 11083 return true; 11084 } 11085 11086 // Permit forward declarations in the case where these two are compatible. 11087 if (!OldFD->isMultiVersion()) { 11088 OldFD->setIsMultiVersion(); 11089 NewFD->setIsMultiVersion(); 11090 Redeclaration = true; 11091 OldDecl = OldFD; 11092 return false; 11093 } 11094 11095 NewFD->setIsMultiVersion(); 11096 Redeclaration = false; 11097 OldDecl = nullptr; 11098 Previous.clear(); 11099 return false; 11100 } 11101 11102 /// Check the validity of a mulitversion function declaration. 11103 /// Also sets the multiversion'ness' of the function itself. 11104 /// 11105 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11106 /// 11107 /// Returns true if there was an error, false otherwise. 11108 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 11109 bool &Redeclaration, NamedDecl *&OldDecl, 11110 LookupResult &Previous) { 11111 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11112 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 11113 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 11114 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 11115 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 11116 11117 // Main isn't allowed to become a multiversion function, however it IS 11118 // permitted to have 'main' be marked with the 'target' optimization hint. 11119 if (NewFD->isMain()) { 11120 if (MVKind != MultiVersionKind::None && 11121 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { 11122 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 11123 NewFD->setInvalidDecl(); 11124 return true; 11125 } 11126 return false; 11127 } 11128 11129 if (!OldDecl || !OldDecl->getAsFunction() || 11130 OldDecl->getDeclContext()->getRedeclContext() != 11131 NewFD->getDeclContext()->getRedeclContext()) { 11132 // If there's no previous declaration, AND this isn't attempting to cause 11133 // multiversioning, this isn't an error condition. 11134 if (MVKind == MultiVersionKind::None) 11135 return false; 11136 return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA); 11137 } 11138 11139 FunctionDecl *OldFD = OldDecl->getAsFunction(); 11140 11141 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) 11142 return false; 11143 11144 // Multiversioned redeclarations aren't allowed to omit the attribute, except 11145 // for target_clones. 11146 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 11147 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { 11148 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 11149 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 11150 NewFD->setInvalidDecl(); 11151 return true; 11152 } 11153 11154 if (!OldFD->isMultiVersion()) { 11155 switch (MVKind) { 11156 case MultiVersionKind::Target: 11157 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 11158 Redeclaration, OldDecl, Previous); 11159 case MultiVersionKind::TargetClones: 11160 if (OldFD->isUsed(false)) { 11161 NewFD->setInvalidDecl(); 11162 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11163 } 11164 OldFD->setIsMultiVersion(); 11165 break; 11166 case MultiVersionKind::CPUDispatch: 11167 case MultiVersionKind::CPUSpecific: 11168 case MultiVersionKind::None: 11169 break; 11170 } 11171 } 11172 11173 // At this point, we have a multiversion function decl (in OldFD) AND an 11174 // appropriate attribute in the current function decl. Resolve that these are 11175 // still compatible with previous declarations. 11176 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA, 11177 NewCPUDisp, NewCPUSpec, NewClones, 11178 Redeclaration, OldDecl, Previous); 11179 } 11180 11181 /// Perform semantic checking of a new function declaration. 11182 /// 11183 /// Performs semantic analysis of the new function declaration 11184 /// NewFD. This routine performs all semantic checking that does not 11185 /// require the actual declarator involved in the declaration, and is 11186 /// used both for the declaration of functions as they are parsed 11187 /// (called via ActOnDeclarator) and for the declaration of functions 11188 /// that have been instantiated via C++ template instantiation (called 11189 /// via InstantiateDecl). 11190 /// 11191 /// \param IsMemberSpecialization whether this new function declaration is 11192 /// a member specialization (that replaces any definition provided by the 11193 /// previous declaration). 11194 /// 11195 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11196 /// 11197 /// \returns true if the function declaration is a redeclaration. 11198 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 11199 LookupResult &Previous, 11200 bool IsMemberSpecialization, 11201 bool DeclIsDefn) { 11202 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 11203 "Variably modified return types are not handled here"); 11204 11205 // Determine whether the type of this function should be merged with 11206 // a previous visible declaration. This never happens for functions in C++, 11207 // and always happens in C if the previous declaration was visible. 11208 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 11209 !Previous.isShadowed(); 11210 11211 bool Redeclaration = false; 11212 NamedDecl *OldDecl = nullptr; 11213 bool MayNeedOverloadableChecks = false; 11214 11215 // Merge or overload the declaration with an existing declaration of 11216 // the same name, if appropriate. 11217 if (!Previous.empty()) { 11218 // Determine whether NewFD is an overload of PrevDecl or 11219 // a declaration that requires merging. If it's an overload, 11220 // there's no more work to do here; we'll just add the new 11221 // function to the scope. 11222 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 11223 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 11224 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 11225 Redeclaration = true; 11226 OldDecl = Candidate; 11227 } 11228 } else { 11229 MayNeedOverloadableChecks = true; 11230 switch (CheckOverload(S, NewFD, Previous, OldDecl, 11231 /*NewIsUsingDecl*/ false)) { 11232 case Ovl_Match: 11233 Redeclaration = true; 11234 break; 11235 11236 case Ovl_NonFunction: 11237 Redeclaration = true; 11238 break; 11239 11240 case Ovl_Overload: 11241 Redeclaration = false; 11242 break; 11243 } 11244 } 11245 } 11246 11247 // Check for a previous extern "C" declaration with this name. 11248 if (!Redeclaration && 11249 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 11250 if (!Previous.empty()) { 11251 // This is an extern "C" declaration with the same name as a previous 11252 // declaration, and thus redeclares that entity... 11253 Redeclaration = true; 11254 OldDecl = Previous.getFoundDecl(); 11255 MergeTypeWithPrevious = false; 11256 11257 // ... except in the presence of __attribute__((overloadable)). 11258 if (OldDecl->hasAttr<OverloadableAttr>() || 11259 NewFD->hasAttr<OverloadableAttr>()) { 11260 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11261 MayNeedOverloadableChecks = true; 11262 Redeclaration = false; 11263 OldDecl = nullptr; 11264 } 11265 } 11266 } 11267 } 11268 11269 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 11270 return Redeclaration; 11271 11272 // PPC MMA non-pointer types are not allowed as function return types. 11273 if (Context.getTargetInfo().getTriple().isPPC64() && 11274 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11275 NewFD->setInvalidDecl(); 11276 } 11277 11278 // C++11 [dcl.constexpr]p8: 11279 // A constexpr specifier for a non-static member function that is not 11280 // a constructor declares that member function to be const. 11281 // 11282 // This needs to be delayed until we know whether this is an out-of-line 11283 // definition of a static member function. 11284 // 11285 // This rule is not present in C++1y, so we produce a backwards 11286 // compatibility warning whenever it happens in C++11. 11287 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11288 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11289 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11290 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11291 CXXMethodDecl *OldMD = nullptr; 11292 if (OldDecl) 11293 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11294 if (!OldMD || !OldMD->isStatic()) { 11295 const FunctionProtoType *FPT = 11296 MD->getType()->castAs<FunctionProtoType>(); 11297 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11298 EPI.TypeQuals.addConst(); 11299 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11300 FPT->getParamTypes(), EPI)); 11301 11302 // Warn that we did this, if we're not performing template instantiation. 11303 // In that case, we'll have warned already when the template was defined. 11304 if (!inTemplateInstantiation()) { 11305 SourceLocation AddConstLoc; 11306 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11307 .IgnoreParens().getAs<FunctionTypeLoc>()) 11308 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11309 11310 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11311 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11312 } 11313 } 11314 } 11315 11316 if (Redeclaration) { 11317 // NewFD and OldDecl represent declarations that need to be 11318 // merged. 11319 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious, 11320 DeclIsDefn)) { 11321 NewFD->setInvalidDecl(); 11322 return Redeclaration; 11323 } 11324 11325 Previous.clear(); 11326 Previous.addDecl(OldDecl); 11327 11328 if (FunctionTemplateDecl *OldTemplateDecl = 11329 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11330 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11331 FunctionTemplateDecl *NewTemplateDecl 11332 = NewFD->getDescribedFunctionTemplate(); 11333 assert(NewTemplateDecl && "Template/non-template mismatch"); 11334 11335 // The call to MergeFunctionDecl above may have created some state in 11336 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11337 // can add it as a redeclaration. 11338 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11339 11340 NewFD->setPreviousDeclaration(OldFD); 11341 if (NewFD->isCXXClassMember()) { 11342 NewFD->setAccess(OldTemplateDecl->getAccess()); 11343 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11344 } 11345 11346 // If this is an explicit specialization of a member that is a function 11347 // template, mark it as a member specialization. 11348 if (IsMemberSpecialization && 11349 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11350 NewTemplateDecl->setMemberSpecialization(); 11351 assert(OldTemplateDecl->isMemberSpecialization()); 11352 // Explicit specializations of a member template do not inherit deleted 11353 // status from the parent member template that they are specializing. 11354 if (OldFD->isDeleted()) { 11355 // FIXME: This assert will not hold in the presence of modules. 11356 assert(OldFD->getCanonicalDecl() == OldFD); 11357 // FIXME: We need an update record for this AST mutation. 11358 OldFD->setDeletedAsWritten(false); 11359 } 11360 } 11361 11362 } else { 11363 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11364 auto *OldFD = cast<FunctionDecl>(OldDecl); 11365 // This needs to happen first so that 'inline' propagates. 11366 NewFD->setPreviousDeclaration(OldFD); 11367 if (NewFD->isCXXClassMember()) 11368 NewFD->setAccess(OldFD->getAccess()); 11369 } 11370 } 11371 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11372 !NewFD->getAttr<OverloadableAttr>()) { 11373 assert((Previous.empty() || 11374 llvm::any_of(Previous, 11375 [](const NamedDecl *ND) { 11376 return ND->hasAttr<OverloadableAttr>(); 11377 })) && 11378 "Non-redecls shouldn't happen without overloadable present"); 11379 11380 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11381 const auto *FD = dyn_cast<FunctionDecl>(ND); 11382 return FD && !FD->hasAttr<OverloadableAttr>(); 11383 }); 11384 11385 if (OtherUnmarkedIter != Previous.end()) { 11386 Diag(NewFD->getLocation(), 11387 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11388 Diag((*OtherUnmarkedIter)->getLocation(), 11389 diag::note_attribute_overloadable_prev_overload) 11390 << false; 11391 11392 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11393 } 11394 } 11395 11396 if (LangOpts.OpenMP) 11397 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11398 11399 // Semantic checking for this function declaration (in isolation). 11400 11401 if (getLangOpts().CPlusPlus) { 11402 // C++-specific checks. 11403 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11404 CheckConstructor(Constructor); 11405 } else if (CXXDestructorDecl *Destructor = 11406 dyn_cast<CXXDestructorDecl>(NewFD)) { 11407 CXXRecordDecl *Record = Destructor->getParent(); 11408 QualType ClassType = Context.getTypeDeclType(Record); 11409 11410 // FIXME: Shouldn't we be able to perform this check even when the class 11411 // type is dependent? Both gcc and edg can handle that. 11412 if (!ClassType->isDependentType()) { 11413 DeclarationName Name 11414 = Context.DeclarationNames.getCXXDestructorName( 11415 Context.getCanonicalType(ClassType)); 11416 if (NewFD->getDeclName() != Name) { 11417 Diag(NewFD->getLocation(), diag::err_destructor_name); 11418 NewFD->setInvalidDecl(); 11419 return Redeclaration; 11420 } 11421 } 11422 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11423 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11424 CheckDeductionGuideTemplate(TD); 11425 11426 // A deduction guide is not on the list of entities that can be 11427 // explicitly specialized. 11428 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11429 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11430 << /*explicit specialization*/ 1; 11431 } 11432 11433 // Find any virtual functions that this function overrides. 11434 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11435 if (!Method->isFunctionTemplateSpecialization() && 11436 !Method->getDescribedFunctionTemplate() && 11437 Method->isCanonicalDecl()) { 11438 AddOverriddenMethods(Method->getParent(), Method); 11439 } 11440 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11441 // C++2a [class.virtual]p6 11442 // A virtual method shall not have a requires-clause. 11443 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11444 diag::err_constrained_virtual_method); 11445 11446 if (Method->isStatic()) 11447 checkThisInStaticMemberFunctionType(Method); 11448 } 11449 11450 // C++20: dcl.decl.general p4: 11451 // The optional requires-clause ([temp.pre]) in an init-declarator or 11452 // member-declarator shall be present only if the declarator declares a 11453 // templated function ([dcl.fct]). 11454 if (Expr *TRC = NewFD->getTrailingRequiresClause()) { 11455 if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation()) 11456 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function); 11457 } 11458 11459 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11460 ActOnConversionDeclarator(Conversion); 11461 11462 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11463 if (NewFD->isOverloadedOperator() && 11464 CheckOverloadedOperatorDeclaration(NewFD)) { 11465 NewFD->setInvalidDecl(); 11466 return Redeclaration; 11467 } 11468 11469 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11470 if (NewFD->getLiteralIdentifier() && 11471 CheckLiteralOperatorDeclaration(NewFD)) { 11472 NewFD->setInvalidDecl(); 11473 return Redeclaration; 11474 } 11475 11476 // In C++, check default arguments now that we have merged decls. Unless 11477 // the lexical context is the class, because in this case this is done 11478 // during delayed parsing anyway. 11479 if (!CurContext->isRecord()) 11480 CheckCXXDefaultArguments(NewFD); 11481 11482 // If this function is declared as being extern "C", then check to see if 11483 // the function returns a UDT (class, struct, or union type) that is not C 11484 // compatible, and if it does, warn the user. 11485 // But, issue any diagnostic on the first declaration only. 11486 if (Previous.empty() && NewFD->isExternC()) { 11487 QualType R = NewFD->getReturnType(); 11488 if (R->isIncompleteType() && !R->isVoidType()) 11489 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11490 << NewFD << R; 11491 else if (!R.isPODType(Context) && !R->isVoidType() && 11492 !R->isObjCObjectPointerType()) 11493 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11494 } 11495 11496 // C++1z [dcl.fct]p6: 11497 // [...] whether the function has a non-throwing exception-specification 11498 // [is] part of the function type 11499 // 11500 // This results in an ABI break between C++14 and C++17 for functions whose 11501 // declared type includes an exception-specification in a parameter or 11502 // return type. (Exception specifications on the function itself are OK in 11503 // most cases, and exception specifications are not permitted in most other 11504 // contexts where they could make it into a mangling.) 11505 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11506 auto HasNoexcept = [&](QualType T) -> bool { 11507 // Strip off declarator chunks that could be between us and a function 11508 // type. We don't need to look far, exception specifications are very 11509 // restricted prior to C++17. 11510 if (auto *RT = T->getAs<ReferenceType>()) 11511 T = RT->getPointeeType(); 11512 else if (T->isAnyPointerType()) 11513 T = T->getPointeeType(); 11514 else if (auto *MPT = T->getAs<MemberPointerType>()) 11515 T = MPT->getPointeeType(); 11516 if (auto *FPT = T->getAs<FunctionProtoType>()) 11517 if (FPT->isNothrow()) 11518 return true; 11519 return false; 11520 }; 11521 11522 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11523 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11524 for (QualType T : FPT->param_types()) 11525 AnyNoexcept |= HasNoexcept(T); 11526 if (AnyNoexcept) 11527 Diag(NewFD->getLocation(), 11528 diag::warn_cxx17_compat_exception_spec_in_signature) 11529 << NewFD; 11530 } 11531 11532 if (!Redeclaration && LangOpts.CUDA) 11533 checkCUDATargetOverload(NewFD, Previous); 11534 } 11535 return Redeclaration; 11536 } 11537 11538 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11539 // C++11 [basic.start.main]p3: 11540 // A program that [...] declares main to be inline, static or 11541 // constexpr is ill-formed. 11542 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11543 // appear in a declaration of main. 11544 // static main is not an error under C99, but we should warn about it. 11545 // We accept _Noreturn main as an extension. 11546 if (FD->getStorageClass() == SC_Static) 11547 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11548 ? diag::err_static_main : diag::warn_static_main) 11549 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11550 if (FD->isInlineSpecified()) 11551 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11552 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11553 if (DS.isNoreturnSpecified()) { 11554 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11555 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11556 Diag(NoreturnLoc, diag::ext_noreturn_main); 11557 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11558 << FixItHint::CreateRemoval(NoreturnRange); 11559 } 11560 if (FD->isConstexpr()) { 11561 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11562 << FD->isConsteval() 11563 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11564 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11565 } 11566 11567 if (getLangOpts().OpenCL) { 11568 Diag(FD->getLocation(), diag::err_opencl_no_main) 11569 << FD->hasAttr<OpenCLKernelAttr>(); 11570 FD->setInvalidDecl(); 11571 return; 11572 } 11573 11574 // Functions named main in hlsl are default entries, but don't have specific 11575 // signatures they are required to conform to. 11576 if (getLangOpts().HLSL) 11577 return; 11578 11579 QualType T = FD->getType(); 11580 assert(T->isFunctionType() && "function decl is not of function type"); 11581 const FunctionType* FT = T->castAs<FunctionType>(); 11582 11583 // Set default calling convention for main() 11584 if (FT->getCallConv() != CC_C) { 11585 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11586 FD->setType(QualType(FT, 0)); 11587 T = Context.getCanonicalType(FD->getType()); 11588 } 11589 11590 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11591 // In C with GNU extensions we allow main() to have non-integer return 11592 // type, but we should warn about the extension, and we disable the 11593 // implicit-return-zero rule. 11594 11595 // GCC in C mode accepts qualified 'int'. 11596 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11597 FD->setHasImplicitReturnZero(true); 11598 else { 11599 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11600 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11601 if (RTRange.isValid()) 11602 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11603 << FixItHint::CreateReplacement(RTRange, "int"); 11604 } 11605 } else { 11606 // In C and C++, main magically returns 0 if you fall off the end; 11607 // set the flag which tells us that. 11608 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11609 11610 // All the standards say that main() should return 'int'. 11611 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11612 FD->setHasImplicitReturnZero(true); 11613 else { 11614 // Otherwise, this is just a flat-out error. 11615 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11616 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11617 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11618 : FixItHint()); 11619 FD->setInvalidDecl(true); 11620 } 11621 } 11622 11623 // Treat protoless main() as nullary. 11624 if (isa<FunctionNoProtoType>(FT)) return; 11625 11626 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11627 unsigned nparams = FTP->getNumParams(); 11628 assert(FD->getNumParams() == nparams); 11629 11630 bool HasExtraParameters = (nparams > 3); 11631 11632 if (FTP->isVariadic()) { 11633 Diag(FD->getLocation(), diag::ext_variadic_main); 11634 // FIXME: if we had information about the location of the ellipsis, we 11635 // could add a FixIt hint to remove it as a parameter. 11636 } 11637 11638 // Darwin passes an undocumented fourth argument of type char**. If 11639 // other platforms start sprouting these, the logic below will start 11640 // getting shifty. 11641 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11642 HasExtraParameters = false; 11643 11644 if (HasExtraParameters) { 11645 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11646 FD->setInvalidDecl(true); 11647 nparams = 3; 11648 } 11649 11650 // FIXME: a lot of the following diagnostics would be improved 11651 // if we had some location information about types. 11652 11653 QualType CharPP = 11654 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11655 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11656 11657 for (unsigned i = 0; i < nparams; ++i) { 11658 QualType AT = FTP->getParamType(i); 11659 11660 bool mismatch = true; 11661 11662 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11663 mismatch = false; 11664 else if (Expected[i] == CharPP) { 11665 // As an extension, the following forms are okay: 11666 // char const ** 11667 // char const * const * 11668 // char * const * 11669 11670 QualifierCollector qs; 11671 const PointerType* PT; 11672 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11673 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11674 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11675 Context.CharTy)) { 11676 qs.removeConst(); 11677 mismatch = !qs.empty(); 11678 } 11679 } 11680 11681 if (mismatch) { 11682 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11683 // TODO: suggest replacing given type with expected type 11684 FD->setInvalidDecl(true); 11685 } 11686 } 11687 11688 if (nparams == 1 && !FD->isInvalidDecl()) { 11689 Diag(FD->getLocation(), diag::warn_main_one_arg); 11690 } 11691 11692 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11693 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11694 FD->setInvalidDecl(); 11695 } 11696 } 11697 11698 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11699 11700 // Default calling convention for main and wmain is __cdecl 11701 if (FD->getName() == "main" || FD->getName() == "wmain") 11702 return false; 11703 11704 // Default calling convention for MinGW is __cdecl 11705 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11706 if (T.isWindowsGNUEnvironment()) 11707 return false; 11708 11709 // Default calling convention for WinMain, wWinMain and DllMain 11710 // is __stdcall on 32 bit Windows 11711 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11712 return true; 11713 11714 return false; 11715 } 11716 11717 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11718 QualType T = FD->getType(); 11719 assert(T->isFunctionType() && "function decl is not of function type"); 11720 const FunctionType *FT = T->castAs<FunctionType>(); 11721 11722 // Set an implicit return of 'zero' if the function can return some integral, 11723 // enumeration, pointer or nullptr type. 11724 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11725 FT->getReturnType()->isAnyPointerType() || 11726 FT->getReturnType()->isNullPtrType()) 11727 // DllMain is exempt because a return value of zero means it failed. 11728 if (FD->getName() != "DllMain") 11729 FD->setHasImplicitReturnZero(true); 11730 11731 // Explicity specified calling conventions are applied to MSVC entry points 11732 if (!hasExplicitCallingConv(T)) { 11733 if (isDefaultStdCall(FD, *this)) { 11734 if (FT->getCallConv() != CC_X86StdCall) { 11735 FT = Context.adjustFunctionType( 11736 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11737 FD->setType(QualType(FT, 0)); 11738 } 11739 } else if (FT->getCallConv() != CC_C) { 11740 FT = Context.adjustFunctionType(FT, 11741 FT->getExtInfo().withCallingConv(CC_C)); 11742 FD->setType(QualType(FT, 0)); 11743 } 11744 } 11745 11746 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11747 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11748 FD->setInvalidDecl(); 11749 } 11750 } 11751 11752 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11753 // FIXME: Need strict checking. In C89, we need to check for 11754 // any assignment, increment, decrement, function-calls, or 11755 // commas outside of a sizeof. In C99, it's the same list, 11756 // except that the aforementioned are allowed in unevaluated 11757 // expressions. Everything else falls under the 11758 // "may accept other forms of constant expressions" exception. 11759 // 11760 // Regular C++ code will not end up here (exceptions: language extensions, 11761 // OpenCL C++ etc), so the constant expression rules there don't matter. 11762 if (Init->isValueDependent()) { 11763 assert(Init->containsErrors() && 11764 "Dependent code should only occur in error-recovery path."); 11765 return true; 11766 } 11767 const Expr *Culprit; 11768 if (Init->isConstantInitializer(Context, false, &Culprit)) 11769 return false; 11770 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11771 << Culprit->getSourceRange(); 11772 return true; 11773 } 11774 11775 namespace { 11776 // Visits an initialization expression to see if OrigDecl is evaluated in 11777 // its own initialization and throws a warning if it does. 11778 class SelfReferenceChecker 11779 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11780 Sema &S; 11781 Decl *OrigDecl; 11782 bool isRecordType; 11783 bool isPODType; 11784 bool isReferenceType; 11785 11786 bool isInitList; 11787 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11788 11789 public: 11790 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11791 11792 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11793 S(S), OrigDecl(OrigDecl) { 11794 isPODType = false; 11795 isRecordType = false; 11796 isReferenceType = false; 11797 isInitList = false; 11798 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11799 isPODType = VD->getType().isPODType(S.Context); 11800 isRecordType = VD->getType()->isRecordType(); 11801 isReferenceType = VD->getType()->isReferenceType(); 11802 } 11803 } 11804 11805 // For most expressions, just call the visitor. For initializer lists, 11806 // track the index of the field being initialized since fields are 11807 // initialized in order allowing use of previously initialized fields. 11808 void CheckExpr(Expr *E) { 11809 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11810 if (!InitList) { 11811 Visit(E); 11812 return; 11813 } 11814 11815 // Track and increment the index here. 11816 isInitList = true; 11817 InitFieldIndex.push_back(0); 11818 for (auto Child : InitList->children()) { 11819 CheckExpr(cast<Expr>(Child)); 11820 ++InitFieldIndex.back(); 11821 } 11822 InitFieldIndex.pop_back(); 11823 } 11824 11825 // Returns true if MemberExpr is checked and no further checking is needed. 11826 // Returns false if additional checking is required. 11827 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11828 llvm::SmallVector<FieldDecl*, 4> Fields; 11829 Expr *Base = E; 11830 bool ReferenceField = false; 11831 11832 // Get the field members used. 11833 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11834 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11835 if (!FD) 11836 return false; 11837 Fields.push_back(FD); 11838 if (FD->getType()->isReferenceType()) 11839 ReferenceField = true; 11840 Base = ME->getBase()->IgnoreParenImpCasts(); 11841 } 11842 11843 // Keep checking only if the base Decl is the same. 11844 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11845 if (!DRE || DRE->getDecl() != OrigDecl) 11846 return false; 11847 11848 // A reference field can be bound to an unininitialized field. 11849 if (CheckReference && !ReferenceField) 11850 return true; 11851 11852 // Convert FieldDecls to their index number. 11853 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11854 for (const FieldDecl *I : llvm::reverse(Fields)) 11855 UsedFieldIndex.push_back(I->getFieldIndex()); 11856 11857 // See if a warning is needed by checking the first difference in index 11858 // numbers. If field being used has index less than the field being 11859 // initialized, then the use is safe. 11860 for (auto UsedIter = UsedFieldIndex.begin(), 11861 UsedEnd = UsedFieldIndex.end(), 11862 OrigIter = InitFieldIndex.begin(), 11863 OrigEnd = InitFieldIndex.end(); 11864 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11865 if (*UsedIter < *OrigIter) 11866 return true; 11867 if (*UsedIter > *OrigIter) 11868 break; 11869 } 11870 11871 // TODO: Add a different warning which will print the field names. 11872 HandleDeclRefExpr(DRE); 11873 return true; 11874 } 11875 11876 // For most expressions, the cast is directly above the DeclRefExpr. 11877 // For conditional operators, the cast can be outside the conditional 11878 // operator if both expressions are DeclRefExpr's. 11879 void HandleValue(Expr *E) { 11880 E = E->IgnoreParens(); 11881 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11882 HandleDeclRefExpr(DRE); 11883 return; 11884 } 11885 11886 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11887 Visit(CO->getCond()); 11888 HandleValue(CO->getTrueExpr()); 11889 HandleValue(CO->getFalseExpr()); 11890 return; 11891 } 11892 11893 if (BinaryConditionalOperator *BCO = 11894 dyn_cast<BinaryConditionalOperator>(E)) { 11895 Visit(BCO->getCond()); 11896 HandleValue(BCO->getFalseExpr()); 11897 return; 11898 } 11899 11900 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11901 HandleValue(OVE->getSourceExpr()); 11902 return; 11903 } 11904 11905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11906 if (BO->getOpcode() == BO_Comma) { 11907 Visit(BO->getLHS()); 11908 HandleValue(BO->getRHS()); 11909 return; 11910 } 11911 } 11912 11913 if (isa<MemberExpr>(E)) { 11914 if (isInitList) { 11915 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11916 false /*CheckReference*/)) 11917 return; 11918 } 11919 11920 Expr *Base = E->IgnoreParenImpCasts(); 11921 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11922 // Check for static member variables and don't warn on them. 11923 if (!isa<FieldDecl>(ME->getMemberDecl())) 11924 return; 11925 Base = ME->getBase()->IgnoreParenImpCasts(); 11926 } 11927 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11928 HandleDeclRefExpr(DRE); 11929 return; 11930 } 11931 11932 Visit(E); 11933 } 11934 11935 // Reference types not handled in HandleValue are handled here since all 11936 // uses of references are bad, not just r-value uses. 11937 void VisitDeclRefExpr(DeclRefExpr *E) { 11938 if (isReferenceType) 11939 HandleDeclRefExpr(E); 11940 } 11941 11942 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11943 if (E->getCastKind() == CK_LValueToRValue) { 11944 HandleValue(E->getSubExpr()); 11945 return; 11946 } 11947 11948 Inherited::VisitImplicitCastExpr(E); 11949 } 11950 11951 void VisitMemberExpr(MemberExpr *E) { 11952 if (isInitList) { 11953 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11954 return; 11955 } 11956 11957 // Don't warn on arrays since they can be treated as pointers. 11958 if (E->getType()->canDecayToPointerType()) return; 11959 11960 // Warn when a non-static method call is followed by non-static member 11961 // field accesses, which is followed by a DeclRefExpr. 11962 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11963 bool Warn = (MD && !MD->isStatic()); 11964 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11965 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11966 if (!isa<FieldDecl>(ME->getMemberDecl())) 11967 Warn = false; 11968 Base = ME->getBase()->IgnoreParenImpCasts(); 11969 } 11970 11971 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11972 if (Warn) 11973 HandleDeclRefExpr(DRE); 11974 return; 11975 } 11976 11977 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11978 // Visit that expression. 11979 Visit(Base); 11980 } 11981 11982 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11983 Expr *Callee = E->getCallee(); 11984 11985 if (isa<UnresolvedLookupExpr>(Callee)) 11986 return Inherited::VisitCXXOperatorCallExpr(E); 11987 11988 Visit(Callee); 11989 for (auto Arg: E->arguments()) 11990 HandleValue(Arg->IgnoreParenImpCasts()); 11991 } 11992 11993 void VisitUnaryOperator(UnaryOperator *E) { 11994 // For POD record types, addresses of its own members are well-defined. 11995 if (E->getOpcode() == UO_AddrOf && isRecordType && 11996 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11997 if (!isPODType) 11998 HandleValue(E->getSubExpr()); 11999 return; 12000 } 12001 12002 if (E->isIncrementDecrementOp()) { 12003 HandleValue(E->getSubExpr()); 12004 return; 12005 } 12006 12007 Inherited::VisitUnaryOperator(E); 12008 } 12009 12010 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 12011 12012 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12013 if (E->getConstructor()->isCopyConstructor()) { 12014 Expr *ArgExpr = E->getArg(0); 12015 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 12016 if (ILE->getNumInits() == 1) 12017 ArgExpr = ILE->getInit(0); 12018 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 12019 if (ICE->getCastKind() == CK_NoOp) 12020 ArgExpr = ICE->getSubExpr(); 12021 HandleValue(ArgExpr); 12022 return; 12023 } 12024 Inherited::VisitCXXConstructExpr(E); 12025 } 12026 12027 void VisitCallExpr(CallExpr *E) { 12028 // Treat std::move as a use. 12029 if (E->isCallToStdMove()) { 12030 HandleValue(E->getArg(0)); 12031 return; 12032 } 12033 12034 Inherited::VisitCallExpr(E); 12035 } 12036 12037 void VisitBinaryOperator(BinaryOperator *E) { 12038 if (E->isCompoundAssignmentOp()) { 12039 HandleValue(E->getLHS()); 12040 Visit(E->getRHS()); 12041 return; 12042 } 12043 12044 Inherited::VisitBinaryOperator(E); 12045 } 12046 12047 // A custom visitor for BinaryConditionalOperator is needed because the 12048 // regular visitor would check the condition and true expression separately 12049 // but both point to the same place giving duplicate diagnostics. 12050 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 12051 Visit(E->getCond()); 12052 Visit(E->getFalseExpr()); 12053 } 12054 12055 void HandleDeclRefExpr(DeclRefExpr *DRE) { 12056 Decl* ReferenceDecl = DRE->getDecl(); 12057 if (OrigDecl != ReferenceDecl) return; 12058 unsigned diag; 12059 if (isReferenceType) { 12060 diag = diag::warn_uninit_self_reference_in_reference_init; 12061 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 12062 diag = diag::warn_static_self_reference_in_init; 12063 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 12064 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 12065 DRE->getDecl()->getType()->isRecordType()) { 12066 diag = diag::warn_uninit_self_reference_in_init; 12067 } else { 12068 // Local variables will be handled by the CFG analysis. 12069 return; 12070 } 12071 12072 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 12073 S.PDiag(diag) 12074 << DRE->getDecl() << OrigDecl->getLocation() 12075 << DRE->getSourceRange()); 12076 } 12077 }; 12078 12079 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 12080 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 12081 bool DirectInit) { 12082 // Parameters arguments are occassionially constructed with itself, 12083 // for instance, in recursive functions. Skip them. 12084 if (isa<ParmVarDecl>(OrigDecl)) 12085 return; 12086 12087 E = E->IgnoreParens(); 12088 12089 // Skip checking T a = a where T is not a record or reference type. 12090 // Doing so is a way to silence uninitialized warnings. 12091 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 12092 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 12093 if (ICE->getCastKind() == CK_LValueToRValue) 12094 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 12095 if (DRE->getDecl() == OrigDecl) 12096 return; 12097 12098 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 12099 } 12100 } // end anonymous namespace 12101 12102 namespace { 12103 // Simple wrapper to add the name of a variable or (if no variable is 12104 // available) a DeclarationName into a diagnostic. 12105 struct VarDeclOrName { 12106 VarDecl *VDecl; 12107 DeclarationName Name; 12108 12109 friend const Sema::SemaDiagnosticBuilder & 12110 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 12111 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 12112 } 12113 }; 12114 } // end anonymous namespace 12115 12116 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 12117 DeclarationName Name, QualType Type, 12118 TypeSourceInfo *TSI, 12119 SourceRange Range, bool DirectInit, 12120 Expr *Init) { 12121 bool IsInitCapture = !VDecl; 12122 assert((!VDecl || !VDecl->isInitCapture()) && 12123 "init captures are expected to be deduced prior to initialization"); 12124 12125 VarDeclOrName VN{VDecl, Name}; 12126 12127 DeducedType *Deduced = Type->getContainedDeducedType(); 12128 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 12129 12130 // C++11 [dcl.spec.auto]p3 12131 if (!Init) { 12132 assert(VDecl && "no init for init capture deduction?"); 12133 12134 // Except for class argument deduction, and then for an initializing 12135 // declaration only, i.e. no static at class scope or extern. 12136 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 12137 VDecl->hasExternalStorage() || 12138 VDecl->isStaticDataMember()) { 12139 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 12140 << VDecl->getDeclName() << Type; 12141 return QualType(); 12142 } 12143 } 12144 12145 ArrayRef<Expr*> DeduceInits; 12146 if (Init) 12147 DeduceInits = Init; 12148 12149 if (DirectInit) { 12150 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 12151 DeduceInits = PL->exprs(); 12152 } 12153 12154 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 12155 assert(VDecl && "non-auto type for init capture deduction?"); 12156 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12157 InitializationKind Kind = InitializationKind::CreateForInit( 12158 VDecl->getLocation(), DirectInit, Init); 12159 // FIXME: Initialization should not be taking a mutable list of inits. 12160 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 12161 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 12162 InitsCopy); 12163 } 12164 12165 if (DirectInit) { 12166 if (auto *IL = dyn_cast<InitListExpr>(Init)) 12167 DeduceInits = IL->inits(); 12168 } 12169 12170 // Deduction only works if we have exactly one source expression. 12171 if (DeduceInits.empty()) { 12172 // It isn't possible to write this directly, but it is possible to 12173 // end up in this situation with "auto x(some_pack...);" 12174 Diag(Init->getBeginLoc(), IsInitCapture 12175 ? diag::err_init_capture_no_expression 12176 : diag::err_auto_var_init_no_expression) 12177 << VN << Type << Range; 12178 return QualType(); 12179 } 12180 12181 if (DeduceInits.size() > 1) { 12182 Diag(DeduceInits[1]->getBeginLoc(), 12183 IsInitCapture ? diag::err_init_capture_multiple_expressions 12184 : diag::err_auto_var_init_multiple_expressions) 12185 << VN << Type << Range; 12186 return QualType(); 12187 } 12188 12189 Expr *DeduceInit = DeduceInits[0]; 12190 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 12191 Diag(Init->getBeginLoc(), IsInitCapture 12192 ? diag::err_init_capture_paren_braces 12193 : diag::err_auto_var_init_paren_braces) 12194 << isa<InitListExpr>(Init) << VN << Type << Range; 12195 return QualType(); 12196 } 12197 12198 // Expressions default to 'id' when we're in a debugger. 12199 bool DefaultedAnyToId = false; 12200 if (getLangOpts().DebuggerCastResultToId && 12201 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 12202 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12203 if (Result.isInvalid()) { 12204 return QualType(); 12205 } 12206 Init = Result.get(); 12207 DefaultedAnyToId = true; 12208 } 12209 12210 // C++ [dcl.decomp]p1: 12211 // If the assignment-expression [...] has array type A and no ref-qualifier 12212 // is present, e has type cv A 12213 if (VDecl && isa<DecompositionDecl>(VDecl) && 12214 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 12215 DeduceInit->getType()->isConstantArrayType()) 12216 return Context.getQualifiedType(DeduceInit->getType(), 12217 Type.getQualifiers()); 12218 12219 QualType DeducedType; 12220 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 12221 if (!IsInitCapture) 12222 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 12223 else if (isa<InitListExpr>(Init)) 12224 Diag(Range.getBegin(), 12225 diag::err_init_capture_deduction_failure_from_init_list) 12226 << VN 12227 << (DeduceInit->getType().isNull() ? TSI->getType() 12228 : DeduceInit->getType()) 12229 << DeduceInit->getSourceRange(); 12230 else 12231 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 12232 << VN << TSI->getType() 12233 << (DeduceInit->getType().isNull() ? TSI->getType() 12234 : DeduceInit->getType()) 12235 << DeduceInit->getSourceRange(); 12236 } 12237 12238 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 12239 // 'id' instead of a specific object type prevents most of our usual 12240 // checks. 12241 // We only want to warn outside of template instantiations, though: 12242 // inside a template, the 'id' could have come from a parameter. 12243 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 12244 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 12245 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 12246 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 12247 } 12248 12249 return DeducedType; 12250 } 12251 12252 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 12253 Expr *Init) { 12254 assert(!Init || !Init->containsErrors()); 12255 QualType DeducedType = deduceVarTypeFromInitializer( 12256 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 12257 VDecl->getSourceRange(), DirectInit, Init); 12258 if (DeducedType.isNull()) { 12259 VDecl->setInvalidDecl(); 12260 return true; 12261 } 12262 12263 VDecl->setType(DeducedType); 12264 assert(VDecl->isLinkageValid()); 12265 12266 // In ARC, infer lifetime. 12267 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 12268 VDecl->setInvalidDecl(); 12269 12270 if (getLangOpts().OpenCL) 12271 deduceOpenCLAddressSpace(VDecl); 12272 12273 // If this is a redeclaration, check that the type we just deduced matches 12274 // the previously declared type. 12275 if (VarDecl *Old = VDecl->getPreviousDecl()) { 12276 // We never need to merge the type, because we cannot form an incomplete 12277 // array of auto, nor deduce such a type. 12278 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 12279 } 12280 12281 // Check the deduced type is valid for a variable declaration. 12282 CheckVariableDeclarationType(VDecl); 12283 return VDecl->isInvalidDecl(); 12284 } 12285 12286 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 12287 SourceLocation Loc) { 12288 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 12289 Init = EWC->getSubExpr(); 12290 12291 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 12292 Init = CE->getSubExpr(); 12293 12294 QualType InitType = Init->getType(); 12295 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12296 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 12297 "shouldn't be called if type doesn't have a non-trivial C struct"); 12298 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 12299 for (auto I : ILE->inits()) { 12300 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 12301 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12302 continue; 12303 SourceLocation SL = I->getExprLoc(); 12304 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 12305 } 12306 return; 12307 } 12308 12309 if (isa<ImplicitValueInitExpr>(Init)) { 12310 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12311 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 12312 NTCUK_Init); 12313 } else { 12314 // Assume all other explicit initializers involving copying some existing 12315 // object. 12316 // TODO: ignore any explicit initializers where we can guarantee 12317 // copy-elision. 12318 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 12319 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 12320 } 12321 } 12322 12323 namespace { 12324 12325 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 12326 // Ignore unavailable fields. A field can be marked as unavailable explicitly 12327 // in the source code or implicitly by the compiler if it is in a union 12328 // defined in a system header and has non-trivial ObjC ownership 12329 // qualifications. We don't want those fields to participate in determining 12330 // whether the containing union is non-trivial. 12331 return FD->hasAttr<UnavailableAttr>(); 12332 } 12333 12334 struct DiagNonTrivalCUnionDefaultInitializeVisitor 12335 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12336 void> { 12337 using Super = 12338 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12339 void>; 12340 12341 DiagNonTrivalCUnionDefaultInitializeVisitor( 12342 QualType OrigTy, SourceLocation OrigLoc, 12343 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12344 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12345 12346 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 12347 const FieldDecl *FD, bool InNonTrivialUnion) { 12348 if (const auto *AT = S.Context.getAsArrayType(QT)) 12349 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12350 InNonTrivialUnion); 12351 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 12352 } 12353 12354 void visitARCStrong(QualType QT, const FieldDecl *FD, 12355 bool InNonTrivialUnion) { 12356 if (InNonTrivialUnion) 12357 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12358 << 1 << 0 << QT << FD->getName(); 12359 } 12360 12361 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12362 if (InNonTrivialUnion) 12363 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12364 << 1 << 0 << QT << FD->getName(); 12365 } 12366 12367 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12368 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12369 if (RD->isUnion()) { 12370 if (OrigLoc.isValid()) { 12371 bool IsUnion = false; 12372 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12373 IsUnion = OrigRD->isUnion(); 12374 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12375 << 0 << OrigTy << IsUnion << UseContext; 12376 // Reset OrigLoc so that this diagnostic is emitted only once. 12377 OrigLoc = SourceLocation(); 12378 } 12379 InNonTrivialUnion = true; 12380 } 12381 12382 if (InNonTrivialUnion) 12383 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12384 << 0 << 0 << QT.getUnqualifiedType() << ""; 12385 12386 for (const FieldDecl *FD : RD->fields()) 12387 if (!shouldIgnoreForRecordTriviality(FD)) 12388 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12389 } 12390 12391 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12392 12393 // The non-trivial C union type or the struct/union type that contains a 12394 // non-trivial C union. 12395 QualType OrigTy; 12396 SourceLocation OrigLoc; 12397 Sema::NonTrivialCUnionContext UseContext; 12398 Sema &S; 12399 }; 12400 12401 struct DiagNonTrivalCUnionDestructedTypeVisitor 12402 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12403 using Super = 12404 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12405 12406 DiagNonTrivalCUnionDestructedTypeVisitor( 12407 QualType OrigTy, SourceLocation OrigLoc, 12408 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12409 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12410 12411 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12412 const FieldDecl *FD, bool InNonTrivialUnion) { 12413 if (const auto *AT = S.Context.getAsArrayType(QT)) 12414 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12415 InNonTrivialUnion); 12416 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12417 } 12418 12419 void visitARCStrong(QualType QT, const FieldDecl *FD, 12420 bool InNonTrivialUnion) { 12421 if (InNonTrivialUnion) 12422 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12423 << 1 << 1 << QT << FD->getName(); 12424 } 12425 12426 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12427 if (InNonTrivialUnion) 12428 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12429 << 1 << 1 << QT << FD->getName(); 12430 } 12431 12432 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12433 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12434 if (RD->isUnion()) { 12435 if (OrigLoc.isValid()) { 12436 bool IsUnion = false; 12437 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12438 IsUnion = OrigRD->isUnion(); 12439 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12440 << 1 << OrigTy << IsUnion << UseContext; 12441 // Reset OrigLoc so that this diagnostic is emitted only once. 12442 OrigLoc = SourceLocation(); 12443 } 12444 InNonTrivialUnion = true; 12445 } 12446 12447 if (InNonTrivialUnion) 12448 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12449 << 0 << 1 << QT.getUnqualifiedType() << ""; 12450 12451 for (const FieldDecl *FD : RD->fields()) 12452 if (!shouldIgnoreForRecordTriviality(FD)) 12453 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12454 } 12455 12456 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12457 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12458 bool InNonTrivialUnion) {} 12459 12460 // The non-trivial C union type or the struct/union type that contains a 12461 // non-trivial C union. 12462 QualType OrigTy; 12463 SourceLocation OrigLoc; 12464 Sema::NonTrivialCUnionContext UseContext; 12465 Sema &S; 12466 }; 12467 12468 struct DiagNonTrivalCUnionCopyVisitor 12469 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12470 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12471 12472 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12473 Sema::NonTrivialCUnionContext UseContext, 12474 Sema &S) 12475 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12476 12477 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12478 const FieldDecl *FD, bool InNonTrivialUnion) { 12479 if (const auto *AT = S.Context.getAsArrayType(QT)) 12480 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12481 InNonTrivialUnion); 12482 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12483 } 12484 12485 void visitARCStrong(QualType QT, const FieldDecl *FD, 12486 bool InNonTrivialUnion) { 12487 if (InNonTrivialUnion) 12488 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12489 << 1 << 2 << QT << FD->getName(); 12490 } 12491 12492 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12493 if (InNonTrivialUnion) 12494 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12495 << 1 << 2 << QT << FD->getName(); 12496 } 12497 12498 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12499 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12500 if (RD->isUnion()) { 12501 if (OrigLoc.isValid()) { 12502 bool IsUnion = false; 12503 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12504 IsUnion = OrigRD->isUnion(); 12505 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12506 << 2 << OrigTy << IsUnion << UseContext; 12507 // Reset OrigLoc so that this diagnostic is emitted only once. 12508 OrigLoc = SourceLocation(); 12509 } 12510 InNonTrivialUnion = true; 12511 } 12512 12513 if (InNonTrivialUnion) 12514 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12515 << 0 << 2 << QT.getUnqualifiedType() << ""; 12516 12517 for (const FieldDecl *FD : RD->fields()) 12518 if (!shouldIgnoreForRecordTriviality(FD)) 12519 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12520 } 12521 12522 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12523 const FieldDecl *FD, bool InNonTrivialUnion) {} 12524 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12525 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12526 bool InNonTrivialUnion) {} 12527 12528 // The non-trivial C union type or the struct/union type that contains a 12529 // non-trivial C union. 12530 QualType OrigTy; 12531 SourceLocation OrigLoc; 12532 Sema::NonTrivialCUnionContext UseContext; 12533 Sema &S; 12534 }; 12535 12536 } // namespace 12537 12538 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12539 NonTrivialCUnionContext UseContext, 12540 unsigned NonTrivialKind) { 12541 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12542 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12543 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12544 "shouldn't be called if type doesn't have a non-trivial C union"); 12545 12546 if ((NonTrivialKind & NTCUK_Init) && 12547 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12548 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12549 .visit(QT, nullptr, false); 12550 if ((NonTrivialKind & NTCUK_Destruct) && 12551 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12552 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12553 .visit(QT, nullptr, false); 12554 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12555 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12556 .visit(QT, nullptr, false); 12557 } 12558 12559 /// AddInitializerToDecl - Adds the initializer Init to the 12560 /// declaration dcl. If DirectInit is true, this is C++ direct 12561 /// initialization rather than copy initialization. 12562 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12563 // If there is no declaration, there was an error parsing it. Just ignore 12564 // the initializer. 12565 if (!RealDecl || RealDecl->isInvalidDecl()) { 12566 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12567 return; 12568 } 12569 12570 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12571 // Pure-specifiers are handled in ActOnPureSpecifier. 12572 Diag(Method->getLocation(), diag::err_member_function_initialization) 12573 << Method->getDeclName() << Init->getSourceRange(); 12574 Method->setInvalidDecl(); 12575 return; 12576 } 12577 12578 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12579 if (!VDecl) { 12580 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12581 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12582 RealDecl->setInvalidDecl(); 12583 return; 12584 } 12585 12586 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12587 if (VDecl->getType()->isUndeducedType()) { 12588 // Attempt typo correction early so that the type of the init expression can 12589 // be deduced based on the chosen correction if the original init contains a 12590 // TypoExpr. 12591 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12592 if (!Res.isUsable()) { 12593 // There are unresolved typos in Init, just drop them. 12594 // FIXME: improve the recovery strategy to preserve the Init. 12595 RealDecl->setInvalidDecl(); 12596 return; 12597 } 12598 if (Res.get()->containsErrors()) { 12599 // Invalidate the decl as we don't know the type for recovery-expr yet. 12600 RealDecl->setInvalidDecl(); 12601 VDecl->setInit(Res.get()); 12602 return; 12603 } 12604 Init = Res.get(); 12605 12606 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12607 return; 12608 } 12609 12610 // dllimport cannot be used on variable definitions. 12611 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12612 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12613 VDecl->setInvalidDecl(); 12614 return; 12615 } 12616 12617 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12618 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12619 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12620 VDecl->setInvalidDecl(); 12621 return; 12622 } 12623 12624 if (!VDecl->getType()->isDependentType()) { 12625 // A definition must end up with a complete type, which means it must be 12626 // complete with the restriction that an array type might be completed by 12627 // the initializer; note that later code assumes this restriction. 12628 QualType BaseDeclType = VDecl->getType(); 12629 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12630 BaseDeclType = Array->getElementType(); 12631 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12632 diag::err_typecheck_decl_incomplete_type)) { 12633 RealDecl->setInvalidDecl(); 12634 return; 12635 } 12636 12637 // The variable can not have an abstract class type. 12638 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12639 diag::err_abstract_type_in_decl, 12640 AbstractVariableType)) 12641 VDecl->setInvalidDecl(); 12642 } 12643 12644 // If adding the initializer will turn this declaration into a definition, 12645 // and we already have a definition for this variable, diagnose or otherwise 12646 // handle the situation. 12647 if (VarDecl *Def = VDecl->getDefinition()) 12648 if (Def != VDecl && 12649 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12650 !VDecl->isThisDeclarationADemotedDefinition() && 12651 checkVarDeclRedefinition(Def, VDecl)) 12652 return; 12653 12654 if (getLangOpts().CPlusPlus) { 12655 // C++ [class.static.data]p4 12656 // If a static data member is of const integral or const 12657 // enumeration type, its declaration in the class definition can 12658 // specify a constant-initializer which shall be an integral 12659 // constant expression (5.19). In that case, the member can appear 12660 // in integral constant expressions. The member shall still be 12661 // defined in a namespace scope if it is used in the program and the 12662 // namespace scope definition shall not contain an initializer. 12663 // 12664 // We already performed a redefinition check above, but for static 12665 // data members we also need to check whether there was an in-class 12666 // declaration with an initializer. 12667 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12668 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12669 << VDecl->getDeclName(); 12670 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12671 diag::note_previous_initializer) 12672 << 0; 12673 return; 12674 } 12675 12676 if (VDecl->hasLocalStorage()) 12677 setFunctionHasBranchProtectedScope(); 12678 12679 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12680 VDecl->setInvalidDecl(); 12681 return; 12682 } 12683 } 12684 12685 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12686 // a kernel function cannot be initialized." 12687 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12688 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12689 VDecl->setInvalidDecl(); 12690 return; 12691 } 12692 12693 // The LoaderUninitialized attribute acts as a definition (of undef). 12694 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12695 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12696 VDecl->setInvalidDecl(); 12697 return; 12698 } 12699 12700 // Get the decls type and save a reference for later, since 12701 // CheckInitializerTypes may change it. 12702 QualType DclT = VDecl->getType(), SavT = DclT; 12703 12704 // Expressions default to 'id' when we're in a debugger 12705 // and we are assigning it to a variable of Objective-C pointer type. 12706 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12707 Init->getType() == Context.UnknownAnyTy) { 12708 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12709 if (Result.isInvalid()) { 12710 VDecl->setInvalidDecl(); 12711 return; 12712 } 12713 Init = Result.get(); 12714 } 12715 12716 // Perform the initialization. 12717 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12718 if (!VDecl->isInvalidDecl()) { 12719 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12720 InitializationKind Kind = InitializationKind::CreateForInit( 12721 VDecl->getLocation(), DirectInit, Init); 12722 12723 MultiExprArg Args = Init; 12724 if (CXXDirectInit) 12725 Args = MultiExprArg(CXXDirectInit->getExprs(), 12726 CXXDirectInit->getNumExprs()); 12727 12728 // Try to correct any TypoExprs in the initialization arguments. 12729 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12730 ExprResult Res = CorrectDelayedTyposInExpr( 12731 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12732 [this, Entity, Kind](Expr *E) { 12733 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12734 return Init.Failed() ? ExprError() : E; 12735 }); 12736 if (Res.isInvalid()) { 12737 VDecl->setInvalidDecl(); 12738 } else if (Res.get() != Args[Idx]) { 12739 Args[Idx] = Res.get(); 12740 } 12741 } 12742 if (VDecl->isInvalidDecl()) 12743 return; 12744 12745 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12746 /*TopLevelOfInitList=*/false, 12747 /*TreatUnavailableAsInvalid=*/false); 12748 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12749 if (Result.isInvalid()) { 12750 // If the provided initializer fails to initialize the var decl, 12751 // we attach a recovery expr for better recovery. 12752 auto RecoveryExpr = 12753 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12754 if (RecoveryExpr.get()) 12755 VDecl->setInit(RecoveryExpr.get()); 12756 return; 12757 } 12758 12759 Init = Result.getAs<Expr>(); 12760 } 12761 12762 // Check for self-references within variable initializers. 12763 // Variables declared within a function/method body (except for references) 12764 // are handled by a dataflow analysis. 12765 // This is undefined behavior in C++, but valid in C. 12766 if (getLangOpts().CPlusPlus) 12767 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12768 VDecl->getType()->isReferenceType()) 12769 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12770 12771 // If the type changed, it means we had an incomplete type that was 12772 // completed by the initializer. For example: 12773 // int ary[] = { 1, 3, 5 }; 12774 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12775 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12776 VDecl->setType(DclT); 12777 12778 if (!VDecl->isInvalidDecl()) { 12779 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12780 12781 if (VDecl->hasAttr<BlocksAttr>()) 12782 checkRetainCycles(VDecl, Init); 12783 12784 // It is safe to assign a weak reference into a strong variable. 12785 // Although this code can still have problems: 12786 // id x = self.weakProp; 12787 // id y = self.weakProp; 12788 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12789 // paths through the function. This should be revisited if 12790 // -Wrepeated-use-of-weak is made flow-sensitive. 12791 if (FunctionScopeInfo *FSI = getCurFunction()) 12792 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12793 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12794 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12795 Init->getBeginLoc())) 12796 FSI->markSafeWeakUse(Init); 12797 } 12798 12799 // The initialization is usually a full-expression. 12800 // 12801 // FIXME: If this is a braced initialization of an aggregate, it is not 12802 // an expression, and each individual field initializer is a separate 12803 // full-expression. For instance, in: 12804 // 12805 // struct Temp { ~Temp(); }; 12806 // struct S { S(Temp); }; 12807 // struct T { S a, b; } t = { Temp(), Temp() } 12808 // 12809 // we should destroy the first Temp before constructing the second. 12810 ExprResult Result = 12811 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12812 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12813 if (Result.isInvalid()) { 12814 VDecl->setInvalidDecl(); 12815 return; 12816 } 12817 Init = Result.get(); 12818 12819 // Attach the initializer to the decl. 12820 VDecl->setInit(Init); 12821 12822 if (VDecl->isLocalVarDecl()) { 12823 // Don't check the initializer if the declaration is malformed. 12824 if (VDecl->isInvalidDecl()) { 12825 // do nothing 12826 12827 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12828 // This is true even in C++ for OpenCL. 12829 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12830 CheckForConstantInitializer(Init, DclT); 12831 12832 // Otherwise, C++ does not restrict the initializer. 12833 } else if (getLangOpts().CPlusPlus) { 12834 // do nothing 12835 12836 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12837 // static storage duration shall be constant expressions or string literals. 12838 } else if (VDecl->getStorageClass() == SC_Static) { 12839 CheckForConstantInitializer(Init, DclT); 12840 12841 // C89 is stricter than C99 for aggregate initializers. 12842 // C89 6.5.7p3: All the expressions [...] in an initializer list 12843 // for an object that has aggregate or union type shall be 12844 // constant expressions. 12845 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12846 isa<InitListExpr>(Init)) { 12847 const Expr *Culprit; 12848 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12849 Diag(Culprit->getExprLoc(), 12850 diag::ext_aggregate_init_not_constant) 12851 << Culprit->getSourceRange(); 12852 } 12853 } 12854 12855 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12856 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12857 if (VDecl->hasLocalStorage()) 12858 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12859 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12860 VDecl->getLexicalDeclContext()->isRecord()) { 12861 // This is an in-class initialization for a static data member, e.g., 12862 // 12863 // struct S { 12864 // static const int value = 17; 12865 // }; 12866 12867 // C++ [class.mem]p4: 12868 // A member-declarator can contain a constant-initializer only 12869 // if it declares a static member (9.4) of const integral or 12870 // const enumeration type, see 9.4.2. 12871 // 12872 // C++11 [class.static.data]p3: 12873 // If a non-volatile non-inline const static data member is of integral 12874 // or enumeration type, its declaration in the class definition can 12875 // specify a brace-or-equal-initializer in which every initializer-clause 12876 // that is an assignment-expression is a constant expression. A static 12877 // data member of literal type can be declared in the class definition 12878 // with the constexpr specifier; if so, its declaration shall specify a 12879 // brace-or-equal-initializer in which every initializer-clause that is 12880 // an assignment-expression is a constant expression. 12881 12882 // Do nothing on dependent types. 12883 if (DclT->isDependentType()) { 12884 12885 // Allow any 'static constexpr' members, whether or not they are of literal 12886 // type. We separately check that every constexpr variable is of literal 12887 // type. 12888 } else if (VDecl->isConstexpr()) { 12889 12890 // Require constness. 12891 } else if (!DclT.isConstQualified()) { 12892 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12893 << Init->getSourceRange(); 12894 VDecl->setInvalidDecl(); 12895 12896 // We allow integer constant expressions in all cases. 12897 } else if (DclT->isIntegralOrEnumerationType()) { 12898 // Check whether the expression is a constant expression. 12899 SourceLocation Loc; 12900 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12901 // In C++11, a non-constexpr const static data member with an 12902 // in-class initializer cannot be volatile. 12903 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12904 else if (Init->isValueDependent()) 12905 ; // Nothing to check. 12906 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12907 ; // Ok, it's an ICE! 12908 else if (Init->getType()->isScopedEnumeralType() && 12909 Init->isCXX11ConstantExpr(Context)) 12910 ; // Ok, it is a scoped-enum constant expression. 12911 else if (Init->isEvaluatable(Context)) { 12912 // If we can constant fold the initializer through heroics, accept it, 12913 // but report this as a use of an extension for -pedantic. 12914 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12915 << Init->getSourceRange(); 12916 } else { 12917 // Otherwise, this is some crazy unknown case. Report the issue at the 12918 // location provided by the isIntegerConstantExpr failed check. 12919 Diag(Loc, diag::err_in_class_initializer_non_constant) 12920 << Init->getSourceRange(); 12921 VDecl->setInvalidDecl(); 12922 } 12923 12924 // We allow foldable floating-point constants as an extension. 12925 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12926 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12927 // it anyway and provide a fixit to add the 'constexpr'. 12928 if (getLangOpts().CPlusPlus11) { 12929 Diag(VDecl->getLocation(), 12930 diag::ext_in_class_initializer_float_type_cxx11) 12931 << DclT << Init->getSourceRange(); 12932 Diag(VDecl->getBeginLoc(), 12933 diag::note_in_class_initializer_float_type_cxx11) 12934 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12935 } else { 12936 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12937 << DclT << Init->getSourceRange(); 12938 12939 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12940 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12941 << Init->getSourceRange(); 12942 VDecl->setInvalidDecl(); 12943 } 12944 } 12945 12946 // Suggest adding 'constexpr' in C++11 for literal types. 12947 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12948 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12949 << DclT << Init->getSourceRange() 12950 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12951 VDecl->setConstexpr(true); 12952 12953 } else { 12954 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12955 << DclT << Init->getSourceRange(); 12956 VDecl->setInvalidDecl(); 12957 } 12958 } else if (VDecl->isFileVarDecl()) { 12959 // In C, extern is typically used to avoid tentative definitions when 12960 // declaring variables in headers, but adding an intializer makes it a 12961 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12962 // In C++, extern is often used to give implictly static const variables 12963 // external linkage, so don't warn in that case. If selectany is present, 12964 // this might be header code intended for C and C++ inclusion, so apply the 12965 // C++ rules. 12966 if (VDecl->getStorageClass() == SC_Extern && 12967 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12968 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12969 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12970 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12971 Diag(VDecl->getLocation(), diag::warn_extern_init); 12972 12973 // In Microsoft C++ mode, a const variable defined in namespace scope has 12974 // external linkage by default if the variable is declared with 12975 // __declspec(dllexport). 12976 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12977 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12978 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12979 VDecl->setStorageClass(SC_Extern); 12980 12981 // C99 6.7.8p4. All file scoped initializers need to be constant. 12982 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12983 CheckForConstantInitializer(Init, DclT); 12984 } 12985 12986 QualType InitType = Init->getType(); 12987 if (!InitType.isNull() && 12988 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12989 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12990 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12991 12992 // We will represent direct-initialization similarly to copy-initialization: 12993 // int x(1); -as-> int x = 1; 12994 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12995 // 12996 // Clients that want to distinguish between the two forms, can check for 12997 // direct initializer using VarDecl::getInitStyle(). 12998 // A major benefit is that clients that don't particularly care about which 12999 // exactly form was it (like the CodeGen) can handle both cases without 13000 // special case code. 13001 13002 // C++ 8.5p11: 13003 // The form of initialization (using parentheses or '=') is generally 13004 // insignificant, but does matter when the entity being initialized has a 13005 // class type. 13006 if (CXXDirectInit) { 13007 assert(DirectInit && "Call-style initializer must be direct init."); 13008 VDecl->setInitStyle(VarDecl::CallInit); 13009 } else if (DirectInit) { 13010 // This must be list-initialization. No other way is direct-initialization. 13011 VDecl->setInitStyle(VarDecl::ListInit); 13012 } 13013 13014 if (LangOpts.OpenMP && 13015 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 13016 VDecl->isFileVarDecl()) 13017 DeclsToCheckForDeferredDiags.insert(VDecl); 13018 CheckCompleteVariableDeclaration(VDecl); 13019 } 13020 13021 /// ActOnInitializerError - Given that there was an error parsing an 13022 /// initializer for the given declaration, try to at least re-establish 13023 /// invariants such as whether a variable's type is either dependent or 13024 /// complete. 13025 void Sema::ActOnInitializerError(Decl *D) { 13026 // Our main concern here is re-establishing invariants like "a 13027 // variable's type is either dependent or complete". 13028 if (!D || D->isInvalidDecl()) return; 13029 13030 VarDecl *VD = dyn_cast<VarDecl>(D); 13031 if (!VD) return; 13032 13033 // Bindings are not usable if we can't make sense of the initializer. 13034 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 13035 for (auto *BD : DD->bindings()) 13036 BD->setInvalidDecl(); 13037 13038 // Auto types are meaningless if we can't make sense of the initializer. 13039 if (VD->getType()->isUndeducedType()) { 13040 D->setInvalidDecl(); 13041 return; 13042 } 13043 13044 QualType Ty = VD->getType(); 13045 if (Ty->isDependentType()) return; 13046 13047 // Require a complete type. 13048 if (RequireCompleteType(VD->getLocation(), 13049 Context.getBaseElementType(Ty), 13050 diag::err_typecheck_decl_incomplete_type)) { 13051 VD->setInvalidDecl(); 13052 return; 13053 } 13054 13055 // Require a non-abstract type. 13056 if (RequireNonAbstractType(VD->getLocation(), Ty, 13057 diag::err_abstract_type_in_decl, 13058 AbstractVariableType)) { 13059 VD->setInvalidDecl(); 13060 return; 13061 } 13062 13063 // Don't bother complaining about constructors or destructors, 13064 // though. 13065 } 13066 13067 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 13068 // If there is no declaration, there was an error parsing it. Just ignore it. 13069 if (!RealDecl) 13070 return; 13071 13072 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 13073 QualType Type = Var->getType(); 13074 13075 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 13076 if (isa<DecompositionDecl>(RealDecl)) { 13077 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 13078 Var->setInvalidDecl(); 13079 return; 13080 } 13081 13082 if (Type->isUndeducedType() && 13083 DeduceVariableDeclarationType(Var, false, nullptr)) 13084 return; 13085 13086 // C++11 [class.static.data]p3: A static data member can be declared with 13087 // the constexpr specifier; if so, its declaration shall specify 13088 // a brace-or-equal-initializer. 13089 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 13090 // the definition of a variable [...] or the declaration of a static data 13091 // member. 13092 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 13093 !Var->isThisDeclarationADemotedDefinition()) { 13094 if (Var->isStaticDataMember()) { 13095 // C++1z removes the relevant rule; the in-class declaration is always 13096 // a definition there. 13097 if (!getLangOpts().CPlusPlus17 && 13098 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13099 Diag(Var->getLocation(), 13100 diag::err_constexpr_static_mem_var_requires_init) 13101 << Var; 13102 Var->setInvalidDecl(); 13103 return; 13104 } 13105 } else { 13106 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 13107 Var->setInvalidDecl(); 13108 return; 13109 } 13110 } 13111 13112 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 13113 // be initialized. 13114 if (!Var->isInvalidDecl() && 13115 Var->getType().getAddressSpace() == LangAS::opencl_constant && 13116 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 13117 bool HasConstExprDefaultConstructor = false; 13118 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13119 for (auto *Ctor : RD->ctors()) { 13120 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 13121 Ctor->getMethodQualifiers().getAddressSpace() == 13122 LangAS::opencl_constant) { 13123 HasConstExprDefaultConstructor = true; 13124 } 13125 } 13126 } 13127 if (!HasConstExprDefaultConstructor) { 13128 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 13129 Var->setInvalidDecl(); 13130 return; 13131 } 13132 } 13133 13134 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 13135 if (Var->getStorageClass() == SC_Extern) { 13136 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 13137 << Var; 13138 Var->setInvalidDecl(); 13139 return; 13140 } 13141 if (RequireCompleteType(Var->getLocation(), Var->getType(), 13142 diag::err_typecheck_decl_incomplete_type)) { 13143 Var->setInvalidDecl(); 13144 return; 13145 } 13146 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13147 if (!RD->hasTrivialDefaultConstructor()) { 13148 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 13149 Var->setInvalidDecl(); 13150 return; 13151 } 13152 } 13153 // The declaration is unitialized, no need for further checks. 13154 return; 13155 } 13156 13157 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 13158 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 13159 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13160 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 13161 NTCUC_DefaultInitializedObject, NTCUK_Init); 13162 13163 13164 switch (DefKind) { 13165 case VarDecl::Definition: 13166 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 13167 break; 13168 13169 // We have an out-of-line definition of a static data member 13170 // that has an in-class initializer, so we type-check this like 13171 // a declaration. 13172 // 13173 LLVM_FALLTHROUGH; 13174 13175 case VarDecl::DeclarationOnly: 13176 // It's only a declaration. 13177 13178 // Block scope. C99 6.7p7: If an identifier for an object is 13179 // declared with no linkage (C99 6.2.2p6), the type for the 13180 // object shall be complete. 13181 if (!Type->isDependentType() && Var->isLocalVarDecl() && 13182 !Var->hasLinkage() && !Var->isInvalidDecl() && 13183 RequireCompleteType(Var->getLocation(), Type, 13184 diag::err_typecheck_decl_incomplete_type)) 13185 Var->setInvalidDecl(); 13186 13187 // Make sure that the type is not abstract. 13188 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13189 RequireNonAbstractType(Var->getLocation(), Type, 13190 diag::err_abstract_type_in_decl, 13191 AbstractVariableType)) 13192 Var->setInvalidDecl(); 13193 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13194 Var->getStorageClass() == SC_PrivateExtern) { 13195 Diag(Var->getLocation(), diag::warn_private_extern); 13196 Diag(Var->getLocation(), diag::note_private_extern); 13197 } 13198 13199 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 13200 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 13201 ExternalDeclarations.push_back(Var); 13202 13203 return; 13204 13205 case VarDecl::TentativeDefinition: 13206 // File scope. C99 6.9.2p2: A declaration of an identifier for an 13207 // object that has file scope without an initializer, and without a 13208 // storage-class specifier or with the storage-class specifier "static", 13209 // constitutes a tentative definition. Note: A tentative definition with 13210 // external linkage is valid (C99 6.2.2p5). 13211 if (!Var->isInvalidDecl()) { 13212 if (const IncompleteArrayType *ArrayT 13213 = Context.getAsIncompleteArrayType(Type)) { 13214 if (RequireCompleteSizedType( 13215 Var->getLocation(), ArrayT->getElementType(), 13216 diag::err_array_incomplete_or_sizeless_type)) 13217 Var->setInvalidDecl(); 13218 } else if (Var->getStorageClass() == SC_Static) { 13219 // C99 6.9.2p3: If the declaration of an identifier for an object is 13220 // a tentative definition and has internal linkage (C99 6.2.2p3), the 13221 // declared type shall not be an incomplete type. 13222 // NOTE: code such as the following 13223 // static struct s; 13224 // struct s { int a; }; 13225 // is accepted by gcc. Hence here we issue a warning instead of 13226 // an error and we do not invalidate the static declaration. 13227 // NOTE: to avoid multiple warnings, only check the first declaration. 13228 if (Var->isFirstDecl()) 13229 RequireCompleteType(Var->getLocation(), Type, 13230 diag::ext_typecheck_decl_incomplete_type); 13231 } 13232 } 13233 13234 // Record the tentative definition; we're done. 13235 if (!Var->isInvalidDecl()) 13236 TentativeDefinitions.push_back(Var); 13237 return; 13238 } 13239 13240 // Provide a specific diagnostic for uninitialized variable 13241 // definitions with incomplete array type. 13242 if (Type->isIncompleteArrayType()) { 13243 Diag(Var->getLocation(), 13244 diag::err_typecheck_incomplete_array_needs_initializer); 13245 Var->setInvalidDecl(); 13246 return; 13247 } 13248 13249 // Provide a specific diagnostic for uninitialized variable 13250 // definitions with reference type. 13251 if (Type->isReferenceType()) { 13252 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 13253 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 13254 return; 13255 } 13256 13257 // Do not attempt to type-check the default initializer for a 13258 // variable with dependent type. 13259 if (Type->isDependentType()) 13260 return; 13261 13262 if (Var->isInvalidDecl()) 13263 return; 13264 13265 if (!Var->hasAttr<AliasAttr>()) { 13266 if (RequireCompleteType(Var->getLocation(), 13267 Context.getBaseElementType(Type), 13268 diag::err_typecheck_decl_incomplete_type)) { 13269 Var->setInvalidDecl(); 13270 return; 13271 } 13272 } else { 13273 return; 13274 } 13275 13276 // The variable can not have an abstract class type. 13277 if (RequireNonAbstractType(Var->getLocation(), Type, 13278 diag::err_abstract_type_in_decl, 13279 AbstractVariableType)) { 13280 Var->setInvalidDecl(); 13281 return; 13282 } 13283 13284 // Check for jumps past the implicit initializer. C++0x 13285 // clarifies that this applies to a "variable with automatic 13286 // storage duration", not a "local variable". 13287 // C++11 [stmt.dcl]p3 13288 // A program that jumps from a point where a variable with automatic 13289 // storage duration is not in scope to a point where it is in scope is 13290 // ill-formed unless the variable has scalar type, class type with a 13291 // trivial default constructor and a trivial destructor, a cv-qualified 13292 // version of one of these types, or an array of one of the preceding 13293 // types and is declared without an initializer. 13294 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 13295 if (const RecordType *Record 13296 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 13297 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 13298 // Mark the function (if we're in one) for further checking even if the 13299 // looser rules of C++11 do not require such checks, so that we can 13300 // diagnose incompatibilities with C++98. 13301 if (!CXXRecord->isPOD()) 13302 setFunctionHasBranchProtectedScope(); 13303 } 13304 } 13305 // In OpenCL, we can't initialize objects in the __local address space, 13306 // even implicitly, so don't synthesize an implicit initializer. 13307 if (getLangOpts().OpenCL && 13308 Var->getType().getAddressSpace() == LangAS::opencl_local) 13309 return; 13310 // C++03 [dcl.init]p9: 13311 // If no initializer is specified for an object, and the 13312 // object is of (possibly cv-qualified) non-POD class type (or 13313 // array thereof), the object shall be default-initialized; if 13314 // the object is of const-qualified type, the underlying class 13315 // type shall have a user-declared default 13316 // constructor. Otherwise, if no initializer is specified for 13317 // a non- static object, the object and its subobjects, if 13318 // any, have an indeterminate initial value); if the object 13319 // or any of its subobjects are of const-qualified type, the 13320 // program is ill-formed. 13321 // C++0x [dcl.init]p11: 13322 // If no initializer is specified for an object, the object is 13323 // default-initialized; [...]. 13324 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 13325 InitializationKind Kind 13326 = InitializationKind::CreateDefault(Var->getLocation()); 13327 13328 InitializationSequence InitSeq(*this, Entity, Kind, None); 13329 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 13330 13331 if (Init.get()) { 13332 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 13333 // This is important for template substitution. 13334 Var->setInitStyle(VarDecl::CallInit); 13335 } else if (Init.isInvalid()) { 13336 // If default-init fails, attach a recovery-expr initializer to track 13337 // that initialization was attempted and failed. 13338 auto RecoveryExpr = 13339 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 13340 if (RecoveryExpr.get()) 13341 Var->setInit(RecoveryExpr.get()); 13342 } 13343 13344 CheckCompleteVariableDeclaration(Var); 13345 } 13346 } 13347 13348 void Sema::ActOnCXXForRangeDecl(Decl *D) { 13349 // If there is no declaration, there was an error parsing it. Ignore it. 13350 if (!D) 13351 return; 13352 13353 VarDecl *VD = dyn_cast<VarDecl>(D); 13354 if (!VD) { 13355 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 13356 D->setInvalidDecl(); 13357 return; 13358 } 13359 13360 VD->setCXXForRangeDecl(true); 13361 13362 // for-range-declaration cannot be given a storage class specifier. 13363 int Error = -1; 13364 switch (VD->getStorageClass()) { 13365 case SC_None: 13366 break; 13367 case SC_Extern: 13368 Error = 0; 13369 break; 13370 case SC_Static: 13371 Error = 1; 13372 break; 13373 case SC_PrivateExtern: 13374 Error = 2; 13375 break; 13376 case SC_Auto: 13377 Error = 3; 13378 break; 13379 case SC_Register: 13380 Error = 4; 13381 break; 13382 } 13383 13384 // for-range-declaration cannot be given a storage class specifier con't. 13385 switch (VD->getTSCSpec()) { 13386 case TSCS_thread_local: 13387 Error = 6; 13388 break; 13389 case TSCS___thread: 13390 case TSCS__Thread_local: 13391 case TSCS_unspecified: 13392 break; 13393 } 13394 13395 if (Error != -1) { 13396 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 13397 << VD << Error; 13398 D->setInvalidDecl(); 13399 } 13400 } 13401 13402 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13403 IdentifierInfo *Ident, 13404 ParsedAttributes &Attrs) { 13405 // C++1y [stmt.iter]p1: 13406 // A range-based for statement of the form 13407 // for ( for-range-identifier : for-range-initializer ) statement 13408 // is equivalent to 13409 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13410 DeclSpec DS(Attrs.getPool().getFactory()); 13411 13412 const char *PrevSpec; 13413 unsigned DiagID; 13414 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13415 getPrintingPolicy()); 13416 13417 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit); 13418 D.SetIdentifier(Ident, IdentLoc); 13419 D.takeAttributes(Attrs); 13420 13421 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13422 IdentLoc); 13423 Decl *Var = ActOnDeclarator(S, D); 13424 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13425 FinalizeDeclaration(Var); 13426 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13427 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 13428 : IdentLoc); 13429 } 13430 13431 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13432 if (var->isInvalidDecl()) return; 13433 13434 MaybeAddCUDAConstantAttr(var); 13435 13436 if (getLangOpts().OpenCL) { 13437 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13438 // initialiser 13439 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13440 !var->hasInit()) { 13441 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13442 << 1 /*Init*/; 13443 var->setInvalidDecl(); 13444 return; 13445 } 13446 } 13447 13448 // In Objective-C, don't allow jumps past the implicit initialization of a 13449 // local retaining variable. 13450 if (getLangOpts().ObjC && 13451 var->hasLocalStorage()) { 13452 switch (var->getType().getObjCLifetime()) { 13453 case Qualifiers::OCL_None: 13454 case Qualifiers::OCL_ExplicitNone: 13455 case Qualifiers::OCL_Autoreleasing: 13456 break; 13457 13458 case Qualifiers::OCL_Weak: 13459 case Qualifiers::OCL_Strong: 13460 setFunctionHasBranchProtectedScope(); 13461 break; 13462 } 13463 } 13464 13465 if (var->hasLocalStorage() && 13466 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13467 setFunctionHasBranchProtectedScope(); 13468 13469 // Warn about externally-visible variables being defined without a 13470 // prior declaration. We only want to do this for global 13471 // declarations, but we also specifically need to avoid doing it for 13472 // class members because the linkage of an anonymous class can 13473 // change if it's later given a typedef name. 13474 if (var->isThisDeclarationADefinition() && 13475 var->getDeclContext()->getRedeclContext()->isFileContext() && 13476 var->isExternallyVisible() && var->hasLinkage() && 13477 !var->isInline() && !var->getDescribedVarTemplate() && 13478 !isa<VarTemplatePartialSpecializationDecl>(var) && 13479 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13480 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13481 var->getLocation())) { 13482 // Find a previous declaration that's not a definition. 13483 VarDecl *prev = var->getPreviousDecl(); 13484 while (prev && prev->isThisDeclarationADefinition()) 13485 prev = prev->getPreviousDecl(); 13486 13487 if (!prev) { 13488 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13489 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13490 << /* variable */ 0; 13491 } 13492 } 13493 13494 // Cache the result of checking for constant initialization. 13495 Optional<bool> CacheHasConstInit; 13496 const Expr *CacheCulprit = nullptr; 13497 auto checkConstInit = [&]() mutable { 13498 if (!CacheHasConstInit) 13499 CacheHasConstInit = var->getInit()->isConstantInitializer( 13500 Context, var->getType()->isReferenceType(), &CacheCulprit); 13501 return *CacheHasConstInit; 13502 }; 13503 13504 if (var->getTLSKind() == VarDecl::TLS_Static) { 13505 if (var->getType().isDestructedType()) { 13506 // GNU C++98 edits for __thread, [basic.start.term]p3: 13507 // The type of an object with thread storage duration shall not 13508 // have a non-trivial destructor. 13509 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13510 if (getLangOpts().CPlusPlus11) 13511 Diag(var->getLocation(), diag::note_use_thread_local); 13512 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13513 if (!checkConstInit()) { 13514 // GNU C++98 edits for __thread, [basic.start.init]p4: 13515 // An object of thread storage duration shall not require dynamic 13516 // initialization. 13517 // FIXME: Need strict checking here. 13518 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13519 << CacheCulprit->getSourceRange(); 13520 if (getLangOpts().CPlusPlus11) 13521 Diag(var->getLocation(), diag::note_use_thread_local); 13522 } 13523 } 13524 } 13525 13526 13527 if (!var->getType()->isStructureType() && var->hasInit() && 13528 isa<InitListExpr>(var->getInit())) { 13529 const auto *ILE = cast<InitListExpr>(var->getInit()); 13530 unsigned NumInits = ILE->getNumInits(); 13531 if (NumInits > 2) 13532 for (unsigned I = 0; I < NumInits; ++I) { 13533 const auto *Init = ILE->getInit(I); 13534 if (!Init) 13535 break; 13536 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13537 if (!SL) 13538 break; 13539 13540 unsigned NumConcat = SL->getNumConcatenated(); 13541 // Diagnose missing comma in string array initialization. 13542 // Do not warn when all the elements in the initializer are concatenated 13543 // together. Do not warn for macros too. 13544 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13545 bool OnlyOneMissingComma = true; 13546 for (unsigned J = I + 1; J < NumInits; ++J) { 13547 const auto *Init = ILE->getInit(J); 13548 if (!Init) 13549 break; 13550 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13551 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13552 OnlyOneMissingComma = false; 13553 break; 13554 } 13555 } 13556 13557 if (OnlyOneMissingComma) { 13558 SmallVector<FixItHint, 1> Hints; 13559 for (unsigned i = 0; i < NumConcat - 1; ++i) 13560 Hints.push_back(FixItHint::CreateInsertion( 13561 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13562 13563 Diag(SL->getStrTokenLoc(1), 13564 diag::warn_concatenated_literal_array_init) 13565 << Hints; 13566 Diag(SL->getBeginLoc(), 13567 diag::note_concatenated_string_literal_silence); 13568 } 13569 // In any case, stop now. 13570 break; 13571 } 13572 } 13573 } 13574 13575 13576 QualType type = var->getType(); 13577 13578 if (var->hasAttr<BlocksAttr>()) 13579 getCurFunction()->addByrefBlockVar(var); 13580 13581 Expr *Init = var->getInit(); 13582 bool GlobalStorage = var->hasGlobalStorage(); 13583 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13584 QualType baseType = Context.getBaseElementType(type); 13585 bool HasConstInit = true; 13586 13587 // Check whether the initializer is sufficiently constant. 13588 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13589 !Init->isValueDependent() && 13590 (GlobalStorage || var->isConstexpr() || 13591 var->mightBeUsableInConstantExpressions(Context))) { 13592 // If this variable might have a constant initializer or might be usable in 13593 // constant expressions, check whether or not it actually is now. We can't 13594 // do this lazily, because the result might depend on things that change 13595 // later, such as which constexpr functions happen to be defined. 13596 SmallVector<PartialDiagnosticAt, 8> Notes; 13597 if (!getLangOpts().CPlusPlus11) { 13598 // Prior to C++11, in contexts where a constant initializer is required, 13599 // the set of valid constant initializers is described by syntactic rules 13600 // in [expr.const]p2-6. 13601 // FIXME: Stricter checking for these rules would be useful for constinit / 13602 // -Wglobal-constructors. 13603 HasConstInit = checkConstInit(); 13604 13605 // Compute and cache the constant value, and remember that we have a 13606 // constant initializer. 13607 if (HasConstInit) { 13608 (void)var->checkForConstantInitialization(Notes); 13609 Notes.clear(); 13610 } else if (CacheCulprit) { 13611 Notes.emplace_back(CacheCulprit->getExprLoc(), 13612 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13613 Notes.back().second << CacheCulprit->getSourceRange(); 13614 } 13615 } else { 13616 // Evaluate the initializer to see if it's a constant initializer. 13617 HasConstInit = var->checkForConstantInitialization(Notes); 13618 } 13619 13620 if (HasConstInit) { 13621 // FIXME: Consider replacing the initializer with a ConstantExpr. 13622 } else if (var->isConstexpr()) { 13623 SourceLocation DiagLoc = var->getLocation(); 13624 // If the note doesn't add any useful information other than a source 13625 // location, fold it into the primary diagnostic. 13626 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13627 diag::note_invalid_subexpr_in_const_expr) { 13628 DiagLoc = Notes[0].first; 13629 Notes.clear(); 13630 } 13631 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13632 << var << Init->getSourceRange(); 13633 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13634 Diag(Notes[I].first, Notes[I].second); 13635 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13636 auto *Attr = var->getAttr<ConstInitAttr>(); 13637 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13638 << Init->getSourceRange(); 13639 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13640 << Attr->getRange() << Attr->isConstinit(); 13641 for (auto &it : Notes) 13642 Diag(it.first, it.second); 13643 } else if (IsGlobal && 13644 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13645 var->getLocation())) { 13646 // Warn about globals which don't have a constant initializer. Don't 13647 // warn about globals with a non-trivial destructor because we already 13648 // warned about them. 13649 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13650 if (!(RD && !RD->hasTrivialDestructor())) { 13651 // checkConstInit() here permits trivial default initialization even in 13652 // C++11 onwards, where such an initializer is not a constant initializer 13653 // but nonetheless doesn't require a global constructor. 13654 if (!checkConstInit()) 13655 Diag(var->getLocation(), diag::warn_global_constructor) 13656 << Init->getSourceRange(); 13657 } 13658 } 13659 } 13660 13661 // Apply section attributes and pragmas to global variables. 13662 if (GlobalStorage && var->isThisDeclarationADefinition() && 13663 !inTemplateInstantiation()) { 13664 PragmaStack<StringLiteral *> *Stack = nullptr; 13665 int SectionFlags = ASTContext::PSF_Read; 13666 if (var->getType().isConstQualified()) { 13667 if (HasConstInit) 13668 Stack = &ConstSegStack; 13669 else { 13670 Stack = &BSSSegStack; 13671 SectionFlags |= ASTContext::PSF_Write; 13672 } 13673 } else if (var->hasInit() && HasConstInit) { 13674 Stack = &DataSegStack; 13675 SectionFlags |= ASTContext::PSF_Write; 13676 } else { 13677 Stack = &BSSSegStack; 13678 SectionFlags |= ASTContext::PSF_Write; 13679 } 13680 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13681 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13682 SectionFlags |= ASTContext::PSF_Implicit; 13683 UnifySection(SA->getName(), SectionFlags, var); 13684 } else if (Stack->CurrentValue) { 13685 SectionFlags |= ASTContext::PSF_Implicit; 13686 auto SectionName = Stack->CurrentValue->getString(); 13687 var->addAttr(SectionAttr::CreateImplicit( 13688 Context, SectionName, Stack->CurrentPragmaLocation, 13689 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13690 if (UnifySection(SectionName, SectionFlags, var)) 13691 var->dropAttr<SectionAttr>(); 13692 } 13693 13694 // Apply the init_seg attribute if this has an initializer. If the 13695 // initializer turns out to not be dynamic, we'll end up ignoring this 13696 // attribute. 13697 if (CurInitSeg && var->getInit()) 13698 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13699 CurInitSegLoc, 13700 AttributeCommonInfo::AS_Pragma)); 13701 } 13702 13703 // All the following checks are C++ only. 13704 if (!getLangOpts().CPlusPlus) { 13705 // If this variable must be emitted, add it as an initializer for the 13706 // current module. 13707 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13708 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13709 return; 13710 } 13711 13712 // Require the destructor. 13713 if (!type->isDependentType()) 13714 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13715 FinalizeVarWithDestructor(var, recordType); 13716 13717 // If this variable must be emitted, add it as an initializer for the current 13718 // module. 13719 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13720 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13721 13722 // Build the bindings if this is a structured binding declaration. 13723 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13724 CheckCompleteDecompositionDeclaration(DD); 13725 } 13726 13727 /// Check if VD needs to be dllexport/dllimport due to being in a 13728 /// dllexport/import function. 13729 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13730 assert(VD->isStaticLocal()); 13731 13732 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13733 13734 // Find outermost function when VD is in lambda function. 13735 while (FD && !getDLLAttr(FD) && 13736 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13737 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13738 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13739 } 13740 13741 if (!FD) 13742 return; 13743 13744 // Static locals inherit dll attributes from their function. 13745 if (Attr *A = getDLLAttr(FD)) { 13746 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13747 NewAttr->setInherited(true); 13748 VD->addAttr(NewAttr); 13749 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13750 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13751 NewAttr->setInherited(true); 13752 VD->addAttr(NewAttr); 13753 13754 // Export this function to enforce exporting this static variable even 13755 // if it is not used in this compilation unit. 13756 if (!FD->hasAttr<DLLExportAttr>()) 13757 FD->addAttr(NewAttr); 13758 13759 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13760 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13761 NewAttr->setInherited(true); 13762 VD->addAttr(NewAttr); 13763 } 13764 } 13765 13766 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13767 /// any semantic actions necessary after any initializer has been attached. 13768 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13769 // Note that we are no longer parsing the initializer for this declaration. 13770 ParsingInitForAutoVars.erase(ThisDecl); 13771 13772 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13773 if (!VD) 13774 return; 13775 13776 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13777 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13778 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13779 if (PragmaClangBSSSection.Valid) 13780 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13781 Context, PragmaClangBSSSection.SectionName, 13782 PragmaClangBSSSection.PragmaLocation, 13783 AttributeCommonInfo::AS_Pragma)); 13784 if (PragmaClangDataSection.Valid) 13785 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13786 Context, PragmaClangDataSection.SectionName, 13787 PragmaClangDataSection.PragmaLocation, 13788 AttributeCommonInfo::AS_Pragma)); 13789 if (PragmaClangRodataSection.Valid) 13790 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13791 Context, PragmaClangRodataSection.SectionName, 13792 PragmaClangRodataSection.PragmaLocation, 13793 AttributeCommonInfo::AS_Pragma)); 13794 if (PragmaClangRelroSection.Valid) 13795 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13796 Context, PragmaClangRelroSection.SectionName, 13797 PragmaClangRelroSection.PragmaLocation, 13798 AttributeCommonInfo::AS_Pragma)); 13799 } 13800 13801 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13802 for (auto *BD : DD->bindings()) { 13803 FinalizeDeclaration(BD); 13804 } 13805 } 13806 13807 checkAttributesAfterMerging(*this, *VD); 13808 13809 // Perform TLS alignment check here after attributes attached to the variable 13810 // which may affect the alignment have been processed. Only perform the check 13811 // if the target has a maximum TLS alignment (zero means no constraints). 13812 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13813 // Protect the check so that it's not performed on dependent types and 13814 // dependent alignments (we can't determine the alignment in that case). 13815 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13816 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13817 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13818 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13819 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13820 << (unsigned)MaxAlignChars.getQuantity(); 13821 } 13822 } 13823 } 13824 13825 if (VD->isStaticLocal()) 13826 CheckStaticLocalForDllExport(VD); 13827 13828 // Perform check for initializers of device-side global variables. 13829 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13830 // 7.5). We must also apply the same checks to all __shared__ 13831 // variables whether they are local or not. CUDA also allows 13832 // constant initializers for __constant__ and __device__ variables. 13833 if (getLangOpts().CUDA) 13834 checkAllowedCUDAInitializer(VD); 13835 13836 // Grab the dllimport or dllexport attribute off of the VarDecl. 13837 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13838 13839 // Imported static data members cannot be defined out-of-line. 13840 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13841 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13842 VD->isThisDeclarationADefinition()) { 13843 // We allow definitions of dllimport class template static data members 13844 // with a warning. 13845 CXXRecordDecl *Context = 13846 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13847 bool IsClassTemplateMember = 13848 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13849 Context->getDescribedClassTemplate(); 13850 13851 Diag(VD->getLocation(), 13852 IsClassTemplateMember 13853 ? diag::warn_attribute_dllimport_static_field_definition 13854 : diag::err_attribute_dllimport_static_field_definition); 13855 Diag(IA->getLocation(), diag::note_attribute); 13856 if (!IsClassTemplateMember) 13857 VD->setInvalidDecl(); 13858 } 13859 } 13860 13861 // dllimport/dllexport variables cannot be thread local, their TLS index 13862 // isn't exported with the variable. 13863 if (DLLAttr && VD->getTLSKind()) { 13864 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13865 if (F && getDLLAttr(F)) { 13866 assert(VD->isStaticLocal()); 13867 // But if this is a static local in a dlimport/dllexport function, the 13868 // function will never be inlined, which means the var would never be 13869 // imported, so having it marked import/export is safe. 13870 } else { 13871 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13872 << DLLAttr; 13873 VD->setInvalidDecl(); 13874 } 13875 } 13876 13877 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13878 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13879 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13880 << Attr; 13881 VD->dropAttr<UsedAttr>(); 13882 } 13883 } 13884 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13885 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13886 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13887 << Attr; 13888 VD->dropAttr<RetainAttr>(); 13889 } 13890 } 13891 13892 const DeclContext *DC = VD->getDeclContext(); 13893 // If there's a #pragma GCC visibility in scope, and this isn't a class 13894 // member, set the visibility of this variable. 13895 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13896 AddPushedVisibilityAttribute(VD); 13897 13898 // FIXME: Warn on unused var template partial specializations. 13899 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13900 MarkUnusedFileScopedDecl(VD); 13901 13902 // Now we have parsed the initializer and can update the table of magic 13903 // tag values. 13904 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13905 !VD->getType()->isIntegralOrEnumerationType()) 13906 return; 13907 13908 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13909 const Expr *MagicValueExpr = VD->getInit(); 13910 if (!MagicValueExpr) { 13911 continue; 13912 } 13913 Optional<llvm::APSInt> MagicValueInt; 13914 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13915 Diag(I->getRange().getBegin(), 13916 diag::err_type_tag_for_datatype_not_ice) 13917 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13918 continue; 13919 } 13920 if (MagicValueInt->getActiveBits() > 64) { 13921 Diag(I->getRange().getBegin(), 13922 diag::err_type_tag_for_datatype_too_large) 13923 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13924 continue; 13925 } 13926 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13927 RegisterTypeTagForDatatype(I->getArgumentKind(), 13928 MagicValue, 13929 I->getMatchingCType(), 13930 I->getLayoutCompatible(), 13931 I->getMustBeNull()); 13932 } 13933 } 13934 13935 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13936 auto *VD = dyn_cast<VarDecl>(DD); 13937 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13938 } 13939 13940 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13941 ArrayRef<Decl *> Group) { 13942 SmallVector<Decl*, 8> Decls; 13943 13944 if (DS.isTypeSpecOwned()) 13945 Decls.push_back(DS.getRepAsDecl()); 13946 13947 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13948 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13949 bool DiagnosedMultipleDecomps = false; 13950 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13951 bool DiagnosedNonDeducedAuto = false; 13952 13953 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13954 if (Decl *D = Group[i]) { 13955 // For declarators, there are some additional syntactic-ish checks we need 13956 // to perform. 13957 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13958 if (!FirstDeclaratorInGroup) 13959 FirstDeclaratorInGroup = DD; 13960 if (!FirstDecompDeclaratorInGroup) 13961 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13962 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13963 !hasDeducedAuto(DD)) 13964 FirstNonDeducedAutoInGroup = DD; 13965 13966 if (FirstDeclaratorInGroup != DD) { 13967 // A decomposition declaration cannot be combined with any other 13968 // declaration in the same group. 13969 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13970 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13971 diag::err_decomp_decl_not_alone) 13972 << FirstDeclaratorInGroup->getSourceRange() 13973 << DD->getSourceRange(); 13974 DiagnosedMultipleDecomps = true; 13975 } 13976 13977 // A declarator that uses 'auto' in any way other than to declare a 13978 // variable with a deduced type cannot be combined with any other 13979 // declarator in the same group. 13980 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13981 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13982 diag::err_auto_non_deduced_not_alone) 13983 << FirstNonDeducedAutoInGroup->getType() 13984 ->hasAutoForTrailingReturnType() 13985 << FirstDeclaratorInGroup->getSourceRange() 13986 << DD->getSourceRange(); 13987 DiagnosedNonDeducedAuto = true; 13988 } 13989 } 13990 } 13991 13992 Decls.push_back(D); 13993 } 13994 } 13995 13996 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13997 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13998 handleTagNumbering(Tag, S); 13999 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 14000 getLangOpts().CPlusPlus) 14001 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 14002 } 14003 } 14004 14005 return BuildDeclaratorGroup(Decls); 14006 } 14007 14008 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 14009 /// group, performing any necessary semantic checking. 14010 Sema::DeclGroupPtrTy 14011 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 14012 // C++14 [dcl.spec.auto]p7: (DR1347) 14013 // If the type that replaces the placeholder type is not the same in each 14014 // deduction, the program is ill-formed. 14015 if (Group.size() > 1) { 14016 QualType Deduced; 14017 VarDecl *DeducedDecl = nullptr; 14018 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 14019 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 14020 if (!D || D->isInvalidDecl()) 14021 break; 14022 DeducedType *DT = D->getType()->getContainedDeducedType(); 14023 if (!DT || DT->getDeducedType().isNull()) 14024 continue; 14025 if (Deduced.isNull()) { 14026 Deduced = DT->getDeducedType(); 14027 DeducedDecl = D; 14028 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 14029 auto *AT = dyn_cast<AutoType>(DT); 14030 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 14031 diag::err_auto_different_deductions) 14032 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 14033 << DeducedDecl->getDeclName() << DT->getDeducedType() 14034 << D->getDeclName(); 14035 if (DeducedDecl->hasInit()) 14036 Dia << DeducedDecl->getInit()->getSourceRange(); 14037 if (D->getInit()) 14038 Dia << D->getInit()->getSourceRange(); 14039 D->setInvalidDecl(); 14040 break; 14041 } 14042 } 14043 } 14044 14045 ActOnDocumentableDecls(Group); 14046 14047 return DeclGroupPtrTy::make( 14048 DeclGroupRef::Create(Context, Group.data(), Group.size())); 14049 } 14050 14051 void Sema::ActOnDocumentableDecl(Decl *D) { 14052 ActOnDocumentableDecls(D); 14053 } 14054 14055 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 14056 // Don't parse the comment if Doxygen diagnostics are ignored. 14057 if (Group.empty() || !Group[0]) 14058 return; 14059 14060 if (Diags.isIgnored(diag::warn_doc_param_not_found, 14061 Group[0]->getLocation()) && 14062 Diags.isIgnored(diag::warn_unknown_comment_command_name, 14063 Group[0]->getLocation())) 14064 return; 14065 14066 if (Group.size() >= 2) { 14067 // This is a decl group. Normally it will contain only declarations 14068 // produced from declarator list. But in case we have any definitions or 14069 // additional declaration references: 14070 // 'typedef struct S {} S;' 14071 // 'typedef struct S *S;' 14072 // 'struct S *pS;' 14073 // FinalizeDeclaratorGroup adds these as separate declarations. 14074 Decl *MaybeTagDecl = Group[0]; 14075 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 14076 Group = Group.slice(1); 14077 } 14078 } 14079 14080 // FIMXE: We assume every Decl in the group is in the same file. 14081 // This is false when preprocessor constructs the group from decls in 14082 // different files (e. g. macros or #include). 14083 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 14084 } 14085 14086 /// Common checks for a parameter-declaration that should apply to both function 14087 /// parameters and non-type template parameters. 14088 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 14089 // Check that there are no default arguments inside the type of this 14090 // parameter. 14091 if (getLangOpts().CPlusPlus) 14092 CheckExtraCXXDefaultArguments(D); 14093 14094 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 14095 if (D.getCXXScopeSpec().isSet()) { 14096 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 14097 << D.getCXXScopeSpec().getRange(); 14098 } 14099 14100 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 14101 // simple identifier except [...irrelevant cases...]. 14102 switch (D.getName().getKind()) { 14103 case UnqualifiedIdKind::IK_Identifier: 14104 break; 14105 14106 case UnqualifiedIdKind::IK_OperatorFunctionId: 14107 case UnqualifiedIdKind::IK_ConversionFunctionId: 14108 case UnqualifiedIdKind::IK_LiteralOperatorId: 14109 case UnqualifiedIdKind::IK_ConstructorName: 14110 case UnqualifiedIdKind::IK_DestructorName: 14111 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14112 case UnqualifiedIdKind::IK_DeductionGuideName: 14113 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 14114 << GetNameForDeclarator(D).getName(); 14115 break; 14116 14117 case UnqualifiedIdKind::IK_TemplateId: 14118 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14119 // GetNameForDeclarator would not produce a useful name in this case. 14120 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 14121 break; 14122 } 14123 } 14124 14125 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 14126 /// to introduce parameters into function prototype scope. 14127 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 14128 const DeclSpec &DS = D.getDeclSpec(); 14129 14130 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 14131 14132 // C++03 [dcl.stc]p2 also permits 'auto'. 14133 StorageClass SC = SC_None; 14134 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 14135 SC = SC_Register; 14136 // In C++11, the 'register' storage class specifier is deprecated. 14137 // In C++17, it is not allowed, but we tolerate it as an extension. 14138 if (getLangOpts().CPlusPlus11) { 14139 Diag(DS.getStorageClassSpecLoc(), 14140 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 14141 : diag::warn_deprecated_register) 14142 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 14143 } 14144 } else if (getLangOpts().CPlusPlus && 14145 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 14146 SC = SC_Auto; 14147 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 14148 Diag(DS.getStorageClassSpecLoc(), 14149 diag::err_invalid_storage_class_in_func_decl); 14150 D.getMutableDeclSpec().ClearStorageClassSpecs(); 14151 } 14152 14153 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 14154 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 14155 << DeclSpec::getSpecifierName(TSCS); 14156 if (DS.isInlineSpecified()) 14157 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 14158 << getLangOpts().CPlusPlus17; 14159 if (DS.hasConstexprSpecifier()) 14160 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 14161 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 14162 14163 DiagnoseFunctionSpecifiers(DS); 14164 14165 CheckFunctionOrTemplateParamDeclarator(S, D); 14166 14167 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14168 QualType parmDeclType = TInfo->getType(); 14169 14170 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 14171 IdentifierInfo *II = D.getIdentifier(); 14172 if (II) { 14173 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 14174 ForVisibleRedeclaration); 14175 LookupName(R, S); 14176 if (R.isSingleResult()) { 14177 NamedDecl *PrevDecl = R.getFoundDecl(); 14178 if (PrevDecl->isTemplateParameter()) { 14179 // Maybe we will complain about the shadowed template parameter. 14180 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14181 // Just pretend that we didn't see the previous declaration. 14182 PrevDecl = nullptr; 14183 } else if (S->isDeclScope(PrevDecl)) { 14184 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 14185 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14186 14187 // Recover by removing the name 14188 II = nullptr; 14189 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 14190 D.setInvalidType(true); 14191 } 14192 } 14193 } 14194 14195 // Temporarily put parameter variables in the translation unit, not 14196 // the enclosing context. This prevents them from accidentally 14197 // looking like class members in C++. 14198 ParmVarDecl *New = 14199 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 14200 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 14201 14202 if (D.isInvalidType()) 14203 New->setInvalidDecl(); 14204 14205 assert(S->isFunctionPrototypeScope()); 14206 assert(S->getFunctionPrototypeDepth() >= 1); 14207 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 14208 S->getNextFunctionPrototypeIndex()); 14209 14210 // Add the parameter declaration into this scope. 14211 S->AddDecl(New); 14212 if (II) 14213 IdResolver.AddDecl(New); 14214 14215 ProcessDeclAttributes(S, New, D); 14216 14217 if (D.getDeclSpec().isModulePrivateSpecified()) 14218 Diag(New->getLocation(), diag::err_module_private_local) 14219 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14220 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14221 14222 if (New->hasAttr<BlocksAttr>()) { 14223 Diag(New->getLocation(), diag::err_block_on_nonlocal); 14224 } 14225 14226 if (getLangOpts().OpenCL) 14227 deduceOpenCLAddressSpace(New); 14228 14229 return New; 14230 } 14231 14232 /// Synthesizes a variable for a parameter arising from a 14233 /// typedef. 14234 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 14235 SourceLocation Loc, 14236 QualType T) { 14237 /* FIXME: setting StartLoc == Loc. 14238 Would it be worth to modify callers so as to provide proper source 14239 location for the unnamed parameters, embedding the parameter's type? */ 14240 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 14241 T, Context.getTrivialTypeSourceInfo(T, Loc), 14242 SC_None, nullptr); 14243 Param->setImplicit(); 14244 return Param; 14245 } 14246 14247 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 14248 // Don't diagnose unused-parameter errors in template instantiations; we 14249 // will already have done so in the template itself. 14250 if (inTemplateInstantiation()) 14251 return; 14252 14253 for (const ParmVarDecl *Parameter : Parameters) { 14254 if (!Parameter->isReferenced() && Parameter->getDeclName() && 14255 !Parameter->hasAttr<UnusedAttr>()) { 14256 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 14257 << Parameter->getDeclName(); 14258 } 14259 } 14260 } 14261 14262 void Sema::DiagnoseSizeOfParametersAndReturnValue( 14263 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 14264 if (LangOpts.NumLargeByValueCopy == 0) // No check. 14265 return; 14266 14267 // Warn if the return value is pass-by-value and larger than the specified 14268 // threshold. 14269 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 14270 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 14271 if (Size > LangOpts.NumLargeByValueCopy) 14272 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 14273 } 14274 14275 // Warn if any parameter is pass-by-value and larger than the specified 14276 // threshold. 14277 for (const ParmVarDecl *Parameter : Parameters) { 14278 QualType T = Parameter->getType(); 14279 if (T->isDependentType() || !T.isPODType(Context)) 14280 continue; 14281 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 14282 if (Size > LangOpts.NumLargeByValueCopy) 14283 Diag(Parameter->getLocation(), diag::warn_parameter_size) 14284 << Parameter << Size; 14285 } 14286 } 14287 14288 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 14289 SourceLocation NameLoc, IdentifierInfo *Name, 14290 QualType T, TypeSourceInfo *TSInfo, 14291 StorageClass SC) { 14292 // In ARC, infer a lifetime qualifier for appropriate parameter types. 14293 if (getLangOpts().ObjCAutoRefCount && 14294 T.getObjCLifetime() == Qualifiers::OCL_None && 14295 T->isObjCLifetimeType()) { 14296 14297 Qualifiers::ObjCLifetime lifetime; 14298 14299 // Special cases for arrays: 14300 // - if it's const, use __unsafe_unretained 14301 // - otherwise, it's an error 14302 if (T->isArrayType()) { 14303 if (!T.isConstQualified()) { 14304 if (DelayedDiagnostics.shouldDelayDiagnostics()) 14305 DelayedDiagnostics.add( 14306 sema::DelayedDiagnostic::makeForbiddenType( 14307 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 14308 else 14309 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 14310 << TSInfo->getTypeLoc().getSourceRange(); 14311 } 14312 lifetime = Qualifiers::OCL_ExplicitNone; 14313 } else { 14314 lifetime = T->getObjCARCImplicitLifetime(); 14315 } 14316 T = Context.getLifetimeQualifiedType(T, lifetime); 14317 } 14318 14319 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 14320 Context.getAdjustedParameterType(T), 14321 TSInfo, SC, nullptr); 14322 14323 // Make a note if we created a new pack in the scope of a lambda, so that 14324 // we know that references to that pack must also be expanded within the 14325 // lambda scope. 14326 if (New->isParameterPack()) 14327 if (auto *LSI = getEnclosingLambda()) 14328 LSI->LocalPacks.push_back(New); 14329 14330 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 14331 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14332 checkNonTrivialCUnion(New->getType(), New->getLocation(), 14333 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 14334 14335 // Parameters can not be abstract class types. 14336 // For record types, this is done by the AbstractClassUsageDiagnoser once 14337 // the class has been completely parsed. 14338 if (!CurContext->isRecord() && 14339 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 14340 AbstractParamType)) 14341 New->setInvalidDecl(); 14342 14343 // Parameter declarators cannot be interface types. All ObjC objects are 14344 // passed by reference. 14345 if (T->isObjCObjectType()) { 14346 SourceLocation TypeEndLoc = 14347 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 14348 Diag(NameLoc, 14349 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 14350 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 14351 T = Context.getObjCObjectPointerType(T); 14352 New->setType(T); 14353 } 14354 14355 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 14356 // duration shall not be qualified by an address-space qualifier." 14357 // Since all parameters have automatic store duration, they can not have 14358 // an address space. 14359 if (T.getAddressSpace() != LangAS::Default && 14360 // OpenCL allows function arguments declared to be an array of a type 14361 // to be qualified with an address space. 14362 !(getLangOpts().OpenCL && 14363 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 14364 Diag(NameLoc, diag::err_arg_with_address_space); 14365 New->setInvalidDecl(); 14366 } 14367 14368 // PPC MMA non-pointer types are not allowed as function argument types. 14369 if (Context.getTargetInfo().getTriple().isPPC64() && 14370 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 14371 New->setInvalidDecl(); 14372 } 14373 14374 return New; 14375 } 14376 14377 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 14378 SourceLocation LocAfterDecls) { 14379 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 14380 14381 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration 14382 // in the declaration list shall have at least one declarator, those 14383 // declarators shall only declare identifiers from the identifier list, and 14384 // every identifier in the identifier list shall be declared. 14385 // 14386 // C89 3.7.1p5 "If a declarator includes an identifier list, only the 14387 // identifiers it names shall be declared in the declaration list." 14388 // 14389 // This is why we only diagnose in C99 and later. Note, the other conditions 14390 // listed are checked elsewhere. 14391 if (!FTI.hasPrototype) { 14392 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 14393 --i; 14394 if (FTI.Params[i].Param == nullptr) { 14395 if (getLangOpts().C99) { 14396 SmallString<256> Code; 14397 llvm::raw_svector_ostream(Code) 14398 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 14399 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 14400 << FTI.Params[i].Ident 14401 << FixItHint::CreateInsertion(LocAfterDecls, Code); 14402 } 14403 14404 // Implicitly declare the argument as type 'int' for lack of a better 14405 // type. 14406 AttributeFactory attrs; 14407 DeclSpec DS(attrs); 14408 const char* PrevSpec; // unused 14409 unsigned DiagID; // unused 14410 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14411 DiagID, Context.getPrintingPolicy()); 14412 // Use the identifier location for the type source range. 14413 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14414 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14415 Declarator ParamD(DS, ParsedAttributesView::none(), 14416 DeclaratorContext::KNRTypeList); 14417 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14418 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14419 } 14420 } 14421 } 14422 } 14423 14424 Decl * 14425 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14426 MultiTemplateParamsArg TemplateParameterLists, 14427 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { 14428 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14429 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14430 Scope *ParentScope = FnBodyScope->getParent(); 14431 14432 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14433 // we define a non-templated function definition, we will create a declaration 14434 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14435 // The base function declaration will have the equivalent of an `omp declare 14436 // variant` annotation which specifies the mangled definition as a 14437 // specialization function under the OpenMP context defined as part of the 14438 // `omp begin declare variant`. 14439 SmallVector<FunctionDecl *, 4> Bases; 14440 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14441 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14442 ParentScope, D, TemplateParameterLists, Bases); 14443 14444 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14445 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14446 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind); 14447 14448 if (!Bases.empty()) 14449 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14450 14451 return Dcl; 14452 } 14453 14454 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14455 Consumer.HandleInlineFunctionDefinition(D); 14456 } 14457 14458 static bool 14459 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14460 const FunctionDecl *&PossiblePrototype) { 14461 // Don't warn about invalid declarations. 14462 if (FD->isInvalidDecl()) 14463 return false; 14464 14465 // Or declarations that aren't global. 14466 if (!FD->isGlobal()) 14467 return false; 14468 14469 // Don't warn about C++ member functions. 14470 if (isa<CXXMethodDecl>(FD)) 14471 return false; 14472 14473 // Don't warn about 'main'. 14474 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14475 if (IdentifierInfo *II = FD->getIdentifier()) 14476 if (II->isStr("main") || II->isStr("efi_main")) 14477 return false; 14478 14479 // Don't warn about inline functions. 14480 if (FD->isInlined()) 14481 return false; 14482 14483 // Don't warn about function templates. 14484 if (FD->getDescribedFunctionTemplate()) 14485 return false; 14486 14487 // Don't warn about function template specializations. 14488 if (FD->isFunctionTemplateSpecialization()) 14489 return false; 14490 14491 // Don't warn for OpenCL kernels. 14492 if (FD->hasAttr<OpenCLKernelAttr>()) 14493 return false; 14494 14495 // Don't warn on explicitly deleted functions. 14496 if (FD->isDeleted()) 14497 return false; 14498 14499 // Don't warn on implicitly local functions (such as having local-typed 14500 // parameters). 14501 if (!FD->isExternallyVisible()) 14502 return false; 14503 14504 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14505 Prev; Prev = Prev->getPreviousDecl()) { 14506 // Ignore any declarations that occur in function or method 14507 // scope, because they aren't visible from the header. 14508 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14509 continue; 14510 14511 PossiblePrototype = Prev; 14512 return Prev->getType()->isFunctionNoProtoType(); 14513 } 14514 14515 return true; 14516 } 14517 14518 void 14519 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14520 const FunctionDecl *EffectiveDefinition, 14521 SkipBodyInfo *SkipBody) { 14522 const FunctionDecl *Definition = EffectiveDefinition; 14523 if (!Definition && 14524 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14525 return; 14526 14527 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14528 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14529 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14530 // A merged copy of the same function, instantiated as a member of 14531 // the same class, is OK. 14532 if (declaresSameEntity(OrigFD, OrigDef) && 14533 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14534 cast<Decl>(FD->getLexicalDeclContext()))) 14535 return; 14536 } 14537 } 14538 } 14539 14540 if (canRedefineFunction(Definition, getLangOpts())) 14541 return; 14542 14543 // Don't emit an error when this is redefinition of a typo-corrected 14544 // definition. 14545 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14546 return; 14547 14548 // If we don't have a visible definition of the function, and it's inline or 14549 // a template, skip the new definition. 14550 if (SkipBody && !hasVisibleDefinition(Definition) && 14551 (Definition->getFormalLinkage() == InternalLinkage || 14552 Definition->isInlined() || 14553 Definition->getDescribedFunctionTemplate() || 14554 Definition->getNumTemplateParameterLists())) { 14555 SkipBody->ShouldSkip = true; 14556 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14557 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14558 makeMergedDefinitionVisible(TD); 14559 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14560 return; 14561 } 14562 14563 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14564 Definition->getStorageClass() == SC_Extern) 14565 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14566 << FD << getLangOpts().CPlusPlus; 14567 else 14568 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14569 14570 Diag(Definition->getLocation(), diag::note_previous_definition); 14571 FD->setInvalidDecl(); 14572 } 14573 14574 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14575 Sema &S) { 14576 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14577 14578 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14579 LSI->CallOperator = CallOperator; 14580 LSI->Lambda = LambdaClass; 14581 LSI->ReturnType = CallOperator->getReturnType(); 14582 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14583 14584 if (LCD == LCD_None) 14585 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14586 else if (LCD == LCD_ByCopy) 14587 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14588 else if (LCD == LCD_ByRef) 14589 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14590 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14591 14592 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14593 LSI->Mutable = !CallOperator->isConst(); 14594 14595 // Add the captures to the LSI so they can be noted as already 14596 // captured within tryCaptureVar. 14597 auto I = LambdaClass->field_begin(); 14598 for (const auto &C : LambdaClass->captures()) { 14599 if (C.capturesVariable()) { 14600 VarDecl *VD = C.getCapturedVar(); 14601 if (VD->isInitCapture()) 14602 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14603 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14604 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14605 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14606 /*EllipsisLoc*/C.isPackExpansion() 14607 ? C.getEllipsisLoc() : SourceLocation(), 14608 I->getType(), /*Invalid*/false); 14609 14610 } else if (C.capturesThis()) { 14611 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14612 C.getCaptureKind() == LCK_StarThis); 14613 } else { 14614 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14615 I->getType()); 14616 } 14617 ++I; 14618 } 14619 } 14620 14621 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14622 SkipBodyInfo *SkipBody, 14623 FnBodyKind BodyKind) { 14624 if (!D) { 14625 // Parsing the function declaration failed in some way. Push on a fake scope 14626 // anyway so we can try to parse the function body. 14627 PushFunctionScope(); 14628 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14629 return D; 14630 } 14631 14632 FunctionDecl *FD = nullptr; 14633 14634 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14635 FD = FunTmpl->getTemplatedDecl(); 14636 else 14637 FD = cast<FunctionDecl>(D); 14638 14639 // Do not push if it is a lambda because one is already pushed when building 14640 // the lambda in ActOnStartOfLambdaDefinition(). 14641 if (!isLambdaCallOperator(FD)) 14642 PushExpressionEvaluationContext( 14643 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14644 : ExprEvalContexts.back().Context); 14645 14646 // Check for defining attributes before the check for redefinition. 14647 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14648 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14649 FD->dropAttr<AliasAttr>(); 14650 FD->setInvalidDecl(); 14651 } 14652 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14653 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14654 FD->dropAttr<IFuncAttr>(); 14655 FD->setInvalidDecl(); 14656 } 14657 14658 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14659 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14660 Ctor->isDefaultConstructor() && 14661 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14662 // If this is an MS ABI dllexport default constructor, instantiate any 14663 // default arguments. 14664 InstantiateDefaultCtorDefaultArgs(Ctor); 14665 } 14666 } 14667 14668 // See if this is a redefinition. If 'will have body' (or similar) is already 14669 // set, then these checks were already performed when it was set. 14670 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14671 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14672 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14673 14674 // If we're skipping the body, we're done. Don't enter the scope. 14675 if (SkipBody && SkipBody->ShouldSkip) 14676 return D; 14677 } 14678 14679 // Mark this function as "will have a body eventually". This lets users to 14680 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14681 // this function. 14682 FD->setWillHaveBody(); 14683 14684 // If we are instantiating a generic lambda call operator, push 14685 // a LambdaScopeInfo onto the function stack. But use the information 14686 // that's already been calculated (ActOnLambdaExpr) to prime the current 14687 // LambdaScopeInfo. 14688 // When the template operator is being specialized, the LambdaScopeInfo, 14689 // has to be properly restored so that tryCaptureVariable doesn't try 14690 // and capture any new variables. In addition when calculating potential 14691 // captures during transformation of nested lambdas, it is necessary to 14692 // have the LSI properly restored. 14693 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14694 assert(inTemplateInstantiation() && 14695 "There should be an active template instantiation on the stack " 14696 "when instantiating a generic lambda!"); 14697 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14698 } else { 14699 // Enter a new function scope 14700 PushFunctionScope(); 14701 } 14702 14703 // Builtin functions cannot be defined. 14704 if (unsigned BuiltinID = FD->getBuiltinID()) { 14705 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14706 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14707 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14708 FD->setInvalidDecl(); 14709 } 14710 } 14711 14712 // The return type of a function definition must be complete (C99 6.9.1p3), 14713 // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2) 14714 QualType ResultType = FD->getReturnType(); 14715 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14716 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && 14717 RequireCompleteType(FD->getLocation(), ResultType, 14718 diag::err_func_def_incomplete_result)) 14719 FD->setInvalidDecl(); 14720 14721 if (FnBodyScope) 14722 PushDeclContext(FnBodyScope, FD); 14723 14724 // Check the validity of our function parameters 14725 if (BodyKind != FnBodyKind::Delete) 14726 CheckParmsForFunctionDef(FD->parameters(), 14727 /*CheckParameterNames=*/true); 14728 14729 // Add non-parameter declarations already in the function to the current 14730 // scope. 14731 if (FnBodyScope) { 14732 for (Decl *NPD : FD->decls()) { 14733 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14734 if (!NonParmDecl) 14735 continue; 14736 assert(!isa<ParmVarDecl>(NonParmDecl) && 14737 "parameters should not be in newly created FD yet"); 14738 14739 // If the decl has a name, make it accessible in the current scope. 14740 if (NonParmDecl->getDeclName()) 14741 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14742 14743 // Similarly, dive into enums and fish their constants out, making them 14744 // accessible in this scope. 14745 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14746 for (auto *EI : ED->enumerators()) 14747 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14748 } 14749 } 14750 } 14751 14752 // Introduce our parameters into the function scope 14753 for (auto Param : FD->parameters()) { 14754 Param->setOwningFunction(FD); 14755 14756 // If this has an identifier, add it to the scope stack. 14757 if (Param->getIdentifier() && FnBodyScope) { 14758 CheckShadow(FnBodyScope, Param); 14759 14760 PushOnScopeChains(Param, FnBodyScope); 14761 } 14762 } 14763 14764 // Ensure that the function's exception specification is instantiated. 14765 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14766 ResolveExceptionSpec(D->getLocation(), FPT); 14767 14768 // dllimport cannot be applied to non-inline function definitions. 14769 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14770 !FD->isTemplateInstantiation()) { 14771 assert(!FD->hasAttr<DLLExportAttr>()); 14772 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14773 FD->setInvalidDecl(); 14774 return D; 14775 } 14776 // We want to attach documentation to original Decl (which might be 14777 // a function template). 14778 ActOnDocumentableDecl(D); 14779 if (getCurLexicalContext()->isObjCContainer() && 14780 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14781 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14782 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14783 14784 return D; 14785 } 14786 14787 /// Given the set of return statements within a function body, 14788 /// compute the variables that are subject to the named return value 14789 /// optimization. 14790 /// 14791 /// Each of the variables that is subject to the named return value 14792 /// optimization will be marked as NRVO variables in the AST, and any 14793 /// return statement that has a marked NRVO variable as its NRVO candidate can 14794 /// use the named return value optimization. 14795 /// 14796 /// This function applies a very simplistic algorithm for NRVO: if every return 14797 /// statement in the scope of a variable has the same NRVO candidate, that 14798 /// candidate is an NRVO variable. 14799 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14800 ReturnStmt **Returns = Scope->Returns.data(); 14801 14802 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14803 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14804 if (!NRVOCandidate->isNRVOVariable()) 14805 Returns[I]->setNRVOCandidate(nullptr); 14806 } 14807 } 14808 } 14809 14810 bool Sema::canDelayFunctionBody(const Declarator &D) { 14811 // We can't delay parsing the body of a constexpr function template (yet). 14812 if (D.getDeclSpec().hasConstexprSpecifier()) 14813 return false; 14814 14815 // We can't delay parsing the body of a function template with a deduced 14816 // return type (yet). 14817 if (D.getDeclSpec().hasAutoTypeSpec()) { 14818 // If the placeholder introduces a non-deduced trailing return type, 14819 // we can still delay parsing it. 14820 if (D.getNumTypeObjects()) { 14821 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14822 if (Outer.Kind == DeclaratorChunk::Function && 14823 Outer.Fun.hasTrailingReturnType()) { 14824 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14825 return Ty.isNull() || !Ty->isUndeducedType(); 14826 } 14827 } 14828 return false; 14829 } 14830 14831 return true; 14832 } 14833 14834 bool Sema::canSkipFunctionBody(Decl *D) { 14835 // We cannot skip the body of a function (or function template) which is 14836 // constexpr, since we may need to evaluate its body in order to parse the 14837 // rest of the file. 14838 // We cannot skip the body of a function with an undeduced return type, 14839 // because any callers of that function need to know the type. 14840 if (const FunctionDecl *FD = D->getAsFunction()) { 14841 if (FD->isConstexpr()) 14842 return false; 14843 // We can't simply call Type::isUndeducedType here, because inside template 14844 // auto can be deduced to a dependent type, which is not considered 14845 // "undeduced". 14846 if (FD->getReturnType()->getContainedDeducedType()) 14847 return false; 14848 } 14849 return Consumer.shouldSkipFunctionBody(D); 14850 } 14851 14852 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14853 if (!Decl) 14854 return nullptr; 14855 if (FunctionDecl *FD = Decl->getAsFunction()) 14856 FD->setHasSkippedBody(); 14857 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14858 MD->setHasSkippedBody(); 14859 return Decl; 14860 } 14861 14862 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14863 return ActOnFinishFunctionBody(D, BodyArg, false); 14864 } 14865 14866 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14867 /// body. 14868 class ExitFunctionBodyRAII { 14869 public: 14870 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14871 ~ExitFunctionBodyRAII() { 14872 if (!IsLambda) 14873 S.PopExpressionEvaluationContext(); 14874 } 14875 14876 private: 14877 Sema &S; 14878 bool IsLambda = false; 14879 }; 14880 14881 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14882 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14883 14884 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14885 if (EscapeInfo.count(BD)) 14886 return EscapeInfo[BD]; 14887 14888 bool R = false; 14889 const BlockDecl *CurBD = BD; 14890 14891 do { 14892 R = !CurBD->doesNotEscape(); 14893 if (R) 14894 break; 14895 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14896 } while (CurBD); 14897 14898 return EscapeInfo[BD] = R; 14899 }; 14900 14901 // If the location where 'self' is implicitly retained is inside a escaping 14902 // block, emit a diagnostic. 14903 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14904 S.ImplicitlyRetainedSelfLocs) 14905 if (IsOrNestedInEscapingBlock(P.second)) 14906 S.Diag(P.first, diag::warn_implicitly_retains_self) 14907 << FixItHint::CreateInsertion(P.first, "self->"); 14908 } 14909 14910 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14911 bool IsInstantiation) { 14912 FunctionScopeInfo *FSI = getCurFunction(); 14913 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14914 14915 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14916 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14917 14918 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14919 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14920 14921 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14922 CheckCompletedCoroutineBody(FD, Body); 14923 14924 { 14925 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14926 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14927 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14928 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14929 14930 if (FD) { 14931 FD->setBody(Body); 14932 FD->setWillHaveBody(false); 14933 14934 if (getLangOpts().CPlusPlus14) { 14935 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14936 FD->getReturnType()->isUndeducedType()) { 14937 // For a function with a deduced result type to return void, 14938 // the result type as written must be 'auto' or 'decltype(auto)', 14939 // possibly cv-qualified or constrained, but not ref-qualified. 14940 if (!FD->getReturnType()->getAs<AutoType>()) { 14941 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14942 << FD->getReturnType(); 14943 FD->setInvalidDecl(); 14944 } else { 14945 // Falling off the end of the function is the same as 'return;'. 14946 Expr *Dummy = nullptr; 14947 if (DeduceFunctionTypeFromReturnExpr( 14948 FD, dcl->getLocation(), Dummy, 14949 FD->getReturnType()->getAs<AutoType>())) 14950 FD->setInvalidDecl(); 14951 } 14952 } 14953 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14954 // In C++11, we don't use 'auto' deduction rules for lambda call 14955 // operators because we don't support return type deduction. 14956 auto *LSI = getCurLambda(); 14957 if (LSI->HasImplicitReturnType) { 14958 deduceClosureReturnType(*LSI); 14959 14960 // C++11 [expr.prim.lambda]p4: 14961 // [...] if there are no return statements in the compound-statement 14962 // [the deduced type is] the type void 14963 QualType RetType = 14964 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14965 14966 // Update the return type to the deduced type. 14967 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14968 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14969 Proto->getExtProtoInfo())); 14970 } 14971 } 14972 14973 // If the function implicitly returns zero (like 'main') or is naked, 14974 // don't complain about missing return statements. 14975 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14976 WP.disableCheckFallThrough(); 14977 14978 // MSVC permits the use of pure specifier (=0) on function definition, 14979 // defined at class scope, warn about this non-standard construct. 14980 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14981 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14982 14983 if (!FD->isInvalidDecl()) { 14984 // Don't diagnose unused parameters of defaulted, deleted or naked 14985 // functions. 14986 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 14987 !FD->hasAttr<NakedAttr>()) 14988 DiagnoseUnusedParameters(FD->parameters()); 14989 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14990 FD->getReturnType(), FD); 14991 14992 // If this is a structor, we need a vtable. 14993 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14994 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14995 else if (CXXDestructorDecl *Destructor = 14996 dyn_cast<CXXDestructorDecl>(FD)) 14997 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14998 14999 // Try to apply the named return value optimization. We have to check 15000 // if we can do this here because lambdas keep return statements around 15001 // to deduce an implicit return type. 15002 if (FD->getReturnType()->isRecordType() && 15003 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 15004 computeNRVO(Body, FSI); 15005 } 15006 15007 // GNU warning -Wmissing-prototypes: 15008 // Warn if a global function is defined without a previous 15009 // prototype declaration. This warning is issued even if the 15010 // definition itself provides a prototype. The aim is to detect 15011 // global functions that fail to be declared in header files. 15012 const FunctionDecl *PossiblePrototype = nullptr; 15013 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 15014 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 15015 15016 if (PossiblePrototype) { 15017 // We found a declaration that is not a prototype, 15018 // but that could be a zero-parameter prototype 15019 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 15020 TypeLoc TL = TI->getTypeLoc(); 15021 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 15022 Diag(PossiblePrototype->getLocation(), 15023 diag::note_declaration_not_a_prototype) 15024 << (FD->getNumParams() != 0) 15025 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 15026 FTL.getRParenLoc(), "void") 15027 : FixItHint{}); 15028 } 15029 } else { 15030 // Returns true if the token beginning at this Loc is `const`. 15031 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 15032 const LangOptions &LangOpts) { 15033 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 15034 if (LocInfo.first.isInvalid()) 15035 return false; 15036 15037 bool Invalid = false; 15038 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 15039 if (Invalid) 15040 return false; 15041 15042 if (LocInfo.second > Buffer.size()) 15043 return false; 15044 15045 const char *LexStart = Buffer.data() + LocInfo.second; 15046 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 15047 15048 return StartTok.consume_front("const") && 15049 (StartTok.empty() || isWhitespace(StartTok[0]) || 15050 StartTok.startswith("/*") || StartTok.startswith("//")); 15051 }; 15052 15053 auto findBeginLoc = [&]() { 15054 // If the return type has `const` qualifier, we want to insert 15055 // `static` before `const` (and not before the typename). 15056 if ((FD->getReturnType()->isAnyPointerType() && 15057 FD->getReturnType()->getPointeeType().isConstQualified()) || 15058 FD->getReturnType().isConstQualified()) { 15059 // But only do this if we can determine where the `const` is. 15060 15061 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 15062 getLangOpts())) 15063 15064 return FD->getBeginLoc(); 15065 } 15066 return FD->getTypeSpecStartLoc(); 15067 }; 15068 Diag(FD->getTypeSpecStartLoc(), 15069 diag::note_static_for_internal_linkage) 15070 << /* function */ 1 15071 << (FD->getStorageClass() == SC_None 15072 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 15073 : FixItHint{}); 15074 } 15075 } 15076 15077 // If the function being defined does not have a prototype, then we may 15078 // need to diagnose it as changing behavior in C2x because we now know 15079 // whether the function accepts arguments or not. This only handles the 15080 // case where the definition has no prototype but does have parameters 15081 // and either there is no previous potential prototype, or the previous 15082 // potential prototype also has no actual prototype. This handles cases 15083 // like: 15084 // void f(); void f(a) int a; {} 15085 // void g(a) int a; {} 15086 // See MergeFunctionDecl() for other cases of the behavior change 15087 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 15088 // type without a prototype. 15089 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && 15090 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && 15091 !PossiblePrototype->isImplicit()))) { 15092 // The function definition has parameters, so this will change behavior 15093 // in C2x. If there is a possible prototype, it comes before the 15094 // function definition. 15095 // FIXME: The declaration may have already been diagnosed as being 15096 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but 15097 // there's no way to test for the "changes behavior" condition in 15098 // SemaType.cpp when forming the declaration's function type. So, we do 15099 // this awkward dance instead. 15100 // 15101 // If we have a possible prototype and it declares a function with a 15102 // prototype, we don't want to diagnose it; if we have a possible 15103 // prototype and it has no prototype, it may have already been 15104 // diagnosed in SemaType.cpp as deprecated depending on whether 15105 // -Wstrict-prototypes is enabled. If we already warned about it being 15106 // deprecated, add a note that it also changes behavior. If we didn't 15107 // warn about it being deprecated (because the diagnostic is not 15108 // enabled), warn now that it is deprecated and changes behavior. 15109 15110 // This K&R C function definition definitely changes behavior in C2x, 15111 // so diagnose it. 15112 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior) 15113 << /*definition*/ 1 << /* not supported in C2x */ 0; 15114 15115 // If we have a possible prototype for the function which is a user- 15116 // visible declaration, we already tested that it has no prototype. 15117 // This will change behavior in C2x. This gets a warning rather than a 15118 // note because it's the same behavior-changing problem as with the 15119 // definition. 15120 if (PossiblePrototype) 15121 Diag(PossiblePrototype->getLocation(), 15122 diag::warn_non_prototype_changes_behavior) 15123 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1 15124 << /*definition*/ 1; 15125 } 15126 15127 // Warn on CPUDispatch with an actual body. 15128 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 15129 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 15130 if (!CmpndBody->body_empty()) 15131 Diag(CmpndBody->body_front()->getBeginLoc(), 15132 diag::warn_dispatch_body_ignored); 15133 15134 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 15135 const CXXMethodDecl *KeyFunction; 15136 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 15137 MD->isVirtual() && 15138 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 15139 MD == KeyFunction->getCanonicalDecl()) { 15140 // Update the key-function state if necessary for this ABI. 15141 if (FD->isInlined() && 15142 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 15143 Context.setNonKeyFunction(MD); 15144 15145 // If the newly-chosen key function is already defined, then we 15146 // need to mark the vtable as used retroactively. 15147 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 15148 const FunctionDecl *Definition; 15149 if (KeyFunction && KeyFunction->isDefined(Definition)) 15150 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 15151 } else { 15152 // We just defined they key function; mark the vtable as used. 15153 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 15154 } 15155 } 15156 } 15157 15158 assert( 15159 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 15160 "Function parsing confused"); 15161 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 15162 assert(MD == getCurMethodDecl() && "Method parsing confused"); 15163 MD->setBody(Body); 15164 if (!MD->isInvalidDecl()) { 15165 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 15166 MD->getReturnType(), MD); 15167 15168 if (Body) 15169 computeNRVO(Body, FSI); 15170 } 15171 if (FSI->ObjCShouldCallSuper) { 15172 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 15173 << MD->getSelector().getAsString(); 15174 FSI->ObjCShouldCallSuper = false; 15175 } 15176 if (FSI->ObjCWarnForNoDesignatedInitChain) { 15177 const ObjCMethodDecl *InitMethod = nullptr; 15178 bool isDesignated = 15179 MD->isDesignatedInitializerForTheInterface(&InitMethod); 15180 assert(isDesignated && InitMethod); 15181 (void)isDesignated; 15182 15183 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 15184 auto IFace = MD->getClassInterface(); 15185 if (!IFace) 15186 return false; 15187 auto SuperD = IFace->getSuperClass(); 15188 if (!SuperD) 15189 return false; 15190 return SuperD->getIdentifier() == 15191 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 15192 }; 15193 // Don't issue this warning for unavailable inits or direct subclasses 15194 // of NSObject. 15195 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 15196 Diag(MD->getLocation(), 15197 diag::warn_objc_designated_init_missing_super_call); 15198 Diag(InitMethod->getLocation(), 15199 diag::note_objc_designated_init_marked_here); 15200 } 15201 FSI->ObjCWarnForNoDesignatedInitChain = false; 15202 } 15203 if (FSI->ObjCWarnForNoInitDelegation) { 15204 // Don't issue this warning for unavaialable inits. 15205 if (!MD->isUnavailable()) 15206 Diag(MD->getLocation(), 15207 diag::warn_objc_secondary_init_missing_init_call); 15208 FSI->ObjCWarnForNoInitDelegation = false; 15209 } 15210 15211 diagnoseImplicitlyRetainedSelf(*this); 15212 } else { 15213 // Parsing the function declaration failed in some way. Pop the fake scope 15214 // we pushed on. 15215 PopFunctionScopeInfo(ActivePolicy, dcl); 15216 return nullptr; 15217 } 15218 15219 if (Body && FSI->HasPotentialAvailabilityViolations) 15220 DiagnoseUnguardedAvailabilityViolations(dcl); 15221 15222 assert(!FSI->ObjCShouldCallSuper && 15223 "This should only be set for ObjC methods, which should have been " 15224 "handled in the block above."); 15225 15226 // Verify and clean out per-function state. 15227 if (Body && (!FD || !FD->isDefaulted())) { 15228 // C++ constructors that have function-try-blocks can't have return 15229 // statements in the handlers of that block. (C++ [except.handle]p14) 15230 // Verify this. 15231 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 15232 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 15233 15234 // Verify that gotos and switch cases don't jump into scopes illegally. 15235 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 15236 DiagnoseInvalidJumps(Body); 15237 15238 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 15239 if (!Destructor->getParent()->isDependentType()) 15240 CheckDestructor(Destructor); 15241 15242 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 15243 Destructor->getParent()); 15244 } 15245 15246 // If any errors have occurred, clear out any temporaries that may have 15247 // been leftover. This ensures that these temporaries won't be picked up 15248 // for deletion in some later function. 15249 if (hasUncompilableErrorOccurred() || 15250 getDiagnostics().getSuppressAllDiagnostics()) { 15251 DiscardCleanupsInEvaluationContext(); 15252 } 15253 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 15254 // Since the body is valid, issue any analysis-based warnings that are 15255 // enabled. 15256 ActivePolicy = &WP; 15257 } 15258 15259 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 15260 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 15261 FD->setInvalidDecl(); 15262 15263 if (FD && FD->hasAttr<NakedAttr>()) { 15264 for (const Stmt *S : Body->children()) { 15265 // Allow local register variables without initializer as they don't 15266 // require prologue. 15267 bool RegisterVariables = false; 15268 if (auto *DS = dyn_cast<DeclStmt>(S)) { 15269 for (const auto *Decl : DS->decls()) { 15270 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 15271 RegisterVariables = 15272 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 15273 if (!RegisterVariables) 15274 break; 15275 } 15276 } 15277 } 15278 if (RegisterVariables) 15279 continue; 15280 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 15281 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 15282 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 15283 FD->setInvalidDecl(); 15284 break; 15285 } 15286 } 15287 } 15288 15289 assert(ExprCleanupObjects.size() == 15290 ExprEvalContexts.back().NumCleanupObjects && 15291 "Leftover temporaries in function"); 15292 assert(!Cleanup.exprNeedsCleanups() && 15293 "Unaccounted cleanups in function"); 15294 assert(MaybeODRUseExprs.empty() && 15295 "Leftover expressions for odr-use checking"); 15296 } 15297 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 15298 // the declaration context below. Otherwise, we're unable to transform 15299 // 'this' expressions when transforming immediate context functions. 15300 15301 if (!IsInstantiation) 15302 PopDeclContext(); 15303 15304 PopFunctionScopeInfo(ActivePolicy, dcl); 15305 // If any errors have occurred, clear out any temporaries that may have 15306 // been leftover. This ensures that these temporaries won't be picked up for 15307 // deletion in some later function. 15308 if (hasUncompilableErrorOccurred()) { 15309 DiscardCleanupsInEvaluationContext(); 15310 } 15311 15312 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 15313 !LangOpts.OMPTargetTriples.empty())) || 15314 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 15315 auto ES = getEmissionStatus(FD); 15316 if (ES == Sema::FunctionEmissionStatus::Emitted || 15317 ES == Sema::FunctionEmissionStatus::Unknown) 15318 DeclsToCheckForDeferredDiags.insert(FD); 15319 } 15320 15321 if (FD && !FD->isDeleted()) 15322 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 15323 15324 return dcl; 15325 } 15326 15327 /// When we finish delayed parsing of an attribute, we must attach it to the 15328 /// relevant Decl. 15329 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 15330 ParsedAttributes &Attrs) { 15331 // Always attach attributes to the underlying decl. 15332 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 15333 D = TD->getTemplatedDecl(); 15334 ProcessDeclAttributeList(S, D, Attrs); 15335 15336 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 15337 if (Method->isStatic()) 15338 checkThisInStaticMemberFunctionAttributes(Method); 15339 } 15340 15341 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 15342 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 15343 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 15344 IdentifierInfo &II, Scope *S) { 15345 // It is not valid to implicitly define a function in C2x. 15346 assert(LangOpts.implicitFunctionsAllowed() && 15347 "Implicit function declarations aren't allowed in this language mode"); 15348 15349 // Find the scope in which the identifier is injected and the corresponding 15350 // DeclContext. 15351 // FIXME: C89 does not say what happens if there is no enclosing block scope. 15352 // In that case, we inject the declaration into the translation unit scope 15353 // instead. 15354 Scope *BlockScope = S; 15355 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 15356 BlockScope = BlockScope->getParent(); 15357 15358 Scope *ContextScope = BlockScope; 15359 while (!ContextScope->getEntity()) 15360 ContextScope = ContextScope->getParent(); 15361 ContextRAII SavedContext(*this, ContextScope->getEntity()); 15362 15363 // Before we produce a declaration for an implicitly defined 15364 // function, see whether there was a locally-scoped declaration of 15365 // this name as a function or variable. If so, use that 15366 // (non-visible) declaration, and complain about it. 15367 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 15368 if (ExternCPrev) { 15369 // We still need to inject the function into the enclosing block scope so 15370 // that later (non-call) uses can see it. 15371 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 15372 15373 // C89 footnote 38: 15374 // If in fact it is not defined as having type "function returning int", 15375 // the behavior is undefined. 15376 if (!isa<FunctionDecl>(ExternCPrev) || 15377 !Context.typesAreCompatible( 15378 cast<FunctionDecl>(ExternCPrev)->getType(), 15379 Context.getFunctionNoProtoType(Context.IntTy))) { 15380 Diag(Loc, diag::ext_use_out_of_scope_declaration) 15381 << ExternCPrev << !getLangOpts().C99; 15382 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 15383 return ExternCPrev; 15384 } 15385 } 15386 15387 // Extension in C99 (defaults to error). Legal in C89, but warn about it. 15388 unsigned diag_id; 15389 if (II.getName().startswith("__builtin_")) 15390 diag_id = diag::warn_builtin_unknown; 15391 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 15392 else if (getLangOpts().C99) 15393 diag_id = diag::ext_implicit_function_decl_c99; 15394 else 15395 diag_id = diag::warn_implicit_function_decl; 15396 15397 TypoCorrection Corrected; 15398 // Because typo correction is expensive, only do it if the implicit 15399 // function declaration is going to be treated as an error. 15400 // 15401 // Perform the corection before issuing the main diagnostic, as some consumers 15402 // use typo-correction callbacks to enhance the main diagnostic. 15403 if (S && !ExternCPrev && 15404 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 15405 DeclFilterCCC<FunctionDecl> CCC{}; 15406 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 15407 S, nullptr, CCC, CTK_NonError); 15408 } 15409 15410 Diag(Loc, diag_id) << &II; 15411 if (Corrected) { 15412 // If the correction is going to suggest an implicitly defined function, 15413 // skip the correction as not being a particularly good idea. 15414 bool Diagnose = true; 15415 if (const auto *D = Corrected.getCorrectionDecl()) 15416 Diagnose = !D->isImplicit(); 15417 if (Diagnose) 15418 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 15419 /*ErrorRecovery*/ false); 15420 } 15421 15422 // If we found a prior declaration of this function, don't bother building 15423 // another one. We've already pushed that one into scope, so there's nothing 15424 // more to do. 15425 if (ExternCPrev) 15426 return ExternCPrev; 15427 15428 // Set a Declarator for the implicit definition: int foo(); 15429 const char *Dummy; 15430 AttributeFactory attrFactory; 15431 DeclSpec DS(attrFactory); 15432 unsigned DiagID; 15433 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 15434 Context.getPrintingPolicy()); 15435 (void)Error; // Silence warning. 15436 assert(!Error && "Error setting up implicit decl!"); 15437 SourceLocation NoLoc; 15438 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block); 15439 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 15440 /*IsAmbiguous=*/false, 15441 /*LParenLoc=*/NoLoc, 15442 /*Params=*/nullptr, 15443 /*NumParams=*/0, 15444 /*EllipsisLoc=*/NoLoc, 15445 /*RParenLoc=*/NoLoc, 15446 /*RefQualifierIsLvalueRef=*/true, 15447 /*RefQualifierLoc=*/NoLoc, 15448 /*MutableLoc=*/NoLoc, EST_None, 15449 /*ESpecRange=*/SourceRange(), 15450 /*Exceptions=*/nullptr, 15451 /*ExceptionRanges=*/nullptr, 15452 /*NumExceptions=*/0, 15453 /*NoexceptExpr=*/nullptr, 15454 /*ExceptionSpecTokens=*/nullptr, 15455 /*DeclsInPrototype=*/None, Loc, 15456 Loc, D), 15457 std::move(DS.getAttributes()), SourceLocation()); 15458 D.SetIdentifier(&II, Loc); 15459 15460 // Insert this function into the enclosing block scope. 15461 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 15462 FD->setImplicit(); 15463 15464 AddKnownFunctionAttributes(FD); 15465 15466 return FD; 15467 } 15468 15469 /// If this function is a C++ replaceable global allocation function 15470 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15471 /// adds any function attributes that we know a priori based on the standard. 15472 /// 15473 /// We need to check for duplicate attributes both here and where user-written 15474 /// attributes are applied to declarations. 15475 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15476 FunctionDecl *FD) { 15477 if (FD->isInvalidDecl()) 15478 return; 15479 15480 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15481 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15482 return; 15483 15484 Optional<unsigned> AlignmentParam; 15485 bool IsNothrow = false; 15486 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15487 return; 15488 15489 // C++2a [basic.stc.dynamic.allocation]p4: 15490 // An allocation function that has a non-throwing exception specification 15491 // indicates failure by returning a null pointer value. Any other allocation 15492 // function never returns a null pointer value and indicates failure only by 15493 // throwing an exception [...] 15494 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15495 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15496 15497 // C++2a [basic.stc.dynamic.allocation]p2: 15498 // An allocation function attempts to allocate the requested amount of 15499 // storage. [...] If the request succeeds, the value returned by a 15500 // replaceable allocation function is a [...] pointer value p0 different 15501 // from any previously returned value p1 [...] 15502 // 15503 // However, this particular information is being added in codegen, 15504 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15505 15506 // C++2a [basic.stc.dynamic.allocation]p2: 15507 // An allocation function attempts to allocate the requested amount of 15508 // storage. If it is successful, it returns the address of the start of a 15509 // block of storage whose length in bytes is at least as large as the 15510 // requested size. 15511 if (!FD->hasAttr<AllocSizeAttr>()) { 15512 FD->addAttr(AllocSizeAttr::CreateImplicit( 15513 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15514 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15515 } 15516 15517 // C++2a [basic.stc.dynamic.allocation]p3: 15518 // For an allocation function [...], the pointer returned on a successful 15519 // call shall represent the address of storage that is aligned as follows: 15520 // (3.1) If the allocation function takes an argument of type 15521 // std::align_val_t, the storage will have the alignment 15522 // specified by the value of this argument. 15523 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) { 15524 FD->addAttr(AllocAlignAttr::CreateImplicit( 15525 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15526 } 15527 15528 // FIXME: 15529 // C++2a [basic.stc.dynamic.allocation]p3: 15530 // For an allocation function [...], the pointer returned on a successful 15531 // call shall represent the address of storage that is aligned as follows: 15532 // (3.2) Otherwise, if the allocation function is named operator new[], 15533 // the storage is aligned for any object that does not have 15534 // new-extended alignment ([basic.align]) and is no larger than the 15535 // requested size. 15536 // (3.3) Otherwise, the storage is aligned for any object that does not 15537 // have new-extended alignment and is of the requested size. 15538 } 15539 15540 /// Adds any function attributes that we know a priori based on 15541 /// the declaration of this function. 15542 /// 15543 /// These attributes can apply both to implicitly-declared builtins 15544 /// (like __builtin___printf_chk) or to library-declared functions 15545 /// like NSLog or printf. 15546 /// 15547 /// We need to check for duplicate attributes both here and where user-written 15548 /// attributes are applied to declarations. 15549 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15550 if (FD->isInvalidDecl()) 15551 return; 15552 15553 // If this is a built-in function, map its builtin attributes to 15554 // actual attributes. 15555 if (unsigned BuiltinID = FD->getBuiltinID()) { 15556 // Handle printf-formatting attributes. 15557 unsigned FormatIdx; 15558 bool HasVAListArg; 15559 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15560 if (!FD->hasAttr<FormatAttr>()) { 15561 const char *fmt = "printf"; 15562 unsigned int NumParams = FD->getNumParams(); 15563 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15564 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15565 fmt = "NSString"; 15566 FD->addAttr(FormatAttr::CreateImplicit(Context, 15567 &Context.Idents.get(fmt), 15568 FormatIdx+1, 15569 HasVAListArg ? 0 : FormatIdx+2, 15570 FD->getLocation())); 15571 } 15572 } 15573 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15574 HasVAListArg)) { 15575 if (!FD->hasAttr<FormatAttr>()) 15576 FD->addAttr(FormatAttr::CreateImplicit(Context, 15577 &Context.Idents.get("scanf"), 15578 FormatIdx+1, 15579 HasVAListArg ? 0 : FormatIdx+2, 15580 FD->getLocation())); 15581 } 15582 15583 // Handle automatically recognized callbacks. 15584 SmallVector<int, 4> Encoding; 15585 if (!FD->hasAttr<CallbackAttr>() && 15586 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15587 FD->addAttr(CallbackAttr::CreateImplicit( 15588 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15589 15590 // Mark const if we don't care about errno and that is the only thing 15591 // preventing the function from being const. This allows IRgen to use LLVM 15592 // intrinsics for such functions. 15593 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15594 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15595 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15596 15597 // We make "fma" on GNU or Windows const because we know it does not set 15598 // errno in those environments even though it could set errno based on the 15599 // C standard. 15600 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15601 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 15602 !FD->hasAttr<ConstAttr>()) { 15603 switch (BuiltinID) { 15604 case Builtin::BI__builtin_fma: 15605 case Builtin::BI__builtin_fmaf: 15606 case Builtin::BI__builtin_fmal: 15607 case Builtin::BIfma: 15608 case Builtin::BIfmaf: 15609 case Builtin::BIfmal: 15610 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15611 break; 15612 default: 15613 break; 15614 } 15615 } 15616 15617 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15618 !FD->hasAttr<ReturnsTwiceAttr>()) 15619 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15620 FD->getLocation())); 15621 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15622 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15623 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15624 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15625 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15626 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15627 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15628 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15629 // Add the appropriate attribute, depending on the CUDA compilation mode 15630 // and which target the builtin belongs to. For example, during host 15631 // compilation, aux builtins are __device__, while the rest are __host__. 15632 if (getLangOpts().CUDAIsDevice != 15633 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15634 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15635 else 15636 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15637 } 15638 15639 // Add known guaranteed alignment for allocation functions. 15640 switch (BuiltinID) { 15641 case Builtin::BImemalign: 15642 case Builtin::BIaligned_alloc: 15643 if (!FD->hasAttr<AllocAlignAttr>()) 15644 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15645 FD->getLocation())); 15646 break; 15647 default: 15648 break; 15649 } 15650 15651 // Add allocsize attribute for allocation functions. 15652 switch (BuiltinID) { 15653 case Builtin::BIcalloc: 15654 FD->addAttr(AllocSizeAttr::CreateImplicit( 15655 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 15656 break; 15657 case Builtin::BImemalign: 15658 case Builtin::BIaligned_alloc: 15659 case Builtin::BIrealloc: 15660 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 15661 ParamIdx(), FD->getLocation())); 15662 break; 15663 case Builtin::BImalloc: 15664 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 15665 ParamIdx(), FD->getLocation())); 15666 break; 15667 default: 15668 break; 15669 } 15670 } 15671 15672 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15673 15674 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15675 // throw, add an implicit nothrow attribute to any extern "C" function we come 15676 // across. 15677 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15678 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15679 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15680 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15681 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15682 } 15683 15684 IdentifierInfo *Name = FD->getIdentifier(); 15685 if (!Name) 15686 return; 15687 if ((!getLangOpts().CPlusPlus && 15688 FD->getDeclContext()->isTranslationUnit()) || 15689 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15690 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15691 LinkageSpecDecl::lang_c)) { 15692 // Okay: this could be a libc/libm/Objective-C function we know 15693 // about. 15694 } else 15695 return; 15696 15697 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15698 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15699 // target-specific builtins, perhaps? 15700 if (!FD->hasAttr<FormatAttr>()) 15701 FD->addAttr(FormatAttr::CreateImplicit(Context, 15702 &Context.Idents.get("printf"), 2, 15703 Name->isStr("vasprintf") ? 0 : 3, 15704 FD->getLocation())); 15705 } 15706 15707 if (Name->isStr("__CFStringMakeConstantString")) { 15708 // We already have a __builtin___CFStringMakeConstantString, 15709 // but builds that use -fno-constant-cfstrings don't go through that. 15710 if (!FD->hasAttr<FormatArgAttr>()) 15711 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15712 FD->getLocation())); 15713 } 15714 } 15715 15716 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15717 TypeSourceInfo *TInfo) { 15718 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15719 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15720 15721 if (!TInfo) { 15722 assert(D.isInvalidType() && "no declarator info for valid type"); 15723 TInfo = Context.getTrivialTypeSourceInfo(T); 15724 } 15725 15726 // Scope manipulation handled by caller. 15727 TypedefDecl *NewTD = 15728 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15729 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15730 15731 // Bail out immediately if we have an invalid declaration. 15732 if (D.isInvalidType()) { 15733 NewTD->setInvalidDecl(); 15734 return NewTD; 15735 } 15736 15737 if (D.getDeclSpec().isModulePrivateSpecified()) { 15738 if (CurContext->isFunctionOrMethod()) 15739 Diag(NewTD->getLocation(), diag::err_module_private_local) 15740 << 2 << NewTD 15741 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15742 << FixItHint::CreateRemoval( 15743 D.getDeclSpec().getModulePrivateSpecLoc()); 15744 else 15745 NewTD->setModulePrivate(); 15746 } 15747 15748 // C++ [dcl.typedef]p8: 15749 // If the typedef declaration defines an unnamed class (or 15750 // enum), the first typedef-name declared by the declaration 15751 // to be that class type (or enum type) is used to denote the 15752 // class type (or enum type) for linkage purposes only. 15753 // We need to check whether the type was declared in the declaration. 15754 switch (D.getDeclSpec().getTypeSpecType()) { 15755 case TST_enum: 15756 case TST_struct: 15757 case TST_interface: 15758 case TST_union: 15759 case TST_class: { 15760 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15761 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15762 break; 15763 } 15764 15765 default: 15766 break; 15767 } 15768 15769 return NewTD; 15770 } 15771 15772 /// Check that this is a valid underlying type for an enum declaration. 15773 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15774 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15775 QualType T = TI->getType(); 15776 15777 if (T->isDependentType()) 15778 return false; 15779 15780 // This doesn't use 'isIntegralType' despite the error message mentioning 15781 // integral type because isIntegralType would also allow enum types in C. 15782 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15783 if (BT->isInteger()) 15784 return false; 15785 15786 if (T->isBitIntType()) 15787 return false; 15788 15789 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15790 } 15791 15792 /// Check whether this is a valid redeclaration of a previous enumeration. 15793 /// \return true if the redeclaration was invalid. 15794 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15795 QualType EnumUnderlyingTy, bool IsFixed, 15796 const EnumDecl *Prev) { 15797 if (IsScoped != Prev->isScoped()) { 15798 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15799 << Prev->isScoped(); 15800 Diag(Prev->getLocation(), diag::note_previous_declaration); 15801 return true; 15802 } 15803 15804 if (IsFixed && Prev->isFixed()) { 15805 if (!EnumUnderlyingTy->isDependentType() && 15806 !Prev->getIntegerType()->isDependentType() && 15807 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15808 Prev->getIntegerType())) { 15809 // TODO: Highlight the underlying type of the redeclaration. 15810 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15811 << EnumUnderlyingTy << Prev->getIntegerType(); 15812 Diag(Prev->getLocation(), diag::note_previous_declaration) 15813 << Prev->getIntegerTypeRange(); 15814 return true; 15815 } 15816 } else if (IsFixed != Prev->isFixed()) { 15817 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15818 << Prev->isFixed(); 15819 Diag(Prev->getLocation(), diag::note_previous_declaration); 15820 return true; 15821 } 15822 15823 return false; 15824 } 15825 15826 /// Get diagnostic %select index for tag kind for 15827 /// redeclaration diagnostic message. 15828 /// WARNING: Indexes apply to particular diagnostics only! 15829 /// 15830 /// \returns diagnostic %select index. 15831 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15832 switch (Tag) { 15833 case TTK_Struct: return 0; 15834 case TTK_Interface: return 1; 15835 case TTK_Class: return 2; 15836 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15837 } 15838 } 15839 15840 /// Determine if tag kind is a class-key compatible with 15841 /// class for redeclaration (class, struct, or __interface). 15842 /// 15843 /// \returns true iff the tag kind is compatible. 15844 static bool isClassCompatTagKind(TagTypeKind Tag) 15845 { 15846 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15847 } 15848 15849 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15850 TagTypeKind TTK) { 15851 if (isa<TypedefDecl>(PrevDecl)) 15852 return NTK_Typedef; 15853 else if (isa<TypeAliasDecl>(PrevDecl)) 15854 return NTK_TypeAlias; 15855 else if (isa<ClassTemplateDecl>(PrevDecl)) 15856 return NTK_Template; 15857 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15858 return NTK_TypeAliasTemplate; 15859 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15860 return NTK_TemplateTemplateArgument; 15861 switch (TTK) { 15862 case TTK_Struct: 15863 case TTK_Interface: 15864 case TTK_Class: 15865 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15866 case TTK_Union: 15867 return NTK_NonUnion; 15868 case TTK_Enum: 15869 return NTK_NonEnum; 15870 } 15871 llvm_unreachable("invalid TTK"); 15872 } 15873 15874 /// Determine whether a tag with a given kind is acceptable 15875 /// as a redeclaration of the given tag declaration. 15876 /// 15877 /// \returns true if the new tag kind is acceptable, false otherwise. 15878 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15879 TagTypeKind NewTag, bool isDefinition, 15880 SourceLocation NewTagLoc, 15881 const IdentifierInfo *Name) { 15882 // C++ [dcl.type.elab]p3: 15883 // The class-key or enum keyword present in the 15884 // elaborated-type-specifier shall agree in kind with the 15885 // declaration to which the name in the elaborated-type-specifier 15886 // refers. This rule also applies to the form of 15887 // elaborated-type-specifier that declares a class-name or 15888 // friend class since it can be construed as referring to the 15889 // definition of the class. Thus, in any 15890 // elaborated-type-specifier, the enum keyword shall be used to 15891 // refer to an enumeration (7.2), the union class-key shall be 15892 // used to refer to a union (clause 9), and either the class or 15893 // struct class-key shall be used to refer to a class (clause 9) 15894 // declared using the class or struct class-key. 15895 TagTypeKind OldTag = Previous->getTagKind(); 15896 if (OldTag != NewTag && 15897 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15898 return false; 15899 15900 // Tags are compatible, but we might still want to warn on mismatched tags. 15901 // Non-class tags can't be mismatched at this point. 15902 if (!isClassCompatTagKind(NewTag)) 15903 return true; 15904 15905 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15906 // by our warning analysis. We don't want to warn about mismatches with (eg) 15907 // declarations in system headers that are designed to be specialized, but if 15908 // a user asks us to warn, we should warn if their code contains mismatched 15909 // declarations. 15910 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15911 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15912 Loc); 15913 }; 15914 if (IsIgnoredLoc(NewTagLoc)) 15915 return true; 15916 15917 auto IsIgnored = [&](const TagDecl *Tag) { 15918 return IsIgnoredLoc(Tag->getLocation()); 15919 }; 15920 while (IsIgnored(Previous)) { 15921 Previous = Previous->getPreviousDecl(); 15922 if (!Previous) 15923 return true; 15924 OldTag = Previous->getTagKind(); 15925 } 15926 15927 bool isTemplate = false; 15928 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15929 isTemplate = Record->getDescribedClassTemplate(); 15930 15931 if (inTemplateInstantiation()) { 15932 if (OldTag != NewTag) { 15933 // In a template instantiation, do not offer fix-its for tag mismatches 15934 // since they usually mess up the template instead of fixing the problem. 15935 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15936 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15937 << getRedeclDiagFromTagKind(OldTag); 15938 // FIXME: Note previous location? 15939 } 15940 return true; 15941 } 15942 15943 if (isDefinition) { 15944 // On definitions, check all previous tags and issue a fix-it for each 15945 // one that doesn't match the current tag. 15946 if (Previous->getDefinition()) { 15947 // Don't suggest fix-its for redefinitions. 15948 return true; 15949 } 15950 15951 bool previousMismatch = false; 15952 for (const TagDecl *I : Previous->redecls()) { 15953 if (I->getTagKind() != NewTag) { 15954 // Ignore previous declarations for which the warning was disabled. 15955 if (IsIgnored(I)) 15956 continue; 15957 15958 if (!previousMismatch) { 15959 previousMismatch = true; 15960 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15961 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15962 << getRedeclDiagFromTagKind(I->getTagKind()); 15963 } 15964 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15965 << getRedeclDiagFromTagKind(NewTag) 15966 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15967 TypeWithKeyword::getTagTypeKindName(NewTag)); 15968 } 15969 } 15970 return true; 15971 } 15972 15973 // Identify the prevailing tag kind: this is the kind of the definition (if 15974 // there is a non-ignored definition), or otherwise the kind of the prior 15975 // (non-ignored) declaration. 15976 const TagDecl *PrevDef = Previous->getDefinition(); 15977 if (PrevDef && IsIgnored(PrevDef)) 15978 PrevDef = nullptr; 15979 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15980 if (Redecl->getTagKind() != NewTag) { 15981 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15982 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15983 << getRedeclDiagFromTagKind(OldTag); 15984 Diag(Redecl->getLocation(), diag::note_previous_use); 15985 15986 // If there is a previous definition, suggest a fix-it. 15987 if (PrevDef) { 15988 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15989 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15990 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15991 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15992 } 15993 } 15994 15995 return true; 15996 } 15997 15998 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15999 /// from an outer enclosing namespace or file scope inside a friend declaration. 16000 /// This should provide the commented out code in the following snippet: 16001 /// namespace N { 16002 /// struct X; 16003 /// namespace M { 16004 /// struct Y { friend struct /*N::*/ X; }; 16005 /// } 16006 /// } 16007 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 16008 SourceLocation NameLoc) { 16009 // While the decl is in a namespace, do repeated lookup of that name and see 16010 // if we get the same namespace back. If we do not, continue until 16011 // translation unit scope, at which point we have a fully qualified NNS. 16012 SmallVector<IdentifierInfo *, 4> Namespaces; 16013 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 16014 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 16015 // This tag should be declared in a namespace, which can only be enclosed by 16016 // other namespaces. Bail if there's an anonymous namespace in the chain. 16017 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 16018 if (!Namespace || Namespace->isAnonymousNamespace()) 16019 return FixItHint(); 16020 IdentifierInfo *II = Namespace->getIdentifier(); 16021 Namespaces.push_back(II); 16022 NamedDecl *Lookup = SemaRef.LookupSingleName( 16023 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 16024 if (Lookup == Namespace) 16025 break; 16026 } 16027 16028 // Once we have all the namespaces, reverse them to go outermost first, and 16029 // build an NNS. 16030 SmallString<64> Insertion; 16031 llvm::raw_svector_ostream OS(Insertion); 16032 if (DC->isTranslationUnit()) 16033 OS << "::"; 16034 std::reverse(Namespaces.begin(), Namespaces.end()); 16035 for (auto *II : Namespaces) 16036 OS << II->getName() << "::"; 16037 return FixItHint::CreateInsertion(NameLoc, Insertion); 16038 } 16039 16040 /// Determine whether a tag originally declared in context \p OldDC can 16041 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 16042 /// found a declaration in \p OldDC as a previous decl, perhaps through a 16043 /// using-declaration). 16044 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 16045 DeclContext *NewDC) { 16046 OldDC = OldDC->getRedeclContext(); 16047 NewDC = NewDC->getRedeclContext(); 16048 16049 if (OldDC->Equals(NewDC)) 16050 return true; 16051 16052 // In MSVC mode, we allow a redeclaration if the contexts are related (either 16053 // encloses the other). 16054 if (S.getLangOpts().MSVCCompat && 16055 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 16056 return true; 16057 16058 return false; 16059 } 16060 16061 /// This is invoked when we see 'struct foo' or 'struct {'. In the 16062 /// former case, Name will be non-null. In the later case, Name will be null. 16063 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 16064 /// reference/declaration/definition of a tag. 16065 /// 16066 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 16067 /// trailing-type-specifier) other than one in an alias-declaration. 16068 /// 16069 /// \param SkipBody If non-null, will be set to indicate if the caller should 16070 /// skip the definition of this tag and treat it as if it were a declaration. 16071 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 16072 SourceLocation KWLoc, CXXScopeSpec &SS, 16073 IdentifierInfo *Name, SourceLocation NameLoc, 16074 const ParsedAttributesView &Attrs, AccessSpecifier AS, 16075 SourceLocation ModulePrivateLoc, 16076 MultiTemplateParamsArg TemplateParameterLists, 16077 bool &OwnedDecl, bool &IsDependent, 16078 SourceLocation ScopedEnumKWLoc, 16079 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 16080 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 16081 SkipBodyInfo *SkipBody) { 16082 // If this is not a definition, it must have a name. 16083 IdentifierInfo *OrigName = Name; 16084 assert((Name != nullptr || TUK == TUK_Definition) && 16085 "Nameless record must be a definition!"); 16086 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 16087 16088 OwnedDecl = false; 16089 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16090 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 16091 16092 // FIXME: Check member specializations more carefully. 16093 bool isMemberSpecialization = false; 16094 bool Invalid = false; 16095 16096 // We only need to do this matching if we have template parameters 16097 // or a scope specifier, which also conveniently avoids this work 16098 // for non-C++ cases. 16099 if (TemplateParameterLists.size() > 0 || 16100 (SS.isNotEmpty() && TUK != TUK_Reference)) { 16101 if (TemplateParameterList *TemplateParams = 16102 MatchTemplateParametersToScopeSpecifier( 16103 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 16104 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 16105 if (Kind == TTK_Enum) { 16106 Diag(KWLoc, diag::err_enum_template); 16107 return nullptr; 16108 } 16109 16110 if (TemplateParams->size() > 0) { 16111 // This is a declaration or definition of a class template (which may 16112 // be a member of another template). 16113 16114 if (Invalid) 16115 return nullptr; 16116 16117 OwnedDecl = false; 16118 DeclResult Result = CheckClassTemplate( 16119 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 16120 AS, ModulePrivateLoc, 16121 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 16122 TemplateParameterLists.data(), SkipBody); 16123 return Result.get(); 16124 } else { 16125 // The "template<>" header is extraneous. 16126 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16127 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16128 isMemberSpecialization = true; 16129 } 16130 } 16131 16132 if (!TemplateParameterLists.empty() && isMemberSpecialization && 16133 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 16134 return nullptr; 16135 } 16136 16137 // Figure out the underlying type if this a enum declaration. We need to do 16138 // this early, because it's needed to detect if this is an incompatible 16139 // redeclaration. 16140 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 16141 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 16142 16143 if (Kind == TTK_Enum) { 16144 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 16145 // No underlying type explicitly specified, or we failed to parse the 16146 // type, default to int. 16147 EnumUnderlying = Context.IntTy.getTypePtr(); 16148 } else if (UnderlyingType.get()) { 16149 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 16150 // integral type; any cv-qualification is ignored. 16151 TypeSourceInfo *TI = nullptr; 16152 GetTypeFromParser(UnderlyingType.get(), &TI); 16153 EnumUnderlying = TI; 16154 16155 if (CheckEnumUnderlyingType(TI)) 16156 // Recover by falling back to int. 16157 EnumUnderlying = Context.IntTy.getTypePtr(); 16158 16159 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 16160 UPPC_FixedUnderlyingType)) 16161 EnumUnderlying = Context.IntTy.getTypePtr(); 16162 16163 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 16164 // For MSVC ABI compatibility, unfixed enums must use an underlying type 16165 // of 'int'. However, if this is an unfixed forward declaration, don't set 16166 // the underlying type unless the user enables -fms-compatibility. This 16167 // makes unfixed forward declared enums incomplete and is more conforming. 16168 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 16169 EnumUnderlying = Context.IntTy.getTypePtr(); 16170 } 16171 } 16172 16173 DeclContext *SearchDC = CurContext; 16174 DeclContext *DC = CurContext; 16175 bool isStdBadAlloc = false; 16176 bool isStdAlignValT = false; 16177 16178 RedeclarationKind Redecl = forRedeclarationInCurContext(); 16179 if (TUK == TUK_Friend || TUK == TUK_Reference) 16180 Redecl = NotForRedeclaration; 16181 16182 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 16183 /// implemented asks for structural equivalence checking, the returned decl 16184 /// here is passed back to the parser, allowing the tag body to be parsed. 16185 auto createTagFromNewDecl = [&]() -> TagDecl * { 16186 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 16187 // If there is an identifier, use the location of the identifier as the 16188 // location of the decl, otherwise use the location of the struct/union 16189 // keyword. 16190 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16191 TagDecl *New = nullptr; 16192 16193 if (Kind == TTK_Enum) { 16194 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 16195 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 16196 // If this is an undefined enum, bail. 16197 if (TUK != TUK_Definition && !Invalid) 16198 return nullptr; 16199 if (EnumUnderlying) { 16200 EnumDecl *ED = cast<EnumDecl>(New); 16201 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 16202 ED->setIntegerTypeSourceInfo(TI); 16203 else 16204 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 16205 ED->setPromotionType(ED->getIntegerType()); 16206 } 16207 } else { // struct/union 16208 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16209 nullptr); 16210 } 16211 16212 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16213 // Add alignment attributes if necessary; these attributes are checked 16214 // when the ASTContext lays out the structure. 16215 // 16216 // It is important for implementing the correct semantics that this 16217 // happen here (in ActOnTag). The #pragma pack stack is 16218 // maintained as a result of parser callbacks which can occur at 16219 // many points during the parsing of a struct declaration (because 16220 // the #pragma tokens are effectively skipped over during the 16221 // parsing of the struct). 16222 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16223 AddAlignmentAttributesForRecord(RD); 16224 AddMsStructLayoutForRecord(RD); 16225 } 16226 } 16227 New->setLexicalDeclContext(CurContext); 16228 return New; 16229 }; 16230 16231 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 16232 if (Name && SS.isNotEmpty()) { 16233 // We have a nested-name tag ('struct foo::bar'). 16234 16235 // Check for invalid 'foo::'. 16236 if (SS.isInvalid()) { 16237 Name = nullptr; 16238 goto CreateNewDecl; 16239 } 16240 16241 // If this is a friend or a reference to a class in a dependent 16242 // context, don't try to make a decl for it. 16243 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16244 DC = computeDeclContext(SS, false); 16245 if (!DC) { 16246 IsDependent = true; 16247 return nullptr; 16248 } 16249 } else { 16250 DC = computeDeclContext(SS, true); 16251 if (!DC) { 16252 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 16253 << SS.getRange(); 16254 return nullptr; 16255 } 16256 } 16257 16258 if (RequireCompleteDeclContext(SS, DC)) 16259 return nullptr; 16260 16261 SearchDC = DC; 16262 // Look-up name inside 'foo::'. 16263 LookupQualifiedName(Previous, DC); 16264 16265 if (Previous.isAmbiguous()) 16266 return nullptr; 16267 16268 if (Previous.empty()) { 16269 // Name lookup did not find anything. However, if the 16270 // nested-name-specifier refers to the current instantiation, 16271 // and that current instantiation has any dependent base 16272 // classes, we might find something at instantiation time: treat 16273 // this as a dependent elaborated-type-specifier. 16274 // But this only makes any sense for reference-like lookups. 16275 if (Previous.wasNotFoundInCurrentInstantiation() && 16276 (TUK == TUK_Reference || TUK == TUK_Friend)) { 16277 IsDependent = true; 16278 return nullptr; 16279 } 16280 16281 // A tag 'foo::bar' must already exist. 16282 Diag(NameLoc, diag::err_not_tag_in_scope) 16283 << Kind << Name << DC << SS.getRange(); 16284 Name = nullptr; 16285 Invalid = true; 16286 goto CreateNewDecl; 16287 } 16288 } else if (Name) { 16289 // C++14 [class.mem]p14: 16290 // If T is the name of a class, then each of the following shall have a 16291 // name different from T: 16292 // -- every member of class T that is itself a type 16293 if (TUK != TUK_Reference && TUK != TUK_Friend && 16294 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 16295 return nullptr; 16296 16297 // If this is a named struct, check to see if there was a previous forward 16298 // declaration or definition. 16299 // FIXME: We're looking into outer scopes here, even when we 16300 // shouldn't be. Doing so can result in ambiguities that we 16301 // shouldn't be diagnosing. 16302 LookupName(Previous, S); 16303 16304 // When declaring or defining a tag, ignore ambiguities introduced 16305 // by types using'ed into this scope. 16306 if (Previous.isAmbiguous() && 16307 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 16308 LookupResult::Filter F = Previous.makeFilter(); 16309 while (F.hasNext()) { 16310 NamedDecl *ND = F.next(); 16311 if (!ND->getDeclContext()->getRedeclContext()->Equals( 16312 SearchDC->getRedeclContext())) 16313 F.erase(); 16314 } 16315 F.done(); 16316 } 16317 16318 // C++11 [namespace.memdef]p3: 16319 // If the name in a friend declaration is neither qualified nor 16320 // a template-id and the declaration is a function or an 16321 // elaborated-type-specifier, the lookup to determine whether 16322 // the entity has been previously declared shall not consider 16323 // any scopes outside the innermost enclosing namespace. 16324 // 16325 // MSVC doesn't implement the above rule for types, so a friend tag 16326 // declaration may be a redeclaration of a type declared in an enclosing 16327 // scope. They do implement this rule for friend functions. 16328 // 16329 // Does it matter that this should be by scope instead of by 16330 // semantic context? 16331 if (!Previous.empty() && TUK == TUK_Friend) { 16332 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 16333 LookupResult::Filter F = Previous.makeFilter(); 16334 bool FriendSawTagOutsideEnclosingNamespace = false; 16335 while (F.hasNext()) { 16336 NamedDecl *ND = F.next(); 16337 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 16338 if (DC->isFileContext() && 16339 !EnclosingNS->Encloses(ND->getDeclContext())) { 16340 if (getLangOpts().MSVCCompat) 16341 FriendSawTagOutsideEnclosingNamespace = true; 16342 else 16343 F.erase(); 16344 } 16345 } 16346 F.done(); 16347 16348 // Diagnose this MSVC extension in the easy case where lookup would have 16349 // unambiguously found something outside the enclosing namespace. 16350 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 16351 NamedDecl *ND = Previous.getFoundDecl(); 16352 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 16353 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 16354 } 16355 } 16356 16357 // Note: there used to be some attempt at recovery here. 16358 if (Previous.isAmbiguous()) 16359 return nullptr; 16360 16361 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 16362 // FIXME: This makes sure that we ignore the contexts associated 16363 // with C structs, unions, and enums when looking for a matching 16364 // tag declaration or definition. See the similar lookup tweak 16365 // in Sema::LookupName; is there a better way to deal with this? 16366 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) 16367 SearchDC = SearchDC->getParent(); 16368 } else if (getLangOpts().CPlusPlus) { 16369 // Inside ObjCContainer want to keep it as a lexical decl context but go 16370 // past it (most often to TranslationUnit) to find the semantic decl 16371 // context. 16372 while (isa<ObjCContainerDecl>(SearchDC)) 16373 SearchDC = SearchDC->getParent(); 16374 } 16375 } else if (getLangOpts().CPlusPlus) { 16376 // Don't use ObjCContainerDecl as the semantic decl context for anonymous 16377 // TagDecl the same way as we skip it for named TagDecl. 16378 while (isa<ObjCContainerDecl>(SearchDC)) 16379 SearchDC = SearchDC->getParent(); 16380 } 16381 16382 if (Previous.isSingleResult() && 16383 Previous.getFoundDecl()->isTemplateParameter()) { 16384 // Maybe we will complain about the shadowed template parameter. 16385 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 16386 // Just pretend that we didn't see the previous declaration. 16387 Previous.clear(); 16388 } 16389 16390 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 16391 DC->Equals(getStdNamespace())) { 16392 if (Name->isStr("bad_alloc")) { 16393 // This is a declaration of or a reference to "std::bad_alloc". 16394 isStdBadAlloc = true; 16395 16396 // If std::bad_alloc has been implicitly declared (but made invisible to 16397 // name lookup), fill in this implicit declaration as the previous 16398 // declaration, so that the declarations get chained appropriately. 16399 if (Previous.empty() && StdBadAlloc) 16400 Previous.addDecl(getStdBadAlloc()); 16401 } else if (Name->isStr("align_val_t")) { 16402 isStdAlignValT = true; 16403 if (Previous.empty() && StdAlignValT) 16404 Previous.addDecl(getStdAlignValT()); 16405 } 16406 } 16407 16408 // If we didn't find a previous declaration, and this is a reference 16409 // (or friend reference), move to the correct scope. In C++, we 16410 // also need to do a redeclaration lookup there, just in case 16411 // there's a shadow friend decl. 16412 if (Name && Previous.empty() && 16413 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 16414 if (Invalid) goto CreateNewDecl; 16415 assert(SS.isEmpty()); 16416 16417 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 16418 // C++ [basic.scope.pdecl]p5: 16419 // -- for an elaborated-type-specifier of the form 16420 // 16421 // class-key identifier 16422 // 16423 // if the elaborated-type-specifier is used in the 16424 // decl-specifier-seq or parameter-declaration-clause of a 16425 // function defined in namespace scope, the identifier is 16426 // declared as a class-name in the namespace that contains 16427 // the declaration; otherwise, except as a friend 16428 // declaration, the identifier is declared in the smallest 16429 // non-class, non-function-prototype scope that contains the 16430 // declaration. 16431 // 16432 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 16433 // C structs and unions. 16434 // 16435 // It is an error in C++ to declare (rather than define) an enum 16436 // type, including via an elaborated type specifier. We'll 16437 // diagnose that later; for now, declare the enum in the same 16438 // scope as we would have picked for any other tag type. 16439 // 16440 // GNU C also supports this behavior as part of its incomplete 16441 // enum types extension, while GNU C++ does not. 16442 // 16443 // Find the context where we'll be declaring the tag. 16444 // FIXME: We would like to maintain the current DeclContext as the 16445 // lexical context, 16446 SearchDC = getTagInjectionContext(SearchDC); 16447 16448 // Find the scope where we'll be declaring the tag. 16449 S = getTagInjectionScope(S, getLangOpts()); 16450 } else { 16451 assert(TUK == TUK_Friend); 16452 // C++ [namespace.memdef]p3: 16453 // If a friend declaration in a non-local class first declares a 16454 // class or function, the friend class or function is a member of 16455 // the innermost enclosing namespace. 16456 SearchDC = SearchDC->getEnclosingNamespaceContext(); 16457 } 16458 16459 // In C++, we need to do a redeclaration lookup to properly 16460 // diagnose some problems. 16461 // FIXME: redeclaration lookup is also used (with and without C++) to find a 16462 // hidden declaration so that we don't get ambiguity errors when using a 16463 // type declared by an elaborated-type-specifier. In C that is not correct 16464 // and we should instead merge compatible types found by lookup. 16465 if (getLangOpts().CPlusPlus) { 16466 // FIXME: This can perform qualified lookups into function contexts, 16467 // which are meaningless. 16468 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16469 LookupQualifiedName(Previous, SearchDC); 16470 } else { 16471 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16472 LookupName(Previous, S); 16473 } 16474 } 16475 16476 // If we have a known previous declaration to use, then use it. 16477 if (Previous.empty() && SkipBody && SkipBody->Previous) 16478 Previous.addDecl(SkipBody->Previous); 16479 16480 if (!Previous.empty()) { 16481 NamedDecl *PrevDecl = Previous.getFoundDecl(); 16482 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 16483 16484 // It's okay to have a tag decl in the same scope as a typedef 16485 // which hides a tag decl in the same scope. Finding this 16486 // with a redeclaration lookup can only actually happen in C++. 16487 // 16488 // This is also okay for elaborated-type-specifiers, which is 16489 // technically forbidden by the current standard but which is 16490 // okay according to the likely resolution of an open issue; 16491 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16492 if (getLangOpts().CPlusPlus) { 16493 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16494 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16495 TagDecl *Tag = TT->getDecl(); 16496 if (Tag->getDeclName() == Name && 16497 Tag->getDeclContext()->getRedeclContext() 16498 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16499 PrevDecl = Tag; 16500 Previous.clear(); 16501 Previous.addDecl(Tag); 16502 Previous.resolveKind(); 16503 } 16504 } 16505 } 16506 } 16507 16508 // If this is a redeclaration of a using shadow declaration, it must 16509 // declare a tag in the same context. In MSVC mode, we allow a 16510 // redefinition if either context is within the other. 16511 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16512 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16513 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16514 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16515 !(OldTag && isAcceptableTagRedeclContext( 16516 *this, OldTag->getDeclContext(), SearchDC))) { 16517 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16518 Diag(Shadow->getTargetDecl()->getLocation(), 16519 diag::note_using_decl_target); 16520 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16521 << 0; 16522 // Recover by ignoring the old declaration. 16523 Previous.clear(); 16524 goto CreateNewDecl; 16525 } 16526 } 16527 16528 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16529 // If this is a use of a previous tag, or if the tag is already declared 16530 // in the same scope (so that the definition/declaration completes or 16531 // rementions the tag), reuse the decl. 16532 if (TUK == TUK_Reference || TUK == TUK_Friend || 16533 isDeclInScope(DirectPrevDecl, SearchDC, S, 16534 SS.isNotEmpty() || isMemberSpecialization)) { 16535 // Make sure that this wasn't declared as an enum and now used as a 16536 // struct or something similar. 16537 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16538 TUK == TUK_Definition, KWLoc, 16539 Name)) { 16540 bool SafeToContinue 16541 = (PrevTagDecl->getTagKind() != TTK_Enum && 16542 Kind != TTK_Enum); 16543 if (SafeToContinue) 16544 Diag(KWLoc, diag::err_use_with_wrong_tag) 16545 << Name 16546 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16547 PrevTagDecl->getKindName()); 16548 else 16549 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16550 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16551 16552 if (SafeToContinue) 16553 Kind = PrevTagDecl->getTagKind(); 16554 else { 16555 // Recover by making this an anonymous redefinition. 16556 Name = nullptr; 16557 Previous.clear(); 16558 Invalid = true; 16559 } 16560 } 16561 16562 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16563 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16564 if (TUK == TUK_Reference || TUK == TUK_Friend) 16565 return PrevTagDecl; 16566 16567 QualType EnumUnderlyingTy; 16568 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16569 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16570 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16571 EnumUnderlyingTy = QualType(T, 0); 16572 16573 // All conflicts with previous declarations are recovered by 16574 // returning the previous declaration, unless this is a definition, 16575 // in which case we want the caller to bail out. 16576 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16577 ScopedEnum, EnumUnderlyingTy, 16578 IsFixed, PrevEnum)) 16579 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16580 } 16581 16582 // C++11 [class.mem]p1: 16583 // A member shall not be declared twice in the member-specification, 16584 // except that a nested class or member class template can be declared 16585 // and then later defined. 16586 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16587 S->isDeclScope(PrevDecl)) { 16588 Diag(NameLoc, diag::ext_member_redeclared); 16589 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16590 } 16591 16592 if (!Invalid) { 16593 // If this is a use, just return the declaration we found, unless 16594 // we have attributes. 16595 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16596 if (!Attrs.empty()) { 16597 // FIXME: Diagnose these attributes. For now, we create a new 16598 // declaration to hold them. 16599 } else if (TUK == TUK_Reference && 16600 (PrevTagDecl->getFriendObjectKind() == 16601 Decl::FOK_Undeclared || 16602 PrevDecl->getOwningModule() != getCurrentModule()) && 16603 SS.isEmpty()) { 16604 // This declaration is a reference to an existing entity, but 16605 // has different visibility from that entity: it either makes 16606 // a friend visible or it makes a type visible in a new module. 16607 // In either case, create a new declaration. We only do this if 16608 // the declaration would have meant the same thing if no prior 16609 // declaration were found, that is, if it was found in the same 16610 // scope where we would have injected a declaration. 16611 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16612 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16613 return PrevTagDecl; 16614 // This is in the injected scope, create a new declaration in 16615 // that scope. 16616 S = getTagInjectionScope(S, getLangOpts()); 16617 } else { 16618 return PrevTagDecl; 16619 } 16620 } 16621 16622 // Diagnose attempts to redefine a tag. 16623 if (TUK == TUK_Definition) { 16624 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16625 // If we're defining a specialization and the previous definition 16626 // is from an implicit instantiation, don't emit an error 16627 // here; we'll catch this in the general case below. 16628 bool IsExplicitSpecializationAfterInstantiation = false; 16629 if (isMemberSpecialization) { 16630 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16631 IsExplicitSpecializationAfterInstantiation = 16632 RD->getTemplateSpecializationKind() != 16633 TSK_ExplicitSpecialization; 16634 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16635 IsExplicitSpecializationAfterInstantiation = 16636 ED->getTemplateSpecializationKind() != 16637 TSK_ExplicitSpecialization; 16638 } 16639 16640 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16641 // not keep more that one definition around (merge them). However, 16642 // ensure the decl passes the structural compatibility check in 16643 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16644 NamedDecl *Hidden = nullptr; 16645 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16646 // There is a definition of this tag, but it is not visible. We 16647 // explicitly make use of C++'s one definition rule here, and 16648 // assume that this definition is identical to the hidden one 16649 // we already have. Make the existing definition visible and 16650 // use it in place of this one. 16651 if (!getLangOpts().CPlusPlus) { 16652 // Postpone making the old definition visible until after we 16653 // complete parsing the new one and do the structural 16654 // comparison. 16655 SkipBody->CheckSameAsPrevious = true; 16656 SkipBody->New = createTagFromNewDecl(); 16657 SkipBody->Previous = Def; 16658 return Def; 16659 } else { 16660 SkipBody->ShouldSkip = true; 16661 SkipBody->Previous = Def; 16662 makeMergedDefinitionVisible(Hidden); 16663 // Carry on and handle it like a normal definition. We'll 16664 // skip starting the definitiion later. 16665 } 16666 } else if (!IsExplicitSpecializationAfterInstantiation) { 16667 // A redeclaration in function prototype scope in C isn't 16668 // visible elsewhere, so merely issue a warning. 16669 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16670 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16671 else 16672 Diag(NameLoc, diag::err_redefinition) << Name; 16673 notePreviousDefinition(Def, 16674 NameLoc.isValid() ? NameLoc : KWLoc); 16675 // If this is a redefinition, recover by making this 16676 // struct be anonymous, which will make any later 16677 // references get the previous definition. 16678 Name = nullptr; 16679 Previous.clear(); 16680 Invalid = true; 16681 } 16682 } else { 16683 // If the type is currently being defined, complain 16684 // about a nested redefinition. 16685 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16686 if (TD->isBeingDefined()) { 16687 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16688 Diag(PrevTagDecl->getLocation(), 16689 diag::note_previous_definition); 16690 Name = nullptr; 16691 Previous.clear(); 16692 Invalid = true; 16693 } 16694 } 16695 16696 // Okay, this is definition of a previously declared or referenced 16697 // tag. We're going to create a new Decl for it. 16698 } 16699 16700 // Okay, we're going to make a redeclaration. If this is some kind 16701 // of reference, make sure we build the redeclaration in the same DC 16702 // as the original, and ignore the current access specifier. 16703 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16704 SearchDC = PrevTagDecl->getDeclContext(); 16705 AS = AS_none; 16706 } 16707 } 16708 // If we get here we have (another) forward declaration or we 16709 // have a definition. Just create a new decl. 16710 16711 } else { 16712 // If we get here, this is a definition of a new tag type in a nested 16713 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16714 // new decl/type. We set PrevDecl to NULL so that the entities 16715 // have distinct types. 16716 Previous.clear(); 16717 } 16718 // If we get here, we're going to create a new Decl. If PrevDecl 16719 // is non-NULL, it's a definition of the tag declared by 16720 // PrevDecl. If it's NULL, we have a new definition. 16721 16722 // Otherwise, PrevDecl is not a tag, but was found with tag 16723 // lookup. This is only actually possible in C++, where a few 16724 // things like templates still live in the tag namespace. 16725 } else { 16726 // Use a better diagnostic if an elaborated-type-specifier 16727 // found the wrong kind of type on the first 16728 // (non-redeclaration) lookup. 16729 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16730 !Previous.isForRedeclaration()) { 16731 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16732 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16733 << Kind; 16734 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16735 Invalid = true; 16736 16737 // Otherwise, only diagnose if the declaration is in scope. 16738 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16739 SS.isNotEmpty() || isMemberSpecialization)) { 16740 // do nothing 16741 16742 // Diagnose implicit declarations introduced by elaborated types. 16743 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16744 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16745 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16746 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16747 Invalid = true; 16748 16749 // Otherwise it's a declaration. Call out a particularly common 16750 // case here. 16751 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16752 unsigned Kind = 0; 16753 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16754 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16755 << Name << Kind << TND->getUnderlyingType(); 16756 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16757 Invalid = true; 16758 16759 // Otherwise, diagnose. 16760 } else { 16761 // The tag name clashes with something else in the target scope, 16762 // issue an error and recover by making this tag be anonymous. 16763 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16764 notePreviousDefinition(PrevDecl, NameLoc); 16765 Name = nullptr; 16766 Invalid = true; 16767 } 16768 16769 // The existing declaration isn't relevant to us; we're in a 16770 // new scope, so clear out the previous declaration. 16771 Previous.clear(); 16772 } 16773 } 16774 16775 CreateNewDecl: 16776 16777 TagDecl *PrevDecl = nullptr; 16778 if (Previous.isSingleResult()) 16779 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16780 16781 // If there is an identifier, use the location of the identifier as the 16782 // location of the decl, otherwise use the location of the struct/union 16783 // keyword. 16784 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16785 16786 // Otherwise, create a new declaration. If there is a previous 16787 // declaration of the same entity, the two will be linked via 16788 // PrevDecl. 16789 TagDecl *New; 16790 16791 if (Kind == TTK_Enum) { 16792 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16793 // enum X { A, B, C } D; D should chain to X. 16794 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16795 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16796 ScopedEnumUsesClassTag, IsFixed); 16797 16798 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16799 StdAlignValT = cast<EnumDecl>(New); 16800 16801 // If this is an undefined enum, warn. 16802 if (TUK != TUK_Definition && !Invalid) { 16803 TagDecl *Def; 16804 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16805 // C++0x: 7.2p2: opaque-enum-declaration. 16806 // Conflicts are diagnosed above. Do nothing. 16807 } 16808 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16809 Diag(Loc, diag::ext_forward_ref_enum_def) 16810 << New; 16811 Diag(Def->getLocation(), diag::note_previous_definition); 16812 } else { 16813 unsigned DiagID = diag::ext_forward_ref_enum; 16814 if (getLangOpts().MSVCCompat) 16815 DiagID = diag::ext_ms_forward_ref_enum; 16816 else if (getLangOpts().CPlusPlus) 16817 DiagID = diag::err_forward_ref_enum; 16818 Diag(Loc, DiagID); 16819 } 16820 } 16821 16822 if (EnumUnderlying) { 16823 EnumDecl *ED = cast<EnumDecl>(New); 16824 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16825 ED->setIntegerTypeSourceInfo(TI); 16826 else 16827 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16828 ED->setPromotionType(ED->getIntegerType()); 16829 assert(ED->isComplete() && "enum with type should be complete"); 16830 } 16831 } else { 16832 // struct/union/class 16833 16834 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16835 // struct X { int A; } D; D should chain to X. 16836 if (getLangOpts().CPlusPlus) { 16837 // FIXME: Look for a way to use RecordDecl for simple structs. 16838 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16839 cast_or_null<CXXRecordDecl>(PrevDecl)); 16840 16841 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16842 StdBadAlloc = cast<CXXRecordDecl>(New); 16843 } else 16844 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16845 cast_or_null<RecordDecl>(PrevDecl)); 16846 } 16847 16848 // C++11 [dcl.type]p3: 16849 // A type-specifier-seq shall not define a class or enumeration [...]. 16850 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16851 TUK == TUK_Definition) { 16852 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16853 << Context.getTagDeclType(New); 16854 Invalid = true; 16855 } 16856 16857 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16858 DC->getDeclKind() == Decl::Enum) { 16859 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16860 << Context.getTagDeclType(New); 16861 Invalid = true; 16862 } 16863 16864 // Maybe add qualifier info. 16865 if (SS.isNotEmpty()) { 16866 if (SS.isSet()) { 16867 // If this is either a declaration or a definition, check the 16868 // nested-name-specifier against the current context. 16869 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16870 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16871 isMemberSpecialization)) 16872 Invalid = true; 16873 16874 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16875 if (TemplateParameterLists.size() > 0) { 16876 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16877 } 16878 } 16879 else 16880 Invalid = true; 16881 } 16882 16883 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16884 // Add alignment attributes if necessary; these attributes are checked when 16885 // the ASTContext lays out the structure. 16886 // 16887 // It is important for implementing the correct semantics that this 16888 // happen here (in ActOnTag). The #pragma pack stack is 16889 // maintained as a result of parser callbacks which can occur at 16890 // many points during the parsing of a struct declaration (because 16891 // the #pragma tokens are effectively skipped over during the 16892 // parsing of the struct). 16893 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16894 AddAlignmentAttributesForRecord(RD); 16895 AddMsStructLayoutForRecord(RD); 16896 } 16897 } 16898 16899 if (ModulePrivateLoc.isValid()) { 16900 if (isMemberSpecialization) 16901 Diag(New->getLocation(), diag::err_module_private_specialization) 16902 << 2 16903 << FixItHint::CreateRemoval(ModulePrivateLoc); 16904 // __module_private__ does not apply to local classes. However, we only 16905 // diagnose this as an error when the declaration specifiers are 16906 // freestanding. Here, we just ignore the __module_private__. 16907 else if (!SearchDC->isFunctionOrMethod()) 16908 New->setModulePrivate(); 16909 } 16910 16911 // If this is a specialization of a member class (of a class template), 16912 // check the specialization. 16913 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16914 Invalid = true; 16915 16916 // If we're declaring or defining a tag in function prototype scope in C, 16917 // note that this type can only be used within the function and add it to 16918 // the list of decls to inject into the function definition scope. 16919 if ((Name || Kind == TTK_Enum) && 16920 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16921 if (getLangOpts().CPlusPlus) { 16922 // C++ [dcl.fct]p6: 16923 // Types shall not be defined in return or parameter types. 16924 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16925 Diag(Loc, diag::err_type_defined_in_param_type) 16926 << Name; 16927 Invalid = true; 16928 } 16929 } else if (!PrevDecl) { 16930 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16931 } 16932 } 16933 16934 if (Invalid) 16935 New->setInvalidDecl(); 16936 16937 // Set the lexical context. If the tag has a C++ scope specifier, the 16938 // lexical context will be different from the semantic context. 16939 New->setLexicalDeclContext(CurContext); 16940 16941 // Mark this as a friend decl if applicable. 16942 // In Microsoft mode, a friend declaration also acts as a forward 16943 // declaration so we always pass true to setObjectOfFriendDecl to make 16944 // the tag name visible. 16945 if (TUK == TUK_Friend) 16946 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16947 16948 // Set the access specifier. 16949 if (!Invalid && SearchDC->isRecord()) 16950 SetMemberAccessSpecifier(New, PrevDecl, AS); 16951 16952 if (PrevDecl) 16953 CheckRedeclarationInModule(New, PrevDecl); 16954 16955 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16956 New->startDefinition(); 16957 16958 ProcessDeclAttributeList(S, New, Attrs); 16959 AddPragmaAttributes(S, New); 16960 16961 // If this has an identifier, add it to the scope stack. 16962 if (TUK == TUK_Friend) { 16963 // We might be replacing an existing declaration in the lookup tables; 16964 // if so, borrow its access specifier. 16965 if (PrevDecl) 16966 New->setAccess(PrevDecl->getAccess()); 16967 16968 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16969 DC->makeDeclVisibleInContext(New); 16970 if (Name) // can be null along some error paths 16971 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16972 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16973 } else if (Name) { 16974 S = getNonFieldDeclScope(S); 16975 PushOnScopeChains(New, S, true); 16976 } else { 16977 CurContext->addDecl(New); 16978 } 16979 16980 // If this is the C FILE type, notify the AST context. 16981 if (IdentifierInfo *II = New->getIdentifier()) 16982 if (!New->isInvalidDecl() && 16983 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16984 II->isStr("FILE")) 16985 Context.setFILEDecl(New); 16986 16987 if (PrevDecl) 16988 mergeDeclAttributes(New, PrevDecl); 16989 16990 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16991 inferGslOwnerPointerAttribute(CXXRD); 16992 16993 // If there's a #pragma GCC visibility in scope, set the visibility of this 16994 // record. 16995 AddPushedVisibilityAttribute(New); 16996 16997 if (isMemberSpecialization && !New->isInvalidDecl()) 16998 CompleteMemberSpecialization(New, Previous); 16999 17000 OwnedDecl = true; 17001 // In C++, don't return an invalid declaration. We can't recover well from 17002 // the cases where we make the type anonymous. 17003 if (Invalid && getLangOpts().CPlusPlus) { 17004 if (New->isBeingDefined()) 17005 if (auto RD = dyn_cast<RecordDecl>(New)) 17006 RD->completeDefinition(); 17007 return nullptr; 17008 } else if (SkipBody && SkipBody->ShouldSkip) { 17009 return SkipBody->Previous; 17010 } else { 17011 return New; 17012 } 17013 } 17014 17015 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 17016 AdjustDeclIfTemplate(TagD); 17017 TagDecl *Tag = cast<TagDecl>(TagD); 17018 17019 // Enter the tag context. 17020 PushDeclContext(S, Tag); 17021 17022 ActOnDocumentableDecl(TagD); 17023 17024 // If there's a #pragma GCC visibility in scope, set the visibility of this 17025 // record. 17026 AddPushedVisibilityAttribute(Tag); 17027 } 17028 17029 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { 17030 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 17031 return false; 17032 17033 // Make the previous decl visible. 17034 makeMergedDefinitionVisible(SkipBody.Previous); 17035 return true; 17036 } 17037 17038 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) { 17039 assert(IDecl->getLexicalParent() == CurContext && 17040 "The next DeclContext should be lexically contained in the current one."); 17041 CurContext = IDecl; 17042 } 17043 17044 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 17045 SourceLocation FinalLoc, 17046 bool IsFinalSpelledSealed, 17047 bool IsAbstract, 17048 SourceLocation LBraceLoc) { 17049 AdjustDeclIfTemplate(TagD); 17050 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 17051 17052 FieldCollector->StartClass(); 17053 17054 if (!Record->getIdentifier()) 17055 return; 17056 17057 if (IsAbstract) 17058 Record->markAbstract(); 17059 17060 if (FinalLoc.isValid()) { 17061 Record->addAttr(FinalAttr::Create( 17062 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 17063 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 17064 } 17065 // C++ [class]p2: 17066 // [...] The class-name is also inserted into the scope of the 17067 // class itself; this is known as the injected-class-name. For 17068 // purposes of access checking, the injected-class-name is treated 17069 // as if it were a public member name. 17070 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 17071 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 17072 Record->getLocation(), Record->getIdentifier(), 17073 /*PrevDecl=*/nullptr, 17074 /*DelayTypeCreation=*/true); 17075 Context.getTypeDeclType(InjectedClassName, Record); 17076 InjectedClassName->setImplicit(); 17077 InjectedClassName->setAccess(AS_public); 17078 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 17079 InjectedClassName->setDescribedClassTemplate(Template); 17080 PushOnScopeChains(InjectedClassName, S); 17081 assert(InjectedClassName->isInjectedClassName() && 17082 "Broken injected-class-name"); 17083 } 17084 17085 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 17086 SourceRange BraceRange) { 17087 AdjustDeclIfTemplate(TagD); 17088 TagDecl *Tag = cast<TagDecl>(TagD); 17089 Tag->setBraceRange(BraceRange); 17090 17091 // Make sure we "complete" the definition even it is invalid. 17092 if (Tag->isBeingDefined()) { 17093 assert(Tag->isInvalidDecl() && "We should already have completed it"); 17094 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 17095 RD->completeDefinition(); 17096 } 17097 17098 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 17099 FieldCollector->FinishClass(); 17100 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 17101 auto *Def = RD->getDefinition(); 17102 assert(Def && "The record is expected to have a completed definition"); 17103 unsigned NumInitMethods = 0; 17104 for (auto *Method : Def->methods()) { 17105 if (!Method->getIdentifier()) 17106 continue; 17107 if (Method->getName() == "__init") 17108 NumInitMethods++; 17109 } 17110 if (NumInitMethods > 1 || !Def->hasInitMethod()) 17111 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 17112 } 17113 } 17114 17115 // Exit this scope of this tag's definition. 17116 PopDeclContext(); 17117 17118 if (getCurLexicalContext()->isObjCContainer() && 17119 Tag->getDeclContext()->isFileContext()) 17120 Tag->setTopLevelDeclInObjCContainer(); 17121 17122 // Notify the consumer that we've defined a tag. 17123 if (!Tag->isInvalidDecl()) 17124 Consumer.HandleTagDeclDefinition(Tag); 17125 17126 // Clangs implementation of #pragma align(packed) differs in bitfield layout 17127 // from XLs and instead matches the XL #pragma pack(1) behavior. 17128 if (Context.getTargetInfo().getTriple().isOSAIX() && 17129 AlignPackStack.hasValue()) { 17130 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 17131 // Only diagnose #pragma align(packed). 17132 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 17133 return; 17134 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 17135 if (!RD) 17136 return; 17137 // Only warn if there is at least 1 bitfield member. 17138 if (llvm::any_of(RD->fields(), 17139 [](const FieldDecl *FD) { return FD->isBitField(); })) 17140 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 17141 } 17142 } 17143 17144 void Sema::ActOnObjCContainerFinishDefinition() { 17145 // Exit this scope of this interface definition. 17146 PopDeclContext(); 17147 } 17148 17149 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) { 17150 assert(ObjCCtx == CurContext && "Mismatch of container contexts"); 17151 OriginalLexicalContext = ObjCCtx; 17152 ActOnObjCContainerFinishDefinition(); 17153 } 17154 17155 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) { 17156 ActOnObjCContainerStartDefinition(ObjCCtx); 17157 OriginalLexicalContext = nullptr; 17158 } 17159 17160 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 17161 AdjustDeclIfTemplate(TagD); 17162 TagDecl *Tag = cast<TagDecl>(TagD); 17163 Tag->setInvalidDecl(); 17164 17165 // Make sure we "complete" the definition even it is invalid. 17166 if (Tag->isBeingDefined()) { 17167 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 17168 RD->completeDefinition(); 17169 } 17170 17171 // We're undoing ActOnTagStartDefinition here, not 17172 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 17173 // the FieldCollector. 17174 17175 PopDeclContext(); 17176 } 17177 17178 // Note that FieldName may be null for anonymous bitfields. 17179 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 17180 IdentifierInfo *FieldName, QualType FieldTy, 17181 bool IsMsStruct, Expr *BitWidth) { 17182 assert(BitWidth); 17183 if (BitWidth->containsErrors()) 17184 return ExprError(); 17185 17186 // C99 6.7.2.1p4 - verify the field type. 17187 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 17188 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 17189 // Handle incomplete and sizeless types with a specific error. 17190 if (RequireCompleteSizedType(FieldLoc, FieldTy, 17191 diag::err_field_incomplete_or_sizeless)) 17192 return ExprError(); 17193 if (FieldName) 17194 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 17195 << FieldName << FieldTy << BitWidth->getSourceRange(); 17196 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 17197 << FieldTy << BitWidth->getSourceRange(); 17198 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 17199 UPPC_BitFieldWidth)) 17200 return ExprError(); 17201 17202 // If the bit-width is type- or value-dependent, don't try to check 17203 // it now. 17204 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 17205 return BitWidth; 17206 17207 llvm::APSInt Value; 17208 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 17209 if (ICE.isInvalid()) 17210 return ICE; 17211 BitWidth = ICE.get(); 17212 17213 // Zero-width bitfield is ok for anonymous field. 17214 if (Value == 0 && FieldName) 17215 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 17216 17217 if (Value.isSigned() && Value.isNegative()) { 17218 if (FieldName) 17219 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 17220 << FieldName << toString(Value, 10); 17221 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 17222 << toString(Value, 10); 17223 } 17224 17225 // The size of the bit-field must not exceed our maximum permitted object 17226 // size. 17227 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 17228 return Diag(FieldLoc, diag::err_bitfield_too_wide) 17229 << !FieldName << FieldName << toString(Value, 10); 17230 } 17231 17232 if (!FieldTy->isDependentType()) { 17233 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 17234 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 17235 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 17236 17237 // Over-wide bitfields are an error in C or when using the MSVC bitfield 17238 // ABI. 17239 bool CStdConstraintViolation = 17240 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 17241 bool MSBitfieldViolation = 17242 Value.ugt(TypeStorageSize) && 17243 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 17244 if (CStdConstraintViolation || MSBitfieldViolation) { 17245 unsigned DiagWidth = 17246 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 17247 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 17248 << (bool)FieldName << FieldName << toString(Value, 10) 17249 << !CStdConstraintViolation << DiagWidth; 17250 } 17251 17252 // Warn on types where the user might conceivably expect to get all 17253 // specified bits as value bits: that's all integral types other than 17254 // 'bool'. 17255 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 17256 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 17257 << FieldName << toString(Value, 10) 17258 << (unsigned)TypeWidth; 17259 } 17260 } 17261 17262 return BitWidth; 17263 } 17264 17265 /// ActOnField - Each field of a C struct/union is passed into this in order 17266 /// to create a FieldDecl object for it. 17267 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 17268 Declarator &D, Expr *BitfieldWidth) { 17269 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 17270 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 17271 /*InitStyle=*/ICIS_NoInit, AS_public); 17272 return Res; 17273 } 17274 17275 /// HandleField - Analyze a field of a C struct or a C++ data member. 17276 /// 17277 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 17278 SourceLocation DeclStart, 17279 Declarator &D, Expr *BitWidth, 17280 InClassInitStyle InitStyle, 17281 AccessSpecifier AS) { 17282 if (D.isDecompositionDeclarator()) { 17283 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 17284 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 17285 << Decomp.getSourceRange(); 17286 return nullptr; 17287 } 17288 17289 IdentifierInfo *II = D.getIdentifier(); 17290 SourceLocation Loc = DeclStart; 17291 if (II) Loc = D.getIdentifierLoc(); 17292 17293 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17294 QualType T = TInfo->getType(); 17295 if (getLangOpts().CPlusPlus) { 17296 CheckExtraCXXDefaultArguments(D); 17297 17298 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17299 UPPC_DataMemberType)) { 17300 D.setInvalidType(); 17301 T = Context.IntTy; 17302 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17303 } 17304 } 17305 17306 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17307 17308 if (D.getDeclSpec().isInlineSpecified()) 17309 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17310 << getLangOpts().CPlusPlus17; 17311 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17312 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17313 diag::err_invalid_thread) 17314 << DeclSpec::getSpecifierName(TSCS); 17315 17316 // Check to see if this name was declared as a member previously 17317 NamedDecl *PrevDecl = nullptr; 17318 LookupResult Previous(*this, II, Loc, LookupMemberName, 17319 ForVisibleRedeclaration); 17320 LookupName(Previous, S); 17321 switch (Previous.getResultKind()) { 17322 case LookupResult::Found: 17323 case LookupResult::FoundUnresolvedValue: 17324 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17325 break; 17326 17327 case LookupResult::FoundOverloaded: 17328 PrevDecl = Previous.getRepresentativeDecl(); 17329 break; 17330 17331 case LookupResult::NotFound: 17332 case LookupResult::NotFoundInCurrentInstantiation: 17333 case LookupResult::Ambiguous: 17334 break; 17335 } 17336 Previous.suppressDiagnostics(); 17337 17338 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17339 // Maybe we will complain about the shadowed template parameter. 17340 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17341 // Just pretend that we didn't see the previous declaration. 17342 PrevDecl = nullptr; 17343 } 17344 17345 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17346 PrevDecl = nullptr; 17347 17348 bool Mutable 17349 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 17350 SourceLocation TSSL = D.getBeginLoc(); 17351 FieldDecl *NewFD 17352 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 17353 TSSL, AS, PrevDecl, &D); 17354 17355 if (NewFD->isInvalidDecl()) 17356 Record->setInvalidDecl(); 17357 17358 if (D.getDeclSpec().isModulePrivateSpecified()) 17359 NewFD->setModulePrivate(); 17360 17361 if (NewFD->isInvalidDecl() && PrevDecl) { 17362 // Don't introduce NewFD into scope; there's already something 17363 // with the same name in the same scope. 17364 } else if (II) { 17365 PushOnScopeChains(NewFD, S); 17366 } else 17367 Record->addDecl(NewFD); 17368 17369 return NewFD; 17370 } 17371 17372 /// Build a new FieldDecl and check its well-formedness. 17373 /// 17374 /// This routine builds a new FieldDecl given the fields name, type, 17375 /// record, etc. \p PrevDecl should refer to any previous declaration 17376 /// with the same name and in the same scope as the field to be 17377 /// created. 17378 /// 17379 /// \returns a new FieldDecl. 17380 /// 17381 /// \todo The Declarator argument is a hack. It will be removed once 17382 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 17383 TypeSourceInfo *TInfo, 17384 RecordDecl *Record, SourceLocation Loc, 17385 bool Mutable, Expr *BitWidth, 17386 InClassInitStyle InitStyle, 17387 SourceLocation TSSL, 17388 AccessSpecifier AS, NamedDecl *PrevDecl, 17389 Declarator *D) { 17390 IdentifierInfo *II = Name.getAsIdentifierInfo(); 17391 bool InvalidDecl = false; 17392 if (D) InvalidDecl = D->isInvalidType(); 17393 17394 // If we receive a broken type, recover by assuming 'int' and 17395 // marking this declaration as invalid. 17396 if (T.isNull() || T->containsErrors()) { 17397 InvalidDecl = true; 17398 T = Context.IntTy; 17399 } 17400 17401 QualType EltTy = Context.getBaseElementType(T); 17402 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 17403 if (RequireCompleteSizedType(Loc, EltTy, 17404 diag::err_field_incomplete_or_sizeless)) { 17405 // Fields of incomplete type force their record to be invalid. 17406 Record->setInvalidDecl(); 17407 InvalidDecl = true; 17408 } else { 17409 NamedDecl *Def; 17410 EltTy->isIncompleteType(&Def); 17411 if (Def && Def->isInvalidDecl()) { 17412 Record->setInvalidDecl(); 17413 InvalidDecl = true; 17414 } 17415 } 17416 } 17417 17418 // TR 18037 does not allow fields to be declared with address space 17419 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 17420 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 17421 Diag(Loc, diag::err_field_with_address_space); 17422 Record->setInvalidDecl(); 17423 InvalidDecl = true; 17424 } 17425 17426 if (LangOpts.OpenCL) { 17427 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 17428 // used as structure or union field: image, sampler, event or block types. 17429 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 17430 T->isBlockPointerType()) { 17431 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 17432 Record->setInvalidDecl(); 17433 InvalidDecl = true; 17434 } 17435 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 17436 // is enabled. 17437 if (BitWidth && !getOpenCLOptions().isAvailableOption( 17438 "__cl_clang_bitfields", LangOpts)) { 17439 Diag(Loc, diag::err_opencl_bitfields); 17440 InvalidDecl = true; 17441 } 17442 } 17443 17444 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 17445 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 17446 T.hasQualifiers()) { 17447 InvalidDecl = true; 17448 Diag(Loc, diag::err_anon_bitfield_qualifiers); 17449 } 17450 17451 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17452 // than a variably modified type. 17453 if (!InvalidDecl && T->isVariablyModifiedType()) { 17454 if (!tryToFixVariablyModifiedVarType( 17455 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 17456 InvalidDecl = true; 17457 } 17458 17459 // Fields can not have abstract class types 17460 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 17461 diag::err_abstract_type_in_decl, 17462 AbstractFieldType)) 17463 InvalidDecl = true; 17464 17465 if (InvalidDecl) 17466 BitWidth = nullptr; 17467 // If this is declared as a bit-field, check the bit-field. 17468 if (BitWidth) { 17469 BitWidth = 17470 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get(); 17471 if (!BitWidth) { 17472 InvalidDecl = true; 17473 BitWidth = nullptr; 17474 } 17475 } 17476 17477 // Check that 'mutable' is consistent with the type of the declaration. 17478 if (!InvalidDecl && Mutable) { 17479 unsigned DiagID = 0; 17480 if (T->isReferenceType()) 17481 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 17482 : diag::err_mutable_reference; 17483 else if (T.isConstQualified()) 17484 DiagID = diag::err_mutable_const; 17485 17486 if (DiagID) { 17487 SourceLocation ErrLoc = Loc; 17488 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17489 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17490 Diag(ErrLoc, DiagID); 17491 if (DiagID != diag::ext_mutable_reference) { 17492 Mutable = false; 17493 InvalidDecl = true; 17494 } 17495 } 17496 } 17497 17498 // C++11 [class.union]p8 (DR1460): 17499 // At most one variant member of a union may have a 17500 // brace-or-equal-initializer. 17501 if (InitStyle != ICIS_NoInit) 17502 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17503 17504 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17505 BitWidth, Mutable, InitStyle); 17506 if (InvalidDecl) 17507 NewFD->setInvalidDecl(); 17508 17509 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17510 Diag(Loc, diag::err_duplicate_member) << II; 17511 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17512 NewFD->setInvalidDecl(); 17513 } 17514 17515 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17516 if (Record->isUnion()) { 17517 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17518 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17519 if (RDecl->getDefinition()) { 17520 // C++ [class.union]p1: An object of a class with a non-trivial 17521 // constructor, a non-trivial copy constructor, a non-trivial 17522 // destructor, or a non-trivial copy assignment operator 17523 // cannot be a member of a union, nor can an array of such 17524 // objects. 17525 if (CheckNontrivialField(NewFD)) 17526 NewFD->setInvalidDecl(); 17527 } 17528 } 17529 17530 // C++ [class.union]p1: If a union contains a member of reference type, 17531 // the program is ill-formed, except when compiling with MSVC extensions 17532 // enabled. 17533 if (EltTy->isReferenceType()) { 17534 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17535 diag::ext_union_member_of_reference_type : 17536 diag::err_union_member_of_reference_type) 17537 << NewFD->getDeclName() << EltTy; 17538 if (!getLangOpts().MicrosoftExt) 17539 NewFD->setInvalidDecl(); 17540 } 17541 } 17542 } 17543 17544 // FIXME: We need to pass in the attributes given an AST 17545 // representation, not a parser representation. 17546 if (D) { 17547 // FIXME: The current scope is almost... but not entirely... correct here. 17548 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17549 17550 if (NewFD->hasAttrs()) 17551 CheckAlignasUnderalignment(NewFD); 17552 } 17553 17554 // In auto-retain/release, infer strong retension for fields of 17555 // retainable type. 17556 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17557 NewFD->setInvalidDecl(); 17558 17559 if (T.isObjCGCWeak()) 17560 Diag(Loc, diag::warn_attribute_weak_on_field); 17561 17562 // PPC MMA non-pointer types are not allowed as field types. 17563 if (Context.getTargetInfo().getTriple().isPPC64() && 17564 CheckPPCMMAType(T, NewFD->getLocation())) 17565 NewFD->setInvalidDecl(); 17566 17567 NewFD->setAccess(AS); 17568 return NewFD; 17569 } 17570 17571 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17572 assert(FD); 17573 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17574 17575 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17576 return false; 17577 17578 QualType EltTy = Context.getBaseElementType(FD->getType()); 17579 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17580 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17581 if (RDecl->getDefinition()) { 17582 // We check for copy constructors before constructors 17583 // because otherwise we'll never get complaints about 17584 // copy constructors. 17585 17586 CXXSpecialMember member = CXXInvalid; 17587 // We're required to check for any non-trivial constructors. Since the 17588 // implicit default constructor is suppressed if there are any 17589 // user-declared constructors, we just need to check that there is a 17590 // trivial default constructor and a trivial copy constructor. (We don't 17591 // worry about move constructors here, since this is a C++98 check.) 17592 if (RDecl->hasNonTrivialCopyConstructor()) 17593 member = CXXCopyConstructor; 17594 else if (!RDecl->hasTrivialDefaultConstructor()) 17595 member = CXXDefaultConstructor; 17596 else if (RDecl->hasNonTrivialCopyAssignment()) 17597 member = CXXCopyAssignment; 17598 else if (RDecl->hasNonTrivialDestructor()) 17599 member = CXXDestructor; 17600 17601 if (member != CXXInvalid) { 17602 if (!getLangOpts().CPlusPlus11 && 17603 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17604 // Objective-C++ ARC: it is an error to have a non-trivial field of 17605 // a union. However, system headers in Objective-C programs 17606 // occasionally have Objective-C lifetime objects within unions, 17607 // and rather than cause the program to fail, we make those 17608 // members unavailable. 17609 SourceLocation Loc = FD->getLocation(); 17610 if (getSourceManager().isInSystemHeader(Loc)) { 17611 if (!FD->hasAttr<UnavailableAttr>()) 17612 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17613 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17614 return false; 17615 } 17616 } 17617 17618 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17619 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17620 diag::err_illegal_union_or_anon_struct_member) 17621 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17622 DiagnoseNontrivial(RDecl, member); 17623 return !getLangOpts().CPlusPlus11; 17624 } 17625 } 17626 } 17627 17628 return false; 17629 } 17630 17631 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17632 /// AST enum value. 17633 static ObjCIvarDecl::AccessControl 17634 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17635 switch (ivarVisibility) { 17636 default: llvm_unreachable("Unknown visitibility kind"); 17637 case tok::objc_private: return ObjCIvarDecl::Private; 17638 case tok::objc_public: return ObjCIvarDecl::Public; 17639 case tok::objc_protected: return ObjCIvarDecl::Protected; 17640 case tok::objc_package: return ObjCIvarDecl::Package; 17641 } 17642 } 17643 17644 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17645 /// in order to create an IvarDecl object for it. 17646 Decl *Sema::ActOnIvar(Scope *S, 17647 SourceLocation DeclStart, 17648 Declarator &D, Expr *BitfieldWidth, 17649 tok::ObjCKeywordKind Visibility) { 17650 17651 IdentifierInfo *II = D.getIdentifier(); 17652 Expr *BitWidth = (Expr*)BitfieldWidth; 17653 SourceLocation Loc = DeclStart; 17654 if (II) Loc = D.getIdentifierLoc(); 17655 17656 // FIXME: Unnamed fields can be handled in various different ways, for 17657 // example, unnamed unions inject all members into the struct namespace! 17658 17659 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17660 QualType T = TInfo->getType(); 17661 17662 if (BitWidth) { 17663 // 6.7.2.1p3, 6.7.2.1p4 17664 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17665 if (!BitWidth) 17666 D.setInvalidType(); 17667 } else { 17668 // Not a bitfield. 17669 17670 // validate II. 17671 17672 } 17673 if (T->isReferenceType()) { 17674 Diag(Loc, diag::err_ivar_reference_type); 17675 D.setInvalidType(); 17676 } 17677 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17678 // than a variably modified type. 17679 else if (T->isVariablyModifiedType()) { 17680 if (!tryToFixVariablyModifiedVarType( 17681 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17682 D.setInvalidType(); 17683 } 17684 17685 // Get the visibility (access control) for this ivar. 17686 ObjCIvarDecl::AccessControl ac = 17687 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17688 : ObjCIvarDecl::None; 17689 // Must set ivar's DeclContext to its enclosing interface. 17690 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17691 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17692 return nullptr; 17693 ObjCContainerDecl *EnclosingContext; 17694 if (ObjCImplementationDecl *IMPDecl = 17695 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17696 if (LangOpts.ObjCRuntime.isFragile()) { 17697 // Case of ivar declared in an implementation. Context is that of its class. 17698 EnclosingContext = IMPDecl->getClassInterface(); 17699 assert(EnclosingContext && "Implementation has no class interface!"); 17700 } 17701 else 17702 EnclosingContext = EnclosingDecl; 17703 } else { 17704 if (ObjCCategoryDecl *CDecl = 17705 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17706 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17707 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17708 return nullptr; 17709 } 17710 } 17711 EnclosingContext = EnclosingDecl; 17712 } 17713 17714 // Construct the decl. 17715 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17716 DeclStart, Loc, II, T, 17717 TInfo, ac, (Expr *)BitfieldWidth); 17718 17719 if (II) { 17720 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17721 ForVisibleRedeclaration); 17722 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17723 && !isa<TagDecl>(PrevDecl)) { 17724 Diag(Loc, diag::err_duplicate_member) << II; 17725 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17726 NewID->setInvalidDecl(); 17727 } 17728 } 17729 17730 // Process attributes attached to the ivar. 17731 ProcessDeclAttributes(S, NewID, D); 17732 17733 if (D.isInvalidType()) 17734 NewID->setInvalidDecl(); 17735 17736 // In ARC, infer 'retaining' for ivars of retainable type. 17737 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17738 NewID->setInvalidDecl(); 17739 17740 if (D.getDeclSpec().isModulePrivateSpecified()) 17741 NewID->setModulePrivate(); 17742 17743 if (II) { 17744 // FIXME: When interfaces are DeclContexts, we'll need to add 17745 // these to the interface. 17746 S->AddDecl(NewID); 17747 IdResolver.AddDecl(NewID); 17748 } 17749 17750 if (LangOpts.ObjCRuntime.isNonFragile() && 17751 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17752 Diag(Loc, diag::warn_ivars_in_interface); 17753 17754 return NewID; 17755 } 17756 17757 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17758 /// class and class extensions. For every class \@interface and class 17759 /// extension \@interface, if the last ivar is a bitfield of any type, 17760 /// then add an implicit `char :0` ivar to the end of that interface. 17761 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17762 SmallVectorImpl<Decl *> &AllIvarDecls) { 17763 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17764 return; 17765 17766 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17767 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17768 17769 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17770 return; 17771 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17772 if (!ID) { 17773 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17774 if (!CD->IsClassExtension()) 17775 return; 17776 } 17777 // No need to add this to end of @implementation. 17778 else 17779 return; 17780 } 17781 // All conditions are met. Add a new bitfield to the tail end of ivars. 17782 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17783 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17784 17785 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17786 DeclLoc, DeclLoc, nullptr, 17787 Context.CharTy, 17788 Context.getTrivialTypeSourceInfo(Context.CharTy, 17789 DeclLoc), 17790 ObjCIvarDecl::Private, BW, 17791 true); 17792 AllIvarDecls.push_back(Ivar); 17793 } 17794 17795 namespace { 17796 /// [class.dtor]p4: 17797 /// At the end of the definition of a class, overload resolution is 17798 /// performed among the prospective destructors declared in that class with 17799 /// an empty argument list to select the destructor for the class, also 17800 /// known as the selected destructor. 17801 /// 17802 /// We do the overload resolution here, then mark the selected constructor in the AST. 17803 /// Later CXXRecordDecl::getDestructor() will return the selected constructor. 17804 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) { 17805 if (!Record->hasUserDeclaredDestructor()) { 17806 return; 17807 } 17808 17809 SourceLocation Loc = Record->getLocation(); 17810 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal); 17811 17812 for (auto *Decl : Record->decls()) { 17813 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) { 17814 if (DD->isInvalidDecl()) 17815 continue; 17816 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {}, 17817 OCS); 17818 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected."); 17819 } 17820 } 17821 17822 if (OCS.empty()) { 17823 return; 17824 } 17825 OverloadCandidateSet::iterator Best; 17826 unsigned Msg = 0; 17827 OverloadCandidateDisplayKind DisplayKind; 17828 17829 switch (OCS.BestViableFunction(S, Loc, Best)) { 17830 case OR_Success: 17831 case OR_Deleted: 17832 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function)); 17833 break; 17834 17835 case OR_Ambiguous: 17836 Msg = diag::err_ambiguous_destructor; 17837 DisplayKind = OCD_AmbiguousCandidates; 17838 break; 17839 17840 case OR_No_Viable_Function: 17841 Msg = diag::err_no_viable_destructor; 17842 DisplayKind = OCD_AllCandidates; 17843 break; 17844 } 17845 17846 if (Msg) { 17847 // OpenCL have got their own thing going with destructors. It's slightly broken, 17848 // but we allow it. 17849 if (!S.LangOpts.OpenCL) { 17850 PartialDiagnostic Diag = S.PDiag(Msg) << Record; 17851 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {}); 17852 Record->setInvalidDecl(); 17853 } 17854 // It's a bit hacky: At this point we've raised an error but we want the 17855 // rest of the compiler to continue somehow working. However almost 17856 // everything we'll try to do with the class will depend on there being a 17857 // destructor. So let's pretend the first one is selected and hope for the 17858 // best. 17859 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function)); 17860 } 17861 } 17862 } // namespace 17863 17864 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17865 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17866 SourceLocation RBrac, 17867 const ParsedAttributesView &Attrs) { 17868 assert(EnclosingDecl && "missing record or interface decl"); 17869 17870 // If this is an Objective-C @implementation or category and we have 17871 // new fields here we should reset the layout of the interface since 17872 // it will now change. 17873 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17874 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17875 switch (DC->getKind()) { 17876 default: break; 17877 case Decl::ObjCCategory: 17878 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17879 break; 17880 case Decl::ObjCImplementation: 17881 Context. 17882 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17883 break; 17884 } 17885 } 17886 17887 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17888 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17889 17890 if (CXXRecord && !CXXRecord->isDependentType()) 17891 ComputeSelectedDestructor(*this, CXXRecord); 17892 17893 // Start counting up the number of named members; make sure to include 17894 // members of anonymous structs and unions in the total. 17895 unsigned NumNamedMembers = 0; 17896 if (Record) { 17897 for (const auto *I : Record->decls()) { 17898 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17899 if (IFD->getDeclName()) 17900 ++NumNamedMembers; 17901 } 17902 } 17903 17904 // Verify that all the fields are okay. 17905 SmallVector<FieldDecl*, 32> RecFields; 17906 17907 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17908 i != end; ++i) { 17909 FieldDecl *FD = cast<FieldDecl>(*i); 17910 17911 // Get the type for the field. 17912 const Type *FDTy = FD->getType().getTypePtr(); 17913 17914 if (!FD->isAnonymousStructOrUnion()) { 17915 // Remember all fields written by the user. 17916 RecFields.push_back(FD); 17917 } 17918 17919 // If the field is already invalid for some reason, don't emit more 17920 // diagnostics about it. 17921 if (FD->isInvalidDecl()) { 17922 EnclosingDecl->setInvalidDecl(); 17923 continue; 17924 } 17925 17926 // C99 6.7.2.1p2: 17927 // A structure or union shall not contain a member with 17928 // incomplete or function type (hence, a structure shall not 17929 // contain an instance of itself, but may contain a pointer to 17930 // an instance of itself), except that the last member of a 17931 // structure with more than one named member may have incomplete 17932 // array type; such a structure (and any union containing, 17933 // possibly recursively, a member that is such a structure) 17934 // shall not be a member of a structure or an element of an 17935 // array. 17936 bool IsLastField = (i + 1 == Fields.end()); 17937 if (FDTy->isFunctionType()) { 17938 // Field declared as a function. 17939 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17940 << FD->getDeclName(); 17941 FD->setInvalidDecl(); 17942 EnclosingDecl->setInvalidDecl(); 17943 continue; 17944 } else if (FDTy->isIncompleteArrayType() && 17945 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17946 if (Record) { 17947 // Flexible array member. 17948 // Microsoft and g++ is more permissive regarding flexible array. 17949 // It will accept flexible array in union and also 17950 // as the sole element of a struct/class. 17951 unsigned DiagID = 0; 17952 if (!Record->isUnion() && !IsLastField) { 17953 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17954 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17955 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17956 FD->setInvalidDecl(); 17957 EnclosingDecl->setInvalidDecl(); 17958 continue; 17959 } else if (Record->isUnion()) 17960 DiagID = getLangOpts().MicrosoftExt 17961 ? diag::ext_flexible_array_union_ms 17962 : getLangOpts().CPlusPlus 17963 ? diag::ext_flexible_array_union_gnu 17964 : diag::err_flexible_array_union; 17965 else if (NumNamedMembers < 1) 17966 DiagID = getLangOpts().MicrosoftExt 17967 ? diag::ext_flexible_array_empty_aggregate_ms 17968 : getLangOpts().CPlusPlus 17969 ? diag::ext_flexible_array_empty_aggregate_gnu 17970 : diag::err_flexible_array_empty_aggregate; 17971 17972 if (DiagID) 17973 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17974 << Record->getTagKind(); 17975 // While the layout of types that contain virtual bases is not specified 17976 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17977 // virtual bases after the derived members. This would make a flexible 17978 // array member declared at the end of an object not adjacent to the end 17979 // of the type. 17980 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17981 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17982 << FD->getDeclName() << Record->getTagKind(); 17983 if (!getLangOpts().C99) 17984 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17985 << FD->getDeclName() << Record->getTagKind(); 17986 17987 // If the element type has a non-trivial destructor, we would not 17988 // implicitly destroy the elements, so disallow it for now. 17989 // 17990 // FIXME: GCC allows this. We should probably either implicitly delete 17991 // the destructor of the containing class, or just allow this. 17992 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17993 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17994 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17995 << FD->getDeclName() << FD->getType(); 17996 FD->setInvalidDecl(); 17997 EnclosingDecl->setInvalidDecl(); 17998 continue; 17999 } 18000 // Okay, we have a legal flexible array member at the end of the struct. 18001 Record->setHasFlexibleArrayMember(true); 18002 } else { 18003 // In ObjCContainerDecl ivars with incomplete array type are accepted, 18004 // unless they are followed by another ivar. That check is done 18005 // elsewhere, after synthesized ivars are known. 18006 } 18007 } else if (!FDTy->isDependentType() && 18008 RequireCompleteSizedType( 18009 FD->getLocation(), FD->getType(), 18010 diag::err_field_incomplete_or_sizeless)) { 18011 // Incomplete type 18012 FD->setInvalidDecl(); 18013 EnclosingDecl->setInvalidDecl(); 18014 continue; 18015 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 18016 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 18017 // A type which contains a flexible array member is considered to be a 18018 // flexible array member. 18019 Record->setHasFlexibleArrayMember(true); 18020 if (!Record->isUnion()) { 18021 // If this is a struct/class and this is not the last element, reject 18022 // it. Note that GCC supports variable sized arrays in the middle of 18023 // structures. 18024 if (!IsLastField) 18025 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 18026 << FD->getDeclName() << FD->getType(); 18027 else { 18028 // We support flexible arrays at the end of structs in 18029 // other structs as an extension. 18030 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 18031 << FD->getDeclName(); 18032 } 18033 } 18034 } 18035 if (isa<ObjCContainerDecl>(EnclosingDecl) && 18036 RequireNonAbstractType(FD->getLocation(), FD->getType(), 18037 diag::err_abstract_type_in_decl, 18038 AbstractIvarType)) { 18039 // Ivars can not have abstract class types 18040 FD->setInvalidDecl(); 18041 } 18042 if (Record && FDTTy->getDecl()->hasObjectMember()) 18043 Record->setHasObjectMember(true); 18044 if (Record && FDTTy->getDecl()->hasVolatileMember()) 18045 Record->setHasVolatileMember(true); 18046 } else if (FDTy->isObjCObjectType()) { 18047 /// A field cannot be an Objective-c object 18048 Diag(FD->getLocation(), diag::err_statically_allocated_object) 18049 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 18050 QualType T = Context.getObjCObjectPointerType(FD->getType()); 18051 FD->setType(T); 18052 } else if (Record && Record->isUnion() && 18053 FD->getType().hasNonTrivialObjCLifetime() && 18054 getSourceManager().isInSystemHeader(FD->getLocation()) && 18055 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 18056 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 18057 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 18058 // For backward compatibility, fields of C unions declared in system 18059 // headers that have non-trivial ObjC ownership qualifications are marked 18060 // as unavailable unless the qualifier is explicit and __strong. This can 18061 // break ABI compatibility between programs compiled with ARC and MRR, but 18062 // is a better option than rejecting programs using those unions under 18063 // ARC. 18064 FD->addAttr(UnavailableAttr::CreateImplicit( 18065 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 18066 FD->getLocation())); 18067 } else if (getLangOpts().ObjC && 18068 getLangOpts().getGC() != LangOptions::NonGC && Record && 18069 !Record->hasObjectMember()) { 18070 if (FD->getType()->isObjCObjectPointerType() || 18071 FD->getType().isObjCGCStrong()) 18072 Record->setHasObjectMember(true); 18073 else if (Context.getAsArrayType(FD->getType())) { 18074 QualType BaseType = Context.getBaseElementType(FD->getType()); 18075 if (BaseType->isRecordType() && 18076 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 18077 Record->setHasObjectMember(true); 18078 else if (BaseType->isObjCObjectPointerType() || 18079 BaseType.isObjCGCStrong()) 18080 Record->setHasObjectMember(true); 18081 } 18082 } 18083 18084 if (Record && !getLangOpts().CPlusPlus && 18085 !shouldIgnoreForRecordTriviality(FD)) { 18086 QualType FT = FD->getType(); 18087 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 18088 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 18089 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 18090 Record->isUnion()) 18091 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 18092 } 18093 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 18094 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 18095 Record->setNonTrivialToPrimitiveCopy(true); 18096 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 18097 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 18098 } 18099 if (FT.isDestructedType()) { 18100 Record->setNonTrivialToPrimitiveDestroy(true); 18101 Record->setParamDestroyedInCallee(true); 18102 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 18103 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 18104 } 18105 18106 if (const auto *RT = FT->getAs<RecordType>()) { 18107 if (RT->getDecl()->getArgPassingRestrictions() == 18108 RecordDecl::APK_CanNeverPassInRegs) 18109 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 18110 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 18111 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 18112 } 18113 18114 if (Record && FD->getType().isVolatileQualified()) 18115 Record->setHasVolatileMember(true); 18116 // Keep track of the number of named members. 18117 if (FD->getIdentifier()) 18118 ++NumNamedMembers; 18119 } 18120 18121 // Okay, we successfully defined 'Record'. 18122 if (Record) { 18123 bool Completed = false; 18124 if (CXXRecord) { 18125 if (!CXXRecord->isInvalidDecl()) { 18126 // Set access bits correctly on the directly-declared conversions. 18127 for (CXXRecordDecl::conversion_iterator 18128 I = CXXRecord->conversion_begin(), 18129 E = CXXRecord->conversion_end(); I != E; ++I) 18130 I.setAccess((*I)->getAccess()); 18131 } 18132 18133 // Add any implicitly-declared members to this class. 18134 AddImplicitlyDeclaredMembersToClass(CXXRecord); 18135 18136 if (!CXXRecord->isDependentType()) { 18137 if (!CXXRecord->isInvalidDecl()) { 18138 // If we have virtual base classes, we may end up finding multiple 18139 // final overriders for a given virtual function. Check for this 18140 // problem now. 18141 if (CXXRecord->getNumVBases()) { 18142 CXXFinalOverriderMap FinalOverriders; 18143 CXXRecord->getFinalOverriders(FinalOverriders); 18144 18145 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 18146 MEnd = FinalOverriders.end(); 18147 M != MEnd; ++M) { 18148 for (OverridingMethods::iterator SO = M->second.begin(), 18149 SOEnd = M->second.end(); 18150 SO != SOEnd; ++SO) { 18151 assert(SO->second.size() > 0 && 18152 "Virtual function without overriding functions?"); 18153 if (SO->second.size() == 1) 18154 continue; 18155 18156 // C++ [class.virtual]p2: 18157 // In a derived class, if a virtual member function of a base 18158 // class subobject has more than one final overrider the 18159 // program is ill-formed. 18160 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 18161 << (const NamedDecl *)M->first << Record; 18162 Diag(M->first->getLocation(), 18163 diag::note_overridden_virtual_function); 18164 for (OverridingMethods::overriding_iterator 18165 OM = SO->second.begin(), 18166 OMEnd = SO->second.end(); 18167 OM != OMEnd; ++OM) 18168 Diag(OM->Method->getLocation(), diag::note_final_overrider) 18169 << (const NamedDecl *)M->first << OM->Method->getParent(); 18170 18171 Record->setInvalidDecl(); 18172 } 18173 } 18174 CXXRecord->completeDefinition(&FinalOverriders); 18175 Completed = true; 18176 } 18177 } 18178 } 18179 } 18180 18181 if (!Completed) 18182 Record->completeDefinition(); 18183 18184 // Handle attributes before checking the layout. 18185 ProcessDeclAttributeList(S, Record, Attrs); 18186 18187 // Check to see if a FieldDecl is a pointer to a function. 18188 auto IsFunctionPointer = [&](const Decl *D) { 18189 const FieldDecl *FD = dyn_cast<FieldDecl>(D); 18190 if (!FD) 18191 return false; 18192 QualType FieldType = FD->getType().getDesugaredType(Context); 18193 if (isa<PointerType>(FieldType)) { 18194 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType(); 18195 return PointeeType.getDesugaredType(Context)->isFunctionType(); 18196 } 18197 return false; 18198 }; 18199 18200 // Maybe randomize the record's decls. We automatically randomize a record 18201 // of function pointers, unless it has the "no_randomize_layout" attribute. 18202 if (!getLangOpts().CPlusPlus && 18203 (Record->hasAttr<RandomizeLayoutAttr>() || 18204 (!Record->hasAttr<NoRandomizeLayoutAttr>() && 18205 llvm::all_of(Record->decls(), IsFunctionPointer))) && 18206 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && 18207 !Record->isRandomized()) { 18208 SmallVector<Decl *, 32> NewDeclOrdering; 18209 if (randstruct::randomizeStructureLayout(Context, Record, 18210 NewDeclOrdering)) 18211 Record->reorderDecls(NewDeclOrdering); 18212 } 18213 18214 // We may have deferred checking for a deleted destructor. Check now. 18215 if (CXXRecord) { 18216 auto *Dtor = CXXRecord->getDestructor(); 18217 if (Dtor && Dtor->isImplicit() && 18218 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 18219 CXXRecord->setImplicitDestructorIsDeleted(); 18220 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 18221 } 18222 } 18223 18224 if (Record->hasAttrs()) { 18225 CheckAlignasUnderalignment(Record); 18226 18227 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 18228 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 18229 IA->getRange(), IA->getBestCase(), 18230 IA->getInheritanceModel()); 18231 } 18232 18233 // Check if the structure/union declaration is a type that can have zero 18234 // size in C. For C this is a language extension, for C++ it may cause 18235 // compatibility problems. 18236 bool CheckForZeroSize; 18237 if (!getLangOpts().CPlusPlus) { 18238 CheckForZeroSize = true; 18239 } else { 18240 // For C++ filter out types that cannot be referenced in C code. 18241 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 18242 CheckForZeroSize = 18243 CXXRecord->getLexicalDeclContext()->isExternCContext() && 18244 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 18245 CXXRecord->isCLike(); 18246 } 18247 if (CheckForZeroSize) { 18248 bool ZeroSize = true; 18249 bool IsEmpty = true; 18250 unsigned NonBitFields = 0; 18251 for (RecordDecl::field_iterator I = Record->field_begin(), 18252 E = Record->field_end(); 18253 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 18254 IsEmpty = false; 18255 if (I->isUnnamedBitfield()) { 18256 if (!I->isZeroLengthBitField(Context)) 18257 ZeroSize = false; 18258 } else { 18259 ++NonBitFields; 18260 QualType FieldType = I->getType(); 18261 if (FieldType->isIncompleteType() || 18262 !Context.getTypeSizeInChars(FieldType).isZero()) 18263 ZeroSize = false; 18264 } 18265 } 18266 18267 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 18268 // allowed in C++, but warn if its declaration is inside 18269 // extern "C" block. 18270 if (ZeroSize) { 18271 Diag(RecLoc, getLangOpts().CPlusPlus ? 18272 diag::warn_zero_size_struct_union_in_extern_c : 18273 diag::warn_zero_size_struct_union_compat) 18274 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 18275 } 18276 18277 // Structs without named members are extension in C (C99 6.7.2.1p7), 18278 // but are accepted by GCC. 18279 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 18280 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 18281 diag::ext_no_named_members_in_struct_union) 18282 << Record->isUnion(); 18283 } 18284 } 18285 } else { 18286 ObjCIvarDecl **ClsFields = 18287 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 18288 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 18289 ID->setEndOfDefinitionLoc(RBrac); 18290 // Add ivar's to class's DeclContext. 18291 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18292 ClsFields[i]->setLexicalDeclContext(ID); 18293 ID->addDecl(ClsFields[i]); 18294 } 18295 // Must enforce the rule that ivars in the base classes may not be 18296 // duplicates. 18297 if (ID->getSuperClass()) 18298 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 18299 } else if (ObjCImplementationDecl *IMPDecl = 18300 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 18301 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 18302 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 18303 // Ivar declared in @implementation never belongs to the implementation. 18304 // Only it is in implementation's lexical context. 18305 ClsFields[I]->setLexicalDeclContext(IMPDecl); 18306 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 18307 IMPDecl->setIvarLBraceLoc(LBrac); 18308 IMPDecl->setIvarRBraceLoc(RBrac); 18309 } else if (ObjCCategoryDecl *CDecl = 18310 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 18311 // case of ivars in class extension; all other cases have been 18312 // reported as errors elsewhere. 18313 // FIXME. Class extension does not have a LocEnd field. 18314 // CDecl->setLocEnd(RBrac); 18315 // Add ivar's to class extension's DeclContext. 18316 // Diagnose redeclaration of private ivars. 18317 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 18318 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18319 if (IDecl) { 18320 if (const ObjCIvarDecl *ClsIvar = 18321 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 18322 Diag(ClsFields[i]->getLocation(), 18323 diag::err_duplicate_ivar_declaration); 18324 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 18325 continue; 18326 } 18327 for (const auto *Ext : IDecl->known_extensions()) { 18328 if (const ObjCIvarDecl *ClsExtIvar 18329 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 18330 Diag(ClsFields[i]->getLocation(), 18331 diag::err_duplicate_ivar_declaration); 18332 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 18333 continue; 18334 } 18335 } 18336 } 18337 ClsFields[i]->setLexicalDeclContext(CDecl); 18338 CDecl->addDecl(ClsFields[i]); 18339 } 18340 CDecl->setIvarLBraceLoc(LBrac); 18341 CDecl->setIvarRBraceLoc(RBrac); 18342 } 18343 } 18344 } 18345 18346 /// Determine whether the given integral value is representable within 18347 /// the given type T. 18348 static bool isRepresentableIntegerValue(ASTContext &Context, 18349 llvm::APSInt &Value, 18350 QualType T) { 18351 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 18352 "Integral type required!"); 18353 unsigned BitWidth = Context.getIntWidth(T); 18354 18355 if (Value.isUnsigned() || Value.isNonNegative()) { 18356 if (T->isSignedIntegerOrEnumerationType()) 18357 --BitWidth; 18358 return Value.getActiveBits() <= BitWidth; 18359 } 18360 return Value.getMinSignedBits() <= BitWidth; 18361 } 18362 18363 // Given an integral type, return the next larger integral type 18364 // (or a NULL type of no such type exists). 18365 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 18366 // FIXME: Int128/UInt128 support, which also needs to be introduced into 18367 // enum checking below. 18368 assert((T->isIntegralType(Context) || 18369 T->isEnumeralType()) && "Integral type required!"); 18370 const unsigned NumTypes = 4; 18371 QualType SignedIntegralTypes[NumTypes] = { 18372 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 18373 }; 18374 QualType UnsignedIntegralTypes[NumTypes] = { 18375 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 18376 Context.UnsignedLongLongTy 18377 }; 18378 18379 unsigned BitWidth = Context.getTypeSize(T); 18380 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 18381 : UnsignedIntegralTypes; 18382 for (unsigned I = 0; I != NumTypes; ++I) 18383 if (Context.getTypeSize(Types[I]) > BitWidth) 18384 return Types[I]; 18385 18386 return QualType(); 18387 } 18388 18389 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 18390 EnumConstantDecl *LastEnumConst, 18391 SourceLocation IdLoc, 18392 IdentifierInfo *Id, 18393 Expr *Val) { 18394 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18395 llvm::APSInt EnumVal(IntWidth); 18396 QualType EltTy; 18397 18398 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 18399 Val = nullptr; 18400 18401 if (Val) 18402 Val = DefaultLvalueConversion(Val).get(); 18403 18404 if (Val) { 18405 if (Enum->isDependentType() || Val->isTypeDependent() || 18406 Val->containsErrors()) 18407 EltTy = Context.DependentTy; 18408 else { 18409 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 18410 // underlying type, but do allow it in all other contexts. 18411 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 18412 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 18413 // constant-expression in the enumerator-definition shall be a converted 18414 // constant expression of the underlying type. 18415 EltTy = Enum->getIntegerType(); 18416 ExprResult Converted = 18417 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 18418 CCEK_Enumerator); 18419 if (Converted.isInvalid()) 18420 Val = nullptr; 18421 else 18422 Val = Converted.get(); 18423 } else if (!Val->isValueDependent() && 18424 !(Val = 18425 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 18426 .get())) { 18427 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 18428 } else { 18429 if (Enum->isComplete()) { 18430 EltTy = Enum->getIntegerType(); 18431 18432 // In Obj-C and Microsoft mode, require the enumeration value to be 18433 // representable in the underlying type of the enumeration. In C++11, 18434 // we perform a non-narrowing conversion as part of converted constant 18435 // expression checking. 18436 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18437 if (Context.getTargetInfo() 18438 .getTriple() 18439 .isWindowsMSVCEnvironment()) { 18440 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 18441 } else { 18442 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 18443 } 18444 } 18445 18446 // Cast to the underlying type. 18447 Val = ImpCastExprToType(Val, EltTy, 18448 EltTy->isBooleanType() ? CK_IntegralToBoolean 18449 : CK_IntegralCast) 18450 .get(); 18451 } else if (getLangOpts().CPlusPlus) { 18452 // C++11 [dcl.enum]p5: 18453 // If the underlying type is not fixed, the type of each enumerator 18454 // is the type of its initializing value: 18455 // - If an initializer is specified for an enumerator, the 18456 // initializing value has the same type as the expression. 18457 EltTy = Val->getType(); 18458 } else { 18459 // C99 6.7.2.2p2: 18460 // The expression that defines the value of an enumeration constant 18461 // shall be an integer constant expression that has a value 18462 // representable as an int. 18463 18464 // Complain if the value is not representable in an int. 18465 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 18466 Diag(IdLoc, diag::ext_enum_value_not_int) 18467 << toString(EnumVal, 10) << Val->getSourceRange() 18468 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 18469 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 18470 // Force the type of the expression to 'int'. 18471 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 18472 } 18473 EltTy = Val->getType(); 18474 } 18475 } 18476 } 18477 } 18478 18479 if (!Val) { 18480 if (Enum->isDependentType()) 18481 EltTy = Context.DependentTy; 18482 else if (!LastEnumConst) { 18483 // C++0x [dcl.enum]p5: 18484 // If the underlying type is not fixed, the type of each enumerator 18485 // is the type of its initializing value: 18486 // - If no initializer is specified for the first enumerator, the 18487 // initializing value has an unspecified integral type. 18488 // 18489 // GCC uses 'int' for its unspecified integral type, as does 18490 // C99 6.7.2.2p3. 18491 if (Enum->isFixed()) { 18492 EltTy = Enum->getIntegerType(); 18493 } 18494 else { 18495 EltTy = Context.IntTy; 18496 } 18497 } else { 18498 // Assign the last value + 1. 18499 EnumVal = LastEnumConst->getInitVal(); 18500 ++EnumVal; 18501 EltTy = LastEnumConst->getType(); 18502 18503 // Check for overflow on increment. 18504 if (EnumVal < LastEnumConst->getInitVal()) { 18505 // C++0x [dcl.enum]p5: 18506 // If the underlying type is not fixed, the type of each enumerator 18507 // is the type of its initializing value: 18508 // 18509 // - Otherwise the type of the initializing value is the same as 18510 // the type of the initializing value of the preceding enumerator 18511 // unless the incremented value is not representable in that type, 18512 // in which case the type is an unspecified integral type 18513 // sufficient to contain the incremented value. If no such type 18514 // exists, the program is ill-formed. 18515 QualType T = getNextLargerIntegralType(Context, EltTy); 18516 if (T.isNull() || Enum->isFixed()) { 18517 // There is no integral type larger enough to represent this 18518 // value. Complain, then allow the value to wrap around. 18519 EnumVal = LastEnumConst->getInitVal(); 18520 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 18521 ++EnumVal; 18522 if (Enum->isFixed()) 18523 // When the underlying type is fixed, this is ill-formed. 18524 Diag(IdLoc, diag::err_enumerator_wrapped) 18525 << toString(EnumVal, 10) 18526 << EltTy; 18527 else 18528 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 18529 << toString(EnumVal, 10); 18530 } else { 18531 EltTy = T; 18532 } 18533 18534 // Retrieve the last enumerator's value, extent that type to the 18535 // type that is supposed to be large enough to represent the incremented 18536 // value, then increment. 18537 EnumVal = LastEnumConst->getInitVal(); 18538 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18539 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 18540 ++EnumVal; 18541 18542 // If we're not in C++, diagnose the overflow of enumerator values, 18543 // which in C99 means that the enumerator value is not representable in 18544 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 18545 // permits enumerator values that are representable in some larger 18546 // integral type. 18547 if (!getLangOpts().CPlusPlus && !T.isNull()) 18548 Diag(IdLoc, diag::warn_enum_value_overflow); 18549 } else if (!getLangOpts().CPlusPlus && 18550 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18551 // Enforce C99 6.7.2.2p2 even when we compute the next value. 18552 Diag(IdLoc, diag::ext_enum_value_not_int) 18553 << toString(EnumVal, 10) << 1; 18554 } 18555 } 18556 } 18557 18558 if (!EltTy->isDependentType()) { 18559 // Make the enumerator value match the signedness and size of the 18560 // enumerator's type. 18561 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 18562 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18563 } 18564 18565 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 18566 Val, EnumVal); 18567 } 18568 18569 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 18570 SourceLocation IILoc) { 18571 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 18572 !getLangOpts().CPlusPlus) 18573 return SkipBodyInfo(); 18574 18575 // We have an anonymous enum definition. Look up the first enumerator to 18576 // determine if we should merge the definition with an existing one and 18577 // skip the body. 18578 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 18579 forRedeclarationInCurContext()); 18580 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 18581 if (!PrevECD) 18582 return SkipBodyInfo(); 18583 18584 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18585 NamedDecl *Hidden; 18586 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18587 SkipBodyInfo Skip; 18588 Skip.Previous = Hidden; 18589 return Skip; 18590 } 18591 18592 return SkipBodyInfo(); 18593 } 18594 18595 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18596 SourceLocation IdLoc, IdentifierInfo *Id, 18597 const ParsedAttributesView &Attrs, 18598 SourceLocation EqualLoc, Expr *Val) { 18599 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18600 EnumConstantDecl *LastEnumConst = 18601 cast_or_null<EnumConstantDecl>(lastEnumConst); 18602 18603 // The scope passed in may not be a decl scope. Zip up the scope tree until 18604 // we find one that is. 18605 S = getNonFieldDeclScope(S); 18606 18607 // Verify that there isn't already something declared with this name in this 18608 // scope. 18609 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18610 LookupName(R, S); 18611 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18612 18613 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18614 // Maybe we will complain about the shadowed template parameter. 18615 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18616 // Just pretend that we didn't see the previous declaration. 18617 PrevDecl = nullptr; 18618 } 18619 18620 // C++ [class.mem]p15: 18621 // If T is the name of a class, then each of the following shall have a name 18622 // different from T: 18623 // - every enumerator of every member of class T that is an unscoped 18624 // enumerated type 18625 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18626 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18627 DeclarationNameInfo(Id, IdLoc)); 18628 18629 EnumConstantDecl *New = 18630 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18631 if (!New) 18632 return nullptr; 18633 18634 if (PrevDecl) { 18635 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18636 // Check for other kinds of shadowing not already handled. 18637 CheckShadow(New, PrevDecl, R); 18638 } 18639 18640 // When in C++, we may get a TagDecl with the same name; in this case the 18641 // enum constant will 'hide' the tag. 18642 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18643 "Received TagDecl when not in C++!"); 18644 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18645 if (isa<EnumConstantDecl>(PrevDecl)) 18646 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18647 else 18648 Diag(IdLoc, diag::err_redefinition) << Id; 18649 notePreviousDefinition(PrevDecl, IdLoc); 18650 return nullptr; 18651 } 18652 } 18653 18654 // Process attributes. 18655 ProcessDeclAttributeList(S, New, Attrs); 18656 AddPragmaAttributes(S, New); 18657 18658 // Register this decl in the current scope stack. 18659 New->setAccess(TheEnumDecl->getAccess()); 18660 PushOnScopeChains(New, S); 18661 18662 ActOnDocumentableDecl(New); 18663 18664 return New; 18665 } 18666 18667 // Returns true when the enum initial expression does not trigger the 18668 // duplicate enum warning. A few common cases are exempted as follows: 18669 // Element2 = Element1 18670 // Element2 = Element1 + 1 18671 // Element2 = Element1 - 1 18672 // Where Element2 and Element1 are from the same enum. 18673 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18674 Expr *InitExpr = ECD->getInitExpr(); 18675 if (!InitExpr) 18676 return true; 18677 InitExpr = InitExpr->IgnoreImpCasts(); 18678 18679 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18680 if (!BO->isAdditiveOp()) 18681 return true; 18682 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18683 if (!IL) 18684 return true; 18685 if (IL->getValue() != 1) 18686 return true; 18687 18688 InitExpr = BO->getLHS(); 18689 } 18690 18691 // This checks if the elements are from the same enum. 18692 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18693 if (!DRE) 18694 return true; 18695 18696 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18697 if (!EnumConstant) 18698 return true; 18699 18700 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18701 Enum) 18702 return true; 18703 18704 return false; 18705 } 18706 18707 // Emits a warning when an element is implicitly set a value that 18708 // a previous element has already been set to. 18709 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18710 EnumDecl *Enum, QualType EnumType) { 18711 // Avoid anonymous enums 18712 if (!Enum->getIdentifier()) 18713 return; 18714 18715 // Only check for small enums. 18716 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18717 return; 18718 18719 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18720 return; 18721 18722 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18723 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18724 18725 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18726 18727 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18728 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18729 18730 // Use int64_t as a key to avoid needing special handling for map keys. 18731 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18732 llvm::APSInt Val = D->getInitVal(); 18733 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18734 }; 18735 18736 DuplicatesVector DupVector; 18737 ValueToVectorMap EnumMap; 18738 18739 // Populate the EnumMap with all values represented by enum constants without 18740 // an initializer. 18741 for (auto *Element : Elements) { 18742 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18743 18744 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18745 // this constant. Skip this enum since it may be ill-formed. 18746 if (!ECD) { 18747 return; 18748 } 18749 18750 // Constants with initalizers are handled in the next loop. 18751 if (ECD->getInitExpr()) 18752 continue; 18753 18754 // Duplicate values are handled in the next loop. 18755 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18756 } 18757 18758 if (EnumMap.size() == 0) 18759 return; 18760 18761 // Create vectors for any values that has duplicates. 18762 for (auto *Element : Elements) { 18763 // The last loop returned if any constant was null. 18764 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18765 if (!ValidDuplicateEnum(ECD, Enum)) 18766 continue; 18767 18768 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18769 if (Iter == EnumMap.end()) 18770 continue; 18771 18772 DeclOrVector& Entry = Iter->second; 18773 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18774 // Ensure constants are different. 18775 if (D == ECD) 18776 continue; 18777 18778 // Create new vector and push values onto it. 18779 auto Vec = std::make_unique<ECDVector>(); 18780 Vec->push_back(D); 18781 Vec->push_back(ECD); 18782 18783 // Update entry to point to the duplicates vector. 18784 Entry = Vec.get(); 18785 18786 // Store the vector somewhere we can consult later for quick emission of 18787 // diagnostics. 18788 DupVector.emplace_back(std::move(Vec)); 18789 continue; 18790 } 18791 18792 ECDVector *Vec = Entry.get<ECDVector*>(); 18793 // Make sure constants are not added more than once. 18794 if (*Vec->begin() == ECD) 18795 continue; 18796 18797 Vec->push_back(ECD); 18798 } 18799 18800 // Emit diagnostics. 18801 for (const auto &Vec : DupVector) { 18802 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18803 18804 // Emit warning for one enum constant. 18805 auto *FirstECD = Vec->front(); 18806 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18807 << FirstECD << toString(FirstECD->getInitVal(), 10) 18808 << FirstECD->getSourceRange(); 18809 18810 // Emit one note for each of the remaining enum constants with 18811 // the same value. 18812 for (auto *ECD : llvm::drop_begin(*Vec)) 18813 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18814 << ECD << toString(ECD->getInitVal(), 10) 18815 << ECD->getSourceRange(); 18816 } 18817 } 18818 18819 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18820 bool AllowMask) const { 18821 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18822 assert(ED->isCompleteDefinition() && "expected enum definition"); 18823 18824 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18825 llvm::APInt &FlagBits = R.first->second; 18826 18827 if (R.second) { 18828 for (auto *E : ED->enumerators()) { 18829 const auto &EVal = E->getInitVal(); 18830 // Only single-bit enumerators introduce new flag values. 18831 if (EVal.isPowerOf2()) 18832 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal; 18833 } 18834 } 18835 18836 // A value is in a flag enum if either its bits are a subset of the enum's 18837 // flag bits (the first condition) or we are allowing masks and the same is 18838 // true of its complement (the second condition). When masks are allowed, we 18839 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18840 // 18841 // While it's true that any value could be used as a mask, the assumption is 18842 // that a mask will have all of the insignificant bits set. Anything else is 18843 // likely a logic error. 18844 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18845 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18846 } 18847 18848 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18849 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18850 const ParsedAttributesView &Attrs) { 18851 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18852 QualType EnumType = Context.getTypeDeclType(Enum); 18853 18854 ProcessDeclAttributeList(S, Enum, Attrs); 18855 18856 if (Enum->isDependentType()) { 18857 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18858 EnumConstantDecl *ECD = 18859 cast_or_null<EnumConstantDecl>(Elements[i]); 18860 if (!ECD) continue; 18861 18862 ECD->setType(EnumType); 18863 } 18864 18865 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18866 return; 18867 } 18868 18869 // TODO: If the result value doesn't fit in an int, it must be a long or long 18870 // long value. ISO C does not support this, but GCC does as an extension, 18871 // emit a warning. 18872 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18873 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18874 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18875 18876 // Verify that all the values are okay, compute the size of the values, and 18877 // reverse the list. 18878 unsigned NumNegativeBits = 0; 18879 unsigned NumPositiveBits = 0; 18880 18881 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18882 EnumConstantDecl *ECD = 18883 cast_or_null<EnumConstantDecl>(Elements[i]); 18884 if (!ECD) continue; // Already issued a diagnostic. 18885 18886 const llvm::APSInt &InitVal = ECD->getInitVal(); 18887 18888 // Keep track of the size of positive and negative values. 18889 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18890 NumPositiveBits = std::max(NumPositiveBits, 18891 (unsigned)InitVal.getActiveBits()); 18892 else 18893 NumNegativeBits = std::max(NumNegativeBits, 18894 (unsigned)InitVal.getMinSignedBits()); 18895 } 18896 18897 // Figure out the type that should be used for this enum. 18898 QualType BestType; 18899 unsigned BestWidth; 18900 18901 // C++0x N3000 [conv.prom]p3: 18902 // An rvalue of an unscoped enumeration type whose underlying 18903 // type is not fixed can be converted to an rvalue of the first 18904 // of the following types that can represent all the values of 18905 // the enumeration: int, unsigned int, long int, unsigned long 18906 // int, long long int, or unsigned long long int. 18907 // C99 6.4.4.3p2: 18908 // An identifier declared as an enumeration constant has type int. 18909 // The C99 rule is modified by a gcc extension 18910 QualType BestPromotionType; 18911 18912 bool Packed = Enum->hasAttr<PackedAttr>(); 18913 // -fshort-enums is the equivalent to specifying the packed attribute on all 18914 // enum definitions. 18915 if (LangOpts.ShortEnums) 18916 Packed = true; 18917 18918 // If the enum already has a type because it is fixed or dictated by the 18919 // target, promote that type instead of analyzing the enumerators. 18920 if (Enum->isComplete()) { 18921 BestType = Enum->getIntegerType(); 18922 if (BestType->isPromotableIntegerType()) 18923 BestPromotionType = Context.getPromotedIntegerType(BestType); 18924 else 18925 BestPromotionType = BestType; 18926 18927 BestWidth = Context.getIntWidth(BestType); 18928 } 18929 else if (NumNegativeBits) { 18930 // If there is a negative value, figure out the smallest integer type (of 18931 // int/long/longlong) that fits. 18932 // If it's packed, check also if it fits a char or a short. 18933 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18934 BestType = Context.SignedCharTy; 18935 BestWidth = CharWidth; 18936 } else if (Packed && NumNegativeBits <= ShortWidth && 18937 NumPositiveBits < ShortWidth) { 18938 BestType = Context.ShortTy; 18939 BestWidth = ShortWidth; 18940 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18941 BestType = Context.IntTy; 18942 BestWidth = IntWidth; 18943 } else { 18944 BestWidth = Context.getTargetInfo().getLongWidth(); 18945 18946 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18947 BestType = Context.LongTy; 18948 } else { 18949 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18950 18951 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18952 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18953 BestType = Context.LongLongTy; 18954 } 18955 } 18956 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18957 } else { 18958 // If there is no negative value, figure out the smallest type that fits 18959 // all of the enumerator values. 18960 // If it's packed, check also if it fits a char or a short. 18961 if (Packed && NumPositiveBits <= CharWidth) { 18962 BestType = Context.UnsignedCharTy; 18963 BestPromotionType = Context.IntTy; 18964 BestWidth = CharWidth; 18965 } else if (Packed && NumPositiveBits <= ShortWidth) { 18966 BestType = Context.UnsignedShortTy; 18967 BestPromotionType = Context.IntTy; 18968 BestWidth = ShortWidth; 18969 } else if (NumPositiveBits <= IntWidth) { 18970 BestType = Context.UnsignedIntTy; 18971 BestWidth = IntWidth; 18972 BestPromotionType 18973 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18974 ? Context.UnsignedIntTy : Context.IntTy; 18975 } else if (NumPositiveBits <= 18976 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18977 BestType = Context.UnsignedLongTy; 18978 BestPromotionType 18979 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18980 ? Context.UnsignedLongTy : Context.LongTy; 18981 } else { 18982 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18983 assert(NumPositiveBits <= BestWidth && 18984 "How could an initializer get larger than ULL?"); 18985 BestType = Context.UnsignedLongLongTy; 18986 BestPromotionType 18987 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18988 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18989 } 18990 } 18991 18992 // Loop over all of the enumerator constants, changing their types to match 18993 // the type of the enum if needed. 18994 for (auto *D : Elements) { 18995 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18996 if (!ECD) continue; // Already issued a diagnostic. 18997 18998 // Standard C says the enumerators have int type, but we allow, as an 18999 // extension, the enumerators to be larger than int size. If each 19000 // enumerator value fits in an int, type it as an int, otherwise type it the 19001 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 19002 // that X has type 'int', not 'unsigned'. 19003 19004 // Determine whether the value fits into an int. 19005 llvm::APSInt InitVal = ECD->getInitVal(); 19006 19007 // If it fits into an integer type, force it. Otherwise force it to match 19008 // the enum decl type. 19009 QualType NewTy; 19010 unsigned NewWidth; 19011 bool NewSign; 19012 if (!getLangOpts().CPlusPlus && 19013 !Enum->isFixed() && 19014 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 19015 NewTy = Context.IntTy; 19016 NewWidth = IntWidth; 19017 NewSign = true; 19018 } else if (ECD->getType() == BestType) { 19019 // Already the right type! 19020 if (getLangOpts().CPlusPlus) 19021 // C++ [dcl.enum]p4: Following the closing brace of an 19022 // enum-specifier, each enumerator has the type of its 19023 // enumeration. 19024 ECD->setType(EnumType); 19025 continue; 19026 } else { 19027 NewTy = BestType; 19028 NewWidth = BestWidth; 19029 NewSign = BestType->isSignedIntegerOrEnumerationType(); 19030 } 19031 19032 // Adjust the APSInt value. 19033 InitVal = InitVal.extOrTrunc(NewWidth); 19034 InitVal.setIsSigned(NewSign); 19035 ECD->setInitVal(InitVal); 19036 19037 // Adjust the Expr initializer and type. 19038 if (ECD->getInitExpr() && 19039 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 19040 ECD->setInitExpr(ImplicitCastExpr::Create( 19041 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 19042 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 19043 if (getLangOpts().CPlusPlus) 19044 // C++ [dcl.enum]p4: Following the closing brace of an 19045 // enum-specifier, each enumerator has the type of its 19046 // enumeration. 19047 ECD->setType(EnumType); 19048 else 19049 ECD->setType(NewTy); 19050 } 19051 19052 Enum->completeDefinition(BestType, BestPromotionType, 19053 NumPositiveBits, NumNegativeBits); 19054 19055 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 19056 19057 if (Enum->isClosedFlag()) { 19058 for (Decl *D : Elements) { 19059 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 19060 if (!ECD) continue; // Already issued a diagnostic. 19061 19062 llvm::APSInt InitVal = ECD->getInitVal(); 19063 if (InitVal != 0 && !InitVal.isPowerOf2() && 19064 !IsValueInFlagEnum(Enum, InitVal, true)) 19065 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 19066 << ECD << Enum; 19067 } 19068 } 19069 19070 // Now that the enum type is defined, ensure it's not been underaligned. 19071 if (Enum->hasAttrs()) 19072 CheckAlignasUnderalignment(Enum); 19073 } 19074 19075 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 19076 SourceLocation StartLoc, 19077 SourceLocation EndLoc) { 19078 StringLiteral *AsmString = cast<StringLiteral>(expr); 19079 19080 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 19081 AsmString, StartLoc, 19082 EndLoc); 19083 CurContext->addDecl(New); 19084 return New; 19085 } 19086 19087 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 19088 IdentifierInfo* AliasName, 19089 SourceLocation PragmaLoc, 19090 SourceLocation NameLoc, 19091 SourceLocation AliasNameLoc) { 19092 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 19093 LookupOrdinaryName); 19094 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 19095 AttributeCommonInfo::AS_Pragma); 19096 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 19097 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 19098 19099 // If a declaration that: 19100 // 1) declares a function or a variable 19101 // 2) has external linkage 19102 // already exists, add a label attribute to it. 19103 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 19104 if (isDeclExternC(PrevDecl)) 19105 PrevDecl->addAttr(Attr); 19106 else 19107 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 19108 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 19109 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 19110 } else 19111 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 19112 } 19113 19114 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 19115 SourceLocation PragmaLoc, 19116 SourceLocation NameLoc) { 19117 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 19118 19119 if (PrevDecl) { 19120 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 19121 } else { 19122 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 19123 } 19124 } 19125 19126 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 19127 IdentifierInfo* AliasName, 19128 SourceLocation PragmaLoc, 19129 SourceLocation NameLoc, 19130 SourceLocation AliasNameLoc) { 19131 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 19132 LookupOrdinaryName); 19133 WeakInfo W = WeakInfo(Name, NameLoc); 19134 19135 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 19136 if (!PrevDecl->hasAttr<AliasAttr>()) 19137 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 19138 DeclApplyPragmaWeak(TUScope, ND, W); 19139 } else { 19140 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 19141 } 19142 } 19143 19144 ObjCContainerDecl *Sema::getObjCDeclContext() const { 19145 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 19146 } 19147 19148 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 19149 bool Final) { 19150 assert(FD && "Expected non-null FunctionDecl"); 19151 19152 // SYCL functions can be template, so we check if they have appropriate 19153 // attribute prior to checking if it is a template. 19154 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 19155 return FunctionEmissionStatus::Emitted; 19156 19157 // Templates are emitted when they're instantiated. 19158 if (FD->isDependentContext()) 19159 return FunctionEmissionStatus::TemplateDiscarded; 19160 19161 // Check whether this function is an externally visible definition. 19162 auto IsEmittedForExternalSymbol = [this, FD]() { 19163 // We have to check the GVA linkage of the function's *definition* -- if we 19164 // only have a declaration, we don't know whether or not the function will 19165 // be emitted, because (say) the definition could include "inline". 19166 FunctionDecl *Def = FD->getDefinition(); 19167 19168 return Def && !isDiscardableGVALinkage( 19169 getASTContext().GetGVALinkageForFunction(Def)); 19170 }; 19171 19172 if (LangOpts.OpenMPIsDevice) { 19173 // In OpenMP device mode we will not emit host only functions, or functions 19174 // we don't need due to their linkage. 19175 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 19176 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 19177 // DevTy may be changed later by 19178 // #pragma omp declare target to(*) device_type(*). 19179 // Therefore DevTy having no value does not imply host. The emission status 19180 // will be checked again at the end of compilation unit with Final = true. 19181 if (DevTy) 19182 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 19183 return FunctionEmissionStatus::OMPDiscarded; 19184 // If we have an explicit value for the device type, or we are in a target 19185 // declare context, we need to emit all extern and used symbols. 19186 if (isInOpenMPDeclareTargetContext() || DevTy) 19187 if (IsEmittedForExternalSymbol()) 19188 return FunctionEmissionStatus::Emitted; 19189 // Device mode only emits what it must, if it wasn't tagged yet and needed, 19190 // we'll omit it. 19191 if (Final) 19192 return FunctionEmissionStatus::OMPDiscarded; 19193 } else if (LangOpts.OpenMP > 45) { 19194 // In OpenMP host compilation prior to 5.0 everything was an emitted host 19195 // function. In 5.0, no_host was introduced which might cause a function to 19196 // be ommitted. 19197 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 19198 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 19199 if (DevTy) 19200 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 19201 return FunctionEmissionStatus::OMPDiscarded; 19202 } 19203 19204 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 19205 return FunctionEmissionStatus::Emitted; 19206 19207 if (LangOpts.CUDA) { 19208 // When compiling for device, host functions are never emitted. Similarly, 19209 // when compiling for host, device and global functions are never emitted. 19210 // (Technically, we do emit a host-side stub for global functions, but this 19211 // doesn't count for our purposes here.) 19212 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 19213 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 19214 return FunctionEmissionStatus::CUDADiscarded; 19215 if (!LangOpts.CUDAIsDevice && 19216 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 19217 return FunctionEmissionStatus::CUDADiscarded; 19218 19219 if (IsEmittedForExternalSymbol()) 19220 return FunctionEmissionStatus::Emitted; 19221 } 19222 19223 // Otherwise, the function is known-emitted if it's in our set of 19224 // known-emitted functions. 19225 return FunctionEmissionStatus::Unknown; 19226 } 19227 19228 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 19229 // Host-side references to a __global__ function refer to the stub, so the 19230 // function itself is never emitted and therefore should not be marked. 19231 // If we have host fn calls kernel fn calls host+device, the HD function 19232 // does not get instantiated on the host. We model this by omitting at the 19233 // call to the kernel from the callgraph. This ensures that, when compiling 19234 // for host, only HD functions actually called from the host get marked as 19235 // known-emitted. 19236 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 19237 IdentifyCUDATarget(Callee) == CFT_Global; 19238 } 19239