1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw_wchar_t: 145 case tok::kw_bool: 146 case tok::kw___underlying_type: 147 case tok::kw___auto_type: 148 return true; 149 150 case tok::annot_typename: 151 case tok::kw_char16_t: 152 case tok::kw_char32_t: 153 case tok::kw_typeof: 154 case tok::annot_decltype: 155 case tok::kw_decltype: 156 return getLangOpts().CPlusPlus; 157 158 case tok::kw_char8_t: 159 return getLangOpts().Char8; 160 161 default: 162 break; 163 } 164 165 return false; 166 } 167 168 namespace { 169 enum class UnqualifiedTypeNameLookupResult { 170 NotFound, 171 FoundNonType, 172 FoundType 173 }; 174 } // end anonymous namespace 175 176 /// Tries to perform unqualified lookup of the type decls in bases for 177 /// dependent class. 178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 179 /// type decl, \a FoundType if only type decls are found. 180 static UnqualifiedTypeNameLookupResult 181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 182 SourceLocation NameLoc, 183 const CXXRecordDecl *RD) { 184 if (!RD->hasDefinition()) 185 return UnqualifiedTypeNameLookupResult::NotFound; 186 // Look for type decls in base classes. 187 UnqualifiedTypeNameLookupResult FoundTypeDecl = 188 UnqualifiedTypeNameLookupResult::NotFound; 189 for (const auto &Base : RD->bases()) { 190 const CXXRecordDecl *BaseRD = nullptr; 191 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 192 BaseRD = BaseTT->getAsCXXRecordDecl(); 193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 194 // Look for type decls in dependent base classes that have known primary 195 // templates. 196 if (!TST || !TST->isDependentType()) 197 continue; 198 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 199 if (!TD) 200 continue; 201 if (auto *BasePrimaryTemplate = 202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 204 BaseRD = BasePrimaryTemplate; 205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 206 if (const ClassTemplatePartialSpecializationDecl *PS = 207 CTD->findPartialSpecialization(Base.getType())) 208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 209 BaseRD = PS; 210 } 211 } 212 } 213 if (BaseRD) { 214 for (NamedDecl *ND : BaseRD->lookup(&II)) { 215 if (!isa<TypeDecl>(ND)) 216 return UnqualifiedTypeNameLookupResult::FoundNonType; 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 } 219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 221 case UnqualifiedTypeNameLookupResult::FoundNonType: 222 return UnqualifiedTypeNameLookupResult::FoundNonType; 223 case UnqualifiedTypeNameLookupResult::FoundType: 224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 225 break; 226 case UnqualifiedTypeNameLookupResult::NotFound: 227 break; 228 } 229 } 230 } 231 } 232 233 return FoundTypeDecl; 234 } 235 236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 237 const IdentifierInfo &II, 238 SourceLocation NameLoc) { 239 // Lookup in the parent class template context, if any. 240 const CXXRecordDecl *RD = nullptr; 241 UnqualifiedTypeNameLookupResult FoundTypeDecl = 242 UnqualifiedTypeNameLookupResult::NotFound; 243 for (DeclContext *DC = S.CurContext; 244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 245 DC = DC->getParent()) { 246 // Look for type decls in dependent base classes that have known primary 247 // templates. 248 RD = dyn_cast<CXXRecordDecl>(DC); 249 if (RD && RD->getDescribedClassTemplate()) 250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 251 } 252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 253 return nullptr; 254 255 // We found some types in dependent base classes. Recover as if the user 256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 257 // lookup during template instantiation. 258 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 259 260 ASTContext &Context = S.Context; 261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 262 cast<Type>(Context.getRecordType(RD))); 263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 264 265 CXXScopeSpec SS; 266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 267 268 TypeLocBuilder Builder; 269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 270 DepTL.setNameLoc(NameLoc); 271 DepTL.setElaboratedKeywordLoc(SourceLocation()); 272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 274 } 275 276 /// If the identifier refers to a type name within this scope, 277 /// return the declaration of that type. 278 /// 279 /// This routine performs ordinary name lookup of the identifier II 280 /// within the given scope, with optional C++ scope specifier SS, to 281 /// determine whether the name refers to a type. If so, returns an 282 /// opaque pointer (actually a QualType) corresponding to that 283 /// type. Otherwise, returns NULL. 284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 285 Scope *S, CXXScopeSpec *SS, 286 bool isClassName, bool HasTrailingDot, 287 ParsedType ObjectTypePtr, 288 bool IsCtorOrDtorName, 289 bool WantNontrivialTypeSourceInfo, 290 bool IsClassTemplateDeductionContext, 291 IdentifierInfo **CorrectedII) { 292 // FIXME: Consider allowing this outside C++1z mode as an extension. 293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 295 !isClassName && !HasTrailingDot; 296 297 // Determine where we will perform name lookup. 298 DeclContext *LookupCtx = nullptr; 299 if (ObjectTypePtr) { 300 QualType ObjectType = ObjectTypePtr.get(); 301 if (ObjectType->isRecordType()) 302 LookupCtx = computeDeclContext(ObjectType); 303 } else if (SS && SS->isNotEmpty()) { 304 LookupCtx = computeDeclContext(*SS, false); 305 306 if (!LookupCtx) { 307 if (isDependentScopeSpecifier(*SS)) { 308 // C++ [temp.res]p3: 309 // A qualified-id that refers to a type and in which the 310 // nested-name-specifier depends on a template-parameter (14.6.2) 311 // shall be prefixed by the keyword typename to indicate that the 312 // qualified-id denotes a type, forming an 313 // elaborated-type-specifier (7.1.5.3). 314 // 315 // We therefore do not perform any name lookup if the result would 316 // refer to a member of an unknown specialization. 317 if (!isClassName && !IsCtorOrDtorName) 318 return nullptr; 319 320 // We know from the grammar that this name refers to a type, 321 // so build a dependent node to describe the type. 322 if (WantNontrivialTypeSourceInfo) 323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 324 325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 327 II, NameLoc); 328 return ParsedType::make(T); 329 } 330 331 return nullptr; 332 } 333 334 if (!LookupCtx->isDependentContext() && 335 RequireCompleteDeclContext(*SS, LookupCtx)) 336 return nullptr; 337 } 338 339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 340 // lookup for class-names. 341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 342 LookupOrdinaryName; 343 LookupResult Result(*this, &II, NameLoc, Kind); 344 if (LookupCtx) { 345 // Perform "qualified" name lookup into the declaration context we 346 // computed, which is either the type of the base of a member access 347 // expression or the declaration context associated with a prior 348 // nested-name-specifier. 349 LookupQualifiedName(Result, LookupCtx); 350 351 if (ObjectTypePtr && Result.empty()) { 352 // C++ [basic.lookup.classref]p3: 353 // If the unqualified-id is ~type-name, the type-name is looked up 354 // in the context of the entire postfix-expression. If the type T of 355 // the object expression is of a class type C, the type-name is also 356 // looked up in the scope of class C. At least one of the lookups shall 357 // find a name that refers to (possibly cv-qualified) T. 358 LookupName(Result, S); 359 } 360 } else { 361 // Perform unqualified name lookup. 362 LookupName(Result, S); 363 364 // For unqualified lookup in a class template in MSVC mode, look into 365 // dependent base classes where the primary class template is known. 366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 367 if (ParsedType TypeInBase = 368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 369 return TypeInBase; 370 } 371 } 372 373 NamedDecl *IIDecl = nullptr; 374 switch (Result.getResultKind()) { 375 case LookupResult::NotFound: 376 case LookupResult::NotFoundInCurrentInstantiation: 377 if (CorrectedII) { 378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 379 AllowDeducedTemplate); 380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 381 S, SS, CCC, CTK_ErrorRecovery); 382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 383 TemplateTy Template; 384 bool MemberOfUnknownSpecialization; 385 UnqualifiedId TemplateName; 386 TemplateName.setIdentifier(NewII, NameLoc); 387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 388 CXXScopeSpec NewSS, *NewSSPtr = SS; 389 if (SS && NNS) { 390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 391 NewSSPtr = &NewSS; 392 } 393 if (Correction && (NNS || NewII != &II) && 394 // Ignore a correction to a template type as the to-be-corrected 395 // identifier is not a template (typo correction for template names 396 // is handled elsewhere). 397 !(getLangOpts().CPlusPlus && NewSSPtr && 398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 399 Template, MemberOfUnknownSpecialization))) { 400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 401 isClassName, HasTrailingDot, ObjectTypePtr, 402 IsCtorOrDtorName, 403 WantNontrivialTypeSourceInfo, 404 IsClassTemplateDeductionContext); 405 if (Ty) { 406 diagnoseTypo(Correction, 407 PDiag(diag::err_unknown_type_or_class_name_suggest) 408 << Result.getLookupName() << isClassName); 409 if (SS && NNS) 410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 411 *CorrectedII = NewII; 412 return Ty; 413 } 414 } 415 } 416 // If typo correction failed or was not performed, fall through 417 LLVM_FALLTHROUGH; 418 case LookupResult::FoundOverloaded: 419 case LookupResult::FoundUnresolvedValue: 420 Result.suppressDiagnostics(); 421 return nullptr; 422 423 case LookupResult::Ambiguous: 424 // Recover from type-hiding ambiguities by hiding the type. We'll 425 // do the lookup again when looking for an object, and we can 426 // diagnose the error then. If we don't do this, then the error 427 // about hiding the type will be immediately followed by an error 428 // that only makes sense if the identifier was treated like a type. 429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 430 Result.suppressDiagnostics(); 431 return nullptr; 432 } 433 434 // Look to see if we have a type anywhere in the list of results. 435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 436 Res != ResEnd; ++Res) { 437 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 439 if (!IIDecl || 440 (*Res)->getLocation().getRawEncoding() < 441 IIDecl->getLocation().getRawEncoding()) 442 IIDecl = *Res; 443 } 444 } 445 446 if (!IIDecl) { 447 // None of the entities we found is a type, so there is no way 448 // to even assume that the result is a type. In this case, don't 449 // complain about the ambiguity. The parser will either try to 450 // perform this lookup again (e.g., as an object name), which 451 // will produce the ambiguity, or will complain that it expected 452 // a type name. 453 Result.suppressDiagnostics(); 454 return nullptr; 455 } 456 457 // We found a type within the ambiguous lookup; diagnose the 458 // ambiguity and then return that type. This might be the right 459 // answer, or it might not be, but it suppresses any attempt to 460 // perform the name lookup again. 461 break; 462 463 case LookupResult::Found: 464 IIDecl = Result.getFoundDecl(); 465 break; 466 } 467 468 assert(IIDecl && "Didn't find decl"); 469 470 QualType T; 471 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 472 // C++ [class.qual]p2: A lookup that would find the injected-class-name 473 // instead names the constructors of the class, except when naming a class. 474 // This is ill-formed when we're not actually forming a ctor or dtor name. 475 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 476 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 477 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 478 FoundRD->isInjectedClassName() && 479 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 480 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 481 << &II << /*Type*/1; 482 483 DiagnoseUseOfDecl(IIDecl, NameLoc); 484 485 T = Context.getTypeDeclType(TD); 486 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 487 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 488 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 489 if (!HasTrailingDot) 490 T = Context.getObjCInterfaceType(IDecl); 491 } else if (AllowDeducedTemplate) { 492 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 493 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 494 QualType(), false); 495 } 496 497 if (T.isNull()) { 498 // If it's not plausibly a type, suppress diagnostics. 499 Result.suppressDiagnostics(); 500 return nullptr; 501 } 502 503 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 504 // constructor or destructor name (in such a case, the scope specifier 505 // will be attached to the enclosing Expr or Decl node). 506 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 507 !isa<ObjCInterfaceDecl>(IIDecl)) { 508 if (WantNontrivialTypeSourceInfo) { 509 // Construct a type with type-source information. 510 TypeLocBuilder Builder; 511 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 512 513 T = getElaboratedType(ETK_None, *SS, T); 514 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 515 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 516 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 517 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 518 } else { 519 T = getElaboratedType(ETK_None, *SS, T); 520 } 521 } 522 523 return ParsedType::make(T); 524 } 525 526 // Builds a fake NNS for the given decl context. 527 static NestedNameSpecifier * 528 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 529 for (;; DC = DC->getLookupParent()) { 530 DC = DC->getPrimaryContext(); 531 auto *ND = dyn_cast<NamespaceDecl>(DC); 532 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 533 return NestedNameSpecifier::Create(Context, nullptr, ND); 534 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 535 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 536 RD->getTypeForDecl()); 537 else if (isa<TranslationUnitDecl>(DC)) 538 return NestedNameSpecifier::GlobalSpecifier(Context); 539 } 540 llvm_unreachable("something isn't in TU scope?"); 541 } 542 543 /// Find the parent class with dependent bases of the innermost enclosing method 544 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 545 /// up allowing unqualified dependent type names at class-level, which MSVC 546 /// correctly rejects. 547 static const CXXRecordDecl * 548 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 549 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 550 DC = DC->getPrimaryContext(); 551 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 552 if (MD->getParent()->hasAnyDependentBases()) 553 return MD->getParent(); 554 } 555 return nullptr; 556 } 557 558 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 559 SourceLocation NameLoc, 560 bool IsTemplateTypeArg) { 561 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 562 563 NestedNameSpecifier *NNS = nullptr; 564 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 565 // If we weren't able to parse a default template argument, delay lookup 566 // until instantiation time by making a non-dependent DependentTypeName. We 567 // pretend we saw a NestedNameSpecifier referring to the current scope, and 568 // lookup is retried. 569 // FIXME: This hurts our diagnostic quality, since we get errors like "no 570 // type named 'Foo' in 'current_namespace'" when the user didn't write any 571 // name specifiers. 572 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 573 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 574 } else if (const CXXRecordDecl *RD = 575 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 576 // Build a DependentNameType that will perform lookup into RD at 577 // instantiation time. 578 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 579 RD->getTypeForDecl()); 580 581 // Diagnose that this identifier was undeclared, and retry the lookup during 582 // template instantiation. 583 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 584 << RD; 585 } else { 586 // This is not a situation that we should recover from. 587 return ParsedType(); 588 } 589 590 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 591 592 // Build type location information. We synthesized the qualifier, so we have 593 // to build a fake NestedNameSpecifierLoc. 594 NestedNameSpecifierLocBuilder NNSLocBuilder; 595 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 596 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 597 598 TypeLocBuilder Builder; 599 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 600 DepTL.setNameLoc(NameLoc); 601 DepTL.setElaboratedKeywordLoc(SourceLocation()); 602 DepTL.setQualifierLoc(QualifierLoc); 603 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 604 } 605 606 /// isTagName() - This method is called *for error recovery purposes only* 607 /// to determine if the specified name is a valid tag name ("struct foo"). If 608 /// so, this returns the TST for the tag corresponding to it (TST_enum, 609 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 610 /// cases in C where the user forgot to specify the tag. 611 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 612 // Do a tag name lookup in this scope. 613 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 614 LookupName(R, S, false); 615 R.suppressDiagnostics(); 616 if (R.getResultKind() == LookupResult::Found) 617 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 618 switch (TD->getTagKind()) { 619 case TTK_Struct: return DeclSpec::TST_struct; 620 case TTK_Interface: return DeclSpec::TST_interface; 621 case TTK_Union: return DeclSpec::TST_union; 622 case TTK_Class: return DeclSpec::TST_class; 623 case TTK_Enum: return DeclSpec::TST_enum; 624 } 625 } 626 627 return DeclSpec::TST_unspecified; 628 } 629 630 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 631 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 632 /// then downgrade the missing typename error to a warning. 633 /// This is needed for MSVC compatibility; Example: 634 /// @code 635 /// template<class T> class A { 636 /// public: 637 /// typedef int TYPE; 638 /// }; 639 /// template<class T> class B : public A<T> { 640 /// public: 641 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 642 /// }; 643 /// @endcode 644 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 645 if (CurContext->isRecord()) { 646 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 647 return true; 648 649 const Type *Ty = SS->getScopeRep()->getAsType(); 650 651 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 652 for (const auto &Base : RD->bases()) 653 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 654 return true; 655 return S->isFunctionPrototypeScope(); 656 } 657 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 658 } 659 660 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 661 SourceLocation IILoc, 662 Scope *S, 663 CXXScopeSpec *SS, 664 ParsedType &SuggestedType, 665 bool IsTemplateName) { 666 // Don't report typename errors for editor placeholders. 667 if (II->isEditorPlaceholder()) 668 return; 669 // We don't have anything to suggest (yet). 670 SuggestedType = nullptr; 671 672 // There may have been a typo in the name of the type. Look up typo 673 // results, in case we have something that we can suggest. 674 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 675 /*AllowTemplates=*/IsTemplateName, 676 /*AllowNonTemplates=*/!IsTemplateName); 677 if (TypoCorrection Corrected = 678 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 679 CCC, CTK_ErrorRecovery)) { 680 // FIXME: Support error recovery for the template-name case. 681 bool CanRecover = !IsTemplateName; 682 if (Corrected.isKeyword()) { 683 // We corrected to a keyword. 684 diagnoseTypo(Corrected, 685 PDiag(IsTemplateName ? diag::err_no_template_suggest 686 : diag::err_unknown_typename_suggest) 687 << II); 688 II = Corrected.getCorrectionAsIdentifierInfo(); 689 } else { 690 // We found a similarly-named type or interface; suggest that. 691 if (!SS || !SS->isSet()) { 692 diagnoseTypo(Corrected, 693 PDiag(IsTemplateName ? diag::err_no_template_suggest 694 : diag::err_unknown_typename_suggest) 695 << II, CanRecover); 696 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 697 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 698 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 699 II->getName().equals(CorrectedStr); 700 diagnoseTypo(Corrected, 701 PDiag(IsTemplateName 702 ? diag::err_no_member_template_suggest 703 : diag::err_unknown_nested_typename_suggest) 704 << II << DC << DroppedSpecifier << SS->getRange(), 705 CanRecover); 706 } else { 707 llvm_unreachable("could not have corrected a typo here"); 708 } 709 710 if (!CanRecover) 711 return; 712 713 CXXScopeSpec tmpSS; 714 if (Corrected.getCorrectionSpecifier()) 715 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 716 SourceRange(IILoc)); 717 // FIXME: Support class template argument deduction here. 718 SuggestedType = 719 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 720 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 721 /*IsCtorOrDtorName=*/false, 722 /*WantNontrivialTypeSourceInfo=*/true); 723 } 724 return; 725 } 726 727 if (getLangOpts().CPlusPlus && !IsTemplateName) { 728 // See if II is a class template that the user forgot to pass arguments to. 729 UnqualifiedId Name; 730 Name.setIdentifier(II, IILoc); 731 CXXScopeSpec EmptySS; 732 TemplateTy TemplateResult; 733 bool MemberOfUnknownSpecialization; 734 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 735 Name, nullptr, true, TemplateResult, 736 MemberOfUnknownSpecialization) == TNK_Type_template) { 737 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 738 return; 739 } 740 } 741 742 // FIXME: Should we move the logic that tries to recover from a missing tag 743 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 744 745 if (!SS || (!SS->isSet() && !SS->isInvalid())) 746 Diag(IILoc, IsTemplateName ? diag::err_no_template 747 : diag::err_unknown_typename) 748 << II; 749 else if (DeclContext *DC = computeDeclContext(*SS, false)) 750 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 751 : diag::err_typename_nested_not_found) 752 << II << DC << SS->getRange(); 753 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 754 SuggestedType = 755 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 756 } else if (isDependentScopeSpecifier(*SS)) { 757 unsigned DiagID = diag::err_typename_missing; 758 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 759 DiagID = diag::ext_typename_missing; 760 761 Diag(SS->getRange().getBegin(), DiagID) 762 << SS->getScopeRep() << II->getName() 763 << SourceRange(SS->getRange().getBegin(), IILoc) 764 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 765 SuggestedType = ActOnTypenameType(S, SourceLocation(), 766 *SS, *II, IILoc).get(); 767 } else { 768 assert(SS && SS->isInvalid() && 769 "Invalid scope specifier has already been diagnosed"); 770 } 771 } 772 773 /// Determine whether the given result set contains either a type name 774 /// or 775 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 776 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 777 NextToken.is(tok::less); 778 779 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 780 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 781 return true; 782 783 if (CheckTemplate && isa<TemplateDecl>(*I)) 784 return true; 785 } 786 787 return false; 788 } 789 790 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 791 Scope *S, CXXScopeSpec &SS, 792 IdentifierInfo *&Name, 793 SourceLocation NameLoc) { 794 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 795 SemaRef.LookupParsedName(R, S, &SS); 796 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 797 StringRef FixItTagName; 798 switch (Tag->getTagKind()) { 799 case TTK_Class: 800 FixItTagName = "class "; 801 break; 802 803 case TTK_Enum: 804 FixItTagName = "enum "; 805 break; 806 807 case TTK_Struct: 808 FixItTagName = "struct "; 809 break; 810 811 case TTK_Interface: 812 FixItTagName = "__interface "; 813 break; 814 815 case TTK_Union: 816 FixItTagName = "union "; 817 break; 818 } 819 820 StringRef TagName = FixItTagName.drop_back(); 821 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 822 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 823 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 824 825 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 826 I != IEnd; ++I) 827 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 828 << Name << TagName; 829 830 // Replace lookup results with just the tag decl. 831 Result.clear(Sema::LookupTagName); 832 SemaRef.LookupParsedName(Result, S, &SS); 833 return true; 834 } 835 836 return false; 837 } 838 839 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 840 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 841 QualType T, SourceLocation NameLoc) { 842 ASTContext &Context = S.Context; 843 844 TypeLocBuilder Builder; 845 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 846 847 T = S.getElaboratedType(ETK_None, SS, T); 848 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 849 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 850 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 851 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 852 } 853 854 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 855 IdentifierInfo *&Name, 856 SourceLocation NameLoc, 857 const Token &NextToken, 858 CorrectionCandidateCallback *CCC) { 859 DeclarationNameInfo NameInfo(Name, NameLoc); 860 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 861 862 assert(NextToken.isNot(tok::coloncolon) && 863 "parse nested name specifiers before calling ClassifyName"); 864 if (getLangOpts().CPlusPlus && SS.isSet() && 865 isCurrentClassName(*Name, S, &SS)) { 866 // Per [class.qual]p2, this names the constructors of SS, not the 867 // injected-class-name. We don't have a classification for that. 868 // There's not much point caching this result, since the parser 869 // will reject it later. 870 return NameClassification::Unknown(); 871 } 872 873 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 874 LookupParsedName(Result, S, &SS, !CurMethod); 875 876 if (SS.isInvalid()) 877 return NameClassification::Error(); 878 879 // For unqualified lookup in a class template in MSVC mode, look into 880 // dependent base classes where the primary class template is known. 881 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 882 if (ParsedType TypeInBase = 883 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 884 return TypeInBase; 885 } 886 887 // Perform lookup for Objective-C instance variables (including automatically 888 // synthesized instance variables), if we're in an Objective-C method. 889 // FIXME: This lookup really, really needs to be folded in to the normal 890 // unqualified lookup mechanism. 891 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 892 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 893 if (Ivar.isInvalid()) 894 return NameClassification::Error(); 895 if (Ivar.isUsable()) 896 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 897 898 // We defer builtin creation until after ivar lookup inside ObjC methods. 899 if (Result.empty()) 900 LookupBuiltin(Result); 901 } 902 903 bool SecondTry = false; 904 bool IsFilteredTemplateName = false; 905 906 Corrected: 907 switch (Result.getResultKind()) { 908 case LookupResult::NotFound: 909 // If an unqualified-id is followed by a '(', then we have a function 910 // call. 911 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 912 // In C++, this is an ADL-only call. 913 // FIXME: Reference? 914 if (getLangOpts().CPlusPlus) 915 return NameClassification::UndeclaredNonType(); 916 917 // C90 6.3.2.2: 918 // If the expression that precedes the parenthesized argument list in a 919 // function call consists solely of an identifier, and if no 920 // declaration is visible for this identifier, the identifier is 921 // implicitly declared exactly as if, in the innermost block containing 922 // the function call, the declaration 923 // 924 // extern int identifier (); 925 // 926 // appeared. 927 // 928 // We also allow this in C99 as an extension. 929 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 930 return NameClassification::NonType(D); 931 } 932 933 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 934 // In C++20 onwards, this could be an ADL-only call to a function 935 // template, and we're required to assume that this is a template name. 936 // 937 // FIXME: Find a way to still do typo correction in this case. 938 TemplateName Template = 939 Context.getAssumedTemplateName(NameInfo.getName()); 940 return NameClassification::UndeclaredTemplate(Template); 941 } 942 943 // In C, we first see whether there is a tag type by the same name, in 944 // which case it's likely that the user just forgot to write "enum", 945 // "struct", or "union". 946 if (!getLangOpts().CPlusPlus && !SecondTry && 947 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 948 break; 949 } 950 951 // Perform typo correction to determine if there is another name that is 952 // close to this name. 953 if (!SecondTry && CCC) { 954 SecondTry = true; 955 if (TypoCorrection Corrected = 956 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 957 &SS, *CCC, CTK_ErrorRecovery)) { 958 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 959 unsigned QualifiedDiag = diag::err_no_member_suggest; 960 961 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 962 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 963 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 964 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 965 UnqualifiedDiag = diag::err_no_template_suggest; 966 QualifiedDiag = diag::err_no_member_template_suggest; 967 } else if (UnderlyingFirstDecl && 968 (isa<TypeDecl>(UnderlyingFirstDecl) || 969 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 970 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 971 UnqualifiedDiag = diag::err_unknown_typename_suggest; 972 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 973 } 974 975 if (SS.isEmpty()) { 976 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 977 } else {// FIXME: is this even reachable? Test it. 978 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 979 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 980 Name->getName().equals(CorrectedStr); 981 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 982 << Name << computeDeclContext(SS, false) 983 << DroppedSpecifier << SS.getRange()); 984 } 985 986 // Update the name, so that the caller has the new name. 987 Name = Corrected.getCorrectionAsIdentifierInfo(); 988 989 // Typo correction corrected to a keyword. 990 if (Corrected.isKeyword()) 991 return Name; 992 993 // Also update the LookupResult... 994 // FIXME: This should probably go away at some point 995 Result.clear(); 996 Result.setLookupName(Corrected.getCorrection()); 997 if (FirstDecl) 998 Result.addDecl(FirstDecl); 999 1000 // If we found an Objective-C instance variable, let 1001 // LookupInObjCMethod build the appropriate expression to 1002 // reference the ivar. 1003 // FIXME: This is a gross hack. 1004 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1005 DeclResult R = 1006 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1007 if (R.isInvalid()) 1008 return NameClassification::Error(); 1009 if (R.isUsable()) 1010 return NameClassification::NonType(Ivar); 1011 } 1012 1013 goto Corrected; 1014 } 1015 } 1016 1017 // We failed to correct; just fall through and let the parser deal with it. 1018 Result.suppressDiagnostics(); 1019 return NameClassification::Unknown(); 1020 1021 case LookupResult::NotFoundInCurrentInstantiation: { 1022 // We performed name lookup into the current instantiation, and there were 1023 // dependent bases, so we treat this result the same way as any other 1024 // dependent nested-name-specifier. 1025 1026 // C++ [temp.res]p2: 1027 // A name used in a template declaration or definition and that is 1028 // dependent on a template-parameter is assumed not to name a type 1029 // unless the applicable name lookup finds a type name or the name is 1030 // qualified by the keyword typename. 1031 // 1032 // FIXME: If the next token is '<', we might want to ask the parser to 1033 // perform some heroics to see if we actually have a 1034 // template-argument-list, which would indicate a missing 'template' 1035 // keyword here. 1036 return NameClassification::DependentNonType(); 1037 } 1038 1039 case LookupResult::Found: 1040 case LookupResult::FoundOverloaded: 1041 case LookupResult::FoundUnresolvedValue: 1042 break; 1043 1044 case LookupResult::Ambiguous: 1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1046 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1047 /*AllowDependent=*/false)) { 1048 // C++ [temp.local]p3: 1049 // A lookup that finds an injected-class-name (10.2) can result in an 1050 // ambiguity in certain cases (for example, if it is found in more than 1051 // one base class). If all of the injected-class-names that are found 1052 // refer to specializations of the same class template, and if the name 1053 // is followed by a template-argument-list, the reference refers to the 1054 // class template itself and not a specialization thereof, and is not 1055 // ambiguous. 1056 // 1057 // This filtering can make an ambiguous result into an unambiguous one, 1058 // so try again after filtering out template names. 1059 FilterAcceptableTemplateNames(Result); 1060 if (!Result.isAmbiguous()) { 1061 IsFilteredTemplateName = true; 1062 break; 1063 } 1064 } 1065 1066 // Diagnose the ambiguity and return an error. 1067 return NameClassification::Error(); 1068 } 1069 1070 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1071 (IsFilteredTemplateName || 1072 hasAnyAcceptableTemplateNames( 1073 Result, /*AllowFunctionTemplates=*/true, 1074 /*AllowDependent=*/false, 1075 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1076 getLangOpts().CPlusPlus20))) { 1077 // C++ [temp.names]p3: 1078 // After name lookup (3.4) finds that a name is a template-name or that 1079 // an operator-function-id or a literal- operator-id refers to a set of 1080 // overloaded functions any member of which is a function template if 1081 // this is followed by a <, the < is always taken as the delimiter of a 1082 // template-argument-list and never as the less-than operator. 1083 // C++2a [temp.names]p2: 1084 // A name is also considered to refer to a template if it is an 1085 // unqualified-id followed by a < and name lookup finds either one 1086 // or more functions or finds nothing. 1087 if (!IsFilteredTemplateName) 1088 FilterAcceptableTemplateNames(Result); 1089 1090 bool IsFunctionTemplate; 1091 bool IsVarTemplate; 1092 TemplateName Template; 1093 if (Result.end() - Result.begin() > 1) { 1094 IsFunctionTemplate = true; 1095 Template = Context.getOverloadedTemplateName(Result.begin(), 1096 Result.end()); 1097 } else if (!Result.empty()) { 1098 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1099 *Result.begin(), /*AllowFunctionTemplates=*/true, 1100 /*AllowDependent=*/false)); 1101 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1102 IsVarTemplate = isa<VarTemplateDecl>(TD); 1103 1104 if (SS.isNotEmpty()) 1105 Template = 1106 Context.getQualifiedTemplateName(SS.getScopeRep(), 1107 /*TemplateKeyword=*/false, TD); 1108 else 1109 Template = TemplateName(TD); 1110 } else { 1111 // All results were non-template functions. This is a function template 1112 // name. 1113 IsFunctionTemplate = true; 1114 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1115 } 1116 1117 if (IsFunctionTemplate) { 1118 // Function templates always go through overload resolution, at which 1119 // point we'll perform the various checks (e.g., accessibility) we need 1120 // to based on which function we selected. 1121 Result.suppressDiagnostics(); 1122 1123 return NameClassification::FunctionTemplate(Template); 1124 } 1125 1126 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1127 : NameClassification::TypeTemplate(Template); 1128 } 1129 1130 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1131 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1132 DiagnoseUseOfDecl(Type, NameLoc); 1133 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1134 QualType T = Context.getTypeDeclType(Type); 1135 if (SS.isNotEmpty()) 1136 return buildNestedType(*this, SS, T, NameLoc); 1137 return ParsedType::make(T); 1138 } 1139 1140 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1141 if (!Class) { 1142 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1143 if (ObjCCompatibleAliasDecl *Alias = 1144 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1145 Class = Alias->getClassInterface(); 1146 } 1147 1148 if (Class) { 1149 DiagnoseUseOfDecl(Class, NameLoc); 1150 1151 if (NextToken.is(tok::period)) { 1152 // Interface. <something> is parsed as a property reference expression. 1153 // Just return "unknown" as a fall-through for now. 1154 Result.suppressDiagnostics(); 1155 return NameClassification::Unknown(); 1156 } 1157 1158 QualType T = Context.getObjCInterfaceType(Class); 1159 return ParsedType::make(T); 1160 } 1161 1162 if (isa<ConceptDecl>(FirstDecl)) 1163 return NameClassification::Concept( 1164 TemplateName(cast<TemplateDecl>(FirstDecl))); 1165 1166 // We can have a type template here if we're classifying a template argument. 1167 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1168 !isa<VarTemplateDecl>(FirstDecl)) 1169 return NameClassification::TypeTemplate( 1170 TemplateName(cast<TemplateDecl>(FirstDecl))); 1171 1172 // Check for a tag type hidden by a non-type decl in a few cases where it 1173 // seems likely a type is wanted instead of the non-type that was found. 1174 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1175 if ((NextToken.is(tok::identifier) || 1176 (NextIsOp && 1177 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1178 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1179 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1180 DiagnoseUseOfDecl(Type, NameLoc); 1181 QualType T = Context.getTypeDeclType(Type); 1182 if (SS.isNotEmpty()) 1183 return buildNestedType(*this, SS, T, NameLoc); 1184 return ParsedType::make(T); 1185 } 1186 1187 // If we already know which single declaration is referenced, just annotate 1188 // that declaration directly. Defer resolving even non-overloaded class 1189 // member accesses, as we need to defer certain access checks until we know 1190 // the context. 1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1192 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1193 return NameClassification::NonType(Result.getRepresentativeDecl()); 1194 1195 // Otherwise, this is an overload set that we will need to resolve later. 1196 Result.suppressDiagnostics(); 1197 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1198 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1199 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1200 Result.begin(), Result.end())); 1201 } 1202 1203 ExprResult 1204 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1205 SourceLocation NameLoc) { 1206 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1207 CXXScopeSpec SS; 1208 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1209 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1210 } 1211 1212 ExprResult 1213 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1214 IdentifierInfo *Name, 1215 SourceLocation NameLoc, 1216 bool IsAddressOfOperand) { 1217 DeclarationNameInfo NameInfo(Name, NameLoc); 1218 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1219 NameInfo, IsAddressOfOperand, 1220 /*TemplateArgs=*/nullptr); 1221 } 1222 1223 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1224 NamedDecl *Found, 1225 SourceLocation NameLoc, 1226 const Token &NextToken) { 1227 if (getCurMethodDecl() && SS.isEmpty()) 1228 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1229 return BuildIvarRefExpr(S, NameLoc, Ivar); 1230 1231 // Reconstruct the lookup result. 1232 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1233 Result.addDecl(Found); 1234 Result.resolveKind(); 1235 1236 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1237 return BuildDeclarationNameExpr(SS, Result, ADL); 1238 } 1239 1240 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1241 // For an implicit class member access, transform the result into a member 1242 // access expression if necessary. 1243 auto *ULE = cast<UnresolvedLookupExpr>(E); 1244 if ((*ULE->decls_begin())->isCXXClassMember()) { 1245 CXXScopeSpec SS; 1246 SS.Adopt(ULE->getQualifierLoc()); 1247 1248 // Reconstruct the lookup result. 1249 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1250 LookupOrdinaryName); 1251 Result.setNamingClass(ULE->getNamingClass()); 1252 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1253 Result.addDecl(*I, I.getAccess()); 1254 Result.resolveKind(); 1255 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1256 nullptr, S); 1257 } 1258 1259 // Otherwise, this is already in the form we needed, and no further checks 1260 // are necessary. 1261 return ULE; 1262 } 1263 1264 Sema::TemplateNameKindForDiagnostics 1265 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1266 auto *TD = Name.getAsTemplateDecl(); 1267 if (!TD) 1268 return TemplateNameKindForDiagnostics::DependentTemplate; 1269 if (isa<ClassTemplateDecl>(TD)) 1270 return TemplateNameKindForDiagnostics::ClassTemplate; 1271 if (isa<FunctionTemplateDecl>(TD)) 1272 return TemplateNameKindForDiagnostics::FunctionTemplate; 1273 if (isa<VarTemplateDecl>(TD)) 1274 return TemplateNameKindForDiagnostics::VarTemplate; 1275 if (isa<TypeAliasTemplateDecl>(TD)) 1276 return TemplateNameKindForDiagnostics::AliasTemplate; 1277 if (isa<TemplateTemplateParmDecl>(TD)) 1278 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1279 if (isa<ConceptDecl>(TD)) 1280 return TemplateNameKindForDiagnostics::Concept; 1281 return TemplateNameKindForDiagnostics::DependentTemplate; 1282 } 1283 1284 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1285 assert(DC->getLexicalParent() == CurContext && 1286 "The next DeclContext should be lexically contained in the current one."); 1287 CurContext = DC; 1288 S->setEntity(DC); 1289 } 1290 1291 void Sema::PopDeclContext() { 1292 assert(CurContext && "DeclContext imbalance!"); 1293 1294 CurContext = CurContext->getLexicalParent(); 1295 assert(CurContext && "Popped translation unit!"); 1296 } 1297 1298 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1299 Decl *D) { 1300 // Unlike PushDeclContext, the context to which we return is not necessarily 1301 // the containing DC of TD, because the new context will be some pre-existing 1302 // TagDecl definition instead of a fresh one. 1303 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1304 CurContext = cast<TagDecl>(D)->getDefinition(); 1305 assert(CurContext && "skipping definition of undefined tag"); 1306 // Start lookups from the parent of the current context; we don't want to look 1307 // into the pre-existing complete definition. 1308 S->setEntity(CurContext->getLookupParent()); 1309 return Result; 1310 } 1311 1312 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1313 CurContext = static_cast<decltype(CurContext)>(Context); 1314 } 1315 1316 /// EnterDeclaratorContext - Used when we must lookup names in the context 1317 /// of a declarator's nested name specifier. 1318 /// 1319 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1320 // C++0x [basic.lookup.unqual]p13: 1321 // A name used in the definition of a static data member of class 1322 // X (after the qualified-id of the static member) is looked up as 1323 // if the name was used in a member function of X. 1324 // C++0x [basic.lookup.unqual]p14: 1325 // If a variable member of a namespace is defined outside of the 1326 // scope of its namespace then any name used in the definition of 1327 // the variable member (after the declarator-id) is looked up as 1328 // if the definition of the variable member occurred in its 1329 // namespace. 1330 // Both of these imply that we should push a scope whose context 1331 // is the semantic context of the declaration. We can't use 1332 // PushDeclContext here because that context is not necessarily 1333 // lexically contained in the current context. Fortunately, 1334 // the containing scope should have the appropriate information. 1335 1336 assert(!S->getEntity() && "scope already has entity"); 1337 1338 #ifndef NDEBUG 1339 Scope *Ancestor = S->getParent(); 1340 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1341 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1342 #endif 1343 1344 CurContext = DC; 1345 S->setEntity(DC); 1346 1347 if (S->getParent()->isTemplateParamScope()) { 1348 // Also set the corresponding entities for all immediately-enclosing 1349 // template parameter scopes. 1350 EnterTemplatedContext(S->getParent(), DC); 1351 } 1352 } 1353 1354 void Sema::ExitDeclaratorContext(Scope *S) { 1355 assert(S->getEntity() == CurContext && "Context imbalance!"); 1356 1357 // Switch back to the lexical context. The safety of this is 1358 // enforced by an assert in EnterDeclaratorContext. 1359 Scope *Ancestor = S->getParent(); 1360 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1361 CurContext = Ancestor->getEntity(); 1362 1363 // We don't need to do anything with the scope, which is going to 1364 // disappear. 1365 } 1366 1367 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1368 assert(S->isTemplateParamScope() && 1369 "expected to be initializing a template parameter scope"); 1370 1371 // C++20 [temp.local]p7: 1372 // In the definition of a member of a class template that appears outside 1373 // of the class template definition, the name of a member of the class 1374 // template hides the name of a template-parameter of any enclosing class 1375 // templates (but not a template-parameter of the member if the member is a 1376 // class or function template). 1377 // C++20 [temp.local]p9: 1378 // In the definition of a class template or in the definition of a member 1379 // of such a template that appears outside of the template definition, for 1380 // each non-dependent base class (13.8.2.1), if the name of the base class 1381 // or the name of a member of the base class is the same as the name of a 1382 // template-parameter, the base class name or member name hides the 1383 // template-parameter name (6.4.10). 1384 // 1385 // This means that a template parameter scope should be searched immediately 1386 // after searching the DeclContext for which it is a template parameter 1387 // scope. For example, for 1388 // template<typename T> template<typename U> template<typename V> 1389 // void N::A<T>::B<U>::f(...) 1390 // we search V then B<U> (and base classes) then U then A<T> (and base 1391 // classes) then T then N then ::. 1392 unsigned ScopeDepth = getTemplateDepth(S); 1393 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1394 DeclContext *SearchDCAfterScope = DC; 1395 for (; DC; DC = DC->getLookupParent()) { 1396 if (const TemplateParameterList *TPL = 1397 cast<Decl>(DC)->getDescribedTemplateParams()) { 1398 unsigned DCDepth = TPL->getDepth() + 1; 1399 if (DCDepth > ScopeDepth) 1400 continue; 1401 if (ScopeDepth == DCDepth) 1402 SearchDCAfterScope = DC = DC->getLookupParent(); 1403 break; 1404 } 1405 } 1406 S->setLookupEntity(SearchDCAfterScope); 1407 } 1408 } 1409 1410 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1411 // We assume that the caller has already called 1412 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1413 FunctionDecl *FD = D->getAsFunction(); 1414 if (!FD) 1415 return; 1416 1417 // Same implementation as PushDeclContext, but enters the context 1418 // from the lexical parent, rather than the top-level class. 1419 assert(CurContext == FD->getLexicalParent() && 1420 "The next DeclContext should be lexically contained in the current one."); 1421 CurContext = FD; 1422 S->setEntity(CurContext); 1423 1424 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1425 ParmVarDecl *Param = FD->getParamDecl(P); 1426 // If the parameter has an identifier, then add it to the scope 1427 if (Param->getIdentifier()) { 1428 S->AddDecl(Param); 1429 IdResolver.AddDecl(Param); 1430 } 1431 } 1432 } 1433 1434 void Sema::ActOnExitFunctionContext() { 1435 // Same implementation as PopDeclContext, but returns to the lexical parent, 1436 // rather than the top-level class. 1437 assert(CurContext && "DeclContext imbalance!"); 1438 CurContext = CurContext->getLexicalParent(); 1439 assert(CurContext && "Popped translation unit!"); 1440 } 1441 1442 /// Determine whether we allow overloading of the function 1443 /// PrevDecl with another declaration. 1444 /// 1445 /// This routine determines whether overloading is possible, not 1446 /// whether some new function is actually an overload. It will return 1447 /// true in C++ (where we can always provide overloads) or, as an 1448 /// extension, in C when the previous function is already an 1449 /// overloaded function declaration or has the "overloadable" 1450 /// attribute. 1451 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1452 ASTContext &Context, 1453 const FunctionDecl *New) { 1454 if (Context.getLangOpts().CPlusPlus) 1455 return true; 1456 1457 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1458 return true; 1459 1460 return Previous.getResultKind() == LookupResult::Found && 1461 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1462 New->hasAttr<OverloadableAttr>()); 1463 } 1464 1465 /// Add this decl to the scope shadowed decl chains. 1466 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1467 // Move up the scope chain until we find the nearest enclosing 1468 // non-transparent context. The declaration will be introduced into this 1469 // scope. 1470 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1471 S = S->getParent(); 1472 1473 // Add scoped declarations into their context, so that they can be 1474 // found later. Declarations without a context won't be inserted 1475 // into any context. 1476 if (AddToContext) 1477 CurContext->addDecl(D); 1478 1479 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1480 // are function-local declarations. 1481 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1482 !D->getDeclContext()->getRedeclContext()->Equals( 1483 D->getLexicalDeclContext()->getRedeclContext()) && 1484 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1485 return; 1486 1487 // Template instantiations should also not be pushed into scope. 1488 if (isa<FunctionDecl>(D) && 1489 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1490 return; 1491 1492 // If this replaces anything in the current scope, 1493 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1494 IEnd = IdResolver.end(); 1495 for (; I != IEnd; ++I) { 1496 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1497 S->RemoveDecl(*I); 1498 IdResolver.RemoveDecl(*I); 1499 1500 // Should only need to replace one decl. 1501 break; 1502 } 1503 } 1504 1505 S->AddDecl(D); 1506 1507 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1508 // Implicitly-generated labels may end up getting generated in an order that 1509 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1510 // the label at the appropriate place in the identifier chain. 1511 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1512 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1513 if (IDC == CurContext) { 1514 if (!S->isDeclScope(*I)) 1515 continue; 1516 } else if (IDC->Encloses(CurContext)) 1517 break; 1518 } 1519 1520 IdResolver.InsertDeclAfter(I, D); 1521 } else { 1522 IdResolver.AddDecl(D); 1523 } 1524 } 1525 1526 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1527 bool AllowInlineNamespace) { 1528 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1529 } 1530 1531 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1532 DeclContext *TargetDC = DC->getPrimaryContext(); 1533 do { 1534 if (DeclContext *ScopeDC = S->getEntity()) 1535 if (ScopeDC->getPrimaryContext() == TargetDC) 1536 return S; 1537 } while ((S = S->getParent())); 1538 1539 return nullptr; 1540 } 1541 1542 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1543 DeclContext*, 1544 ASTContext&); 1545 1546 /// Filters out lookup results that don't fall within the given scope 1547 /// as determined by isDeclInScope. 1548 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1549 bool ConsiderLinkage, 1550 bool AllowInlineNamespace) { 1551 LookupResult::Filter F = R.makeFilter(); 1552 while (F.hasNext()) { 1553 NamedDecl *D = F.next(); 1554 1555 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1556 continue; 1557 1558 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1559 continue; 1560 1561 F.erase(); 1562 } 1563 1564 F.done(); 1565 } 1566 1567 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1568 /// have compatible owning modules. 1569 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1570 // FIXME: The Modules TS is not clear about how friend declarations are 1571 // to be treated. It's not meaningful to have different owning modules for 1572 // linkage in redeclarations of the same entity, so for now allow the 1573 // redeclaration and change the owning modules to match. 1574 if (New->getFriendObjectKind() && 1575 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1576 New->setLocalOwningModule(Old->getOwningModule()); 1577 makeMergedDefinitionVisible(New); 1578 return false; 1579 } 1580 1581 Module *NewM = New->getOwningModule(); 1582 Module *OldM = Old->getOwningModule(); 1583 1584 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1585 NewM = NewM->Parent; 1586 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1587 OldM = OldM->Parent; 1588 1589 if (NewM == OldM) 1590 return false; 1591 1592 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1593 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1594 if (NewIsModuleInterface || OldIsModuleInterface) { 1595 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1596 // if a declaration of D [...] appears in the purview of a module, all 1597 // other such declarations shall appear in the purview of the same module 1598 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1599 << New 1600 << NewIsModuleInterface 1601 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1602 << OldIsModuleInterface 1603 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1604 Diag(Old->getLocation(), diag::note_previous_declaration); 1605 New->setInvalidDecl(); 1606 return true; 1607 } 1608 1609 return false; 1610 } 1611 1612 static bool isUsingDecl(NamedDecl *D) { 1613 return isa<UsingShadowDecl>(D) || 1614 isa<UnresolvedUsingTypenameDecl>(D) || 1615 isa<UnresolvedUsingValueDecl>(D); 1616 } 1617 1618 /// Removes using shadow declarations from the lookup results. 1619 static void RemoveUsingDecls(LookupResult &R) { 1620 LookupResult::Filter F = R.makeFilter(); 1621 while (F.hasNext()) 1622 if (isUsingDecl(F.next())) 1623 F.erase(); 1624 1625 F.done(); 1626 } 1627 1628 /// Check for this common pattern: 1629 /// @code 1630 /// class S { 1631 /// S(const S&); // DO NOT IMPLEMENT 1632 /// void operator=(const S&); // DO NOT IMPLEMENT 1633 /// }; 1634 /// @endcode 1635 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1636 // FIXME: Should check for private access too but access is set after we get 1637 // the decl here. 1638 if (D->doesThisDeclarationHaveABody()) 1639 return false; 1640 1641 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1642 return CD->isCopyConstructor(); 1643 return D->isCopyAssignmentOperator(); 1644 } 1645 1646 // We need this to handle 1647 // 1648 // typedef struct { 1649 // void *foo() { return 0; } 1650 // } A; 1651 // 1652 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1653 // for example. If 'A', foo will have external linkage. If we have '*A', 1654 // foo will have no linkage. Since we can't know until we get to the end 1655 // of the typedef, this function finds out if D might have non-external linkage. 1656 // Callers should verify at the end of the TU if it D has external linkage or 1657 // not. 1658 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1659 const DeclContext *DC = D->getDeclContext(); 1660 while (!DC->isTranslationUnit()) { 1661 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1662 if (!RD->hasNameForLinkage()) 1663 return true; 1664 } 1665 DC = DC->getParent(); 1666 } 1667 1668 return !D->isExternallyVisible(); 1669 } 1670 1671 // FIXME: This needs to be refactored; some other isInMainFile users want 1672 // these semantics. 1673 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1674 if (S.TUKind != TU_Complete) 1675 return false; 1676 return S.SourceMgr.isInMainFile(Loc); 1677 } 1678 1679 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1680 assert(D); 1681 1682 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1683 return false; 1684 1685 // Ignore all entities declared within templates, and out-of-line definitions 1686 // of members of class templates. 1687 if (D->getDeclContext()->isDependentContext() || 1688 D->getLexicalDeclContext()->isDependentContext()) 1689 return false; 1690 1691 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1692 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1693 return false; 1694 // A non-out-of-line declaration of a member specialization was implicitly 1695 // instantiated; it's the out-of-line declaration that we're interested in. 1696 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1697 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1698 return false; 1699 1700 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1701 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1702 return false; 1703 } else { 1704 // 'static inline' functions are defined in headers; don't warn. 1705 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1706 return false; 1707 } 1708 1709 if (FD->doesThisDeclarationHaveABody() && 1710 Context.DeclMustBeEmitted(FD)) 1711 return false; 1712 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1713 // Constants and utility variables are defined in headers with internal 1714 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1715 // like "inline".) 1716 if (!isMainFileLoc(*this, VD->getLocation())) 1717 return false; 1718 1719 if (Context.DeclMustBeEmitted(VD)) 1720 return false; 1721 1722 if (VD->isStaticDataMember() && 1723 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1724 return false; 1725 if (VD->isStaticDataMember() && 1726 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1727 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1728 return false; 1729 1730 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1731 return false; 1732 } else { 1733 return false; 1734 } 1735 1736 // Only warn for unused decls internal to the translation unit. 1737 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1738 // for inline functions defined in the main source file, for instance. 1739 return mightHaveNonExternalLinkage(D); 1740 } 1741 1742 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1743 if (!D) 1744 return; 1745 1746 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1747 const FunctionDecl *First = FD->getFirstDecl(); 1748 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1749 return; // First should already be in the vector. 1750 } 1751 1752 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1753 const VarDecl *First = VD->getFirstDecl(); 1754 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1755 return; // First should already be in the vector. 1756 } 1757 1758 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1759 UnusedFileScopedDecls.push_back(D); 1760 } 1761 1762 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1763 if (D->isInvalidDecl()) 1764 return false; 1765 1766 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1767 // For a decomposition declaration, warn if none of the bindings are 1768 // referenced, instead of if the variable itself is referenced (which 1769 // it is, by the bindings' expressions). 1770 for (auto *BD : DD->bindings()) 1771 if (BD->isReferenced()) 1772 return false; 1773 } else if (!D->getDeclName()) { 1774 return false; 1775 } else if (D->isReferenced() || D->isUsed()) { 1776 return false; 1777 } 1778 1779 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1780 return false; 1781 1782 if (isa<LabelDecl>(D)) 1783 return true; 1784 1785 // Except for labels, we only care about unused decls that are local to 1786 // functions. 1787 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1788 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1789 // For dependent types, the diagnostic is deferred. 1790 WithinFunction = 1791 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1792 if (!WithinFunction) 1793 return false; 1794 1795 if (isa<TypedefNameDecl>(D)) 1796 return true; 1797 1798 // White-list anything that isn't a local variable. 1799 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1800 return false; 1801 1802 // Types of valid local variables should be complete, so this should succeed. 1803 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1804 1805 // White-list anything with an __attribute__((unused)) type. 1806 const auto *Ty = VD->getType().getTypePtr(); 1807 1808 // Only look at the outermost level of typedef. 1809 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1810 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1811 return false; 1812 } 1813 1814 // If we failed to complete the type for some reason, or if the type is 1815 // dependent, don't diagnose the variable. 1816 if (Ty->isIncompleteType() || Ty->isDependentType()) 1817 return false; 1818 1819 // Look at the element type to ensure that the warning behaviour is 1820 // consistent for both scalars and arrays. 1821 Ty = Ty->getBaseElementTypeUnsafe(); 1822 1823 if (const TagType *TT = Ty->getAs<TagType>()) { 1824 const TagDecl *Tag = TT->getDecl(); 1825 if (Tag->hasAttr<UnusedAttr>()) 1826 return false; 1827 1828 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1829 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1830 return false; 1831 1832 if (const Expr *Init = VD->getInit()) { 1833 if (const ExprWithCleanups *Cleanups = 1834 dyn_cast<ExprWithCleanups>(Init)) 1835 Init = Cleanups->getSubExpr(); 1836 const CXXConstructExpr *Construct = 1837 dyn_cast<CXXConstructExpr>(Init); 1838 if (Construct && !Construct->isElidable()) { 1839 CXXConstructorDecl *CD = Construct->getConstructor(); 1840 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1841 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1842 return false; 1843 } 1844 1845 // Suppress the warning if we don't know how this is constructed, and 1846 // it could possibly be non-trivial constructor. 1847 if (Init->isTypeDependent()) 1848 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1849 if (!Ctor->isTrivial()) 1850 return false; 1851 } 1852 } 1853 } 1854 1855 // TODO: __attribute__((unused)) templates? 1856 } 1857 1858 return true; 1859 } 1860 1861 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1862 FixItHint &Hint) { 1863 if (isa<LabelDecl>(D)) { 1864 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1865 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1866 true); 1867 if (AfterColon.isInvalid()) 1868 return; 1869 Hint = FixItHint::CreateRemoval( 1870 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1871 } 1872 } 1873 1874 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1875 if (D->getTypeForDecl()->isDependentType()) 1876 return; 1877 1878 for (auto *TmpD : D->decls()) { 1879 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1880 DiagnoseUnusedDecl(T); 1881 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1882 DiagnoseUnusedNestedTypedefs(R); 1883 } 1884 } 1885 1886 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1887 /// unless they are marked attr(unused). 1888 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1889 if (!ShouldDiagnoseUnusedDecl(D)) 1890 return; 1891 1892 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1893 // typedefs can be referenced later on, so the diagnostics are emitted 1894 // at end-of-translation-unit. 1895 UnusedLocalTypedefNameCandidates.insert(TD); 1896 return; 1897 } 1898 1899 FixItHint Hint; 1900 GenerateFixForUnusedDecl(D, Context, Hint); 1901 1902 unsigned DiagID; 1903 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1904 DiagID = diag::warn_unused_exception_param; 1905 else if (isa<LabelDecl>(D)) 1906 DiagID = diag::warn_unused_label; 1907 else 1908 DiagID = diag::warn_unused_variable; 1909 1910 Diag(D->getLocation(), DiagID) << D << Hint; 1911 } 1912 1913 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1914 // Verify that we have no forward references left. If so, there was a goto 1915 // or address of a label taken, but no definition of it. Label fwd 1916 // definitions are indicated with a null substmt which is also not a resolved 1917 // MS inline assembly label name. 1918 bool Diagnose = false; 1919 if (L->isMSAsmLabel()) 1920 Diagnose = !L->isResolvedMSAsmLabel(); 1921 else 1922 Diagnose = L->getStmt() == nullptr; 1923 if (Diagnose) 1924 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1925 } 1926 1927 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1928 S->mergeNRVOIntoParent(); 1929 1930 if (S->decl_empty()) return; 1931 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1932 "Scope shouldn't contain decls!"); 1933 1934 for (auto *TmpD : S->decls()) { 1935 assert(TmpD && "This decl didn't get pushed??"); 1936 1937 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1938 NamedDecl *D = cast<NamedDecl>(TmpD); 1939 1940 // Diagnose unused variables in this scope. 1941 if (!S->hasUnrecoverableErrorOccurred()) { 1942 DiagnoseUnusedDecl(D); 1943 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1944 DiagnoseUnusedNestedTypedefs(RD); 1945 } 1946 1947 if (!D->getDeclName()) continue; 1948 1949 // If this was a forward reference to a label, verify it was defined. 1950 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1951 CheckPoppedLabel(LD, *this); 1952 1953 // Remove this name from our lexical scope, and warn on it if we haven't 1954 // already. 1955 IdResolver.RemoveDecl(D); 1956 auto ShadowI = ShadowingDecls.find(D); 1957 if (ShadowI != ShadowingDecls.end()) { 1958 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1959 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1960 << D << FD << FD->getParent(); 1961 Diag(FD->getLocation(), diag::note_previous_declaration); 1962 } 1963 ShadowingDecls.erase(ShadowI); 1964 } 1965 } 1966 } 1967 1968 /// Look for an Objective-C class in the translation unit. 1969 /// 1970 /// \param Id The name of the Objective-C class we're looking for. If 1971 /// typo-correction fixes this name, the Id will be updated 1972 /// to the fixed name. 1973 /// 1974 /// \param IdLoc The location of the name in the translation unit. 1975 /// 1976 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1977 /// if there is no class with the given name. 1978 /// 1979 /// \returns The declaration of the named Objective-C class, or NULL if the 1980 /// class could not be found. 1981 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1982 SourceLocation IdLoc, 1983 bool DoTypoCorrection) { 1984 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1985 // creation from this context. 1986 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1987 1988 if (!IDecl && DoTypoCorrection) { 1989 // Perform typo correction at the given location, but only if we 1990 // find an Objective-C class name. 1991 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1992 if (TypoCorrection C = 1993 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1994 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1995 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1996 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1997 Id = IDecl->getIdentifier(); 1998 } 1999 } 2000 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2001 // This routine must always return a class definition, if any. 2002 if (Def && Def->getDefinition()) 2003 Def = Def->getDefinition(); 2004 return Def; 2005 } 2006 2007 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2008 /// from S, where a non-field would be declared. This routine copes 2009 /// with the difference between C and C++ scoping rules in structs and 2010 /// unions. For example, the following code is well-formed in C but 2011 /// ill-formed in C++: 2012 /// @code 2013 /// struct S6 { 2014 /// enum { BAR } e; 2015 /// }; 2016 /// 2017 /// void test_S6() { 2018 /// struct S6 a; 2019 /// a.e = BAR; 2020 /// } 2021 /// @endcode 2022 /// For the declaration of BAR, this routine will return a different 2023 /// scope. The scope S will be the scope of the unnamed enumeration 2024 /// within S6. In C++, this routine will return the scope associated 2025 /// with S6, because the enumeration's scope is a transparent 2026 /// context but structures can contain non-field names. In C, this 2027 /// routine will return the translation unit scope, since the 2028 /// enumeration's scope is a transparent context and structures cannot 2029 /// contain non-field names. 2030 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2031 while (((S->getFlags() & Scope::DeclScope) == 0) || 2032 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2033 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2034 S = S->getParent(); 2035 return S; 2036 } 2037 2038 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2039 ASTContext::GetBuiltinTypeError Error) { 2040 switch (Error) { 2041 case ASTContext::GE_None: 2042 return ""; 2043 case ASTContext::GE_Missing_type: 2044 return BuiltinInfo.getHeaderName(ID); 2045 case ASTContext::GE_Missing_stdio: 2046 return "stdio.h"; 2047 case ASTContext::GE_Missing_setjmp: 2048 return "setjmp.h"; 2049 case ASTContext::GE_Missing_ucontext: 2050 return "ucontext.h"; 2051 } 2052 llvm_unreachable("unhandled error kind"); 2053 } 2054 2055 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2056 unsigned ID, SourceLocation Loc) { 2057 DeclContext *Parent = Context.getTranslationUnitDecl(); 2058 2059 if (getLangOpts().CPlusPlus) { 2060 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2061 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2062 CLinkageDecl->setImplicit(); 2063 Parent->addDecl(CLinkageDecl); 2064 Parent = CLinkageDecl; 2065 } 2066 2067 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2068 /*TInfo=*/nullptr, SC_Extern, false, 2069 Type->isFunctionProtoType()); 2070 New->setImplicit(); 2071 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2072 2073 // Create Decl objects for each parameter, adding them to the 2074 // FunctionDecl. 2075 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2076 SmallVector<ParmVarDecl *, 16> Params; 2077 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2078 ParmVarDecl *parm = ParmVarDecl::Create( 2079 Context, New, SourceLocation(), SourceLocation(), nullptr, 2080 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2081 parm->setScopeInfo(0, i); 2082 Params.push_back(parm); 2083 } 2084 New->setParams(Params); 2085 } 2086 2087 AddKnownFunctionAttributes(New); 2088 return New; 2089 } 2090 2091 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2092 /// file scope. lazily create a decl for it. ForRedeclaration is true 2093 /// if we're creating this built-in in anticipation of redeclaring the 2094 /// built-in. 2095 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2096 Scope *S, bool ForRedeclaration, 2097 SourceLocation Loc) { 2098 LookupNecessaryTypesForBuiltin(S, ID); 2099 2100 ASTContext::GetBuiltinTypeError Error; 2101 QualType R = Context.GetBuiltinType(ID, Error); 2102 if (Error) { 2103 if (!ForRedeclaration) 2104 return nullptr; 2105 2106 // If we have a builtin without an associated type we should not emit a 2107 // warning when we were not able to find a type for it. 2108 if (Error == ASTContext::GE_Missing_type || 2109 Context.BuiltinInfo.allowTypeMismatch(ID)) 2110 return nullptr; 2111 2112 // If we could not find a type for setjmp it is because the jmp_buf type was 2113 // not defined prior to the setjmp declaration. 2114 if (Error == ASTContext::GE_Missing_setjmp) { 2115 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2116 << Context.BuiltinInfo.getName(ID); 2117 return nullptr; 2118 } 2119 2120 // Generally, we emit a warning that the declaration requires the 2121 // appropriate header. 2122 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2123 << getHeaderName(Context.BuiltinInfo, ID, Error) 2124 << Context.BuiltinInfo.getName(ID); 2125 return nullptr; 2126 } 2127 2128 if (!ForRedeclaration && 2129 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2130 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2131 Diag(Loc, diag::ext_implicit_lib_function_decl) 2132 << Context.BuiltinInfo.getName(ID) << R; 2133 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2134 Diag(Loc, diag::note_include_header_or_declare) 2135 << Header << Context.BuiltinInfo.getName(ID); 2136 } 2137 2138 if (R.isNull()) 2139 return nullptr; 2140 2141 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2142 RegisterLocallyScopedExternCDecl(New, S); 2143 2144 // TUScope is the translation-unit scope to insert this function into. 2145 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2146 // relate Scopes to DeclContexts, and probably eliminate CurContext 2147 // entirely, but we're not there yet. 2148 DeclContext *SavedContext = CurContext; 2149 CurContext = New->getDeclContext(); 2150 PushOnScopeChains(New, TUScope); 2151 CurContext = SavedContext; 2152 return New; 2153 } 2154 2155 /// Typedef declarations don't have linkage, but they still denote the same 2156 /// entity if their types are the same. 2157 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2158 /// isSameEntity. 2159 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2160 TypedefNameDecl *Decl, 2161 LookupResult &Previous) { 2162 // This is only interesting when modules are enabled. 2163 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2164 return; 2165 2166 // Empty sets are uninteresting. 2167 if (Previous.empty()) 2168 return; 2169 2170 LookupResult::Filter Filter = Previous.makeFilter(); 2171 while (Filter.hasNext()) { 2172 NamedDecl *Old = Filter.next(); 2173 2174 // Non-hidden declarations are never ignored. 2175 if (S.isVisible(Old)) 2176 continue; 2177 2178 // Declarations of the same entity are not ignored, even if they have 2179 // different linkages. 2180 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2181 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2182 Decl->getUnderlyingType())) 2183 continue; 2184 2185 // If both declarations give a tag declaration a typedef name for linkage 2186 // purposes, then they declare the same entity. 2187 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2188 Decl->getAnonDeclWithTypedefName()) 2189 continue; 2190 } 2191 2192 Filter.erase(); 2193 } 2194 2195 Filter.done(); 2196 } 2197 2198 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2199 QualType OldType; 2200 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2201 OldType = OldTypedef->getUnderlyingType(); 2202 else 2203 OldType = Context.getTypeDeclType(Old); 2204 QualType NewType = New->getUnderlyingType(); 2205 2206 if (NewType->isVariablyModifiedType()) { 2207 // Must not redefine a typedef with a variably-modified type. 2208 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2209 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2210 << Kind << NewType; 2211 if (Old->getLocation().isValid()) 2212 notePreviousDefinition(Old, New->getLocation()); 2213 New->setInvalidDecl(); 2214 return true; 2215 } 2216 2217 if (OldType != NewType && 2218 !OldType->isDependentType() && 2219 !NewType->isDependentType() && 2220 !Context.hasSameType(OldType, NewType)) { 2221 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2222 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2223 << Kind << NewType << OldType; 2224 if (Old->getLocation().isValid()) 2225 notePreviousDefinition(Old, New->getLocation()); 2226 New->setInvalidDecl(); 2227 return true; 2228 } 2229 return false; 2230 } 2231 2232 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2233 /// same name and scope as a previous declaration 'Old'. Figure out 2234 /// how to resolve this situation, merging decls or emitting 2235 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2236 /// 2237 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2238 LookupResult &OldDecls) { 2239 // If the new decl is known invalid already, don't bother doing any 2240 // merging checks. 2241 if (New->isInvalidDecl()) return; 2242 2243 // Allow multiple definitions for ObjC built-in typedefs. 2244 // FIXME: Verify the underlying types are equivalent! 2245 if (getLangOpts().ObjC) { 2246 const IdentifierInfo *TypeID = New->getIdentifier(); 2247 switch (TypeID->getLength()) { 2248 default: break; 2249 case 2: 2250 { 2251 if (!TypeID->isStr("id")) 2252 break; 2253 QualType T = New->getUnderlyingType(); 2254 if (!T->isPointerType()) 2255 break; 2256 if (!T->isVoidPointerType()) { 2257 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2258 if (!PT->isStructureType()) 2259 break; 2260 } 2261 Context.setObjCIdRedefinitionType(T); 2262 // Install the built-in type for 'id', ignoring the current definition. 2263 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2264 return; 2265 } 2266 case 5: 2267 if (!TypeID->isStr("Class")) 2268 break; 2269 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2270 // Install the built-in type for 'Class', ignoring the current definition. 2271 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2272 return; 2273 case 3: 2274 if (!TypeID->isStr("SEL")) 2275 break; 2276 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2277 // Install the built-in type for 'SEL', ignoring the current definition. 2278 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2279 return; 2280 } 2281 // Fall through - the typedef name was not a builtin type. 2282 } 2283 2284 // Verify the old decl was also a type. 2285 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2286 if (!Old) { 2287 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2288 << New->getDeclName(); 2289 2290 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2291 if (OldD->getLocation().isValid()) 2292 notePreviousDefinition(OldD, New->getLocation()); 2293 2294 return New->setInvalidDecl(); 2295 } 2296 2297 // If the old declaration is invalid, just give up here. 2298 if (Old->isInvalidDecl()) 2299 return New->setInvalidDecl(); 2300 2301 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2302 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2303 auto *NewTag = New->getAnonDeclWithTypedefName(); 2304 NamedDecl *Hidden = nullptr; 2305 if (OldTag && NewTag && 2306 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2307 !hasVisibleDefinition(OldTag, &Hidden)) { 2308 // There is a definition of this tag, but it is not visible. Use it 2309 // instead of our tag. 2310 New->setTypeForDecl(OldTD->getTypeForDecl()); 2311 if (OldTD->isModed()) 2312 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2313 OldTD->getUnderlyingType()); 2314 else 2315 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2316 2317 // Make the old tag definition visible. 2318 makeMergedDefinitionVisible(Hidden); 2319 2320 // If this was an unscoped enumeration, yank all of its enumerators 2321 // out of the scope. 2322 if (isa<EnumDecl>(NewTag)) { 2323 Scope *EnumScope = getNonFieldDeclScope(S); 2324 for (auto *D : NewTag->decls()) { 2325 auto *ED = cast<EnumConstantDecl>(D); 2326 assert(EnumScope->isDeclScope(ED)); 2327 EnumScope->RemoveDecl(ED); 2328 IdResolver.RemoveDecl(ED); 2329 ED->getLexicalDeclContext()->removeDecl(ED); 2330 } 2331 } 2332 } 2333 } 2334 2335 // If the typedef types are not identical, reject them in all languages and 2336 // with any extensions enabled. 2337 if (isIncompatibleTypedef(Old, New)) 2338 return; 2339 2340 // The types match. Link up the redeclaration chain and merge attributes if 2341 // the old declaration was a typedef. 2342 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2343 New->setPreviousDecl(Typedef); 2344 mergeDeclAttributes(New, Old); 2345 } 2346 2347 if (getLangOpts().MicrosoftExt) 2348 return; 2349 2350 if (getLangOpts().CPlusPlus) { 2351 // C++ [dcl.typedef]p2: 2352 // In a given non-class scope, a typedef specifier can be used to 2353 // redefine the name of any type declared in that scope to refer 2354 // to the type to which it already refers. 2355 if (!isa<CXXRecordDecl>(CurContext)) 2356 return; 2357 2358 // C++0x [dcl.typedef]p4: 2359 // In a given class scope, a typedef specifier can be used to redefine 2360 // any class-name declared in that scope that is not also a typedef-name 2361 // to refer to the type to which it already refers. 2362 // 2363 // This wording came in via DR424, which was a correction to the 2364 // wording in DR56, which accidentally banned code like: 2365 // 2366 // struct S { 2367 // typedef struct A { } A; 2368 // }; 2369 // 2370 // in the C++03 standard. We implement the C++0x semantics, which 2371 // allow the above but disallow 2372 // 2373 // struct S { 2374 // typedef int I; 2375 // typedef int I; 2376 // }; 2377 // 2378 // since that was the intent of DR56. 2379 if (!isa<TypedefNameDecl>(Old)) 2380 return; 2381 2382 Diag(New->getLocation(), diag::err_redefinition) 2383 << New->getDeclName(); 2384 notePreviousDefinition(Old, New->getLocation()); 2385 return New->setInvalidDecl(); 2386 } 2387 2388 // Modules always permit redefinition of typedefs, as does C11. 2389 if (getLangOpts().Modules || getLangOpts().C11) 2390 return; 2391 2392 // If we have a redefinition of a typedef in C, emit a warning. This warning 2393 // is normally mapped to an error, but can be controlled with 2394 // -Wtypedef-redefinition. If either the original or the redefinition is 2395 // in a system header, don't emit this for compatibility with GCC. 2396 if (getDiagnostics().getSuppressSystemWarnings() && 2397 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2398 (Old->isImplicit() || 2399 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2400 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2401 return; 2402 2403 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2404 << New->getDeclName(); 2405 notePreviousDefinition(Old, New->getLocation()); 2406 } 2407 2408 /// DeclhasAttr - returns true if decl Declaration already has the target 2409 /// attribute. 2410 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2411 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2412 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2413 for (const auto *i : D->attrs()) 2414 if (i->getKind() == A->getKind()) { 2415 if (Ann) { 2416 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2417 return true; 2418 continue; 2419 } 2420 // FIXME: Don't hardcode this check 2421 if (OA && isa<OwnershipAttr>(i)) 2422 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2423 return true; 2424 } 2425 2426 return false; 2427 } 2428 2429 static bool isAttributeTargetADefinition(Decl *D) { 2430 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2431 return VD->isThisDeclarationADefinition(); 2432 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2433 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2434 return true; 2435 } 2436 2437 /// Merge alignment attributes from \p Old to \p New, taking into account the 2438 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2439 /// 2440 /// \return \c true if any attributes were added to \p New. 2441 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2442 // Look for alignas attributes on Old, and pick out whichever attribute 2443 // specifies the strictest alignment requirement. 2444 AlignedAttr *OldAlignasAttr = nullptr; 2445 AlignedAttr *OldStrictestAlignAttr = nullptr; 2446 unsigned OldAlign = 0; 2447 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2448 // FIXME: We have no way of representing inherited dependent alignments 2449 // in a case like: 2450 // template<int A, int B> struct alignas(A) X; 2451 // template<int A, int B> struct alignas(B) X {}; 2452 // For now, we just ignore any alignas attributes which are not on the 2453 // definition in such a case. 2454 if (I->isAlignmentDependent()) 2455 return false; 2456 2457 if (I->isAlignas()) 2458 OldAlignasAttr = I; 2459 2460 unsigned Align = I->getAlignment(S.Context); 2461 if (Align > OldAlign) { 2462 OldAlign = Align; 2463 OldStrictestAlignAttr = I; 2464 } 2465 } 2466 2467 // Look for alignas attributes on New. 2468 AlignedAttr *NewAlignasAttr = nullptr; 2469 unsigned NewAlign = 0; 2470 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2471 if (I->isAlignmentDependent()) 2472 return false; 2473 2474 if (I->isAlignas()) 2475 NewAlignasAttr = I; 2476 2477 unsigned Align = I->getAlignment(S.Context); 2478 if (Align > NewAlign) 2479 NewAlign = Align; 2480 } 2481 2482 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2483 // Both declarations have 'alignas' attributes. We require them to match. 2484 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2485 // fall short. (If two declarations both have alignas, they must both match 2486 // every definition, and so must match each other if there is a definition.) 2487 2488 // If either declaration only contains 'alignas(0)' specifiers, then it 2489 // specifies the natural alignment for the type. 2490 if (OldAlign == 0 || NewAlign == 0) { 2491 QualType Ty; 2492 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2493 Ty = VD->getType(); 2494 else 2495 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2496 2497 if (OldAlign == 0) 2498 OldAlign = S.Context.getTypeAlign(Ty); 2499 if (NewAlign == 0) 2500 NewAlign = S.Context.getTypeAlign(Ty); 2501 } 2502 2503 if (OldAlign != NewAlign) { 2504 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2505 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2506 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2507 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2508 } 2509 } 2510 2511 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2512 // C++11 [dcl.align]p6: 2513 // if any declaration of an entity has an alignment-specifier, 2514 // every defining declaration of that entity shall specify an 2515 // equivalent alignment. 2516 // C11 6.7.5/7: 2517 // If the definition of an object does not have an alignment 2518 // specifier, any other declaration of that object shall also 2519 // have no alignment specifier. 2520 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2521 << OldAlignasAttr; 2522 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2523 << OldAlignasAttr; 2524 } 2525 2526 bool AnyAdded = false; 2527 2528 // Ensure we have an attribute representing the strictest alignment. 2529 if (OldAlign > NewAlign) { 2530 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2531 Clone->setInherited(true); 2532 New->addAttr(Clone); 2533 AnyAdded = true; 2534 } 2535 2536 // Ensure we have an alignas attribute if the old declaration had one. 2537 if (OldAlignasAttr && !NewAlignasAttr && 2538 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2539 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2540 Clone->setInherited(true); 2541 New->addAttr(Clone); 2542 AnyAdded = true; 2543 } 2544 2545 return AnyAdded; 2546 } 2547 2548 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2549 const InheritableAttr *Attr, 2550 Sema::AvailabilityMergeKind AMK) { 2551 // This function copies an attribute Attr from a previous declaration to the 2552 // new declaration D if the new declaration doesn't itself have that attribute 2553 // yet or if that attribute allows duplicates. 2554 // If you're adding a new attribute that requires logic different from 2555 // "use explicit attribute on decl if present, else use attribute from 2556 // previous decl", for example if the attribute needs to be consistent 2557 // between redeclarations, you need to call a custom merge function here. 2558 InheritableAttr *NewAttr = nullptr; 2559 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2560 NewAttr = S.mergeAvailabilityAttr( 2561 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2562 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2563 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2564 AA->getPriority()); 2565 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2566 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2567 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2568 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2569 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2570 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2571 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2572 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2573 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2574 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2575 FA->getFirstArg()); 2576 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2577 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2578 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2579 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2580 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2581 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2582 IA->getInheritanceModel()); 2583 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2584 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2585 &S.Context.Idents.get(AA->getSpelling())); 2586 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2587 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2588 isa<CUDAGlobalAttr>(Attr))) { 2589 // CUDA target attributes are part of function signature for 2590 // overloading purposes and must not be merged. 2591 return false; 2592 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2593 NewAttr = S.mergeMinSizeAttr(D, *MA); 2594 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2595 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2596 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2597 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2598 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2599 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2600 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2601 NewAttr = S.mergeCommonAttr(D, *CommonA); 2602 else if (isa<AlignedAttr>(Attr)) 2603 // AlignedAttrs are handled separately, because we need to handle all 2604 // such attributes on a declaration at the same time. 2605 NewAttr = nullptr; 2606 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2607 (AMK == Sema::AMK_Override || 2608 AMK == Sema::AMK_ProtocolImplementation)) 2609 NewAttr = nullptr; 2610 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2611 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2612 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2613 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2614 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2615 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2616 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2617 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2618 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2619 NewAttr = S.mergeImportNameAttr(D, *INA); 2620 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2621 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2622 2623 if (NewAttr) { 2624 NewAttr->setInherited(true); 2625 D->addAttr(NewAttr); 2626 if (isa<MSInheritanceAttr>(NewAttr)) 2627 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2628 return true; 2629 } 2630 2631 return false; 2632 } 2633 2634 static const NamedDecl *getDefinition(const Decl *D) { 2635 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2636 return TD->getDefinition(); 2637 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2638 const VarDecl *Def = VD->getDefinition(); 2639 if (Def) 2640 return Def; 2641 return VD->getActingDefinition(); 2642 } 2643 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2644 return FD->getDefinition(); 2645 return nullptr; 2646 } 2647 2648 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2649 for (const auto *Attribute : D->attrs()) 2650 if (Attribute->getKind() == Kind) 2651 return true; 2652 return false; 2653 } 2654 2655 /// checkNewAttributesAfterDef - If we already have a definition, check that 2656 /// there are no new attributes in this declaration. 2657 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2658 if (!New->hasAttrs()) 2659 return; 2660 2661 const NamedDecl *Def = getDefinition(Old); 2662 if (!Def || Def == New) 2663 return; 2664 2665 AttrVec &NewAttributes = New->getAttrs(); 2666 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2667 const Attr *NewAttribute = NewAttributes[I]; 2668 2669 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2670 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2671 Sema::SkipBodyInfo SkipBody; 2672 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2673 2674 // If we're skipping this definition, drop the "alias" attribute. 2675 if (SkipBody.ShouldSkip) { 2676 NewAttributes.erase(NewAttributes.begin() + I); 2677 --E; 2678 continue; 2679 } 2680 } else { 2681 VarDecl *VD = cast<VarDecl>(New); 2682 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2683 VarDecl::TentativeDefinition 2684 ? diag::err_alias_after_tentative 2685 : diag::err_redefinition; 2686 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2687 if (Diag == diag::err_redefinition) 2688 S.notePreviousDefinition(Def, VD->getLocation()); 2689 else 2690 S.Diag(Def->getLocation(), diag::note_previous_definition); 2691 VD->setInvalidDecl(); 2692 } 2693 ++I; 2694 continue; 2695 } 2696 2697 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2698 // Tentative definitions are only interesting for the alias check above. 2699 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2700 ++I; 2701 continue; 2702 } 2703 } 2704 2705 if (hasAttribute(Def, NewAttribute->getKind())) { 2706 ++I; 2707 continue; // regular attr merging will take care of validating this. 2708 } 2709 2710 if (isa<C11NoReturnAttr>(NewAttribute)) { 2711 // C's _Noreturn is allowed to be added to a function after it is defined. 2712 ++I; 2713 continue; 2714 } else if (isa<UuidAttr>(NewAttribute)) { 2715 // msvc will allow a subsequent definition to add an uuid to a class 2716 ++I; 2717 continue; 2718 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2719 if (AA->isAlignas()) { 2720 // C++11 [dcl.align]p6: 2721 // if any declaration of an entity has an alignment-specifier, 2722 // every defining declaration of that entity shall specify an 2723 // equivalent alignment. 2724 // C11 6.7.5/7: 2725 // If the definition of an object does not have an alignment 2726 // specifier, any other declaration of that object shall also 2727 // have no alignment specifier. 2728 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2729 << AA; 2730 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2731 << AA; 2732 NewAttributes.erase(NewAttributes.begin() + I); 2733 --E; 2734 continue; 2735 } 2736 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2737 // If there is a C definition followed by a redeclaration with this 2738 // attribute then there are two different definitions. In C++, prefer the 2739 // standard diagnostics. 2740 if (!S.getLangOpts().CPlusPlus) { 2741 S.Diag(NewAttribute->getLocation(), 2742 diag::err_loader_uninitialized_redeclaration); 2743 S.Diag(Def->getLocation(), diag::note_previous_definition); 2744 NewAttributes.erase(NewAttributes.begin() + I); 2745 --E; 2746 continue; 2747 } 2748 } else if (isa<SelectAnyAttr>(NewAttribute) && 2749 cast<VarDecl>(New)->isInline() && 2750 !cast<VarDecl>(New)->isInlineSpecified()) { 2751 // Don't warn about applying selectany to implicitly inline variables. 2752 // Older compilers and language modes would require the use of selectany 2753 // to make such variables inline, and it would have no effect if we 2754 // honored it. 2755 ++I; 2756 continue; 2757 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2758 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2759 // declarations after defintions. 2760 ++I; 2761 continue; 2762 } 2763 2764 S.Diag(NewAttribute->getLocation(), 2765 diag::warn_attribute_precede_definition); 2766 S.Diag(Def->getLocation(), diag::note_previous_definition); 2767 NewAttributes.erase(NewAttributes.begin() + I); 2768 --E; 2769 } 2770 } 2771 2772 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2773 const ConstInitAttr *CIAttr, 2774 bool AttrBeforeInit) { 2775 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2776 2777 // Figure out a good way to write this specifier on the old declaration. 2778 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2779 // enough of the attribute list spelling information to extract that without 2780 // heroics. 2781 std::string SuitableSpelling; 2782 if (S.getLangOpts().CPlusPlus20) 2783 SuitableSpelling = std::string( 2784 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2785 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2786 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2787 InsertLoc, {tok::l_square, tok::l_square, 2788 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2789 S.PP.getIdentifierInfo("require_constant_initialization"), 2790 tok::r_square, tok::r_square})); 2791 if (SuitableSpelling.empty()) 2792 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2793 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2794 S.PP.getIdentifierInfo("require_constant_initialization"), 2795 tok::r_paren, tok::r_paren})); 2796 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2797 SuitableSpelling = "constinit"; 2798 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2799 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2800 if (SuitableSpelling.empty()) 2801 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2802 SuitableSpelling += " "; 2803 2804 if (AttrBeforeInit) { 2805 // extern constinit int a; 2806 // int a = 0; // error (missing 'constinit'), accepted as extension 2807 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2808 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2809 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2810 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2811 } else { 2812 // int a = 0; 2813 // constinit extern int a; // error (missing 'constinit') 2814 S.Diag(CIAttr->getLocation(), 2815 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2816 : diag::warn_require_const_init_added_too_late) 2817 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2818 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2819 << CIAttr->isConstinit() 2820 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2821 } 2822 } 2823 2824 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2825 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2826 AvailabilityMergeKind AMK) { 2827 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2828 UsedAttr *NewAttr = OldAttr->clone(Context); 2829 NewAttr->setInherited(true); 2830 New->addAttr(NewAttr); 2831 } 2832 2833 if (!Old->hasAttrs() && !New->hasAttrs()) 2834 return; 2835 2836 // [dcl.constinit]p1: 2837 // If the [constinit] specifier is applied to any declaration of a 2838 // variable, it shall be applied to the initializing declaration. 2839 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2840 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2841 if (bool(OldConstInit) != bool(NewConstInit)) { 2842 const auto *OldVD = cast<VarDecl>(Old); 2843 auto *NewVD = cast<VarDecl>(New); 2844 2845 // Find the initializing declaration. Note that we might not have linked 2846 // the new declaration into the redeclaration chain yet. 2847 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2848 if (!InitDecl && 2849 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2850 InitDecl = NewVD; 2851 2852 if (InitDecl == NewVD) { 2853 // This is the initializing declaration. If it would inherit 'constinit', 2854 // that's ill-formed. (Note that we do not apply this to the attribute 2855 // form). 2856 if (OldConstInit && OldConstInit->isConstinit()) 2857 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2858 /*AttrBeforeInit=*/true); 2859 } else if (NewConstInit) { 2860 // This is the first time we've been told that this declaration should 2861 // have a constant initializer. If we already saw the initializing 2862 // declaration, this is too late. 2863 if (InitDecl && InitDecl != NewVD) { 2864 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2865 /*AttrBeforeInit=*/false); 2866 NewVD->dropAttr<ConstInitAttr>(); 2867 } 2868 } 2869 } 2870 2871 // Attributes declared post-definition are currently ignored. 2872 checkNewAttributesAfterDef(*this, New, Old); 2873 2874 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2875 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2876 if (!OldA->isEquivalent(NewA)) { 2877 // This redeclaration changes __asm__ label. 2878 Diag(New->getLocation(), diag::err_different_asm_label); 2879 Diag(OldA->getLocation(), diag::note_previous_declaration); 2880 } 2881 } else if (Old->isUsed()) { 2882 // This redeclaration adds an __asm__ label to a declaration that has 2883 // already been ODR-used. 2884 Diag(New->getLocation(), diag::err_late_asm_label_name) 2885 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2886 } 2887 } 2888 2889 // Re-declaration cannot add abi_tag's. 2890 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2891 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2892 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2893 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2894 NewTag) == OldAbiTagAttr->tags_end()) { 2895 Diag(NewAbiTagAttr->getLocation(), 2896 diag::err_new_abi_tag_on_redeclaration) 2897 << NewTag; 2898 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2899 } 2900 } 2901 } else { 2902 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2903 Diag(Old->getLocation(), diag::note_previous_declaration); 2904 } 2905 } 2906 2907 // This redeclaration adds a section attribute. 2908 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2909 if (auto *VD = dyn_cast<VarDecl>(New)) { 2910 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2911 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2912 Diag(Old->getLocation(), diag::note_previous_declaration); 2913 } 2914 } 2915 } 2916 2917 // Redeclaration adds code-seg attribute. 2918 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2919 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2920 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2921 Diag(New->getLocation(), diag::warn_mismatched_section) 2922 << 0 /*codeseg*/; 2923 Diag(Old->getLocation(), diag::note_previous_declaration); 2924 } 2925 2926 if (!Old->hasAttrs()) 2927 return; 2928 2929 bool foundAny = New->hasAttrs(); 2930 2931 // Ensure that any moving of objects within the allocated map is done before 2932 // we process them. 2933 if (!foundAny) New->setAttrs(AttrVec()); 2934 2935 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2936 // Ignore deprecated/unavailable/availability attributes if requested. 2937 AvailabilityMergeKind LocalAMK = AMK_None; 2938 if (isa<DeprecatedAttr>(I) || 2939 isa<UnavailableAttr>(I) || 2940 isa<AvailabilityAttr>(I)) { 2941 switch (AMK) { 2942 case AMK_None: 2943 continue; 2944 2945 case AMK_Redeclaration: 2946 case AMK_Override: 2947 case AMK_ProtocolImplementation: 2948 LocalAMK = AMK; 2949 break; 2950 } 2951 } 2952 2953 // Already handled. 2954 if (isa<UsedAttr>(I)) 2955 continue; 2956 2957 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2958 foundAny = true; 2959 } 2960 2961 if (mergeAlignedAttrs(*this, New, Old)) 2962 foundAny = true; 2963 2964 if (!foundAny) New->dropAttrs(); 2965 } 2966 2967 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2968 /// to the new one. 2969 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2970 const ParmVarDecl *oldDecl, 2971 Sema &S) { 2972 // C++11 [dcl.attr.depend]p2: 2973 // The first declaration of a function shall specify the 2974 // carries_dependency attribute for its declarator-id if any declaration 2975 // of the function specifies the carries_dependency attribute. 2976 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2977 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2978 S.Diag(CDA->getLocation(), 2979 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2980 // Find the first declaration of the parameter. 2981 // FIXME: Should we build redeclaration chains for function parameters? 2982 const FunctionDecl *FirstFD = 2983 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2984 const ParmVarDecl *FirstVD = 2985 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2986 S.Diag(FirstVD->getLocation(), 2987 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2988 } 2989 2990 if (!oldDecl->hasAttrs()) 2991 return; 2992 2993 bool foundAny = newDecl->hasAttrs(); 2994 2995 // Ensure that any moving of objects within the allocated map is 2996 // done before we process them. 2997 if (!foundAny) newDecl->setAttrs(AttrVec()); 2998 2999 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3000 if (!DeclHasAttr(newDecl, I)) { 3001 InheritableAttr *newAttr = 3002 cast<InheritableParamAttr>(I->clone(S.Context)); 3003 newAttr->setInherited(true); 3004 newDecl->addAttr(newAttr); 3005 foundAny = true; 3006 } 3007 } 3008 3009 if (!foundAny) newDecl->dropAttrs(); 3010 } 3011 3012 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3013 const ParmVarDecl *OldParam, 3014 Sema &S) { 3015 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3016 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3017 if (*Oldnullability != *Newnullability) { 3018 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3019 << DiagNullabilityKind( 3020 *Newnullability, 3021 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3022 != 0)) 3023 << DiagNullabilityKind( 3024 *Oldnullability, 3025 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3026 != 0)); 3027 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3028 } 3029 } else { 3030 QualType NewT = NewParam->getType(); 3031 NewT = S.Context.getAttributedType( 3032 AttributedType::getNullabilityAttrKind(*Oldnullability), 3033 NewT, NewT); 3034 NewParam->setType(NewT); 3035 } 3036 } 3037 } 3038 3039 namespace { 3040 3041 /// Used in MergeFunctionDecl to keep track of function parameters in 3042 /// C. 3043 struct GNUCompatibleParamWarning { 3044 ParmVarDecl *OldParm; 3045 ParmVarDecl *NewParm; 3046 QualType PromotedType; 3047 }; 3048 3049 } // end anonymous namespace 3050 3051 // Determine whether the previous declaration was a definition, implicit 3052 // declaration, or a declaration. 3053 template <typename T> 3054 static std::pair<diag::kind, SourceLocation> 3055 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3056 diag::kind PrevDiag; 3057 SourceLocation OldLocation = Old->getLocation(); 3058 if (Old->isThisDeclarationADefinition()) 3059 PrevDiag = diag::note_previous_definition; 3060 else if (Old->isImplicit()) { 3061 PrevDiag = diag::note_previous_implicit_declaration; 3062 if (OldLocation.isInvalid()) 3063 OldLocation = New->getLocation(); 3064 } else 3065 PrevDiag = diag::note_previous_declaration; 3066 return std::make_pair(PrevDiag, OldLocation); 3067 } 3068 3069 /// canRedefineFunction - checks if a function can be redefined. Currently, 3070 /// only extern inline functions can be redefined, and even then only in 3071 /// GNU89 mode. 3072 static bool canRedefineFunction(const FunctionDecl *FD, 3073 const LangOptions& LangOpts) { 3074 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3075 !LangOpts.CPlusPlus && 3076 FD->isInlineSpecified() && 3077 FD->getStorageClass() == SC_Extern); 3078 } 3079 3080 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3081 const AttributedType *AT = T->getAs<AttributedType>(); 3082 while (AT && !AT->isCallingConv()) 3083 AT = AT->getModifiedType()->getAs<AttributedType>(); 3084 return AT; 3085 } 3086 3087 template <typename T> 3088 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3089 const DeclContext *DC = Old->getDeclContext(); 3090 if (DC->isRecord()) 3091 return false; 3092 3093 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3094 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3095 return true; 3096 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3097 return true; 3098 return false; 3099 } 3100 3101 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3102 static bool isExternC(VarTemplateDecl *) { return false; } 3103 3104 /// Check whether a redeclaration of an entity introduced by a 3105 /// using-declaration is valid, given that we know it's not an overload 3106 /// (nor a hidden tag declaration). 3107 template<typename ExpectedDecl> 3108 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3109 ExpectedDecl *New) { 3110 // C++11 [basic.scope.declarative]p4: 3111 // Given a set of declarations in a single declarative region, each of 3112 // which specifies the same unqualified name, 3113 // -- they shall all refer to the same entity, or all refer to functions 3114 // and function templates; or 3115 // -- exactly one declaration shall declare a class name or enumeration 3116 // name that is not a typedef name and the other declarations shall all 3117 // refer to the same variable or enumerator, or all refer to functions 3118 // and function templates; in this case the class name or enumeration 3119 // name is hidden (3.3.10). 3120 3121 // C++11 [namespace.udecl]p14: 3122 // If a function declaration in namespace scope or block scope has the 3123 // same name and the same parameter-type-list as a function introduced 3124 // by a using-declaration, and the declarations do not declare the same 3125 // function, the program is ill-formed. 3126 3127 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3128 if (Old && 3129 !Old->getDeclContext()->getRedeclContext()->Equals( 3130 New->getDeclContext()->getRedeclContext()) && 3131 !(isExternC(Old) && isExternC(New))) 3132 Old = nullptr; 3133 3134 if (!Old) { 3135 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3136 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3137 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3138 return true; 3139 } 3140 return false; 3141 } 3142 3143 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3144 const FunctionDecl *B) { 3145 assert(A->getNumParams() == B->getNumParams()); 3146 3147 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3148 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3149 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3150 if (AttrA == AttrB) 3151 return true; 3152 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3153 AttrA->isDynamic() == AttrB->isDynamic(); 3154 }; 3155 3156 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3157 } 3158 3159 /// If necessary, adjust the semantic declaration context for a qualified 3160 /// declaration to name the correct inline namespace within the qualifier. 3161 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3162 DeclaratorDecl *OldD) { 3163 // The only case where we need to update the DeclContext is when 3164 // redeclaration lookup for a qualified name finds a declaration 3165 // in an inline namespace within the context named by the qualifier: 3166 // 3167 // inline namespace N { int f(); } 3168 // int ::f(); // Sema DC needs adjusting from :: to N::. 3169 // 3170 // For unqualified declarations, the semantic context *can* change 3171 // along the redeclaration chain (for local extern declarations, 3172 // extern "C" declarations, and friend declarations in particular). 3173 if (!NewD->getQualifier()) 3174 return; 3175 3176 // NewD is probably already in the right context. 3177 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3178 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3179 if (NamedDC->Equals(SemaDC)) 3180 return; 3181 3182 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3183 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3184 "unexpected context for redeclaration"); 3185 3186 auto *LexDC = NewD->getLexicalDeclContext(); 3187 auto FixSemaDC = [=](NamedDecl *D) { 3188 if (!D) 3189 return; 3190 D->setDeclContext(SemaDC); 3191 D->setLexicalDeclContext(LexDC); 3192 }; 3193 3194 FixSemaDC(NewD); 3195 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3196 FixSemaDC(FD->getDescribedFunctionTemplate()); 3197 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3198 FixSemaDC(VD->getDescribedVarTemplate()); 3199 } 3200 3201 /// MergeFunctionDecl - We just parsed a function 'New' from 3202 /// declarator D which has the same name and scope as a previous 3203 /// declaration 'Old'. Figure out how to resolve this situation, 3204 /// merging decls or emitting diagnostics as appropriate. 3205 /// 3206 /// In C++, New and Old must be declarations that are not 3207 /// overloaded. Use IsOverload to determine whether New and Old are 3208 /// overloaded, and to select the Old declaration that New should be 3209 /// merged with. 3210 /// 3211 /// Returns true if there was an error, false otherwise. 3212 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3213 Scope *S, bool MergeTypeWithOld) { 3214 // Verify the old decl was also a function. 3215 FunctionDecl *Old = OldD->getAsFunction(); 3216 if (!Old) { 3217 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3218 if (New->getFriendObjectKind()) { 3219 Diag(New->getLocation(), diag::err_using_decl_friend); 3220 Diag(Shadow->getTargetDecl()->getLocation(), 3221 diag::note_using_decl_target); 3222 Diag(Shadow->getUsingDecl()->getLocation(), 3223 diag::note_using_decl) << 0; 3224 return true; 3225 } 3226 3227 // Check whether the two declarations might declare the same function. 3228 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3229 return true; 3230 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3231 } else { 3232 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3233 << New->getDeclName(); 3234 notePreviousDefinition(OldD, New->getLocation()); 3235 return true; 3236 } 3237 } 3238 3239 // If the old declaration is invalid, just give up here. 3240 if (Old->isInvalidDecl()) 3241 return true; 3242 3243 // Disallow redeclaration of some builtins. 3244 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3245 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3246 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3247 << Old << Old->getType(); 3248 return true; 3249 } 3250 3251 diag::kind PrevDiag; 3252 SourceLocation OldLocation; 3253 std::tie(PrevDiag, OldLocation) = 3254 getNoteDiagForInvalidRedeclaration(Old, New); 3255 3256 // Don't complain about this if we're in GNU89 mode and the old function 3257 // is an extern inline function. 3258 // Don't complain about specializations. They are not supposed to have 3259 // storage classes. 3260 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3261 New->getStorageClass() == SC_Static && 3262 Old->hasExternalFormalLinkage() && 3263 !New->getTemplateSpecializationInfo() && 3264 !canRedefineFunction(Old, getLangOpts())) { 3265 if (getLangOpts().MicrosoftExt) { 3266 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3267 Diag(OldLocation, PrevDiag); 3268 } else { 3269 Diag(New->getLocation(), diag::err_static_non_static) << New; 3270 Diag(OldLocation, PrevDiag); 3271 return true; 3272 } 3273 } 3274 3275 if (New->hasAttr<InternalLinkageAttr>() && 3276 !Old->hasAttr<InternalLinkageAttr>()) { 3277 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3278 << New->getDeclName(); 3279 notePreviousDefinition(Old, New->getLocation()); 3280 New->dropAttr<InternalLinkageAttr>(); 3281 } 3282 3283 if (CheckRedeclarationModuleOwnership(New, Old)) 3284 return true; 3285 3286 if (!getLangOpts().CPlusPlus) { 3287 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3288 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3289 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3290 << New << OldOvl; 3291 3292 // Try our best to find a decl that actually has the overloadable 3293 // attribute for the note. In most cases (e.g. programs with only one 3294 // broken declaration/definition), this won't matter. 3295 // 3296 // FIXME: We could do this if we juggled some extra state in 3297 // OverloadableAttr, rather than just removing it. 3298 const Decl *DiagOld = Old; 3299 if (OldOvl) { 3300 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3301 const auto *A = D->getAttr<OverloadableAttr>(); 3302 return A && !A->isImplicit(); 3303 }); 3304 // If we've implicitly added *all* of the overloadable attrs to this 3305 // chain, emitting a "previous redecl" note is pointless. 3306 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3307 } 3308 3309 if (DiagOld) 3310 Diag(DiagOld->getLocation(), 3311 diag::note_attribute_overloadable_prev_overload) 3312 << OldOvl; 3313 3314 if (OldOvl) 3315 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3316 else 3317 New->dropAttr<OverloadableAttr>(); 3318 } 3319 } 3320 3321 // If a function is first declared with a calling convention, but is later 3322 // declared or defined without one, all following decls assume the calling 3323 // convention of the first. 3324 // 3325 // It's OK if a function is first declared without a calling convention, 3326 // but is later declared or defined with the default calling convention. 3327 // 3328 // To test if either decl has an explicit calling convention, we look for 3329 // AttributedType sugar nodes on the type as written. If they are missing or 3330 // were canonicalized away, we assume the calling convention was implicit. 3331 // 3332 // Note also that we DO NOT return at this point, because we still have 3333 // other tests to run. 3334 QualType OldQType = Context.getCanonicalType(Old->getType()); 3335 QualType NewQType = Context.getCanonicalType(New->getType()); 3336 const FunctionType *OldType = cast<FunctionType>(OldQType); 3337 const FunctionType *NewType = cast<FunctionType>(NewQType); 3338 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3339 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3340 bool RequiresAdjustment = false; 3341 3342 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3343 FunctionDecl *First = Old->getFirstDecl(); 3344 const FunctionType *FT = 3345 First->getType().getCanonicalType()->castAs<FunctionType>(); 3346 FunctionType::ExtInfo FI = FT->getExtInfo(); 3347 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3348 if (!NewCCExplicit) { 3349 // Inherit the CC from the previous declaration if it was specified 3350 // there but not here. 3351 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3352 RequiresAdjustment = true; 3353 } else if (Old->getBuiltinID()) { 3354 // Builtin attribute isn't propagated to the new one yet at this point, 3355 // so we check if the old one is a builtin. 3356 3357 // Calling Conventions on a Builtin aren't really useful and setting a 3358 // default calling convention and cdecl'ing some builtin redeclarations is 3359 // common, so warn and ignore the calling convention on the redeclaration. 3360 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3361 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3362 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3363 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3364 RequiresAdjustment = true; 3365 } else { 3366 // Calling conventions aren't compatible, so complain. 3367 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3368 Diag(New->getLocation(), diag::err_cconv_change) 3369 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3370 << !FirstCCExplicit 3371 << (!FirstCCExplicit ? "" : 3372 FunctionType::getNameForCallConv(FI.getCC())); 3373 3374 // Put the note on the first decl, since it is the one that matters. 3375 Diag(First->getLocation(), diag::note_previous_declaration); 3376 return true; 3377 } 3378 } 3379 3380 // FIXME: diagnose the other way around? 3381 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3382 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3383 RequiresAdjustment = true; 3384 } 3385 3386 // Merge regparm attribute. 3387 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3388 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3389 if (NewTypeInfo.getHasRegParm()) { 3390 Diag(New->getLocation(), diag::err_regparm_mismatch) 3391 << NewType->getRegParmType() 3392 << OldType->getRegParmType(); 3393 Diag(OldLocation, diag::note_previous_declaration); 3394 return true; 3395 } 3396 3397 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3398 RequiresAdjustment = true; 3399 } 3400 3401 // Merge ns_returns_retained attribute. 3402 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3403 if (NewTypeInfo.getProducesResult()) { 3404 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3405 << "'ns_returns_retained'"; 3406 Diag(OldLocation, diag::note_previous_declaration); 3407 return true; 3408 } 3409 3410 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3411 RequiresAdjustment = true; 3412 } 3413 3414 if (OldTypeInfo.getNoCallerSavedRegs() != 3415 NewTypeInfo.getNoCallerSavedRegs()) { 3416 if (NewTypeInfo.getNoCallerSavedRegs()) { 3417 AnyX86NoCallerSavedRegistersAttr *Attr = 3418 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3419 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3420 Diag(OldLocation, diag::note_previous_declaration); 3421 return true; 3422 } 3423 3424 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3425 RequiresAdjustment = true; 3426 } 3427 3428 if (RequiresAdjustment) { 3429 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3430 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3431 New->setType(QualType(AdjustedType, 0)); 3432 NewQType = Context.getCanonicalType(New->getType()); 3433 } 3434 3435 // If this redeclaration makes the function inline, we may need to add it to 3436 // UndefinedButUsed. 3437 if (!Old->isInlined() && New->isInlined() && 3438 !New->hasAttr<GNUInlineAttr>() && 3439 !getLangOpts().GNUInline && 3440 Old->isUsed(false) && 3441 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3442 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3443 SourceLocation())); 3444 3445 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3446 // about it. 3447 if (New->hasAttr<GNUInlineAttr>() && 3448 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3449 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3450 } 3451 3452 // If pass_object_size params don't match up perfectly, this isn't a valid 3453 // redeclaration. 3454 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3455 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3456 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3457 << New->getDeclName(); 3458 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3459 return true; 3460 } 3461 3462 if (getLangOpts().CPlusPlus) { 3463 // C++1z [over.load]p2 3464 // Certain function declarations cannot be overloaded: 3465 // -- Function declarations that differ only in the return type, 3466 // the exception specification, or both cannot be overloaded. 3467 3468 // Check the exception specifications match. This may recompute the type of 3469 // both Old and New if it resolved exception specifications, so grab the 3470 // types again after this. Because this updates the type, we do this before 3471 // any of the other checks below, which may update the "de facto" NewQType 3472 // but do not necessarily update the type of New. 3473 if (CheckEquivalentExceptionSpec(Old, New)) 3474 return true; 3475 OldQType = Context.getCanonicalType(Old->getType()); 3476 NewQType = Context.getCanonicalType(New->getType()); 3477 3478 // Go back to the type source info to compare the declared return types, 3479 // per C++1y [dcl.type.auto]p13: 3480 // Redeclarations or specializations of a function or function template 3481 // with a declared return type that uses a placeholder type shall also 3482 // use that placeholder, not a deduced type. 3483 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3484 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3485 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3486 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3487 OldDeclaredReturnType)) { 3488 QualType ResQT; 3489 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3490 OldDeclaredReturnType->isObjCObjectPointerType()) 3491 // FIXME: This does the wrong thing for a deduced return type. 3492 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3493 if (ResQT.isNull()) { 3494 if (New->isCXXClassMember() && New->isOutOfLine()) 3495 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3496 << New << New->getReturnTypeSourceRange(); 3497 else 3498 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3499 << New->getReturnTypeSourceRange(); 3500 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3501 << Old->getReturnTypeSourceRange(); 3502 return true; 3503 } 3504 else 3505 NewQType = ResQT; 3506 } 3507 3508 QualType OldReturnType = OldType->getReturnType(); 3509 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3510 if (OldReturnType != NewReturnType) { 3511 // If this function has a deduced return type and has already been 3512 // defined, copy the deduced value from the old declaration. 3513 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3514 if (OldAT && OldAT->isDeduced()) { 3515 New->setType( 3516 SubstAutoType(New->getType(), 3517 OldAT->isDependentType() ? Context.DependentTy 3518 : OldAT->getDeducedType())); 3519 NewQType = Context.getCanonicalType( 3520 SubstAutoType(NewQType, 3521 OldAT->isDependentType() ? Context.DependentTy 3522 : OldAT->getDeducedType())); 3523 } 3524 } 3525 3526 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3527 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3528 if (OldMethod && NewMethod) { 3529 // Preserve triviality. 3530 NewMethod->setTrivial(OldMethod->isTrivial()); 3531 3532 // MSVC allows explicit template specialization at class scope: 3533 // 2 CXXMethodDecls referring to the same function will be injected. 3534 // We don't want a redeclaration error. 3535 bool IsClassScopeExplicitSpecialization = 3536 OldMethod->isFunctionTemplateSpecialization() && 3537 NewMethod->isFunctionTemplateSpecialization(); 3538 bool isFriend = NewMethod->getFriendObjectKind(); 3539 3540 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3541 !IsClassScopeExplicitSpecialization) { 3542 // -- Member function declarations with the same name and the 3543 // same parameter types cannot be overloaded if any of them 3544 // is a static member function declaration. 3545 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3546 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3547 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3548 return true; 3549 } 3550 3551 // C++ [class.mem]p1: 3552 // [...] A member shall not be declared twice in the 3553 // member-specification, except that a nested class or member 3554 // class template can be declared and then later defined. 3555 if (!inTemplateInstantiation()) { 3556 unsigned NewDiag; 3557 if (isa<CXXConstructorDecl>(OldMethod)) 3558 NewDiag = diag::err_constructor_redeclared; 3559 else if (isa<CXXDestructorDecl>(NewMethod)) 3560 NewDiag = diag::err_destructor_redeclared; 3561 else if (isa<CXXConversionDecl>(NewMethod)) 3562 NewDiag = diag::err_conv_function_redeclared; 3563 else 3564 NewDiag = diag::err_member_redeclared; 3565 3566 Diag(New->getLocation(), NewDiag); 3567 } else { 3568 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3569 << New << New->getType(); 3570 } 3571 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3572 return true; 3573 3574 // Complain if this is an explicit declaration of a special 3575 // member that was initially declared implicitly. 3576 // 3577 // As an exception, it's okay to befriend such methods in order 3578 // to permit the implicit constructor/destructor/operator calls. 3579 } else if (OldMethod->isImplicit()) { 3580 if (isFriend) { 3581 NewMethod->setImplicit(); 3582 } else { 3583 Diag(NewMethod->getLocation(), 3584 diag::err_definition_of_implicitly_declared_member) 3585 << New << getSpecialMember(OldMethod); 3586 return true; 3587 } 3588 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3589 Diag(NewMethod->getLocation(), 3590 diag::err_definition_of_explicitly_defaulted_member) 3591 << getSpecialMember(OldMethod); 3592 return true; 3593 } 3594 } 3595 3596 // C++11 [dcl.attr.noreturn]p1: 3597 // The first declaration of a function shall specify the noreturn 3598 // attribute if any declaration of that function specifies the noreturn 3599 // attribute. 3600 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3601 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3602 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3603 Diag(Old->getFirstDecl()->getLocation(), 3604 diag::note_noreturn_missing_first_decl); 3605 } 3606 3607 // C++11 [dcl.attr.depend]p2: 3608 // The first declaration of a function shall specify the 3609 // carries_dependency attribute for its declarator-id if any declaration 3610 // of the function specifies the carries_dependency attribute. 3611 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3612 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3613 Diag(CDA->getLocation(), 3614 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3615 Diag(Old->getFirstDecl()->getLocation(), 3616 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3617 } 3618 3619 // (C++98 8.3.5p3): 3620 // All declarations for a function shall agree exactly in both the 3621 // return type and the parameter-type-list. 3622 // We also want to respect all the extended bits except noreturn. 3623 3624 // noreturn should now match unless the old type info didn't have it. 3625 QualType OldQTypeForComparison = OldQType; 3626 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3627 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3628 const FunctionType *OldTypeForComparison 3629 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3630 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3631 assert(OldQTypeForComparison.isCanonical()); 3632 } 3633 3634 if (haveIncompatibleLanguageLinkages(Old, New)) { 3635 // As a special case, retain the language linkage from previous 3636 // declarations of a friend function as an extension. 3637 // 3638 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3639 // and is useful because there's otherwise no way to specify language 3640 // linkage within class scope. 3641 // 3642 // Check cautiously as the friend object kind isn't yet complete. 3643 if (New->getFriendObjectKind() != Decl::FOK_None) { 3644 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3645 Diag(OldLocation, PrevDiag); 3646 } else { 3647 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3648 Diag(OldLocation, PrevDiag); 3649 return true; 3650 } 3651 } 3652 3653 // If the function types are compatible, merge the declarations. Ignore the 3654 // exception specifier because it was already checked above in 3655 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3656 // about incompatible types under -fms-compatibility. 3657 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3658 NewQType)) 3659 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3660 3661 // If the types are imprecise (due to dependent constructs in friends or 3662 // local extern declarations), it's OK if they differ. We'll check again 3663 // during instantiation. 3664 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3665 return false; 3666 3667 // Fall through for conflicting redeclarations and redefinitions. 3668 } 3669 3670 // C: Function types need to be compatible, not identical. This handles 3671 // duplicate function decls like "void f(int); void f(enum X);" properly. 3672 if (!getLangOpts().CPlusPlus && 3673 Context.typesAreCompatible(OldQType, NewQType)) { 3674 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3675 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3676 const FunctionProtoType *OldProto = nullptr; 3677 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3678 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3679 // The old declaration provided a function prototype, but the 3680 // new declaration does not. Merge in the prototype. 3681 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3682 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3683 NewQType = 3684 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3685 OldProto->getExtProtoInfo()); 3686 New->setType(NewQType); 3687 New->setHasInheritedPrototype(); 3688 3689 // Synthesize parameters with the same types. 3690 SmallVector<ParmVarDecl*, 16> Params; 3691 for (const auto &ParamType : OldProto->param_types()) { 3692 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3693 SourceLocation(), nullptr, 3694 ParamType, /*TInfo=*/nullptr, 3695 SC_None, nullptr); 3696 Param->setScopeInfo(0, Params.size()); 3697 Param->setImplicit(); 3698 Params.push_back(Param); 3699 } 3700 3701 New->setParams(Params); 3702 } 3703 3704 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3705 } 3706 3707 // Check if the function types are compatible when pointer size address 3708 // spaces are ignored. 3709 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3710 return false; 3711 3712 // GNU C permits a K&R definition to follow a prototype declaration 3713 // if the declared types of the parameters in the K&R definition 3714 // match the types in the prototype declaration, even when the 3715 // promoted types of the parameters from the K&R definition differ 3716 // from the types in the prototype. GCC then keeps the types from 3717 // the prototype. 3718 // 3719 // If a variadic prototype is followed by a non-variadic K&R definition, 3720 // the K&R definition becomes variadic. This is sort of an edge case, but 3721 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3722 // C99 6.9.1p8. 3723 if (!getLangOpts().CPlusPlus && 3724 Old->hasPrototype() && !New->hasPrototype() && 3725 New->getType()->getAs<FunctionProtoType>() && 3726 Old->getNumParams() == New->getNumParams()) { 3727 SmallVector<QualType, 16> ArgTypes; 3728 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3729 const FunctionProtoType *OldProto 3730 = Old->getType()->getAs<FunctionProtoType>(); 3731 const FunctionProtoType *NewProto 3732 = New->getType()->getAs<FunctionProtoType>(); 3733 3734 // Determine whether this is the GNU C extension. 3735 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3736 NewProto->getReturnType()); 3737 bool LooseCompatible = !MergedReturn.isNull(); 3738 for (unsigned Idx = 0, End = Old->getNumParams(); 3739 LooseCompatible && Idx != End; ++Idx) { 3740 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3741 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3742 if (Context.typesAreCompatible(OldParm->getType(), 3743 NewProto->getParamType(Idx))) { 3744 ArgTypes.push_back(NewParm->getType()); 3745 } else if (Context.typesAreCompatible(OldParm->getType(), 3746 NewParm->getType(), 3747 /*CompareUnqualified=*/true)) { 3748 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3749 NewProto->getParamType(Idx) }; 3750 Warnings.push_back(Warn); 3751 ArgTypes.push_back(NewParm->getType()); 3752 } else 3753 LooseCompatible = false; 3754 } 3755 3756 if (LooseCompatible) { 3757 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3758 Diag(Warnings[Warn].NewParm->getLocation(), 3759 diag::ext_param_promoted_not_compatible_with_prototype) 3760 << Warnings[Warn].PromotedType 3761 << Warnings[Warn].OldParm->getType(); 3762 if (Warnings[Warn].OldParm->getLocation().isValid()) 3763 Diag(Warnings[Warn].OldParm->getLocation(), 3764 diag::note_previous_declaration); 3765 } 3766 3767 if (MergeTypeWithOld) 3768 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3769 OldProto->getExtProtoInfo())); 3770 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3771 } 3772 3773 // Fall through to diagnose conflicting types. 3774 } 3775 3776 // A function that has already been declared has been redeclared or 3777 // defined with a different type; show an appropriate diagnostic. 3778 3779 // If the previous declaration was an implicitly-generated builtin 3780 // declaration, then at the very least we should use a specialized note. 3781 unsigned BuiltinID; 3782 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3783 // If it's actually a library-defined builtin function like 'malloc' 3784 // or 'printf', just warn about the incompatible redeclaration. 3785 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3786 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3787 Diag(OldLocation, diag::note_previous_builtin_declaration) 3788 << Old << Old->getType(); 3789 return false; 3790 } 3791 3792 PrevDiag = diag::note_previous_builtin_declaration; 3793 } 3794 3795 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3796 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3797 return true; 3798 } 3799 3800 /// Completes the merge of two function declarations that are 3801 /// known to be compatible. 3802 /// 3803 /// This routine handles the merging of attributes and other 3804 /// properties of function declarations from the old declaration to 3805 /// the new declaration, once we know that New is in fact a 3806 /// redeclaration of Old. 3807 /// 3808 /// \returns false 3809 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3810 Scope *S, bool MergeTypeWithOld) { 3811 // Merge the attributes 3812 mergeDeclAttributes(New, Old); 3813 3814 // Merge "pure" flag. 3815 if (Old->isPure()) 3816 New->setPure(); 3817 3818 // Merge "used" flag. 3819 if (Old->getMostRecentDecl()->isUsed(false)) 3820 New->setIsUsed(); 3821 3822 // Merge attributes from the parameters. These can mismatch with K&R 3823 // declarations. 3824 if (New->getNumParams() == Old->getNumParams()) 3825 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3826 ParmVarDecl *NewParam = New->getParamDecl(i); 3827 ParmVarDecl *OldParam = Old->getParamDecl(i); 3828 mergeParamDeclAttributes(NewParam, OldParam, *this); 3829 mergeParamDeclTypes(NewParam, OldParam, *this); 3830 } 3831 3832 if (getLangOpts().CPlusPlus) 3833 return MergeCXXFunctionDecl(New, Old, S); 3834 3835 // Merge the function types so the we get the composite types for the return 3836 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3837 // was visible. 3838 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3839 if (!Merged.isNull() && MergeTypeWithOld) 3840 New->setType(Merged); 3841 3842 return false; 3843 } 3844 3845 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3846 ObjCMethodDecl *oldMethod) { 3847 // Merge the attributes, including deprecated/unavailable 3848 AvailabilityMergeKind MergeKind = 3849 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3850 ? AMK_ProtocolImplementation 3851 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3852 : AMK_Override; 3853 3854 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3855 3856 // Merge attributes from the parameters. 3857 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3858 oe = oldMethod->param_end(); 3859 for (ObjCMethodDecl::param_iterator 3860 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3861 ni != ne && oi != oe; ++ni, ++oi) 3862 mergeParamDeclAttributes(*ni, *oi, *this); 3863 3864 CheckObjCMethodOverride(newMethod, oldMethod); 3865 } 3866 3867 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3868 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3869 3870 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3871 ? diag::err_redefinition_different_type 3872 : diag::err_redeclaration_different_type) 3873 << New->getDeclName() << New->getType() << Old->getType(); 3874 3875 diag::kind PrevDiag; 3876 SourceLocation OldLocation; 3877 std::tie(PrevDiag, OldLocation) 3878 = getNoteDiagForInvalidRedeclaration(Old, New); 3879 S.Diag(OldLocation, PrevDiag); 3880 New->setInvalidDecl(); 3881 } 3882 3883 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3884 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3885 /// emitting diagnostics as appropriate. 3886 /// 3887 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3888 /// to here in AddInitializerToDecl. We can't check them before the initializer 3889 /// is attached. 3890 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3891 bool MergeTypeWithOld) { 3892 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3893 return; 3894 3895 QualType MergedT; 3896 if (getLangOpts().CPlusPlus) { 3897 if (New->getType()->isUndeducedType()) { 3898 // We don't know what the new type is until the initializer is attached. 3899 return; 3900 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3901 // These could still be something that needs exception specs checked. 3902 return MergeVarDeclExceptionSpecs(New, Old); 3903 } 3904 // C++ [basic.link]p10: 3905 // [...] the types specified by all declarations referring to a given 3906 // object or function shall be identical, except that declarations for an 3907 // array object can specify array types that differ by the presence or 3908 // absence of a major array bound (8.3.4). 3909 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3910 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3911 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3912 3913 // We are merging a variable declaration New into Old. If it has an array 3914 // bound, and that bound differs from Old's bound, we should diagnose the 3915 // mismatch. 3916 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3917 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3918 PrevVD = PrevVD->getPreviousDecl()) { 3919 QualType PrevVDTy = PrevVD->getType(); 3920 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3921 continue; 3922 3923 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3924 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3925 } 3926 } 3927 3928 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3929 if (Context.hasSameType(OldArray->getElementType(), 3930 NewArray->getElementType())) 3931 MergedT = New->getType(); 3932 } 3933 // FIXME: Check visibility. New is hidden but has a complete type. If New 3934 // has no array bound, it should not inherit one from Old, if Old is not 3935 // visible. 3936 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3937 if (Context.hasSameType(OldArray->getElementType(), 3938 NewArray->getElementType())) 3939 MergedT = Old->getType(); 3940 } 3941 } 3942 else if (New->getType()->isObjCObjectPointerType() && 3943 Old->getType()->isObjCObjectPointerType()) { 3944 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3945 Old->getType()); 3946 } 3947 } else { 3948 // C 6.2.7p2: 3949 // All declarations that refer to the same object or function shall have 3950 // compatible type. 3951 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3952 } 3953 if (MergedT.isNull()) { 3954 // It's OK if we couldn't merge types if either type is dependent, for a 3955 // block-scope variable. In other cases (static data members of class 3956 // templates, variable templates, ...), we require the types to be 3957 // equivalent. 3958 // FIXME: The C++ standard doesn't say anything about this. 3959 if ((New->getType()->isDependentType() || 3960 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3961 // If the old type was dependent, we can't merge with it, so the new type 3962 // becomes dependent for now. We'll reproduce the original type when we 3963 // instantiate the TypeSourceInfo for the variable. 3964 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3965 New->setType(Context.DependentTy); 3966 return; 3967 } 3968 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3969 } 3970 3971 // Don't actually update the type on the new declaration if the old 3972 // declaration was an extern declaration in a different scope. 3973 if (MergeTypeWithOld) 3974 New->setType(MergedT); 3975 } 3976 3977 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3978 LookupResult &Previous) { 3979 // C11 6.2.7p4: 3980 // For an identifier with internal or external linkage declared 3981 // in a scope in which a prior declaration of that identifier is 3982 // visible, if the prior declaration specifies internal or 3983 // external linkage, the type of the identifier at the later 3984 // declaration becomes the composite type. 3985 // 3986 // If the variable isn't visible, we do not merge with its type. 3987 if (Previous.isShadowed()) 3988 return false; 3989 3990 if (S.getLangOpts().CPlusPlus) { 3991 // C++11 [dcl.array]p3: 3992 // If there is a preceding declaration of the entity in the same 3993 // scope in which the bound was specified, an omitted array bound 3994 // is taken to be the same as in that earlier declaration. 3995 return NewVD->isPreviousDeclInSameBlockScope() || 3996 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3997 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3998 } else { 3999 // If the old declaration was function-local, don't merge with its 4000 // type unless we're in the same function. 4001 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4002 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4003 } 4004 } 4005 4006 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4007 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4008 /// situation, merging decls or emitting diagnostics as appropriate. 4009 /// 4010 /// Tentative definition rules (C99 6.9.2p2) are checked by 4011 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4012 /// definitions here, since the initializer hasn't been attached. 4013 /// 4014 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4015 // If the new decl is already invalid, don't do any other checking. 4016 if (New->isInvalidDecl()) 4017 return; 4018 4019 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4020 return; 4021 4022 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4023 4024 // Verify the old decl was also a variable or variable template. 4025 VarDecl *Old = nullptr; 4026 VarTemplateDecl *OldTemplate = nullptr; 4027 if (Previous.isSingleResult()) { 4028 if (NewTemplate) { 4029 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4030 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4031 4032 if (auto *Shadow = 4033 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4034 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4035 return New->setInvalidDecl(); 4036 } else { 4037 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4038 4039 if (auto *Shadow = 4040 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4041 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4042 return New->setInvalidDecl(); 4043 } 4044 } 4045 if (!Old) { 4046 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4047 << New->getDeclName(); 4048 notePreviousDefinition(Previous.getRepresentativeDecl(), 4049 New->getLocation()); 4050 return New->setInvalidDecl(); 4051 } 4052 4053 // Ensure the template parameters are compatible. 4054 if (NewTemplate && 4055 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4056 OldTemplate->getTemplateParameters(), 4057 /*Complain=*/true, TPL_TemplateMatch)) 4058 return New->setInvalidDecl(); 4059 4060 // C++ [class.mem]p1: 4061 // A member shall not be declared twice in the member-specification [...] 4062 // 4063 // Here, we need only consider static data members. 4064 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4065 Diag(New->getLocation(), diag::err_duplicate_member) 4066 << New->getIdentifier(); 4067 Diag(Old->getLocation(), diag::note_previous_declaration); 4068 New->setInvalidDecl(); 4069 } 4070 4071 mergeDeclAttributes(New, Old); 4072 // Warn if an already-declared variable is made a weak_import in a subsequent 4073 // declaration 4074 if (New->hasAttr<WeakImportAttr>() && 4075 Old->getStorageClass() == SC_None && 4076 !Old->hasAttr<WeakImportAttr>()) { 4077 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4078 notePreviousDefinition(Old, New->getLocation()); 4079 // Remove weak_import attribute on new declaration. 4080 New->dropAttr<WeakImportAttr>(); 4081 } 4082 4083 if (New->hasAttr<InternalLinkageAttr>() && 4084 !Old->hasAttr<InternalLinkageAttr>()) { 4085 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4086 << New->getDeclName(); 4087 notePreviousDefinition(Old, New->getLocation()); 4088 New->dropAttr<InternalLinkageAttr>(); 4089 } 4090 4091 // Merge the types. 4092 VarDecl *MostRecent = Old->getMostRecentDecl(); 4093 if (MostRecent != Old) { 4094 MergeVarDeclTypes(New, MostRecent, 4095 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4096 if (New->isInvalidDecl()) 4097 return; 4098 } 4099 4100 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4101 if (New->isInvalidDecl()) 4102 return; 4103 4104 diag::kind PrevDiag; 4105 SourceLocation OldLocation; 4106 std::tie(PrevDiag, OldLocation) = 4107 getNoteDiagForInvalidRedeclaration(Old, New); 4108 4109 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4110 if (New->getStorageClass() == SC_Static && 4111 !New->isStaticDataMember() && 4112 Old->hasExternalFormalLinkage()) { 4113 if (getLangOpts().MicrosoftExt) { 4114 Diag(New->getLocation(), diag::ext_static_non_static) 4115 << New->getDeclName(); 4116 Diag(OldLocation, PrevDiag); 4117 } else { 4118 Diag(New->getLocation(), diag::err_static_non_static) 4119 << New->getDeclName(); 4120 Diag(OldLocation, PrevDiag); 4121 return New->setInvalidDecl(); 4122 } 4123 } 4124 // C99 6.2.2p4: 4125 // For an identifier declared with the storage-class specifier 4126 // extern in a scope in which a prior declaration of that 4127 // identifier is visible,23) if the prior declaration specifies 4128 // internal or external linkage, the linkage of the identifier at 4129 // the later declaration is the same as the linkage specified at 4130 // the prior declaration. If no prior declaration is visible, or 4131 // if the prior declaration specifies no linkage, then the 4132 // identifier has external linkage. 4133 if (New->hasExternalStorage() && Old->hasLinkage()) 4134 /* Okay */; 4135 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4136 !New->isStaticDataMember() && 4137 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4138 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4139 Diag(OldLocation, PrevDiag); 4140 return New->setInvalidDecl(); 4141 } 4142 4143 // Check if extern is followed by non-extern and vice-versa. 4144 if (New->hasExternalStorage() && 4145 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4146 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4147 Diag(OldLocation, PrevDiag); 4148 return New->setInvalidDecl(); 4149 } 4150 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4151 !New->hasExternalStorage()) { 4152 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4153 Diag(OldLocation, PrevDiag); 4154 return New->setInvalidDecl(); 4155 } 4156 4157 if (CheckRedeclarationModuleOwnership(New, Old)) 4158 return; 4159 4160 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4161 4162 // FIXME: The test for external storage here seems wrong? We still 4163 // need to check for mismatches. 4164 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4165 // Don't complain about out-of-line definitions of static members. 4166 !(Old->getLexicalDeclContext()->isRecord() && 4167 !New->getLexicalDeclContext()->isRecord())) { 4168 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4169 Diag(OldLocation, PrevDiag); 4170 return New->setInvalidDecl(); 4171 } 4172 4173 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4174 if (VarDecl *Def = Old->getDefinition()) { 4175 // C++1z [dcl.fcn.spec]p4: 4176 // If the definition of a variable appears in a translation unit before 4177 // its first declaration as inline, the program is ill-formed. 4178 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4179 Diag(Def->getLocation(), diag::note_previous_definition); 4180 } 4181 } 4182 4183 // If this redeclaration makes the variable inline, we may need to add it to 4184 // UndefinedButUsed. 4185 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4186 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4187 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4188 SourceLocation())); 4189 4190 if (New->getTLSKind() != Old->getTLSKind()) { 4191 if (!Old->getTLSKind()) { 4192 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4193 Diag(OldLocation, PrevDiag); 4194 } else if (!New->getTLSKind()) { 4195 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4196 Diag(OldLocation, PrevDiag); 4197 } else { 4198 // Do not allow redeclaration to change the variable between requiring 4199 // static and dynamic initialization. 4200 // FIXME: GCC allows this, but uses the TLS keyword on the first 4201 // declaration to determine the kind. Do we need to be compatible here? 4202 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4203 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4204 Diag(OldLocation, PrevDiag); 4205 } 4206 } 4207 4208 // C++ doesn't have tentative definitions, so go right ahead and check here. 4209 if (getLangOpts().CPlusPlus && 4210 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4211 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4212 Old->getCanonicalDecl()->isConstexpr()) { 4213 // This definition won't be a definition any more once it's been merged. 4214 Diag(New->getLocation(), 4215 diag::warn_deprecated_redundant_constexpr_static_def); 4216 } else if (VarDecl *Def = Old->getDefinition()) { 4217 if (checkVarDeclRedefinition(Def, New)) 4218 return; 4219 } 4220 } 4221 4222 if (haveIncompatibleLanguageLinkages(Old, New)) { 4223 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4224 Diag(OldLocation, PrevDiag); 4225 New->setInvalidDecl(); 4226 return; 4227 } 4228 4229 // Merge "used" flag. 4230 if (Old->getMostRecentDecl()->isUsed(false)) 4231 New->setIsUsed(); 4232 4233 // Keep a chain of previous declarations. 4234 New->setPreviousDecl(Old); 4235 if (NewTemplate) 4236 NewTemplate->setPreviousDecl(OldTemplate); 4237 adjustDeclContextForDeclaratorDecl(New, Old); 4238 4239 // Inherit access appropriately. 4240 New->setAccess(Old->getAccess()); 4241 if (NewTemplate) 4242 NewTemplate->setAccess(New->getAccess()); 4243 4244 if (Old->isInline()) 4245 New->setImplicitlyInline(); 4246 } 4247 4248 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4249 SourceManager &SrcMgr = getSourceManager(); 4250 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4251 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4252 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4253 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4254 auto &HSI = PP.getHeaderSearchInfo(); 4255 StringRef HdrFilename = 4256 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4257 4258 auto noteFromModuleOrInclude = [&](Module *Mod, 4259 SourceLocation IncLoc) -> bool { 4260 // Redefinition errors with modules are common with non modular mapped 4261 // headers, example: a non-modular header H in module A that also gets 4262 // included directly in a TU. Pointing twice to the same header/definition 4263 // is confusing, try to get better diagnostics when modules is on. 4264 if (IncLoc.isValid()) { 4265 if (Mod) { 4266 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4267 << HdrFilename.str() << Mod->getFullModuleName(); 4268 if (!Mod->DefinitionLoc.isInvalid()) 4269 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4270 << Mod->getFullModuleName(); 4271 } else { 4272 Diag(IncLoc, diag::note_redefinition_include_same_file) 4273 << HdrFilename.str(); 4274 } 4275 return true; 4276 } 4277 4278 return false; 4279 }; 4280 4281 // Is it the same file and same offset? Provide more information on why 4282 // this leads to a redefinition error. 4283 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4284 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4285 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4286 bool EmittedDiag = 4287 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4288 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4289 4290 // If the header has no guards, emit a note suggesting one. 4291 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4292 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4293 4294 if (EmittedDiag) 4295 return; 4296 } 4297 4298 // Redefinition coming from different files or couldn't do better above. 4299 if (Old->getLocation().isValid()) 4300 Diag(Old->getLocation(), diag::note_previous_definition); 4301 } 4302 4303 /// We've just determined that \p Old and \p New both appear to be definitions 4304 /// of the same variable. Either diagnose or fix the problem. 4305 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4306 if (!hasVisibleDefinition(Old) && 4307 (New->getFormalLinkage() == InternalLinkage || 4308 New->isInline() || 4309 New->getDescribedVarTemplate() || 4310 New->getNumTemplateParameterLists() || 4311 New->getDeclContext()->isDependentContext())) { 4312 // The previous definition is hidden, and multiple definitions are 4313 // permitted (in separate TUs). Demote this to a declaration. 4314 New->demoteThisDefinitionToDeclaration(); 4315 4316 // Make the canonical definition visible. 4317 if (auto *OldTD = Old->getDescribedVarTemplate()) 4318 makeMergedDefinitionVisible(OldTD); 4319 makeMergedDefinitionVisible(Old); 4320 return false; 4321 } else { 4322 Diag(New->getLocation(), diag::err_redefinition) << New; 4323 notePreviousDefinition(Old, New->getLocation()); 4324 New->setInvalidDecl(); 4325 return true; 4326 } 4327 } 4328 4329 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4330 /// no declarator (e.g. "struct foo;") is parsed. 4331 Decl * 4332 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4333 RecordDecl *&AnonRecord) { 4334 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4335 AnonRecord); 4336 } 4337 4338 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4339 // disambiguate entities defined in different scopes. 4340 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4341 // compatibility. 4342 // We will pick our mangling number depending on which version of MSVC is being 4343 // targeted. 4344 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4345 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4346 ? S->getMSCurManglingNumber() 4347 : S->getMSLastManglingNumber(); 4348 } 4349 4350 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4351 if (!Context.getLangOpts().CPlusPlus) 4352 return; 4353 4354 if (isa<CXXRecordDecl>(Tag->getParent())) { 4355 // If this tag is the direct child of a class, number it if 4356 // it is anonymous. 4357 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4358 return; 4359 MangleNumberingContext &MCtx = 4360 Context.getManglingNumberContext(Tag->getParent()); 4361 Context.setManglingNumber( 4362 Tag, MCtx.getManglingNumber( 4363 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4364 return; 4365 } 4366 4367 // If this tag isn't a direct child of a class, number it if it is local. 4368 MangleNumberingContext *MCtx; 4369 Decl *ManglingContextDecl; 4370 std::tie(MCtx, ManglingContextDecl) = 4371 getCurrentMangleNumberContext(Tag->getDeclContext()); 4372 if (MCtx) { 4373 Context.setManglingNumber( 4374 Tag, MCtx->getManglingNumber( 4375 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4376 } 4377 } 4378 4379 namespace { 4380 struct NonCLikeKind { 4381 enum { 4382 None, 4383 BaseClass, 4384 DefaultMemberInit, 4385 Lambda, 4386 Friend, 4387 OtherMember, 4388 Invalid, 4389 } Kind = None; 4390 SourceRange Range; 4391 4392 explicit operator bool() { return Kind != None; } 4393 }; 4394 } 4395 4396 /// Determine whether a class is C-like, according to the rules of C++ 4397 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4398 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4399 if (RD->isInvalidDecl()) 4400 return {NonCLikeKind::Invalid, {}}; 4401 4402 // C++ [dcl.typedef]p9: [P1766R1] 4403 // An unnamed class with a typedef name for linkage purposes shall not 4404 // 4405 // -- have any base classes 4406 if (RD->getNumBases()) 4407 return {NonCLikeKind::BaseClass, 4408 SourceRange(RD->bases_begin()->getBeginLoc(), 4409 RD->bases_end()[-1].getEndLoc())}; 4410 bool Invalid = false; 4411 for (Decl *D : RD->decls()) { 4412 // Don't complain about things we already diagnosed. 4413 if (D->isInvalidDecl()) { 4414 Invalid = true; 4415 continue; 4416 } 4417 4418 // -- have any [...] default member initializers 4419 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4420 if (FD->hasInClassInitializer()) { 4421 auto *Init = FD->getInClassInitializer(); 4422 return {NonCLikeKind::DefaultMemberInit, 4423 Init ? Init->getSourceRange() : D->getSourceRange()}; 4424 } 4425 continue; 4426 } 4427 4428 // FIXME: We don't allow friend declarations. This violates the wording of 4429 // P1766, but not the intent. 4430 if (isa<FriendDecl>(D)) 4431 return {NonCLikeKind::Friend, D->getSourceRange()}; 4432 4433 // -- declare any members other than non-static data members, member 4434 // enumerations, or member classes, 4435 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4436 isa<EnumDecl>(D)) 4437 continue; 4438 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4439 if (!MemberRD) { 4440 if (D->isImplicit()) 4441 continue; 4442 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4443 } 4444 4445 // -- contain a lambda-expression, 4446 if (MemberRD->isLambda()) 4447 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4448 4449 // and all member classes shall also satisfy these requirements 4450 // (recursively). 4451 if (MemberRD->isThisDeclarationADefinition()) { 4452 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4453 return Kind; 4454 } 4455 } 4456 4457 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4458 } 4459 4460 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4461 TypedefNameDecl *NewTD) { 4462 if (TagFromDeclSpec->isInvalidDecl()) 4463 return; 4464 4465 // Do nothing if the tag already has a name for linkage purposes. 4466 if (TagFromDeclSpec->hasNameForLinkage()) 4467 return; 4468 4469 // A well-formed anonymous tag must always be a TUK_Definition. 4470 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4471 4472 // The type must match the tag exactly; no qualifiers allowed. 4473 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4474 Context.getTagDeclType(TagFromDeclSpec))) { 4475 if (getLangOpts().CPlusPlus) 4476 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4477 return; 4478 } 4479 4480 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4481 // An unnamed class with a typedef name for linkage purposes shall [be 4482 // C-like]. 4483 // 4484 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4485 // shouldn't happen, but there are constructs that the language rule doesn't 4486 // disallow for which we can't reasonably avoid computing linkage early. 4487 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4488 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4489 : NonCLikeKind(); 4490 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4491 if (NonCLike || ChangesLinkage) { 4492 if (NonCLike.Kind == NonCLikeKind::Invalid) 4493 return; 4494 4495 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4496 if (ChangesLinkage) { 4497 // If the linkage changes, we can't accept this as an extension. 4498 if (NonCLike.Kind == NonCLikeKind::None) 4499 DiagID = diag::err_typedef_changes_linkage; 4500 else 4501 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4502 } 4503 4504 SourceLocation FixitLoc = 4505 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4506 llvm::SmallString<40> TextToInsert; 4507 TextToInsert += ' '; 4508 TextToInsert += NewTD->getIdentifier()->getName(); 4509 4510 Diag(FixitLoc, DiagID) 4511 << isa<TypeAliasDecl>(NewTD) 4512 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4513 if (NonCLike.Kind != NonCLikeKind::None) { 4514 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4515 << NonCLike.Kind - 1 << NonCLike.Range; 4516 } 4517 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4518 << NewTD << isa<TypeAliasDecl>(NewTD); 4519 4520 if (ChangesLinkage) 4521 return; 4522 } 4523 4524 // Otherwise, set this as the anon-decl typedef for the tag. 4525 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4526 } 4527 4528 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4529 switch (T) { 4530 case DeclSpec::TST_class: 4531 return 0; 4532 case DeclSpec::TST_struct: 4533 return 1; 4534 case DeclSpec::TST_interface: 4535 return 2; 4536 case DeclSpec::TST_union: 4537 return 3; 4538 case DeclSpec::TST_enum: 4539 return 4; 4540 default: 4541 llvm_unreachable("unexpected type specifier"); 4542 } 4543 } 4544 4545 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4546 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4547 /// parameters to cope with template friend declarations. 4548 Decl * 4549 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4550 MultiTemplateParamsArg TemplateParams, 4551 bool IsExplicitInstantiation, 4552 RecordDecl *&AnonRecord) { 4553 Decl *TagD = nullptr; 4554 TagDecl *Tag = nullptr; 4555 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4556 DS.getTypeSpecType() == DeclSpec::TST_struct || 4557 DS.getTypeSpecType() == DeclSpec::TST_interface || 4558 DS.getTypeSpecType() == DeclSpec::TST_union || 4559 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4560 TagD = DS.getRepAsDecl(); 4561 4562 if (!TagD) // We probably had an error 4563 return nullptr; 4564 4565 // Note that the above type specs guarantee that the 4566 // type rep is a Decl, whereas in many of the others 4567 // it's a Type. 4568 if (isa<TagDecl>(TagD)) 4569 Tag = cast<TagDecl>(TagD); 4570 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4571 Tag = CTD->getTemplatedDecl(); 4572 } 4573 4574 if (Tag) { 4575 handleTagNumbering(Tag, S); 4576 Tag->setFreeStanding(); 4577 if (Tag->isInvalidDecl()) 4578 return Tag; 4579 } 4580 4581 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4582 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4583 // or incomplete types shall not be restrict-qualified." 4584 if (TypeQuals & DeclSpec::TQ_restrict) 4585 Diag(DS.getRestrictSpecLoc(), 4586 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4587 << DS.getSourceRange(); 4588 } 4589 4590 if (DS.isInlineSpecified()) 4591 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4592 << getLangOpts().CPlusPlus17; 4593 4594 if (DS.hasConstexprSpecifier()) { 4595 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4596 // and definitions of functions and variables. 4597 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4598 // the declaration of a function or function template 4599 if (Tag) 4600 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4601 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4602 << DS.getConstexprSpecifier(); 4603 else 4604 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4605 << DS.getConstexprSpecifier(); 4606 // Don't emit warnings after this error. 4607 return TagD; 4608 } 4609 4610 DiagnoseFunctionSpecifiers(DS); 4611 4612 if (DS.isFriendSpecified()) { 4613 // If we're dealing with a decl but not a TagDecl, assume that 4614 // whatever routines created it handled the friendship aspect. 4615 if (TagD && !Tag) 4616 return nullptr; 4617 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4618 } 4619 4620 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4621 bool IsExplicitSpecialization = 4622 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4623 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4624 !IsExplicitInstantiation && !IsExplicitSpecialization && 4625 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4626 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4627 // nested-name-specifier unless it is an explicit instantiation 4628 // or an explicit specialization. 4629 // 4630 // FIXME: We allow class template partial specializations here too, per the 4631 // obvious intent of DR1819. 4632 // 4633 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4634 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4635 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4636 return nullptr; 4637 } 4638 4639 // Track whether this decl-specifier declares anything. 4640 bool DeclaresAnything = true; 4641 4642 // Handle anonymous struct definitions. 4643 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4644 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4645 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4646 if (getLangOpts().CPlusPlus || 4647 Record->getDeclContext()->isRecord()) { 4648 // If CurContext is a DeclContext that can contain statements, 4649 // RecursiveASTVisitor won't visit the decls that 4650 // BuildAnonymousStructOrUnion() will put into CurContext. 4651 // Also store them here so that they can be part of the 4652 // DeclStmt that gets created in this case. 4653 // FIXME: Also return the IndirectFieldDecls created by 4654 // BuildAnonymousStructOr union, for the same reason? 4655 if (CurContext->isFunctionOrMethod()) 4656 AnonRecord = Record; 4657 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4658 Context.getPrintingPolicy()); 4659 } 4660 4661 DeclaresAnything = false; 4662 } 4663 } 4664 4665 // C11 6.7.2.1p2: 4666 // A struct-declaration that does not declare an anonymous structure or 4667 // anonymous union shall contain a struct-declarator-list. 4668 // 4669 // This rule also existed in C89 and C99; the grammar for struct-declaration 4670 // did not permit a struct-declaration without a struct-declarator-list. 4671 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4672 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4673 // Check for Microsoft C extension: anonymous struct/union member. 4674 // Handle 2 kinds of anonymous struct/union: 4675 // struct STRUCT; 4676 // union UNION; 4677 // and 4678 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4679 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4680 if ((Tag && Tag->getDeclName()) || 4681 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4682 RecordDecl *Record = nullptr; 4683 if (Tag) 4684 Record = dyn_cast<RecordDecl>(Tag); 4685 else if (const RecordType *RT = 4686 DS.getRepAsType().get()->getAsStructureType()) 4687 Record = RT->getDecl(); 4688 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4689 Record = UT->getDecl(); 4690 4691 if (Record && getLangOpts().MicrosoftExt) { 4692 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4693 << Record->isUnion() << DS.getSourceRange(); 4694 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4695 } 4696 4697 DeclaresAnything = false; 4698 } 4699 } 4700 4701 // Skip all the checks below if we have a type error. 4702 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4703 (TagD && TagD->isInvalidDecl())) 4704 return TagD; 4705 4706 if (getLangOpts().CPlusPlus && 4707 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4708 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4709 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4710 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4711 DeclaresAnything = false; 4712 4713 if (!DS.isMissingDeclaratorOk()) { 4714 // Customize diagnostic for a typedef missing a name. 4715 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4716 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4717 << DS.getSourceRange(); 4718 else 4719 DeclaresAnything = false; 4720 } 4721 4722 if (DS.isModulePrivateSpecified() && 4723 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4724 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4725 << Tag->getTagKind() 4726 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4727 4728 ActOnDocumentableDecl(TagD); 4729 4730 // C 6.7/2: 4731 // A declaration [...] shall declare at least a declarator [...], a tag, 4732 // or the members of an enumeration. 4733 // C++ [dcl.dcl]p3: 4734 // [If there are no declarators], and except for the declaration of an 4735 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4736 // names into the program, or shall redeclare a name introduced by a 4737 // previous declaration. 4738 if (!DeclaresAnything) { 4739 // In C, we allow this as a (popular) extension / bug. Don't bother 4740 // producing further diagnostics for redundant qualifiers after this. 4741 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4742 ? diag::err_no_declarators 4743 : diag::ext_no_declarators) 4744 << DS.getSourceRange(); 4745 return TagD; 4746 } 4747 4748 // C++ [dcl.stc]p1: 4749 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4750 // init-declarator-list of the declaration shall not be empty. 4751 // C++ [dcl.fct.spec]p1: 4752 // If a cv-qualifier appears in a decl-specifier-seq, the 4753 // init-declarator-list of the declaration shall not be empty. 4754 // 4755 // Spurious qualifiers here appear to be valid in C. 4756 unsigned DiagID = diag::warn_standalone_specifier; 4757 if (getLangOpts().CPlusPlus) 4758 DiagID = diag::ext_standalone_specifier; 4759 4760 // Note that a linkage-specification sets a storage class, but 4761 // 'extern "C" struct foo;' is actually valid and not theoretically 4762 // useless. 4763 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4764 if (SCS == DeclSpec::SCS_mutable) 4765 // Since mutable is not a viable storage class specifier in C, there is 4766 // no reason to treat it as an extension. Instead, diagnose as an error. 4767 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4768 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4769 Diag(DS.getStorageClassSpecLoc(), DiagID) 4770 << DeclSpec::getSpecifierName(SCS); 4771 } 4772 4773 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4774 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4775 << DeclSpec::getSpecifierName(TSCS); 4776 if (DS.getTypeQualifiers()) { 4777 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4778 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4779 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4780 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4781 // Restrict is covered above. 4782 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4783 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4784 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4785 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4786 } 4787 4788 // Warn about ignored type attributes, for example: 4789 // __attribute__((aligned)) struct A; 4790 // Attributes should be placed after tag to apply to type declaration. 4791 if (!DS.getAttributes().empty()) { 4792 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4793 if (TypeSpecType == DeclSpec::TST_class || 4794 TypeSpecType == DeclSpec::TST_struct || 4795 TypeSpecType == DeclSpec::TST_interface || 4796 TypeSpecType == DeclSpec::TST_union || 4797 TypeSpecType == DeclSpec::TST_enum) { 4798 for (const ParsedAttr &AL : DS.getAttributes()) 4799 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4800 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4801 } 4802 } 4803 4804 return TagD; 4805 } 4806 4807 /// We are trying to inject an anonymous member into the given scope; 4808 /// check if there's an existing declaration that can't be overloaded. 4809 /// 4810 /// \return true if this is a forbidden redeclaration 4811 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4812 Scope *S, 4813 DeclContext *Owner, 4814 DeclarationName Name, 4815 SourceLocation NameLoc, 4816 bool IsUnion) { 4817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4818 Sema::ForVisibleRedeclaration); 4819 if (!SemaRef.LookupName(R, S)) return false; 4820 4821 // Pick a representative declaration. 4822 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4823 assert(PrevDecl && "Expected a non-null Decl"); 4824 4825 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4826 return false; 4827 4828 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4829 << IsUnion << Name; 4830 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4831 4832 return true; 4833 } 4834 4835 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4836 /// anonymous struct or union AnonRecord into the owning context Owner 4837 /// and scope S. This routine will be invoked just after we realize 4838 /// that an unnamed union or struct is actually an anonymous union or 4839 /// struct, e.g., 4840 /// 4841 /// @code 4842 /// union { 4843 /// int i; 4844 /// float f; 4845 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4846 /// // f into the surrounding scope.x 4847 /// @endcode 4848 /// 4849 /// This routine is recursive, injecting the names of nested anonymous 4850 /// structs/unions into the owning context and scope as well. 4851 static bool 4852 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4853 RecordDecl *AnonRecord, AccessSpecifier AS, 4854 SmallVectorImpl<NamedDecl *> &Chaining) { 4855 bool Invalid = false; 4856 4857 // Look every FieldDecl and IndirectFieldDecl with a name. 4858 for (auto *D : AnonRecord->decls()) { 4859 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4860 cast<NamedDecl>(D)->getDeclName()) { 4861 ValueDecl *VD = cast<ValueDecl>(D); 4862 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4863 VD->getLocation(), 4864 AnonRecord->isUnion())) { 4865 // C++ [class.union]p2: 4866 // The names of the members of an anonymous union shall be 4867 // distinct from the names of any other entity in the 4868 // scope in which the anonymous union is declared. 4869 Invalid = true; 4870 } else { 4871 // C++ [class.union]p2: 4872 // For the purpose of name lookup, after the anonymous union 4873 // definition, the members of the anonymous union are 4874 // considered to have been defined in the scope in which the 4875 // anonymous union is declared. 4876 unsigned OldChainingSize = Chaining.size(); 4877 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4878 Chaining.append(IF->chain_begin(), IF->chain_end()); 4879 else 4880 Chaining.push_back(VD); 4881 4882 assert(Chaining.size() >= 2); 4883 NamedDecl **NamedChain = 4884 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4885 for (unsigned i = 0; i < Chaining.size(); i++) 4886 NamedChain[i] = Chaining[i]; 4887 4888 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4889 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4890 VD->getType(), {NamedChain, Chaining.size()}); 4891 4892 for (const auto *Attr : VD->attrs()) 4893 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4894 4895 IndirectField->setAccess(AS); 4896 IndirectField->setImplicit(); 4897 SemaRef.PushOnScopeChains(IndirectField, S); 4898 4899 // That includes picking up the appropriate access specifier. 4900 if (AS != AS_none) IndirectField->setAccess(AS); 4901 4902 Chaining.resize(OldChainingSize); 4903 } 4904 } 4905 } 4906 4907 return Invalid; 4908 } 4909 4910 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4911 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4912 /// illegal input values are mapped to SC_None. 4913 static StorageClass 4914 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4915 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4916 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4917 "Parser allowed 'typedef' as storage class VarDecl."); 4918 switch (StorageClassSpec) { 4919 case DeclSpec::SCS_unspecified: return SC_None; 4920 case DeclSpec::SCS_extern: 4921 if (DS.isExternInLinkageSpec()) 4922 return SC_None; 4923 return SC_Extern; 4924 case DeclSpec::SCS_static: return SC_Static; 4925 case DeclSpec::SCS_auto: return SC_Auto; 4926 case DeclSpec::SCS_register: return SC_Register; 4927 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4928 // Illegal SCSs map to None: error reporting is up to the caller. 4929 case DeclSpec::SCS_mutable: // Fall through. 4930 case DeclSpec::SCS_typedef: return SC_None; 4931 } 4932 llvm_unreachable("unknown storage class specifier"); 4933 } 4934 4935 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4936 assert(Record->hasInClassInitializer()); 4937 4938 for (const auto *I : Record->decls()) { 4939 const auto *FD = dyn_cast<FieldDecl>(I); 4940 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4941 FD = IFD->getAnonField(); 4942 if (FD && FD->hasInClassInitializer()) 4943 return FD->getLocation(); 4944 } 4945 4946 llvm_unreachable("couldn't find in-class initializer"); 4947 } 4948 4949 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4950 SourceLocation DefaultInitLoc) { 4951 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4952 return; 4953 4954 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4955 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4956 } 4957 4958 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4959 CXXRecordDecl *AnonUnion) { 4960 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4961 return; 4962 4963 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4964 } 4965 4966 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4967 /// anonymous structure or union. Anonymous unions are a C++ feature 4968 /// (C++ [class.union]) and a C11 feature; anonymous structures 4969 /// are a C11 feature and GNU C++ extension. 4970 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4971 AccessSpecifier AS, 4972 RecordDecl *Record, 4973 const PrintingPolicy &Policy) { 4974 DeclContext *Owner = Record->getDeclContext(); 4975 4976 // Diagnose whether this anonymous struct/union is an extension. 4977 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4978 Diag(Record->getLocation(), diag::ext_anonymous_union); 4979 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4980 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4981 else if (!Record->isUnion() && !getLangOpts().C11) 4982 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4983 4984 // C and C++ require different kinds of checks for anonymous 4985 // structs/unions. 4986 bool Invalid = false; 4987 if (getLangOpts().CPlusPlus) { 4988 const char *PrevSpec = nullptr; 4989 if (Record->isUnion()) { 4990 // C++ [class.union]p6: 4991 // C++17 [class.union.anon]p2: 4992 // Anonymous unions declared in a named namespace or in the 4993 // global namespace shall be declared static. 4994 unsigned DiagID; 4995 DeclContext *OwnerScope = Owner->getRedeclContext(); 4996 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4997 (OwnerScope->isTranslationUnit() || 4998 (OwnerScope->isNamespace() && 4999 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5000 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5001 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5002 5003 // Recover by adding 'static'. 5004 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5005 PrevSpec, DiagID, Policy); 5006 } 5007 // C++ [class.union]p6: 5008 // A storage class is not allowed in a declaration of an 5009 // anonymous union in a class scope. 5010 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5011 isa<RecordDecl>(Owner)) { 5012 Diag(DS.getStorageClassSpecLoc(), 5013 diag::err_anonymous_union_with_storage_spec) 5014 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5015 5016 // Recover by removing the storage specifier. 5017 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5018 SourceLocation(), 5019 PrevSpec, DiagID, Context.getPrintingPolicy()); 5020 } 5021 } 5022 5023 // Ignore const/volatile/restrict qualifiers. 5024 if (DS.getTypeQualifiers()) { 5025 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5026 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5027 << Record->isUnion() << "const" 5028 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5029 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5030 Diag(DS.getVolatileSpecLoc(), 5031 diag::ext_anonymous_struct_union_qualified) 5032 << Record->isUnion() << "volatile" 5033 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5034 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5035 Diag(DS.getRestrictSpecLoc(), 5036 diag::ext_anonymous_struct_union_qualified) 5037 << Record->isUnion() << "restrict" 5038 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5039 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5040 Diag(DS.getAtomicSpecLoc(), 5041 diag::ext_anonymous_struct_union_qualified) 5042 << Record->isUnion() << "_Atomic" 5043 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5044 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5045 Diag(DS.getUnalignedSpecLoc(), 5046 diag::ext_anonymous_struct_union_qualified) 5047 << Record->isUnion() << "__unaligned" 5048 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5049 5050 DS.ClearTypeQualifiers(); 5051 } 5052 5053 // C++ [class.union]p2: 5054 // The member-specification of an anonymous union shall only 5055 // define non-static data members. [Note: nested types and 5056 // functions cannot be declared within an anonymous union. ] 5057 for (auto *Mem : Record->decls()) { 5058 // Ignore invalid declarations; we already diagnosed them. 5059 if (Mem->isInvalidDecl()) 5060 continue; 5061 5062 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5063 // C++ [class.union]p3: 5064 // An anonymous union shall not have private or protected 5065 // members (clause 11). 5066 assert(FD->getAccess() != AS_none); 5067 if (FD->getAccess() != AS_public) { 5068 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5069 << Record->isUnion() << (FD->getAccess() == AS_protected); 5070 Invalid = true; 5071 } 5072 5073 // C++ [class.union]p1 5074 // An object of a class with a non-trivial constructor, a non-trivial 5075 // copy constructor, a non-trivial destructor, or a non-trivial copy 5076 // assignment operator cannot be a member of a union, nor can an 5077 // array of such objects. 5078 if (CheckNontrivialField(FD)) 5079 Invalid = true; 5080 } else if (Mem->isImplicit()) { 5081 // Any implicit members are fine. 5082 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5083 // This is a type that showed up in an 5084 // elaborated-type-specifier inside the anonymous struct or 5085 // union, but which actually declares a type outside of the 5086 // anonymous struct or union. It's okay. 5087 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5088 if (!MemRecord->isAnonymousStructOrUnion() && 5089 MemRecord->getDeclName()) { 5090 // Visual C++ allows type definition in anonymous struct or union. 5091 if (getLangOpts().MicrosoftExt) 5092 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5093 << Record->isUnion(); 5094 else { 5095 // This is a nested type declaration. 5096 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5097 << Record->isUnion(); 5098 Invalid = true; 5099 } 5100 } else { 5101 // This is an anonymous type definition within another anonymous type. 5102 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5103 // not part of standard C++. 5104 Diag(MemRecord->getLocation(), 5105 diag::ext_anonymous_record_with_anonymous_type) 5106 << Record->isUnion(); 5107 } 5108 } else if (isa<AccessSpecDecl>(Mem)) { 5109 // Any access specifier is fine. 5110 } else if (isa<StaticAssertDecl>(Mem)) { 5111 // In C++1z, static_assert declarations are also fine. 5112 } else { 5113 // We have something that isn't a non-static data 5114 // member. Complain about it. 5115 unsigned DK = diag::err_anonymous_record_bad_member; 5116 if (isa<TypeDecl>(Mem)) 5117 DK = diag::err_anonymous_record_with_type; 5118 else if (isa<FunctionDecl>(Mem)) 5119 DK = diag::err_anonymous_record_with_function; 5120 else if (isa<VarDecl>(Mem)) 5121 DK = diag::err_anonymous_record_with_static; 5122 5123 // Visual C++ allows type definition in anonymous struct or union. 5124 if (getLangOpts().MicrosoftExt && 5125 DK == diag::err_anonymous_record_with_type) 5126 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5127 << Record->isUnion(); 5128 else { 5129 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5130 Invalid = true; 5131 } 5132 } 5133 } 5134 5135 // C++11 [class.union]p8 (DR1460): 5136 // At most one variant member of a union may have a 5137 // brace-or-equal-initializer. 5138 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5139 Owner->isRecord()) 5140 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5141 cast<CXXRecordDecl>(Record)); 5142 } 5143 5144 if (!Record->isUnion() && !Owner->isRecord()) { 5145 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5146 << getLangOpts().CPlusPlus; 5147 Invalid = true; 5148 } 5149 5150 // C++ [dcl.dcl]p3: 5151 // [If there are no declarators], and except for the declaration of an 5152 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5153 // names into the program 5154 // C++ [class.mem]p2: 5155 // each such member-declaration shall either declare at least one member 5156 // name of the class or declare at least one unnamed bit-field 5157 // 5158 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5159 if (getLangOpts().CPlusPlus && Record->field_empty()) 5160 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5161 5162 // Mock up a declarator. 5163 Declarator Dc(DS, DeclaratorContext::MemberContext); 5164 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5165 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5166 5167 // Create a declaration for this anonymous struct/union. 5168 NamedDecl *Anon = nullptr; 5169 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5170 Anon = FieldDecl::Create( 5171 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5172 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5173 /*BitWidth=*/nullptr, /*Mutable=*/false, 5174 /*InitStyle=*/ICIS_NoInit); 5175 Anon->setAccess(AS); 5176 ProcessDeclAttributes(S, Anon, Dc); 5177 5178 if (getLangOpts().CPlusPlus) 5179 FieldCollector->Add(cast<FieldDecl>(Anon)); 5180 } else { 5181 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5182 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5183 if (SCSpec == DeclSpec::SCS_mutable) { 5184 // mutable can only appear on non-static class members, so it's always 5185 // an error here 5186 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5187 Invalid = true; 5188 SC = SC_None; 5189 } 5190 5191 assert(DS.getAttributes().empty() && "No attribute expected"); 5192 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5193 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5194 Context.getTypeDeclType(Record), TInfo, SC); 5195 5196 // Default-initialize the implicit variable. This initialization will be 5197 // trivial in almost all cases, except if a union member has an in-class 5198 // initializer: 5199 // union { int n = 0; }; 5200 ActOnUninitializedDecl(Anon); 5201 } 5202 Anon->setImplicit(); 5203 5204 // Mark this as an anonymous struct/union type. 5205 Record->setAnonymousStructOrUnion(true); 5206 5207 // Add the anonymous struct/union object to the current 5208 // context. We'll be referencing this object when we refer to one of 5209 // its members. 5210 Owner->addDecl(Anon); 5211 5212 // Inject the members of the anonymous struct/union into the owning 5213 // context and into the identifier resolver chain for name lookup 5214 // purposes. 5215 SmallVector<NamedDecl*, 2> Chain; 5216 Chain.push_back(Anon); 5217 5218 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5219 Invalid = true; 5220 5221 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5222 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5223 MangleNumberingContext *MCtx; 5224 Decl *ManglingContextDecl; 5225 std::tie(MCtx, ManglingContextDecl) = 5226 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5227 if (MCtx) { 5228 Context.setManglingNumber( 5229 NewVD, MCtx->getManglingNumber( 5230 NewVD, getMSManglingNumber(getLangOpts(), S))); 5231 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5232 } 5233 } 5234 } 5235 5236 if (Invalid) 5237 Anon->setInvalidDecl(); 5238 5239 return Anon; 5240 } 5241 5242 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5243 /// Microsoft C anonymous structure. 5244 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5245 /// Example: 5246 /// 5247 /// struct A { int a; }; 5248 /// struct B { struct A; int b; }; 5249 /// 5250 /// void foo() { 5251 /// B var; 5252 /// var.a = 3; 5253 /// } 5254 /// 5255 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5256 RecordDecl *Record) { 5257 assert(Record && "expected a record!"); 5258 5259 // Mock up a declarator. 5260 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5261 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5262 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5263 5264 auto *ParentDecl = cast<RecordDecl>(CurContext); 5265 QualType RecTy = Context.getTypeDeclType(Record); 5266 5267 // Create a declaration for this anonymous struct. 5268 NamedDecl *Anon = 5269 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5270 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5271 /*BitWidth=*/nullptr, /*Mutable=*/false, 5272 /*InitStyle=*/ICIS_NoInit); 5273 Anon->setImplicit(); 5274 5275 // Add the anonymous struct object to the current context. 5276 CurContext->addDecl(Anon); 5277 5278 // Inject the members of the anonymous struct into the current 5279 // context and into the identifier resolver chain for name lookup 5280 // purposes. 5281 SmallVector<NamedDecl*, 2> Chain; 5282 Chain.push_back(Anon); 5283 5284 RecordDecl *RecordDef = Record->getDefinition(); 5285 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5286 diag::err_field_incomplete_or_sizeless) || 5287 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5288 AS_none, Chain)) { 5289 Anon->setInvalidDecl(); 5290 ParentDecl->setInvalidDecl(); 5291 } 5292 5293 return Anon; 5294 } 5295 5296 /// GetNameForDeclarator - Determine the full declaration name for the 5297 /// given Declarator. 5298 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5299 return GetNameFromUnqualifiedId(D.getName()); 5300 } 5301 5302 /// Retrieves the declaration name from a parsed unqualified-id. 5303 DeclarationNameInfo 5304 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5305 DeclarationNameInfo NameInfo; 5306 NameInfo.setLoc(Name.StartLocation); 5307 5308 switch (Name.getKind()) { 5309 5310 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5311 case UnqualifiedIdKind::IK_Identifier: 5312 NameInfo.setName(Name.Identifier); 5313 return NameInfo; 5314 5315 case UnqualifiedIdKind::IK_DeductionGuideName: { 5316 // C++ [temp.deduct.guide]p3: 5317 // The simple-template-id shall name a class template specialization. 5318 // The template-name shall be the same identifier as the template-name 5319 // of the simple-template-id. 5320 // These together intend to imply that the template-name shall name a 5321 // class template. 5322 // FIXME: template<typename T> struct X {}; 5323 // template<typename T> using Y = X<T>; 5324 // Y(int) -> Y<int>; 5325 // satisfies these rules but does not name a class template. 5326 TemplateName TN = Name.TemplateName.get().get(); 5327 auto *Template = TN.getAsTemplateDecl(); 5328 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5329 Diag(Name.StartLocation, 5330 diag::err_deduction_guide_name_not_class_template) 5331 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5332 if (Template) 5333 Diag(Template->getLocation(), diag::note_template_decl_here); 5334 return DeclarationNameInfo(); 5335 } 5336 5337 NameInfo.setName( 5338 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5339 return NameInfo; 5340 } 5341 5342 case UnqualifiedIdKind::IK_OperatorFunctionId: 5343 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5344 Name.OperatorFunctionId.Operator)); 5345 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5346 = Name.OperatorFunctionId.SymbolLocations[0]; 5347 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5348 = Name.EndLocation.getRawEncoding(); 5349 return NameInfo; 5350 5351 case UnqualifiedIdKind::IK_LiteralOperatorId: 5352 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5353 Name.Identifier)); 5354 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5355 return NameInfo; 5356 5357 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5358 TypeSourceInfo *TInfo; 5359 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5360 if (Ty.isNull()) 5361 return DeclarationNameInfo(); 5362 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5363 Context.getCanonicalType(Ty))); 5364 NameInfo.setNamedTypeInfo(TInfo); 5365 return NameInfo; 5366 } 5367 5368 case UnqualifiedIdKind::IK_ConstructorName: { 5369 TypeSourceInfo *TInfo; 5370 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5371 if (Ty.isNull()) 5372 return DeclarationNameInfo(); 5373 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5374 Context.getCanonicalType(Ty))); 5375 NameInfo.setNamedTypeInfo(TInfo); 5376 return NameInfo; 5377 } 5378 5379 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5380 // In well-formed code, we can only have a constructor 5381 // template-id that refers to the current context, so go there 5382 // to find the actual type being constructed. 5383 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5384 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5385 return DeclarationNameInfo(); 5386 5387 // Determine the type of the class being constructed. 5388 QualType CurClassType = Context.getTypeDeclType(CurClass); 5389 5390 // FIXME: Check two things: that the template-id names the same type as 5391 // CurClassType, and that the template-id does not occur when the name 5392 // was qualified. 5393 5394 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5395 Context.getCanonicalType(CurClassType))); 5396 // FIXME: should we retrieve TypeSourceInfo? 5397 NameInfo.setNamedTypeInfo(nullptr); 5398 return NameInfo; 5399 } 5400 5401 case UnqualifiedIdKind::IK_DestructorName: { 5402 TypeSourceInfo *TInfo; 5403 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5404 if (Ty.isNull()) 5405 return DeclarationNameInfo(); 5406 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5407 Context.getCanonicalType(Ty))); 5408 NameInfo.setNamedTypeInfo(TInfo); 5409 return NameInfo; 5410 } 5411 5412 case UnqualifiedIdKind::IK_TemplateId: { 5413 TemplateName TName = Name.TemplateId->Template.get(); 5414 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5415 return Context.getNameForTemplate(TName, TNameLoc); 5416 } 5417 5418 } // switch (Name.getKind()) 5419 5420 llvm_unreachable("Unknown name kind"); 5421 } 5422 5423 static QualType getCoreType(QualType Ty) { 5424 do { 5425 if (Ty->isPointerType() || Ty->isReferenceType()) 5426 Ty = Ty->getPointeeType(); 5427 else if (Ty->isArrayType()) 5428 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5429 else 5430 return Ty.withoutLocalFastQualifiers(); 5431 } while (true); 5432 } 5433 5434 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5435 /// and Definition have "nearly" matching parameters. This heuristic is 5436 /// used to improve diagnostics in the case where an out-of-line function 5437 /// definition doesn't match any declaration within the class or namespace. 5438 /// Also sets Params to the list of indices to the parameters that differ 5439 /// between the declaration and the definition. If hasSimilarParameters 5440 /// returns true and Params is empty, then all of the parameters match. 5441 static bool hasSimilarParameters(ASTContext &Context, 5442 FunctionDecl *Declaration, 5443 FunctionDecl *Definition, 5444 SmallVectorImpl<unsigned> &Params) { 5445 Params.clear(); 5446 if (Declaration->param_size() != Definition->param_size()) 5447 return false; 5448 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5449 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5450 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5451 5452 // The parameter types are identical 5453 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5454 continue; 5455 5456 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5457 QualType DefParamBaseTy = getCoreType(DefParamTy); 5458 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5459 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5460 5461 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5462 (DeclTyName && DeclTyName == DefTyName)) 5463 Params.push_back(Idx); 5464 else // The two parameters aren't even close 5465 return false; 5466 } 5467 5468 return true; 5469 } 5470 5471 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5472 /// declarator needs to be rebuilt in the current instantiation. 5473 /// Any bits of declarator which appear before the name are valid for 5474 /// consideration here. That's specifically the type in the decl spec 5475 /// and the base type in any member-pointer chunks. 5476 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5477 DeclarationName Name) { 5478 // The types we specifically need to rebuild are: 5479 // - typenames, typeofs, and decltypes 5480 // - types which will become injected class names 5481 // Of course, we also need to rebuild any type referencing such a 5482 // type. It's safest to just say "dependent", but we call out a 5483 // few cases here. 5484 5485 DeclSpec &DS = D.getMutableDeclSpec(); 5486 switch (DS.getTypeSpecType()) { 5487 case DeclSpec::TST_typename: 5488 case DeclSpec::TST_typeofType: 5489 case DeclSpec::TST_underlyingType: 5490 case DeclSpec::TST_atomic: { 5491 // Grab the type from the parser. 5492 TypeSourceInfo *TSI = nullptr; 5493 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5494 if (T.isNull() || !T->isDependentType()) break; 5495 5496 // Make sure there's a type source info. This isn't really much 5497 // of a waste; most dependent types should have type source info 5498 // attached already. 5499 if (!TSI) 5500 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5501 5502 // Rebuild the type in the current instantiation. 5503 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5504 if (!TSI) return true; 5505 5506 // Store the new type back in the decl spec. 5507 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5508 DS.UpdateTypeRep(LocType); 5509 break; 5510 } 5511 5512 case DeclSpec::TST_decltype: 5513 case DeclSpec::TST_typeofExpr: { 5514 Expr *E = DS.getRepAsExpr(); 5515 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5516 if (Result.isInvalid()) return true; 5517 DS.UpdateExprRep(Result.get()); 5518 break; 5519 } 5520 5521 default: 5522 // Nothing to do for these decl specs. 5523 break; 5524 } 5525 5526 // It doesn't matter what order we do this in. 5527 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5528 DeclaratorChunk &Chunk = D.getTypeObject(I); 5529 5530 // The only type information in the declarator which can come 5531 // before the declaration name is the base type of a member 5532 // pointer. 5533 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5534 continue; 5535 5536 // Rebuild the scope specifier in-place. 5537 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5538 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5539 return true; 5540 } 5541 5542 return false; 5543 } 5544 5545 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5546 D.setFunctionDefinitionKind(FDK_Declaration); 5547 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5548 5549 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5550 Dcl && Dcl->getDeclContext()->isFileContext()) 5551 Dcl->setTopLevelDeclInObjCContainer(); 5552 5553 if (getLangOpts().OpenCL) 5554 setCurrentOpenCLExtensionForDecl(Dcl); 5555 5556 return Dcl; 5557 } 5558 5559 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5560 /// If T is the name of a class, then each of the following shall have a 5561 /// name different from T: 5562 /// - every static data member of class T; 5563 /// - every member function of class T 5564 /// - every member of class T that is itself a type; 5565 /// \returns true if the declaration name violates these rules. 5566 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5567 DeclarationNameInfo NameInfo) { 5568 DeclarationName Name = NameInfo.getName(); 5569 5570 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5571 while (Record && Record->isAnonymousStructOrUnion()) 5572 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5573 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5574 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5575 return true; 5576 } 5577 5578 return false; 5579 } 5580 5581 /// Diagnose a declaration whose declarator-id has the given 5582 /// nested-name-specifier. 5583 /// 5584 /// \param SS The nested-name-specifier of the declarator-id. 5585 /// 5586 /// \param DC The declaration context to which the nested-name-specifier 5587 /// resolves. 5588 /// 5589 /// \param Name The name of the entity being declared. 5590 /// 5591 /// \param Loc The location of the name of the entity being declared. 5592 /// 5593 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5594 /// we're declaring an explicit / partial specialization / instantiation. 5595 /// 5596 /// \returns true if we cannot safely recover from this error, false otherwise. 5597 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5598 DeclarationName Name, 5599 SourceLocation Loc, bool IsTemplateId) { 5600 DeclContext *Cur = CurContext; 5601 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5602 Cur = Cur->getParent(); 5603 5604 // If the user provided a superfluous scope specifier that refers back to the 5605 // class in which the entity is already declared, diagnose and ignore it. 5606 // 5607 // class X { 5608 // void X::f(); 5609 // }; 5610 // 5611 // Note, it was once ill-formed to give redundant qualification in all 5612 // contexts, but that rule was removed by DR482. 5613 if (Cur->Equals(DC)) { 5614 if (Cur->isRecord()) { 5615 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5616 : diag::err_member_extra_qualification) 5617 << Name << FixItHint::CreateRemoval(SS.getRange()); 5618 SS.clear(); 5619 } else { 5620 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5621 } 5622 return false; 5623 } 5624 5625 // Check whether the qualifying scope encloses the scope of the original 5626 // declaration. For a template-id, we perform the checks in 5627 // CheckTemplateSpecializationScope. 5628 if (!Cur->Encloses(DC) && !IsTemplateId) { 5629 if (Cur->isRecord()) 5630 Diag(Loc, diag::err_member_qualification) 5631 << Name << SS.getRange(); 5632 else if (isa<TranslationUnitDecl>(DC)) 5633 Diag(Loc, diag::err_invalid_declarator_global_scope) 5634 << Name << SS.getRange(); 5635 else if (isa<FunctionDecl>(Cur)) 5636 Diag(Loc, diag::err_invalid_declarator_in_function) 5637 << Name << SS.getRange(); 5638 else if (isa<BlockDecl>(Cur)) 5639 Diag(Loc, diag::err_invalid_declarator_in_block) 5640 << Name << SS.getRange(); 5641 else 5642 Diag(Loc, diag::err_invalid_declarator_scope) 5643 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5644 5645 return true; 5646 } 5647 5648 if (Cur->isRecord()) { 5649 // Cannot qualify members within a class. 5650 Diag(Loc, diag::err_member_qualification) 5651 << Name << SS.getRange(); 5652 SS.clear(); 5653 5654 // C++ constructors and destructors with incorrect scopes can break 5655 // our AST invariants by having the wrong underlying types. If 5656 // that's the case, then drop this declaration entirely. 5657 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5658 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5659 !Context.hasSameType(Name.getCXXNameType(), 5660 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5661 return true; 5662 5663 return false; 5664 } 5665 5666 // C++11 [dcl.meaning]p1: 5667 // [...] "The nested-name-specifier of the qualified declarator-id shall 5668 // not begin with a decltype-specifer" 5669 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5670 while (SpecLoc.getPrefix()) 5671 SpecLoc = SpecLoc.getPrefix(); 5672 if (dyn_cast_or_null<DecltypeType>( 5673 SpecLoc.getNestedNameSpecifier()->getAsType())) 5674 Diag(Loc, diag::err_decltype_in_declarator) 5675 << SpecLoc.getTypeLoc().getSourceRange(); 5676 5677 return false; 5678 } 5679 5680 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5681 MultiTemplateParamsArg TemplateParamLists) { 5682 // TODO: consider using NameInfo for diagnostic. 5683 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5684 DeclarationName Name = NameInfo.getName(); 5685 5686 // All of these full declarators require an identifier. If it doesn't have 5687 // one, the ParsedFreeStandingDeclSpec action should be used. 5688 if (D.isDecompositionDeclarator()) { 5689 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5690 } else if (!Name) { 5691 if (!D.isInvalidType()) // Reject this if we think it is valid. 5692 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5693 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5694 return nullptr; 5695 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5696 return nullptr; 5697 5698 // The scope passed in may not be a decl scope. Zip up the scope tree until 5699 // we find one that is. 5700 while ((S->getFlags() & Scope::DeclScope) == 0 || 5701 (S->getFlags() & Scope::TemplateParamScope) != 0) 5702 S = S->getParent(); 5703 5704 DeclContext *DC = CurContext; 5705 if (D.getCXXScopeSpec().isInvalid()) 5706 D.setInvalidType(); 5707 else if (D.getCXXScopeSpec().isSet()) { 5708 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5709 UPPC_DeclarationQualifier)) 5710 return nullptr; 5711 5712 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5713 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5714 if (!DC || isa<EnumDecl>(DC)) { 5715 // If we could not compute the declaration context, it's because the 5716 // declaration context is dependent but does not refer to a class, 5717 // class template, or class template partial specialization. Complain 5718 // and return early, to avoid the coming semantic disaster. 5719 Diag(D.getIdentifierLoc(), 5720 diag::err_template_qualified_declarator_no_match) 5721 << D.getCXXScopeSpec().getScopeRep() 5722 << D.getCXXScopeSpec().getRange(); 5723 return nullptr; 5724 } 5725 bool IsDependentContext = DC->isDependentContext(); 5726 5727 if (!IsDependentContext && 5728 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5729 return nullptr; 5730 5731 // If a class is incomplete, do not parse entities inside it. 5732 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5733 Diag(D.getIdentifierLoc(), 5734 diag::err_member_def_undefined_record) 5735 << Name << DC << D.getCXXScopeSpec().getRange(); 5736 return nullptr; 5737 } 5738 if (!D.getDeclSpec().isFriendSpecified()) { 5739 if (diagnoseQualifiedDeclaration( 5740 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5741 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5742 if (DC->isRecord()) 5743 return nullptr; 5744 5745 D.setInvalidType(); 5746 } 5747 } 5748 5749 // Check whether we need to rebuild the type of the given 5750 // declaration in the current instantiation. 5751 if (EnteringContext && IsDependentContext && 5752 TemplateParamLists.size() != 0) { 5753 ContextRAII SavedContext(*this, DC); 5754 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5755 D.setInvalidType(); 5756 } 5757 } 5758 5759 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5760 QualType R = TInfo->getType(); 5761 5762 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5763 UPPC_DeclarationType)) 5764 D.setInvalidType(); 5765 5766 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5767 forRedeclarationInCurContext()); 5768 5769 // See if this is a redefinition of a variable in the same scope. 5770 if (!D.getCXXScopeSpec().isSet()) { 5771 bool IsLinkageLookup = false; 5772 bool CreateBuiltins = false; 5773 5774 // If the declaration we're planning to build will be a function 5775 // or object with linkage, then look for another declaration with 5776 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5777 // 5778 // If the declaration we're planning to build will be declared with 5779 // external linkage in the translation unit, create any builtin with 5780 // the same name. 5781 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5782 /* Do nothing*/; 5783 else if (CurContext->isFunctionOrMethod() && 5784 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5785 R->isFunctionType())) { 5786 IsLinkageLookup = true; 5787 CreateBuiltins = 5788 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5789 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5790 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5791 CreateBuiltins = true; 5792 5793 if (IsLinkageLookup) { 5794 Previous.clear(LookupRedeclarationWithLinkage); 5795 Previous.setRedeclarationKind(ForExternalRedeclaration); 5796 } 5797 5798 LookupName(Previous, S, CreateBuiltins); 5799 } else { // Something like "int foo::x;" 5800 LookupQualifiedName(Previous, DC); 5801 5802 // C++ [dcl.meaning]p1: 5803 // When the declarator-id is qualified, the declaration shall refer to a 5804 // previously declared member of the class or namespace to which the 5805 // qualifier refers (or, in the case of a namespace, of an element of the 5806 // inline namespace set of that namespace (7.3.1)) or to a specialization 5807 // thereof; [...] 5808 // 5809 // Note that we already checked the context above, and that we do not have 5810 // enough information to make sure that Previous contains the declaration 5811 // we want to match. For example, given: 5812 // 5813 // class X { 5814 // void f(); 5815 // void f(float); 5816 // }; 5817 // 5818 // void X::f(int) { } // ill-formed 5819 // 5820 // In this case, Previous will point to the overload set 5821 // containing the two f's declared in X, but neither of them 5822 // matches. 5823 5824 // C++ [dcl.meaning]p1: 5825 // [...] the member shall not merely have been introduced by a 5826 // using-declaration in the scope of the class or namespace nominated by 5827 // the nested-name-specifier of the declarator-id. 5828 RemoveUsingDecls(Previous); 5829 } 5830 5831 if (Previous.isSingleResult() && 5832 Previous.getFoundDecl()->isTemplateParameter()) { 5833 // Maybe we will complain about the shadowed template parameter. 5834 if (!D.isInvalidType()) 5835 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5836 Previous.getFoundDecl()); 5837 5838 // Just pretend that we didn't see the previous declaration. 5839 Previous.clear(); 5840 } 5841 5842 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5843 // Forget that the previous declaration is the injected-class-name. 5844 Previous.clear(); 5845 5846 // In C++, the previous declaration we find might be a tag type 5847 // (class or enum). In this case, the new declaration will hide the 5848 // tag type. Note that this applies to functions, function templates, and 5849 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5850 if (Previous.isSingleTagDecl() && 5851 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5852 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5853 Previous.clear(); 5854 5855 // Check that there are no default arguments other than in the parameters 5856 // of a function declaration (C++ only). 5857 if (getLangOpts().CPlusPlus) 5858 CheckExtraCXXDefaultArguments(D); 5859 5860 NamedDecl *New; 5861 5862 bool AddToScope = true; 5863 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5864 if (TemplateParamLists.size()) { 5865 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5866 return nullptr; 5867 } 5868 5869 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5870 } else if (R->isFunctionType()) { 5871 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5872 TemplateParamLists, 5873 AddToScope); 5874 } else { 5875 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5876 AddToScope); 5877 } 5878 5879 if (!New) 5880 return nullptr; 5881 5882 // If this has an identifier and is not a function template specialization, 5883 // add it to the scope stack. 5884 if (New->getDeclName() && AddToScope) 5885 PushOnScopeChains(New, S); 5886 5887 if (isInOpenMPDeclareTargetContext()) 5888 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5889 5890 return New; 5891 } 5892 5893 /// Helper method to turn variable array types into constant array 5894 /// types in certain situations which would otherwise be errors (for 5895 /// GCC compatibility). 5896 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5897 ASTContext &Context, 5898 bool &SizeIsNegative, 5899 llvm::APSInt &Oversized) { 5900 // This method tries to turn a variable array into a constant 5901 // array even when the size isn't an ICE. This is necessary 5902 // for compatibility with code that depends on gcc's buggy 5903 // constant expression folding, like struct {char x[(int)(char*)2];} 5904 SizeIsNegative = false; 5905 Oversized = 0; 5906 5907 if (T->isDependentType()) 5908 return QualType(); 5909 5910 QualifierCollector Qs; 5911 const Type *Ty = Qs.strip(T); 5912 5913 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5914 QualType Pointee = PTy->getPointeeType(); 5915 QualType FixedType = 5916 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5917 Oversized); 5918 if (FixedType.isNull()) return FixedType; 5919 FixedType = Context.getPointerType(FixedType); 5920 return Qs.apply(Context, FixedType); 5921 } 5922 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5923 QualType Inner = PTy->getInnerType(); 5924 QualType FixedType = 5925 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5926 Oversized); 5927 if (FixedType.isNull()) return FixedType; 5928 FixedType = Context.getParenType(FixedType); 5929 return Qs.apply(Context, FixedType); 5930 } 5931 5932 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5933 if (!VLATy) 5934 return QualType(); 5935 // FIXME: We should probably handle this case 5936 if (VLATy->getElementType()->isVariablyModifiedType()) 5937 return QualType(); 5938 5939 Expr::EvalResult Result; 5940 if (!VLATy->getSizeExpr() || 5941 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5942 return QualType(); 5943 5944 llvm::APSInt Res = Result.Val.getInt(); 5945 5946 // Check whether the array size is negative. 5947 if (Res.isSigned() && Res.isNegative()) { 5948 SizeIsNegative = true; 5949 return QualType(); 5950 } 5951 5952 // Check whether the array is too large to be addressed. 5953 unsigned ActiveSizeBits 5954 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5955 Res); 5956 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5957 Oversized = Res; 5958 return QualType(); 5959 } 5960 5961 return Context.getConstantArrayType( 5962 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5963 } 5964 5965 static void 5966 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5967 SrcTL = SrcTL.getUnqualifiedLoc(); 5968 DstTL = DstTL.getUnqualifiedLoc(); 5969 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5970 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5971 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5972 DstPTL.getPointeeLoc()); 5973 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5974 return; 5975 } 5976 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5977 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5978 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5979 DstPTL.getInnerLoc()); 5980 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5981 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5982 return; 5983 } 5984 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5985 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5986 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5987 TypeLoc DstElemTL = DstATL.getElementLoc(); 5988 DstElemTL.initializeFullCopy(SrcElemTL); 5989 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5990 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5991 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5992 } 5993 5994 /// Helper method to turn variable array types into constant array 5995 /// types in certain situations which would otherwise be errors (for 5996 /// GCC compatibility). 5997 static TypeSourceInfo* 5998 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5999 ASTContext &Context, 6000 bool &SizeIsNegative, 6001 llvm::APSInt &Oversized) { 6002 QualType FixedTy 6003 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6004 SizeIsNegative, Oversized); 6005 if (FixedTy.isNull()) 6006 return nullptr; 6007 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6008 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6009 FixedTInfo->getTypeLoc()); 6010 return FixedTInfo; 6011 } 6012 6013 /// Register the given locally-scoped extern "C" declaration so 6014 /// that it can be found later for redeclarations. We include any extern "C" 6015 /// declaration that is not visible in the translation unit here, not just 6016 /// function-scope declarations. 6017 void 6018 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6019 if (!getLangOpts().CPlusPlus && 6020 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6021 // Don't need to track declarations in the TU in C. 6022 return; 6023 6024 // Note that we have a locally-scoped external with this name. 6025 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6026 } 6027 6028 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6029 // FIXME: We can have multiple results via __attribute__((overloadable)). 6030 auto Result = Context.getExternCContextDecl()->lookup(Name); 6031 return Result.empty() ? nullptr : *Result.begin(); 6032 } 6033 6034 /// Diagnose function specifiers on a declaration of an identifier that 6035 /// does not identify a function. 6036 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6037 // FIXME: We should probably indicate the identifier in question to avoid 6038 // confusion for constructs like "virtual int a(), b;" 6039 if (DS.isVirtualSpecified()) 6040 Diag(DS.getVirtualSpecLoc(), 6041 diag::err_virtual_non_function); 6042 6043 if (DS.hasExplicitSpecifier()) 6044 Diag(DS.getExplicitSpecLoc(), 6045 diag::err_explicit_non_function); 6046 6047 if (DS.isNoreturnSpecified()) 6048 Diag(DS.getNoreturnSpecLoc(), 6049 diag::err_noreturn_non_function); 6050 } 6051 6052 NamedDecl* 6053 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6054 TypeSourceInfo *TInfo, LookupResult &Previous) { 6055 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6056 if (D.getCXXScopeSpec().isSet()) { 6057 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6058 << D.getCXXScopeSpec().getRange(); 6059 D.setInvalidType(); 6060 // Pretend we didn't see the scope specifier. 6061 DC = CurContext; 6062 Previous.clear(); 6063 } 6064 6065 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6066 6067 if (D.getDeclSpec().isInlineSpecified()) 6068 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6069 << getLangOpts().CPlusPlus17; 6070 if (D.getDeclSpec().hasConstexprSpecifier()) 6071 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6072 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6073 6074 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6075 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6076 Diag(D.getName().StartLocation, 6077 diag::err_deduction_guide_invalid_specifier) 6078 << "typedef"; 6079 else 6080 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6081 << D.getName().getSourceRange(); 6082 return nullptr; 6083 } 6084 6085 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6086 if (!NewTD) return nullptr; 6087 6088 // Handle attributes prior to checking for duplicates in MergeVarDecl 6089 ProcessDeclAttributes(S, NewTD, D); 6090 6091 CheckTypedefForVariablyModifiedType(S, NewTD); 6092 6093 bool Redeclaration = D.isRedeclaration(); 6094 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6095 D.setRedeclaration(Redeclaration); 6096 return ND; 6097 } 6098 6099 void 6100 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6101 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6102 // then it shall have block scope. 6103 // Note that variably modified types must be fixed before merging the decl so 6104 // that redeclarations will match. 6105 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6106 QualType T = TInfo->getType(); 6107 if (T->isVariablyModifiedType()) { 6108 setFunctionHasBranchProtectedScope(); 6109 6110 if (S->getFnParent() == nullptr) { 6111 bool SizeIsNegative; 6112 llvm::APSInt Oversized; 6113 TypeSourceInfo *FixedTInfo = 6114 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6115 SizeIsNegative, 6116 Oversized); 6117 if (FixedTInfo) { 6118 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6119 NewTD->setTypeSourceInfo(FixedTInfo); 6120 } else { 6121 if (SizeIsNegative) 6122 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6123 else if (T->isVariableArrayType()) 6124 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6125 else if (Oversized.getBoolValue()) 6126 Diag(NewTD->getLocation(), diag::err_array_too_large) 6127 << Oversized.toString(10); 6128 else 6129 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6130 NewTD->setInvalidDecl(); 6131 } 6132 } 6133 } 6134 } 6135 6136 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6137 /// declares a typedef-name, either using the 'typedef' type specifier or via 6138 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6139 NamedDecl* 6140 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6141 LookupResult &Previous, bool &Redeclaration) { 6142 6143 // Find the shadowed declaration before filtering for scope. 6144 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6145 6146 // Merge the decl with the existing one if appropriate. If the decl is 6147 // in an outer scope, it isn't the same thing. 6148 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6149 /*AllowInlineNamespace*/false); 6150 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6151 if (!Previous.empty()) { 6152 Redeclaration = true; 6153 MergeTypedefNameDecl(S, NewTD, Previous); 6154 } else { 6155 inferGslPointerAttribute(NewTD); 6156 } 6157 6158 if (ShadowedDecl && !Redeclaration) 6159 CheckShadow(NewTD, ShadowedDecl, Previous); 6160 6161 // If this is the C FILE type, notify the AST context. 6162 if (IdentifierInfo *II = NewTD->getIdentifier()) 6163 if (!NewTD->isInvalidDecl() && 6164 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6165 if (II->isStr("FILE")) 6166 Context.setFILEDecl(NewTD); 6167 else if (II->isStr("jmp_buf")) 6168 Context.setjmp_bufDecl(NewTD); 6169 else if (II->isStr("sigjmp_buf")) 6170 Context.setsigjmp_bufDecl(NewTD); 6171 else if (II->isStr("ucontext_t")) 6172 Context.setucontext_tDecl(NewTD); 6173 } 6174 6175 return NewTD; 6176 } 6177 6178 /// Determines whether the given declaration is an out-of-scope 6179 /// previous declaration. 6180 /// 6181 /// This routine should be invoked when name lookup has found a 6182 /// previous declaration (PrevDecl) that is not in the scope where a 6183 /// new declaration by the same name is being introduced. If the new 6184 /// declaration occurs in a local scope, previous declarations with 6185 /// linkage may still be considered previous declarations (C99 6186 /// 6.2.2p4-5, C++ [basic.link]p6). 6187 /// 6188 /// \param PrevDecl the previous declaration found by name 6189 /// lookup 6190 /// 6191 /// \param DC the context in which the new declaration is being 6192 /// declared. 6193 /// 6194 /// \returns true if PrevDecl is an out-of-scope previous declaration 6195 /// for a new delcaration with the same name. 6196 static bool 6197 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6198 ASTContext &Context) { 6199 if (!PrevDecl) 6200 return false; 6201 6202 if (!PrevDecl->hasLinkage()) 6203 return false; 6204 6205 if (Context.getLangOpts().CPlusPlus) { 6206 // C++ [basic.link]p6: 6207 // If there is a visible declaration of an entity with linkage 6208 // having the same name and type, ignoring entities declared 6209 // outside the innermost enclosing namespace scope, the block 6210 // scope declaration declares that same entity and receives the 6211 // linkage of the previous declaration. 6212 DeclContext *OuterContext = DC->getRedeclContext(); 6213 if (!OuterContext->isFunctionOrMethod()) 6214 // This rule only applies to block-scope declarations. 6215 return false; 6216 6217 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6218 if (PrevOuterContext->isRecord()) 6219 // We found a member function: ignore it. 6220 return false; 6221 6222 // Find the innermost enclosing namespace for the new and 6223 // previous declarations. 6224 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6225 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6226 6227 // The previous declaration is in a different namespace, so it 6228 // isn't the same function. 6229 if (!OuterContext->Equals(PrevOuterContext)) 6230 return false; 6231 } 6232 6233 return true; 6234 } 6235 6236 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6237 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6238 if (!SS.isSet()) return; 6239 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6240 } 6241 6242 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6243 QualType type = decl->getType(); 6244 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6245 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6246 // Various kinds of declaration aren't allowed to be __autoreleasing. 6247 unsigned kind = -1U; 6248 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6249 if (var->hasAttr<BlocksAttr>()) 6250 kind = 0; // __block 6251 else if (!var->hasLocalStorage()) 6252 kind = 1; // global 6253 } else if (isa<ObjCIvarDecl>(decl)) { 6254 kind = 3; // ivar 6255 } else if (isa<FieldDecl>(decl)) { 6256 kind = 2; // field 6257 } 6258 6259 if (kind != -1U) { 6260 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6261 << kind; 6262 } 6263 } else if (lifetime == Qualifiers::OCL_None) { 6264 // Try to infer lifetime. 6265 if (!type->isObjCLifetimeType()) 6266 return false; 6267 6268 lifetime = type->getObjCARCImplicitLifetime(); 6269 type = Context.getLifetimeQualifiedType(type, lifetime); 6270 decl->setType(type); 6271 } 6272 6273 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6274 // Thread-local variables cannot have lifetime. 6275 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6276 var->getTLSKind()) { 6277 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6278 << var->getType(); 6279 return true; 6280 } 6281 } 6282 6283 return false; 6284 } 6285 6286 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6287 if (Decl->getType().hasAddressSpace()) 6288 return; 6289 if (Decl->getType()->isDependentType()) 6290 return; 6291 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6292 QualType Type = Var->getType(); 6293 if (Type->isSamplerT() || Type->isVoidType()) 6294 return; 6295 LangAS ImplAS = LangAS::opencl_private; 6296 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6297 Var->hasGlobalStorage()) 6298 ImplAS = LangAS::opencl_global; 6299 // If the original type from a decayed type is an array type and that array 6300 // type has no address space yet, deduce it now. 6301 if (auto DT = dyn_cast<DecayedType>(Type)) { 6302 auto OrigTy = DT->getOriginalType(); 6303 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6304 // Add the address space to the original array type and then propagate 6305 // that to the element type through `getAsArrayType`. 6306 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6307 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6308 // Re-generate the decayed type. 6309 Type = Context.getDecayedType(OrigTy); 6310 } 6311 } 6312 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6313 // Apply any qualifiers (including address space) from the array type to 6314 // the element type. This implements C99 6.7.3p8: "If the specification of 6315 // an array type includes any type qualifiers, the element type is so 6316 // qualified, not the array type." 6317 if (Type->isArrayType()) 6318 Type = QualType(Context.getAsArrayType(Type), 0); 6319 Decl->setType(Type); 6320 } 6321 } 6322 6323 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6324 // Ensure that an auto decl is deduced otherwise the checks below might cache 6325 // the wrong linkage. 6326 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6327 6328 // 'weak' only applies to declarations with external linkage. 6329 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6330 if (!ND.isExternallyVisible()) { 6331 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6332 ND.dropAttr<WeakAttr>(); 6333 } 6334 } 6335 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6336 if (ND.isExternallyVisible()) { 6337 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6338 ND.dropAttr<WeakRefAttr>(); 6339 ND.dropAttr<AliasAttr>(); 6340 } 6341 } 6342 6343 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6344 if (VD->hasInit()) { 6345 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6346 assert(VD->isThisDeclarationADefinition() && 6347 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6348 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6349 VD->dropAttr<AliasAttr>(); 6350 } 6351 } 6352 } 6353 6354 // 'selectany' only applies to externally visible variable declarations. 6355 // It does not apply to functions. 6356 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6357 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6358 S.Diag(Attr->getLocation(), 6359 diag::err_attribute_selectany_non_extern_data); 6360 ND.dropAttr<SelectAnyAttr>(); 6361 } 6362 } 6363 6364 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6365 auto *VD = dyn_cast<VarDecl>(&ND); 6366 bool IsAnonymousNS = false; 6367 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6368 if (VD) { 6369 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6370 while (NS && !IsAnonymousNS) { 6371 IsAnonymousNS = NS->isAnonymousNamespace(); 6372 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6373 } 6374 } 6375 // dll attributes require external linkage. Static locals may have external 6376 // linkage but still cannot be explicitly imported or exported. 6377 // In Microsoft mode, a variable defined in anonymous namespace must have 6378 // external linkage in order to be exported. 6379 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6380 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6381 (!AnonNSInMicrosoftMode && 6382 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6383 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6384 << &ND << Attr; 6385 ND.setInvalidDecl(); 6386 } 6387 } 6388 6389 // Virtual functions cannot be marked as 'notail'. 6390 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6391 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6392 if (MD->isVirtual()) { 6393 S.Diag(ND.getLocation(), 6394 diag::err_invalid_attribute_on_virtual_function) 6395 << Attr; 6396 ND.dropAttr<NotTailCalledAttr>(); 6397 } 6398 6399 // Check the attributes on the function type, if any. 6400 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6401 // Don't declare this variable in the second operand of the for-statement; 6402 // GCC miscompiles that by ending its lifetime before evaluating the 6403 // third operand. See gcc.gnu.org/PR86769. 6404 AttributedTypeLoc ATL; 6405 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6406 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6407 TL = ATL.getModifiedLoc()) { 6408 // The [[lifetimebound]] attribute can be applied to the implicit object 6409 // parameter of a non-static member function (other than a ctor or dtor) 6410 // by applying it to the function type. 6411 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6412 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6413 if (!MD || MD->isStatic()) { 6414 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6415 << !MD << A->getRange(); 6416 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6417 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6418 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6419 } 6420 } 6421 } 6422 } 6423 } 6424 6425 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6426 NamedDecl *NewDecl, 6427 bool IsSpecialization, 6428 bool IsDefinition) { 6429 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6430 return; 6431 6432 bool IsTemplate = false; 6433 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6434 OldDecl = OldTD->getTemplatedDecl(); 6435 IsTemplate = true; 6436 if (!IsSpecialization) 6437 IsDefinition = false; 6438 } 6439 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6440 NewDecl = NewTD->getTemplatedDecl(); 6441 IsTemplate = true; 6442 } 6443 6444 if (!OldDecl || !NewDecl) 6445 return; 6446 6447 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6448 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6449 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6450 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6451 6452 // dllimport and dllexport are inheritable attributes so we have to exclude 6453 // inherited attribute instances. 6454 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6455 (NewExportAttr && !NewExportAttr->isInherited()); 6456 6457 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6458 // the only exception being explicit specializations. 6459 // Implicitly generated declarations are also excluded for now because there 6460 // is no other way to switch these to use dllimport or dllexport. 6461 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6462 6463 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6464 // Allow with a warning for free functions and global variables. 6465 bool JustWarn = false; 6466 if (!OldDecl->isCXXClassMember()) { 6467 auto *VD = dyn_cast<VarDecl>(OldDecl); 6468 if (VD && !VD->getDescribedVarTemplate()) 6469 JustWarn = true; 6470 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6471 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6472 JustWarn = true; 6473 } 6474 6475 // We cannot change a declaration that's been used because IR has already 6476 // been emitted. Dllimported functions will still work though (modulo 6477 // address equality) as they can use the thunk. 6478 if (OldDecl->isUsed()) 6479 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6480 JustWarn = false; 6481 6482 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6483 : diag::err_attribute_dll_redeclaration; 6484 S.Diag(NewDecl->getLocation(), DiagID) 6485 << NewDecl 6486 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6487 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6488 if (!JustWarn) { 6489 NewDecl->setInvalidDecl(); 6490 return; 6491 } 6492 } 6493 6494 // A redeclaration is not allowed to drop a dllimport attribute, the only 6495 // exceptions being inline function definitions (except for function 6496 // templates), local extern declarations, qualified friend declarations or 6497 // special MSVC extension: in the last case, the declaration is treated as if 6498 // it were marked dllexport. 6499 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6500 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6501 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6502 // Ignore static data because out-of-line definitions are diagnosed 6503 // separately. 6504 IsStaticDataMember = VD->isStaticDataMember(); 6505 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6506 VarDecl::DeclarationOnly; 6507 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6508 IsInline = FD->isInlined(); 6509 IsQualifiedFriend = FD->getQualifier() && 6510 FD->getFriendObjectKind() == Decl::FOK_Declared; 6511 } 6512 6513 if (OldImportAttr && !HasNewAttr && 6514 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6515 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6516 if (IsMicrosoft && IsDefinition) { 6517 S.Diag(NewDecl->getLocation(), 6518 diag::warn_redeclaration_without_import_attribute) 6519 << NewDecl; 6520 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6521 NewDecl->dropAttr<DLLImportAttr>(); 6522 NewDecl->addAttr( 6523 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6524 } else { 6525 S.Diag(NewDecl->getLocation(), 6526 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6527 << NewDecl << OldImportAttr; 6528 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6529 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6530 OldDecl->dropAttr<DLLImportAttr>(); 6531 NewDecl->dropAttr<DLLImportAttr>(); 6532 } 6533 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6534 // In MinGW, seeing a function declared inline drops the dllimport 6535 // attribute. 6536 OldDecl->dropAttr<DLLImportAttr>(); 6537 NewDecl->dropAttr<DLLImportAttr>(); 6538 S.Diag(NewDecl->getLocation(), 6539 diag::warn_dllimport_dropped_from_inline_function) 6540 << NewDecl << OldImportAttr; 6541 } 6542 6543 // A specialization of a class template member function is processed here 6544 // since it's a redeclaration. If the parent class is dllexport, the 6545 // specialization inherits that attribute. This doesn't happen automatically 6546 // since the parent class isn't instantiated until later. 6547 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6548 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6549 !NewImportAttr && !NewExportAttr) { 6550 if (const DLLExportAttr *ParentExportAttr = 6551 MD->getParent()->getAttr<DLLExportAttr>()) { 6552 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6553 NewAttr->setInherited(true); 6554 NewDecl->addAttr(NewAttr); 6555 } 6556 } 6557 } 6558 } 6559 6560 /// Given that we are within the definition of the given function, 6561 /// will that definition behave like C99's 'inline', where the 6562 /// definition is discarded except for optimization purposes? 6563 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6564 // Try to avoid calling GetGVALinkageForFunction. 6565 6566 // All cases of this require the 'inline' keyword. 6567 if (!FD->isInlined()) return false; 6568 6569 // This is only possible in C++ with the gnu_inline attribute. 6570 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6571 return false; 6572 6573 // Okay, go ahead and call the relatively-more-expensive function. 6574 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6575 } 6576 6577 /// Determine whether a variable is extern "C" prior to attaching 6578 /// an initializer. We can't just call isExternC() here, because that 6579 /// will also compute and cache whether the declaration is externally 6580 /// visible, which might change when we attach the initializer. 6581 /// 6582 /// This can only be used if the declaration is known to not be a 6583 /// redeclaration of an internal linkage declaration. 6584 /// 6585 /// For instance: 6586 /// 6587 /// auto x = []{}; 6588 /// 6589 /// Attaching the initializer here makes this declaration not externally 6590 /// visible, because its type has internal linkage. 6591 /// 6592 /// FIXME: This is a hack. 6593 template<typename T> 6594 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6595 if (S.getLangOpts().CPlusPlus) { 6596 // In C++, the overloadable attribute negates the effects of extern "C". 6597 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6598 return false; 6599 6600 // So do CUDA's host/device attributes. 6601 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6602 D->template hasAttr<CUDAHostAttr>())) 6603 return false; 6604 } 6605 return D->isExternC(); 6606 } 6607 6608 static bool shouldConsiderLinkage(const VarDecl *VD) { 6609 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6610 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6611 isa<OMPDeclareMapperDecl>(DC)) 6612 return VD->hasExternalStorage(); 6613 if (DC->isFileContext()) 6614 return true; 6615 if (DC->isRecord()) 6616 return false; 6617 if (isa<RequiresExprBodyDecl>(DC)) 6618 return false; 6619 llvm_unreachable("Unexpected context"); 6620 } 6621 6622 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6623 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6624 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6625 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6626 return true; 6627 if (DC->isRecord()) 6628 return false; 6629 llvm_unreachable("Unexpected context"); 6630 } 6631 6632 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6633 ParsedAttr::Kind Kind) { 6634 // Check decl attributes on the DeclSpec. 6635 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6636 return true; 6637 6638 // Walk the declarator structure, checking decl attributes that were in a type 6639 // position to the decl itself. 6640 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6641 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6642 return true; 6643 } 6644 6645 // Finally, check attributes on the decl itself. 6646 return PD.getAttributes().hasAttribute(Kind); 6647 } 6648 6649 /// Adjust the \c DeclContext for a function or variable that might be a 6650 /// function-local external declaration. 6651 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6652 if (!DC->isFunctionOrMethod()) 6653 return false; 6654 6655 // If this is a local extern function or variable declared within a function 6656 // template, don't add it into the enclosing namespace scope until it is 6657 // instantiated; it might have a dependent type right now. 6658 if (DC->isDependentContext()) 6659 return true; 6660 6661 // C++11 [basic.link]p7: 6662 // When a block scope declaration of an entity with linkage is not found to 6663 // refer to some other declaration, then that entity is a member of the 6664 // innermost enclosing namespace. 6665 // 6666 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6667 // semantically-enclosing namespace, not a lexically-enclosing one. 6668 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6669 DC = DC->getParent(); 6670 return true; 6671 } 6672 6673 /// Returns true if given declaration has external C language linkage. 6674 static bool isDeclExternC(const Decl *D) { 6675 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6676 return FD->isExternC(); 6677 if (const auto *VD = dyn_cast<VarDecl>(D)) 6678 return VD->isExternC(); 6679 6680 llvm_unreachable("Unknown type of decl!"); 6681 } 6682 /// Returns true if there hasn't been any invalid type diagnosed. 6683 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6684 DeclContext *DC, QualType R) { 6685 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6686 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6687 // argument. 6688 if (R->isImageType() || R->isPipeType()) { 6689 Se.Diag(D.getIdentifierLoc(), 6690 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6691 << R; 6692 D.setInvalidType(); 6693 return false; 6694 } 6695 6696 // OpenCL v1.2 s6.9.r: 6697 // The event type cannot be used to declare a program scope variable. 6698 // OpenCL v2.0 s6.9.q: 6699 // The clk_event_t and reserve_id_t types cannot be declared in program 6700 // scope. 6701 if (NULL == S->getParent()) { 6702 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6703 Se.Diag(D.getIdentifierLoc(), 6704 diag::err_invalid_type_for_program_scope_var) 6705 << R; 6706 D.setInvalidType(); 6707 return false; 6708 } 6709 } 6710 6711 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6712 QualType NR = R; 6713 while (NR->isPointerType()) { 6714 if (NR->isFunctionPointerType()) { 6715 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6716 D.setInvalidType(); 6717 return false; 6718 } 6719 NR = NR->getPointeeType(); 6720 } 6721 6722 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6723 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6724 // half array type (unless the cl_khr_fp16 extension is enabled). 6725 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6726 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6727 D.setInvalidType(); 6728 return false; 6729 } 6730 } 6731 6732 // OpenCL v1.2 s6.9.r: 6733 // The event type cannot be used with the __local, __constant and __global 6734 // address space qualifiers. 6735 if (R->isEventT()) { 6736 if (R.getAddressSpace() != LangAS::opencl_private) { 6737 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6738 D.setInvalidType(); 6739 return false; 6740 } 6741 } 6742 6743 // C++ for OpenCL does not allow the thread_local storage qualifier. 6744 // OpenCL C does not support thread_local either, and 6745 // also reject all other thread storage class specifiers. 6746 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6747 if (TSC != TSCS_unspecified) { 6748 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6749 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6750 diag::err_opencl_unknown_type_specifier) 6751 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6752 << DeclSpec::getSpecifierName(TSC) << 1; 6753 D.setInvalidType(); 6754 return false; 6755 } 6756 6757 if (R->isSamplerT()) { 6758 // OpenCL v1.2 s6.9.b p4: 6759 // The sampler type cannot be used with the __local and __global address 6760 // space qualifiers. 6761 if (R.getAddressSpace() == LangAS::opencl_local || 6762 R.getAddressSpace() == LangAS::opencl_global) { 6763 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6764 D.setInvalidType(); 6765 } 6766 6767 // OpenCL v1.2 s6.12.14.1: 6768 // A global sampler must be declared with either the constant address 6769 // space qualifier or with the const qualifier. 6770 if (DC->isTranslationUnit() && 6771 !(R.getAddressSpace() == LangAS::opencl_constant || 6772 R.isConstQualified())) { 6773 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6774 D.setInvalidType(); 6775 } 6776 if (D.isInvalidType()) 6777 return false; 6778 } 6779 return true; 6780 } 6781 6782 NamedDecl *Sema::ActOnVariableDeclarator( 6783 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6784 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6785 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6786 QualType R = TInfo->getType(); 6787 DeclarationName Name = GetNameForDeclarator(D).getName(); 6788 6789 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6790 6791 if (D.isDecompositionDeclarator()) { 6792 // Take the name of the first declarator as our name for diagnostic 6793 // purposes. 6794 auto &Decomp = D.getDecompositionDeclarator(); 6795 if (!Decomp.bindings().empty()) { 6796 II = Decomp.bindings()[0].Name; 6797 Name = II; 6798 } 6799 } else if (!II) { 6800 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6801 return nullptr; 6802 } 6803 6804 6805 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6806 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6807 6808 // dllimport globals without explicit storage class are treated as extern. We 6809 // have to change the storage class this early to get the right DeclContext. 6810 if (SC == SC_None && !DC->isRecord() && 6811 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6812 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6813 SC = SC_Extern; 6814 6815 DeclContext *OriginalDC = DC; 6816 bool IsLocalExternDecl = SC == SC_Extern && 6817 adjustContextForLocalExternDecl(DC); 6818 6819 if (SCSpec == DeclSpec::SCS_mutable) { 6820 // mutable can only appear on non-static class members, so it's always 6821 // an error here 6822 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6823 D.setInvalidType(); 6824 SC = SC_None; 6825 } 6826 6827 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6828 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6829 D.getDeclSpec().getStorageClassSpecLoc())) { 6830 // In C++11, the 'register' storage class specifier is deprecated. 6831 // Suppress the warning in system macros, it's used in macros in some 6832 // popular C system headers, such as in glibc's htonl() macro. 6833 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6834 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6835 : diag::warn_deprecated_register) 6836 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6837 } 6838 6839 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6840 6841 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6842 // C99 6.9p2: The storage-class specifiers auto and register shall not 6843 // appear in the declaration specifiers in an external declaration. 6844 // Global Register+Asm is a GNU extension we support. 6845 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6846 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6847 D.setInvalidType(); 6848 } 6849 } 6850 6851 bool IsMemberSpecialization = false; 6852 bool IsVariableTemplateSpecialization = false; 6853 bool IsPartialSpecialization = false; 6854 bool IsVariableTemplate = false; 6855 VarDecl *NewVD = nullptr; 6856 VarTemplateDecl *NewTemplate = nullptr; 6857 TemplateParameterList *TemplateParams = nullptr; 6858 if (!getLangOpts().CPlusPlus) { 6859 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6860 II, R, TInfo, SC); 6861 6862 if (R->getContainedDeducedType()) 6863 ParsingInitForAutoVars.insert(NewVD); 6864 6865 if (D.isInvalidType()) 6866 NewVD->setInvalidDecl(); 6867 6868 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6869 NewVD->hasLocalStorage()) 6870 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6871 NTCUC_AutoVar, NTCUK_Destruct); 6872 } else { 6873 bool Invalid = false; 6874 6875 if (DC->isRecord() && !CurContext->isRecord()) { 6876 // This is an out-of-line definition of a static data member. 6877 switch (SC) { 6878 case SC_None: 6879 break; 6880 case SC_Static: 6881 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6882 diag::err_static_out_of_line) 6883 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6884 break; 6885 case SC_Auto: 6886 case SC_Register: 6887 case SC_Extern: 6888 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6889 // to names of variables declared in a block or to function parameters. 6890 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6891 // of class members 6892 6893 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6894 diag::err_storage_class_for_static_member) 6895 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6896 break; 6897 case SC_PrivateExtern: 6898 llvm_unreachable("C storage class in c++!"); 6899 } 6900 } 6901 6902 if (SC == SC_Static && CurContext->isRecord()) { 6903 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6904 // Walk up the enclosing DeclContexts to check for any that are 6905 // incompatible with static data members. 6906 const DeclContext *FunctionOrMethod = nullptr; 6907 const CXXRecordDecl *AnonStruct = nullptr; 6908 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6909 if (Ctxt->isFunctionOrMethod()) { 6910 FunctionOrMethod = Ctxt; 6911 break; 6912 } 6913 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6914 if (ParentDecl && !ParentDecl->getDeclName()) { 6915 AnonStruct = ParentDecl; 6916 break; 6917 } 6918 } 6919 if (FunctionOrMethod) { 6920 // C++ [class.static.data]p5: A local class shall not have static data 6921 // members. 6922 Diag(D.getIdentifierLoc(), 6923 diag::err_static_data_member_not_allowed_in_local_class) 6924 << Name << RD->getDeclName() << RD->getTagKind(); 6925 } else if (AnonStruct) { 6926 // C++ [class.static.data]p4: Unnamed classes and classes contained 6927 // directly or indirectly within unnamed classes shall not contain 6928 // static data members. 6929 Diag(D.getIdentifierLoc(), 6930 diag::err_static_data_member_not_allowed_in_anon_struct) 6931 << Name << AnonStruct->getTagKind(); 6932 Invalid = true; 6933 } else if (RD->isUnion()) { 6934 // C++98 [class.union]p1: If a union contains a static data member, 6935 // the program is ill-formed. C++11 drops this restriction. 6936 Diag(D.getIdentifierLoc(), 6937 getLangOpts().CPlusPlus11 6938 ? diag::warn_cxx98_compat_static_data_member_in_union 6939 : diag::ext_static_data_member_in_union) << Name; 6940 } 6941 } 6942 } 6943 6944 // Match up the template parameter lists with the scope specifier, then 6945 // determine whether we have a template or a template specialization. 6946 bool InvalidScope = false; 6947 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6948 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6949 D.getCXXScopeSpec(), 6950 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6951 ? D.getName().TemplateId 6952 : nullptr, 6953 TemplateParamLists, 6954 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6955 Invalid |= InvalidScope; 6956 6957 if (TemplateParams) { 6958 if (!TemplateParams->size() && 6959 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6960 // There is an extraneous 'template<>' for this variable. Complain 6961 // about it, but allow the declaration of the variable. 6962 Diag(TemplateParams->getTemplateLoc(), 6963 diag::err_template_variable_noparams) 6964 << II 6965 << SourceRange(TemplateParams->getTemplateLoc(), 6966 TemplateParams->getRAngleLoc()); 6967 TemplateParams = nullptr; 6968 } else { 6969 // Check that we can declare a template here. 6970 if (CheckTemplateDeclScope(S, TemplateParams)) 6971 return nullptr; 6972 6973 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6974 // This is an explicit specialization or a partial specialization. 6975 IsVariableTemplateSpecialization = true; 6976 IsPartialSpecialization = TemplateParams->size() > 0; 6977 } else { // if (TemplateParams->size() > 0) 6978 // This is a template declaration. 6979 IsVariableTemplate = true; 6980 6981 // Only C++1y supports variable templates (N3651). 6982 Diag(D.getIdentifierLoc(), 6983 getLangOpts().CPlusPlus14 6984 ? diag::warn_cxx11_compat_variable_template 6985 : diag::ext_variable_template); 6986 } 6987 } 6988 } else { 6989 // Check that we can declare a member specialization here. 6990 if (!TemplateParamLists.empty() && IsMemberSpecialization && 6991 CheckTemplateDeclScope(S, TemplateParamLists.back())) 6992 return nullptr; 6993 assert((Invalid || 6994 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6995 "should have a 'template<>' for this decl"); 6996 } 6997 6998 if (IsVariableTemplateSpecialization) { 6999 SourceLocation TemplateKWLoc = 7000 TemplateParamLists.size() > 0 7001 ? TemplateParamLists[0]->getTemplateLoc() 7002 : SourceLocation(); 7003 DeclResult Res = ActOnVarTemplateSpecialization( 7004 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7005 IsPartialSpecialization); 7006 if (Res.isInvalid()) 7007 return nullptr; 7008 NewVD = cast<VarDecl>(Res.get()); 7009 AddToScope = false; 7010 } else if (D.isDecompositionDeclarator()) { 7011 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7012 D.getIdentifierLoc(), R, TInfo, SC, 7013 Bindings); 7014 } else 7015 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7016 D.getIdentifierLoc(), II, R, TInfo, SC); 7017 7018 // If this is supposed to be a variable template, create it as such. 7019 if (IsVariableTemplate) { 7020 NewTemplate = 7021 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7022 TemplateParams, NewVD); 7023 NewVD->setDescribedVarTemplate(NewTemplate); 7024 } 7025 7026 // If this decl has an auto type in need of deduction, make a note of the 7027 // Decl so we can diagnose uses of it in its own initializer. 7028 if (R->getContainedDeducedType()) 7029 ParsingInitForAutoVars.insert(NewVD); 7030 7031 if (D.isInvalidType() || Invalid) { 7032 NewVD->setInvalidDecl(); 7033 if (NewTemplate) 7034 NewTemplate->setInvalidDecl(); 7035 } 7036 7037 SetNestedNameSpecifier(*this, NewVD, D); 7038 7039 // If we have any template parameter lists that don't directly belong to 7040 // the variable (matching the scope specifier), store them. 7041 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7042 if (TemplateParamLists.size() > VDTemplateParamLists) 7043 NewVD->setTemplateParameterListsInfo( 7044 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7045 } 7046 7047 if (D.getDeclSpec().isInlineSpecified()) { 7048 if (!getLangOpts().CPlusPlus) { 7049 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7050 << 0; 7051 } else if (CurContext->isFunctionOrMethod()) { 7052 // 'inline' is not allowed on block scope variable declaration. 7053 Diag(D.getDeclSpec().getInlineSpecLoc(), 7054 diag::err_inline_declaration_block_scope) << Name 7055 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7056 } else { 7057 Diag(D.getDeclSpec().getInlineSpecLoc(), 7058 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7059 : diag::ext_inline_variable); 7060 NewVD->setInlineSpecified(); 7061 } 7062 } 7063 7064 // Set the lexical context. If the declarator has a C++ scope specifier, the 7065 // lexical context will be different from the semantic context. 7066 NewVD->setLexicalDeclContext(CurContext); 7067 if (NewTemplate) 7068 NewTemplate->setLexicalDeclContext(CurContext); 7069 7070 if (IsLocalExternDecl) { 7071 if (D.isDecompositionDeclarator()) 7072 for (auto *B : Bindings) 7073 B->setLocalExternDecl(); 7074 else 7075 NewVD->setLocalExternDecl(); 7076 } 7077 7078 bool EmitTLSUnsupportedError = false; 7079 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7080 // C++11 [dcl.stc]p4: 7081 // When thread_local is applied to a variable of block scope the 7082 // storage-class-specifier static is implied if it does not appear 7083 // explicitly. 7084 // Core issue: 'static' is not implied if the variable is declared 7085 // 'extern'. 7086 if (NewVD->hasLocalStorage() && 7087 (SCSpec != DeclSpec::SCS_unspecified || 7088 TSCS != DeclSpec::TSCS_thread_local || 7089 !DC->isFunctionOrMethod())) 7090 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7091 diag::err_thread_non_global) 7092 << DeclSpec::getSpecifierName(TSCS); 7093 else if (!Context.getTargetInfo().isTLSSupported()) { 7094 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7095 getLangOpts().SYCLIsDevice) { 7096 // Postpone error emission until we've collected attributes required to 7097 // figure out whether it's a host or device variable and whether the 7098 // error should be ignored. 7099 EmitTLSUnsupportedError = true; 7100 // We still need to mark the variable as TLS so it shows up in AST with 7101 // proper storage class for other tools to use even if we're not going 7102 // to emit any code for it. 7103 NewVD->setTSCSpec(TSCS); 7104 } else 7105 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7106 diag::err_thread_unsupported); 7107 } else 7108 NewVD->setTSCSpec(TSCS); 7109 } 7110 7111 switch (D.getDeclSpec().getConstexprSpecifier()) { 7112 case CSK_unspecified: 7113 break; 7114 7115 case CSK_consteval: 7116 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7117 diag::err_constexpr_wrong_decl_kind) 7118 << D.getDeclSpec().getConstexprSpecifier(); 7119 LLVM_FALLTHROUGH; 7120 7121 case CSK_constexpr: 7122 NewVD->setConstexpr(true); 7123 MaybeAddCUDAConstantAttr(NewVD); 7124 // C++1z [dcl.spec.constexpr]p1: 7125 // A static data member declared with the constexpr specifier is 7126 // implicitly an inline variable. 7127 if (NewVD->isStaticDataMember() && 7128 (getLangOpts().CPlusPlus17 || 7129 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7130 NewVD->setImplicitlyInline(); 7131 break; 7132 7133 case CSK_constinit: 7134 if (!NewVD->hasGlobalStorage()) 7135 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7136 diag::err_constinit_local_variable); 7137 else 7138 NewVD->addAttr(ConstInitAttr::Create( 7139 Context, D.getDeclSpec().getConstexprSpecLoc(), 7140 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7141 break; 7142 } 7143 7144 // C99 6.7.4p3 7145 // An inline definition of a function with external linkage shall 7146 // not contain a definition of a modifiable object with static or 7147 // thread storage duration... 7148 // We only apply this when the function is required to be defined 7149 // elsewhere, i.e. when the function is not 'extern inline'. Note 7150 // that a local variable with thread storage duration still has to 7151 // be marked 'static'. Also note that it's possible to get these 7152 // semantics in C++ using __attribute__((gnu_inline)). 7153 if (SC == SC_Static && S->getFnParent() != nullptr && 7154 !NewVD->getType().isConstQualified()) { 7155 FunctionDecl *CurFD = getCurFunctionDecl(); 7156 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7157 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7158 diag::warn_static_local_in_extern_inline); 7159 MaybeSuggestAddingStaticToDecl(CurFD); 7160 } 7161 } 7162 7163 if (D.getDeclSpec().isModulePrivateSpecified()) { 7164 if (IsVariableTemplateSpecialization) 7165 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7166 << (IsPartialSpecialization ? 1 : 0) 7167 << FixItHint::CreateRemoval( 7168 D.getDeclSpec().getModulePrivateSpecLoc()); 7169 else if (IsMemberSpecialization) 7170 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7171 << 2 7172 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7173 else if (NewVD->hasLocalStorage()) 7174 Diag(NewVD->getLocation(), diag::err_module_private_local) 7175 << 0 << NewVD 7176 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7177 << FixItHint::CreateRemoval( 7178 D.getDeclSpec().getModulePrivateSpecLoc()); 7179 else { 7180 NewVD->setModulePrivate(); 7181 if (NewTemplate) 7182 NewTemplate->setModulePrivate(); 7183 for (auto *B : Bindings) 7184 B->setModulePrivate(); 7185 } 7186 } 7187 7188 if (getLangOpts().OpenCL) { 7189 7190 deduceOpenCLAddressSpace(NewVD); 7191 7192 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7193 } 7194 7195 // Handle attributes prior to checking for duplicates in MergeVarDecl 7196 ProcessDeclAttributes(S, NewVD, D); 7197 7198 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7199 getLangOpts().SYCLIsDevice) { 7200 if (EmitTLSUnsupportedError && 7201 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7202 (getLangOpts().OpenMPIsDevice && 7203 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7204 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7205 diag::err_thread_unsupported); 7206 7207 if (EmitTLSUnsupportedError && 7208 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7209 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7210 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7211 // storage [duration]." 7212 if (SC == SC_None && S->getFnParent() != nullptr && 7213 (NewVD->hasAttr<CUDASharedAttr>() || 7214 NewVD->hasAttr<CUDAConstantAttr>())) { 7215 NewVD->setStorageClass(SC_Static); 7216 } 7217 } 7218 7219 // Ensure that dllimport globals without explicit storage class are treated as 7220 // extern. The storage class is set above using parsed attributes. Now we can 7221 // check the VarDecl itself. 7222 assert(!NewVD->hasAttr<DLLImportAttr>() || 7223 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7224 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7225 7226 // In auto-retain/release, infer strong retension for variables of 7227 // retainable type. 7228 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7229 NewVD->setInvalidDecl(); 7230 7231 // Handle GNU asm-label extension (encoded as an attribute). 7232 if (Expr *E = (Expr*)D.getAsmLabel()) { 7233 // The parser guarantees this is a string. 7234 StringLiteral *SE = cast<StringLiteral>(E); 7235 StringRef Label = SE->getString(); 7236 if (S->getFnParent() != nullptr) { 7237 switch (SC) { 7238 case SC_None: 7239 case SC_Auto: 7240 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7241 break; 7242 case SC_Register: 7243 // Local Named register 7244 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7245 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7246 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7247 break; 7248 case SC_Static: 7249 case SC_Extern: 7250 case SC_PrivateExtern: 7251 break; 7252 } 7253 } else if (SC == SC_Register) { 7254 // Global Named register 7255 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7256 const auto &TI = Context.getTargetInfo(); 7257 bool HasSizeMismatch; 7258 7259 if (!TI.isValidGCCRegisterName(Label)) 7260 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7261 else if (!TI.validateGlobalRegisterVariable(Label, 7262 Context.getTypeSize(R), 7263 HasSizeMismatch)) 7264 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7265 else if (HasSizeMismatch) 7266 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7267 } 7268 7269 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7270 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7271 NewVD->setInvalidDecl(true); 7272 } 7273 } 7274 7275 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7276 /*IsLiteralLabel=*/true, 7277 SE->getStrTokenLoc(0))); 7278 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7279 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7280 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7281 if (I != ExtnameUndeclaredIdentifiers.end()) { 7282 if (isDeclExternC(NewVD)) { 7283 NewVD->addAttr(I->second); 7284 ExtnameUndeclaredIdentifiers.erase(I); 7285 } else 7286 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7287 << /*Variable*/1 << NewVD; 7288 } 7289 } 7290 7291 // Find the shadowed declaration before filtering for scope. 7292 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7293 ? getShadowedDeclaration(NewVD, Previous) 7294 : nullptr; 7295 7296 // Don't consider existing declarations that are in a different 7297 // scope and are out-of-semantic-context declarations (if the new 7298 // declaration has linkage). 7299 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7300 D.getCXXScopeSpec().isNotEmpty() || 7301 IsMemberSpecialization || 7302 IsVariableTemplateSpecialization); 7303 7304 // Check whether the previous declaration is in the same block scope. This 7305 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7306 if (getLangOpts().CPlusPlus && 7307 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7308 NewVD->setPreviousDeclInSameBlockScope( 7309 Previous.isSingleResult() && !Previous.isShadowed() && 7310 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7311 7312 if (!getLangOpts().CPlusPlus) { 7313 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7314 } else { 7315 // If this is an explicit specialization of a static data member, check it. 7316 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7317 CheckMemberSpecialization(NewVD, Previous)) 7318 NewVD->setInvalidDecl(); 7319 7320 // Merge the decl with the existing one if appropriate. 7321 if (!Previous.empty()) { 7322 if (Previous.isSingleResult() && 7323 isa<FieldDecl>(Previous.getFoundDecl()) && 7324 D.getCXXScopeSpec().isSet()) { 7325 // The user tried to define a non-static data member 7326 // out-of-line (C++ [dcl.meaning]p1). 7327 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7328 << D.getCXXScopeSpec().getRange(); 7329 Previous.clear(); 7330 NewVD->setInvalidDecl(); 7331 } 7332 } else if (D.getCXXScopeSpec().isSet()) { 7333 // No previous declaration in the qualifying scope. 7334 Diag(D.getIdentifierLoc(), diag::err_no_member) 7335 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7336 << D.getCXXScopeSpec().getRange(); 7337 NewVD->setInvalidDecl(); 7338 } 7339 7340 if (!IsVariableTemplateSpecialization) 7341 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7342 7343 if (NewTemplate) { 7344 VarTemplateDecl *PrevVarTemplate = 7345 NewVD->getPreviousDecl() 7346 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7347 : nullptr; 7348 7349 // Check the template parameter list of this declaration, possibly 7350 // merging in the template parameter list from the previous variable 7351 // template declaration. 7352 if (CheckTemplateParameterList( 7353 TemplateParams, 7354 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7355 : nullptr, 7356 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7357 DC->isDependentContext()) 7358 ? TPC_ClassTemplateMember 7359 : TPC_VarTemplate)) 7360 NewVD->setInvalidDecl(); 7361 7362 // If we are providing an explicit specialization of a static variable 7363 // template, make a note of that. 7364 if (PrevVarTemplate && 7365 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7366 PrevVarTemplate->setMemberSpecialization(); 7367 } 7368 } 7369 7370 // Diagnose shadowed variables iff this isn't a redeclaration. 7371 if (ShadowedDecl && !D.isRedeclaration()) 7372 CheckShadow(NewVD, ShadowedDecl, Previous); 7373 7374 ProcessPragmaWeak(S, NewVD); 7375 7376 // If this is the first declaration of an extern C variable, update 7377 // the map of such variables. 7378 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7379 isIncompleteDeclExternC(*this, NewVD)) 7380 RegisterLocallyScopedExternCDecl(NewVD, S); 7381 7382 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7383 MangleNumberingContext *MCtx; 7384 Decl *ManglingContextDecl; 7385 std::tie(MCtx, ManglingContextDecl) = 7386 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7387 if (MCtx) { 7388 Context.setManglingNumber( 7389 NewVD, MCtx->getManglingNumber( 7390 NewVD, getMSManglingNumber(getLangOpts(), S))); 7391 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7392 } 7393 } 7394 7395 // Special handling of variable named 'main'. 7396 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7397 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7398 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7399 7400 // C++ [basic.start.main]p3 7401 // A program that declares a variable main at global scope is ill-formed. 7402 if (getLangOpts().CPlusPlus) 7403 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7404 7405 // In C, and external-linkage variable named main results in undefined 7406 // behavior. 7407 else if (NewVD->hasExternalFormalLinkage()) 7408 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7409 } 7410 7411 if (D.isRedeclaration() && !Previous.empty()) { 7412 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7413 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7414 D.isFunctionDefinition()); 7415 } 7416 7417 if (NewTemplate) { 7418 if (NewVD->isInvalidDecl()) 7419 NewTemplate->setInvalidDecl(); 7420 ActOnDocumentableDecl(NewTemplate); 7421 return NewTemplate; 7422 } 7423 7424 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7425 CompleteMemberSpecialization(NewVD, Previous); 7426 7427 return NewVD; 7428 } 7429 7430 /// Enum describing the %select options in diag::warn_decl_shadow. 7431 enum ShadowedDeclKind { 7432 SDK_Local, 7433 SDK_Global, 7434 SDK_StaticMember, 7435 SDK_Field, 7436 SDK_Typedef, 7437 SDK_Using 7438 }; 7439 7440 /// Determine what kind of declaration we're shadowing. 7441 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7442 const DeclContext *OldDC) { 7443 if (isa<TypeAliasDecl>(ShadowedDecl)) 7444 return SDK_Using; 7445 else if (isa<TypedefDecl>(ShadowedDecl)) 7446 return SDK_Typedef; 7447 else if (isa<RecordDecl>(OldDC)) 7448 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7449 7450 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7451 } 7452 7453 /// Return the location of the capture if the given lambda captures the given 7454 /// variable \p VD, or an invalid source location otherwise. 7455 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7456 const VarDecl *VD) { 7457 for (const Capture &Capture : LSI->Captures) { 7458 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7459 return Capture.getLocation(); 7460 } 7461 return SourceLocation(); 7462 } 7463 7464 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7465 const LookupResult &R) { 7466 // Only diagnose if we're shadowing an unambiguous field or variable. 7467 if (R.getResultKind() != LookupResult::Found) 7468 return false; 7469 7470 // Return false if warning is ignored. 7471 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7472 } 7473 7474 /// Return the declaration shadowed by the given variable \p D, or null 7475 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7476 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7477 const LookupResult &R) { 7478 if (!shouldWarnIfShadowedDecl(Diags, R)) 7479 return nullptr; 7480 7481 // Don't diagnose declarations at file scope. 7482 if (D->hasGlobalStorage()) 7483 return nullptr; 7484 7485 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7486 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7487 ? ShadowedDecl 7488 : nullptr; 7489 } 7490 7491 /// Return the declaration shadowed by the given typedef \p D, or null 7492 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7493 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7494 const LookupResult &R) { 7495 // Don't warn if typedef declaration is part of a class 7496 if (D->getDeclContext()->isRecord()) 7497 return nullptr; 7498 7499 if (!shouldWarnIfShadowedDecl(Diags, R)) 7500 return nullptr; 7501 7502 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7503 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7504 } 7505 7506 /// Diagnose variable or built-in function shadowing. Implements 7507 /// -Wshadow. 7508 /// 7509 /// This method is called whenever a VarDecl is added to a "useful" 7510 /// scope. 7511 /// 7512 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7513 /// \param R the lookup of the name 7514 /// 7515 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7516 const LookupResult &R) { 7517 DeclContext *NewDC = D->getDeclContext(); 7518 7519 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7520 // Fields are not shadowed by variables in C++ static methods. 7521 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7522 if (MD->isStatic()) 7523 return; 7524 7525 // Fields shadowed by constructor parameters are a special case. Usually 7526 // the constructor initializes the field with the parameter. 7527 if (isa<CXXConstructorDecl>(NewDC)) 7528 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7529 // Remember that this was shadowed so we can either warn about its 7530 // modification or its existence depending on warning settings. 7531 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7532 return; 7533 } 7534 } 7535 7536 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7537 if (shadowedVar->isExternC()) { 7538 // For shadowing external vars, make sure that we point to the global 7539 // declaration, not a locally scoped extern declaration. 7540 for (auto I : shadowedVar->redecls()) 7541 if (I->isFileVarDecl()) { 7542 ShadowedDecl = I; 7543 break; 7544 } 7545 } 7546 7547 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7548 7549 unsigned WarningDiag = diag::warn_decl_shadow; 7550 SourceLocation CaptureLoc; 7551 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7552 isa<CXXMethodDecl>(NewDC)) { 7553 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7554 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7555 if (RD->getLambdaCaptureDefault() == LCD_None) { 7556 // Try to avoid warnings for lambdas with an explicit capture list. 7557 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7558 // Warn only when the lambda captures the shadowed decl explicitly. 7559 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7560 if (CaptureLoc.isInvalid()) 7561 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7562 } else { 7563 // Remember that this was shadowed so we can avoid the warning if the 7564 // shadowed decl isn't captured and the warning settings allow it. 7565 cast<LambdaScopeInfo>(getCurFunction()) 7566 ->ShadowingDecls.push_back( 7567 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7568 return; 7569 } 7570 } 7571 7572 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7573 // A variable can't shadow a local variable in an enclosing scope, if 7574 // they are separated by a non-capturing declaration context. 7575 for (DeclContext *ParentDC = NewDC; 7576 ParentDC && !ParentDC->Equals(OldDC); 7577 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7578 // Only block literals, captured statements, and lambda expressions 7579 // can capture; other scopes don't. 7580 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7581 !isLambdaCallOperator(ParentDC)) { 7582 return; 7583 } 7584 } 7585 } 7586 } 7587 } 7588 7589 // Only warn about certain kinds of shadowing for class members. 7590 if (NewDC && NewDC->isRecord()) { 7591 // In particular, don't warn about shadowing non-class members. 7592 if (!OldDC->isRecord()) 7593 return; 7594 7595 // TODO: should we warn about static data members shadowing 7596 // static data members from base classes? 7597 7598 // TODO: don't diagnose for inaccessible shadowed members. 7599 // This is hard to do perfectly because we might friend the 7600 // shadowing context, but that's just a false negative. 7601 } 7602 7603 7604 DeclarationName Name = R.getLookupName(); 7605 7606 // Emit warning and note. 7607 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7608 return; 7609 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7610 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7611 if (!CaptureLoc.isInvalid()) 7612 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7613 << Name << /*explicitly*/ 1; 7614 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7615 } 7616 7617 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7618 /// when these variables are captured by the lambda. 7619 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7620 for (const auto &Shadow : LSI->ShadowingDecls) { 7621 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7622 // Try to avoid the warning when the shadowed decl isn't captured. 7623 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7624 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7625 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7626 ? diag::warn_decl_shadow_uncaptured_local 7627 : diag::warn_decl_shadow) 7628 << Shadow.VD->getDeclName() 7629 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7630 if (!CaptureLoc.isInvalid()) 7631 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7632 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7633 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7634 } 7635 } 7636 7637 /// Check -Wshadow without the advantage of a previous lookup. 7638 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7639 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7640 return; 7641 7642 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7643 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7644 LookupName(R, S); 7645 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7646 CheckShadow(D, ShadowedDecl, R); 7647 } 7648 7649 /// Check if 'E', which is an expression that is about to be modified, refers 7650 /// to a constructor parameter that shadows a field. 7651 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7652 // Quickly ignore expressions that can't be shadowing ctor parameters. 7653 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7654 return; 7655 E = E->IgnoreParenImpCasts(); 7656 auto *DRE = dyn_cast<DeclRefExpr>(E); 7657 if (!DRE) 7658 return; 7659 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7660 auto I = ShadowingDecls.find(D); 7661 if (I == ShadowingDecls.end()) 7662 return; 7663 const NamedDecl *ShadowedDecl = I->second; 7664 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7665 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7666 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7667 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7668 7669 // Avoid issuing multiple warnings about the same decl. 7670 ShadowingDecls.erase(I); 7671 } 7672 7673 /// Check for conflict between this global or extern "C" declaration and 7674 /// previous global or extern "C" declarations. This is only used in C++. 7675 template<typename T> 7676 static bool checkGlobalOrExternCConflict( 7677 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7678 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7679 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7680 7681 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7682 // The common case: this global doesn't conflict with any extern "C" 7683 // declaration. 7684 return false; 7685 } 7686 7687 if (Prev) { 7688 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7689 // Both the old and new declarations have C language linkage. This is a 7690 // redeclaration. 7691 Previous.clear(); 7692 Previous.addDecl(Prev); 7693 return true; 7694 } 7695 7696 // This is a global, non-extern "C" declaration, and there is a previous 7697 // non-global extern "C" declaration. Diagnose if this is a variable 7698 // declaration. 7699 if (!isa<VarDecl>(ND)) 7700 return false; 7701 } else { 7702 // The declaration is extern "C". Check for any declaration in the 7703 // translation unit which might conflict. 7704 if (IsGlobal) { 7705 // We have already performed the lookup into the translation unit. 7706 IsGlobal = false; 7707 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7708 I != E; ++I) { 7709 if (isa<VarDecl>(*I)) { 7710 Prev = *I; 7711 break; 7712 } 7713 } 7714 } else { 7715 DeclContext::lookup_result R = 7716 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7717 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7718 I != E; ++I) { 7719 if (isa<VarDecl>(*I)) { 7720 Prev = *I; 7721 break; 7722 } 7723 // FIXME: If we have any other entity with this name in global scope, 7724 // the declaration is ill-formed, but that is a defect: it breaks the 7725 // 'stat' hack, for instance. Only variables can have mangled name 7726 // clashes with extern "C" declarations, so only they deserve a 7727 // diagnostic. 7728 } 7729 } 7730 7731 if (!Prev) 7732 return false; 7733 } 7734 7735 // Use the first declaration's location to ensure we point at something which 7736 // is lexically inside an extern "C" linkage-spec. 7737 assert(Prev && "should have found a previous declaration to diagnose"); 7738 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7739 Prev = FD->getFirstDecl(); 7740 else 7741 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7742 7743 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7744 << IsGlobal << ND; 7745 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7746 << IsGlobal; 7747 return false; 7748 } 7749 7750 /// Apply special rules for handling extern "C" declarations. Returns \c true 7751 /// if we have found that this is a redeclaration of some prior entity. 7752 /// 7753 /// Per C++ [dcl.link]p6: 7754 /// Two declarations [for a function or variable] with C language linkage 7755 /// with the same name that appear in different scopes refer to the same 7756 /// [entity]. An entity with C language linkage shall not be declared with 7757 /// the same name as an entity in global scope. 7758 template<typename T> 7759 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7760 LookupResult &Previous) { 7761 if (!S.getLangOpts().CPlusPlus) { 7762 // In C, when declaring a global variable, look for a corresponding 'extern' 7763 // variable declared in function scope. We don't need this in C++, because 7764 // we find local extern decls in the surrounding file-scope DeclContext. 7765 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7766 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7767 Previous.clear(); 7768 Previous.addDecl(Prev); 7769 return true; 7770 } 7771 } 7772 return false; 7773 } 7774 7775 // A declaration in the translation unit can conflict with an extern "C" 7776 // declaration. 7777 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7778 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7779 7780 // An extern "C" declaration can conflict with a declaration in the 7781 // translation unit or can be a redeclaration of an extern "C" declaration 7782 // in another scope. 7783 if (isIncompleteDeclExternC(S,ND)) 7784 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7785 7786 // Neither global nor extern "C": nothing to do. 7787 return false; 7788 } 7789 7790 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7791 // If the decl is already known invalid, don't check it. 7792 if (NewVD->isInvalidDecl()) 7793 return; 7794 7795 QualType T = NewVD->getType(); 7796 7797 // Defer checking an 'auto' type until its initializer is attached. 7798 if (T->isUndeducedType()) 7799 return; 7800 7801 if (NewVD->hasAttrs()) 7802 CheckAlignasUnderalignment(NewVD); 7803 7804 if (T->isObjCObjectType()) { 7805 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7806 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7807 T = Context.getObjCObjectPointerType(T); 7808 NewVD->setType(T); 7809 } 7810 7811 // Emit an error if an address space was applied to decl with local storage. 7812 // This includes arrays of objects with address space qualifiers, but not 7813 // automatic variables that point to other address spaces. 7814 // ISO/IEC TR 18037 S5.1.2 7815 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7816 T.getAddressSpace() != LangAS::Default) { 7817 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7818 NewVD->setInvalidDecl(); 7819 return; 7820 } 7821 7822 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7823 // scope. 7824 if (getLangOpts().OpenCLVersion == 120 && 7825 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7826 NewVD->isStaticLocal()) { 7827 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7828 NewVD->setInvalidDecl(); 7829 return; 7830 } 7831 7832 if (getLangOpts().OpenCL) { 7833 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7834 if (NewVD->hasAttr<BlocksAttr>()) { 7835 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7836 return; 7837 } 7838 7839 if (T->isBlockPointerType()) { 7840 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7841 // can't use 'extern' storage class. 7842 if (!T.isConstQualified()) { 7843 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7844 << 0 /*const*/; 7845 NewVD->setInvalidDecl(); 7846 return; 7847 } 7848 if (NewVD->hasExternalStorage()) { 7849 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7850 NewVD->setInvalidDecl(); 7851 return; 7852 } 7853 } 7854 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7855 // __constant address space. 7856 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7857 // variables inside a function can also be declared in the global 7858 // address space. 7859 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7860 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7861 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7862 NewVD->hasExternalStorage()) { 7863 if (!T->isSamplerT() && 7864 !T->isDependentType() && 7865 !(T.getAddressSpace() == LangAS::opencl_constant || 7866 (T.getAddressSpace() == LangAS::opencl_global && 7867 (getLangOpts().OpenCLVersion == 200 || 7868 getLangOpts().OpenCLCPlusPlus)))) { 7869 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7870 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7871 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7872 << Scope << "global or constant"; 7873 else 7874 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7875 << Scope << "constant"; 7876 NewVD->setInvalidDecl(); 7877 return; 7878 } 7879 } else { 7880 if (T.getAddressSpace() == LangAS::opencl_global) { 7881 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7882 << 1 /*is any function*/ << "global"; 7883 NewVD->setInvalidDecl(); 7884 return; 7885 } 7886 if (T.getAddressSpace() == LangAS::opencl_constant || 7887 T.getAddressSpace() == LangAS::opencl_local) { 7888 FunctionDecl *FD = getCurFunctionDecl(); 7889 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7890 // in functions. 7891 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7892 if (T.getAddressSpace() == LangAS::opencl_constant) 7893 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7894 << 0 /*non-kernel only*/ << "constant"; 7895 else 7896 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7897 << 0 /*non-kernel only*/ << "local"; 7898 NewVD->setInvalidDecl(); 7899 return; 7900 } 7901 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7902 // in the outermost scope of a kernel function. 7903 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7904 if (!getCurScope()->isFunctionScope()) { 7905 if (T.getAddressSpace() == LangAS::opencl_constant) 7906 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7907 << "constant"; 7908 else 7909 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7910 << "local"; 7911 NewVD->setInvalidDecl(); 7912 return; 7913 } 7914 } 7915 } else if (T.getAddressSpace() != LangAS::opencl_private && 7916 // If we are parsing a template we didn't deduce an addr 7917 // space yet. 7918 T.getAddressSpace() != LangAS::Default) { 7919 // Do not allow other address spaces on automatic variable. 7920 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7921 NewVD->setInvalidDecl(); 7922 return; 7923 } 7924 } 7925 } 7926 7927 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7928 && !NewVD->hasAttr<BlocksAttr>()) { 7929 if (getLangOpts().getGC() != LangOptions::NonGC) 7930 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7931 else { 7932 assert(!getLangOpts().ObjCAutoRefCount); 7933 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7934 } 7935 } 7936 7937 bool isVM = T->isVariablyModifiedType(); 7938 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7939 NewVD->hasAttr<BlocksAttr>()) 7940 setFunctionHasBranchProtectedScope(); 7941 7942 if ((isVM && NewVD->hasLinkage()) || 7943 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7944 bool SizeIsNegative; 7945 llvm::APSInt Oversized; 7946 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7947 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7948 QualType FixedT; 7949 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7950 FixedT = FixedTInfo->getType(); 7951 else if (FixedTInfo) { 7952 // Type and type-as-written are canonically different. We need to fix up 7953 // both types separately. 7954 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7955 Oversized); 7956 } 7957 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7958 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7959 // FIXME: This won't give the correct result for 7960 // int a[10][n]; 7961 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7962 7963 if (NewVD->isFileVarDecl()) 7964 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7965 << SizeRange; 7966 else if (NewVD->isStaticLocal()) 7967 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7968 << SizeRange; 7969 else 7970 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7971 << SizeRange; 7972 NewVD->setInvalidDecl(); 7973 return; 7974 } 7975 7976 if (!FixedTInfo) { 7977 if (NewVD->isFileVarDecl()) 7978 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7979 else 7980 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7981 NewVD->setInvalidDecl(); 7982 return; 7983 } 7984 7985 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7986 NewVD->setType(FixedT); 7987 NewVD->setTypeSourceInfo(FixedTInfo); 7988 } 7989 7990 if (T->isVoidType()) { 7991 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7992 // of objects and functions. 7993 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7994 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7995 << T; 7996 NewVD->setInvalidDecl(); 7997 return; 7998 } 7999 } 8000 8001 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8002 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8003 NewVD->setInvalidDecl(); 8004 return; 8005 } 8006 8007 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8008 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8009 NewVD->setInvalidDecl(); 8010 return; 8011 } 8012 8013 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8014 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8015 NewVD->setInvalidDecl(); 8016 return; 8017 } 8018 8019 if (NewVD->isConstexpr() && !T->isDependentType() && 8020 RequireLiteralType(NewVD->getLocation(), T, 8021 diag::err_constexpr_var_non_literal)) { 8022 NewVD->setInvalidDecl(); 8023 return; 8024 } 8025 } 8026 8027 /// Perform semantic checking on a newly-created variable 8028 /// declaration. 8029 /// 8030 /// This routine performs all of the type-checking required for a 8031 /// variable declaration once it has been built. It is used both to 8032 /// check variables after they have been parsed and their declarators 8033 /// have been translated into a declaration, and to check variables 8034 /// that have been instantiated from a template. 8035 /// 8036 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8037 /// 8038 /// Returns true if the variable declaration is a redeclaration. 8039 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8040 CheckVariableDeclarationType(NewVD); 8041 8042 // If the decl is already known invalid, don't check it. 8043 if (NewVD->isInvalidDecl()) 8044 return false; 8045 8046 // If we did not find anything by this name, look for a non-visible 8047 // extern "C" declaration with the same name. 8048 if (Previous.empty() && 8049 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8050 Previous.setShadowed(); 8051 8052 if (!Previous.empty()) { 8053 MergeVarDecl(NewVD, Previous); 8054 return true; 8055 } 8056 return false; 8057 } 8058 8059 namespace { 8060 struct FindOverriddenMethod { 8061 Sema *S; 8062 CXXMethodDecl *Method; 8063 8064 /// Member lookup function that determines whether a given C++ 8065 /// method overrides a method in a base class, to be used with 8066 /// CXXRecordDecl::lookupInBases(). 8067 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8068 RecordDecl *BaseRecord = 8069 Specifier->getType()->castAs<RecordType>()->getDecl(); 8070 8071 DeclarationName Name = Method->getDeclName(); 8072 8073 // FIXME: Do we care about other names here too? 8074 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8075 // We really want to find the base class destructor here. 8076 QualType T = S->Context.getTypeDeclType(BaseRecord); 8077 CanQualType CT = S->Context.getCanonicalType(T); 8078 8079 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8080 } 8081 8082 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8083 Path.Decls = Path.Decls.slice(1)) { 8084 NamedDecl *D = Path.Decls.front(); 8085 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8086 if (MD->isVirtual() && 8087 !S->IsOverload( 8088 Method, MD, /*UseMemberUsingDeclRules=*/false, 8089 /*ConsiderCudaAttrs=*/true, 8090 // C++2a [class.virtual]p2 does not consider requires clauses 8091 // when overriding. 8092 /*ConsiderRequiresClauses=*/false)) 8093 return true; 8094 } 8095 } 8096 8097 return false; 8098 } 8099 }; 8100 } // end anonymous namespace 8101 8102 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8103 /// and if so, check that it's a valid override and remember it. 8104 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8105 // Look for methods in base classes that this method might override. 8106 CXXBasePaths Paths; 8107 FindOverriddenMethod FOM; 8108 FOM.Method = MD; 8109 FOM.S = this; 8110 bool AddedAny = false; 8111 if (DC->lookupInBases(FOM, Paths)) { 8112 for (auto *I : Paths.found_decls()) { 8113 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8114 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8115 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8116 !CheckOverridingFunctionAttributes(MD, OldMD) && 8117 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8118 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8119 AddedAny = true; 8120 } 8121 } 8122 } 8123 } 8124 8125 return AddedAny; 8126 } 8127 8128 namespace { 8129 // Struct for holding all of the extra arguments needed by 8130 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8131 struct ActOnFDArgs { 8132 Scope *S; 8133 Declarator &D; 8134 MultiTemplateParamsArg TemplateParamLists; 8135 bool AddToScope; 8136 }; 8137 } // end anonymous namespace 8138 8139 namespace { 8140 8141 // Callback to only accept typo corrections that have a non-zero edit distance. 8142 // Also only accept corrections that have the same parent decl. 8143 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8144 public: 8145 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8146 CXXRecordDecl *Parent) 8147 : Context(Context), OriginalFD(TypoFD), 8148 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8149 8150 bool ValidateCandidate(const TypoCorrection &candidate) override { 8151 if (candidate.getEditDistance() == 0) 8152 return false; 8153 8154 SmallVector<unsigned, 1> MismatchedParams; 8155 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8156 CDeclEnd = candidate.end(); 8157 CDecl != CDeclEnd; ++CDecl) { 8158 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8159 8160 if (FD && !FD->hasBody() && 8161 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8162 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8163 CXXRecordDecl *Parent = MD->getParent(); 8164 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8165 return true; 8166 } else if (!ExpectedParent) { 8167 return true; 8168 } 8169 } 8170 } 8171 8172 return false; 8173 } 8174 8175 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8176 return std::make_unique<DifferentNameValidatorCCC>(*this); 8177 } 8178 8179 private: 8180 ASTContext &Context; 8181 FunctionDecl *OriginalFD; 8182 CXXRecordDecl *ExpectedParent; 8183 }; 8184 8185 } // end anonymous namespace 8186 8187 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8188 TypoCorrectedFunctionDefinitions.insert(F); 8189 } 8190 8191 /// Generate diagnostics for an invalid function redeclaration. 8192 /// 8193 /// This routine handles generating the diagnostic messages for an invalid 8194 /// function redeclaration, including finding possible similar declarations 8195 /// or performing typo correction if there are no previous declarations with 8196 /// the same name. 8197 /// 8198 /// Returns a NamedDecl iff typo correction was performed and substituting in 8199 /// the new declaration name does not cause new errors. 8200 static NamedDecl *DiagnoseInvalidRedeclaration( 8201 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8202 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8203 DeclarationName Name = NewFD->getDeclName(); 8204 DeclContext *NewDC = NewFD->getDeclContext(); 8205 SmallVector<unsigned, 1> MismatchedParams; 8206 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8207 TypoCorrection Correction; 8208 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8209 unsigned DiagMsg = 8210 IsLocalFriend ? diag::err_no_matching_local_friend : 8211 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8212 diag::err_member_decl_does_not_match; 8213 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8214 IsLocalFriend ? Sema::LookupLocalFriendName 8215 : Sema::LookupOrdinaryName, 8216 Sema::ForVisibleRedeclaration); 8217 8218 NewFD->setInvalidDecl(); 8219 if (IsLocalFriend) 8220 SemaRef.LookupName(Prev, S); 8221 else 8222 SemaRef.LookupQualifiedName(Prev, NewDC); 8223 assert(!Prev.isAmbiguous() && 8224 "Cannot have an ambiguity in previous-declaration lookup"); 8225 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8226 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8227 MD ? MD->getParent() : nullptr); 8228 if (!Prev.empty()) { 8229 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8230 Func != FuncEnd; ++Func) { 8231 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8232 if (FD && 8233 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8234 // Add 1 to the index so that 0 can mean the mismatch didn't 8235 // involve a parameter 8236 unsigned ParamNum = 8237 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8238 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8239 } 8240 } 8241 // If the qualified name lookup yielded nothing, try typo correction 8242 } else if ((Correction = SemaRef.CorrectTypo( 8243 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8244 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8245 IsLocalFriend ? nullptr : NewDC))) { 8246 // Set up everything for the call to ActOnFunctionDeclarator 8247 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8248 ExtraArgs.D.getIdentifierLoc()); 8249 Previous.clear(); 8250 Previous.setLookupName(Correction.getCorrection()); 8251 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8252 CDeclEnd = Correction.end(); 8253 CDecl != CDeclEnd; ++CDecl) { 8254 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8255 if (FD && !FD->hasBody() && 8256 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8257 Previous.addDecl(FD); 8258 } 8259 } 8260 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8261 8262 NamedDecl *Result; 8263 // Retry building the function declaration with the new previous 8264 // declarations, and with errors suppressed. 8265 { 8266 // Trap errors. 8267 Sema::SFINAETrap Trap(SemaRef); 8268 8269 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8270 // pieces need to verify the typo-corrected C++ declaration and hopefully 8271 // eliminate the need for the parameter pack ExtraArgs. 8272 Result = SemaRef.ActOnFunctionDeclarator( 8273 ExtraArgs.S, ExtraArgs.D, 8274 Correction.getCorrectionDecl()->getDeclContext(), 8275 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8276 ExtraArgs.AddToScope); 8277 8278 if (Trap.hasErrorOccurred()) 8279 Result = nullptr; 8280 } 8281 8282 if (Result) { 8283 // Determine which correction we picked. 8284 Decl *Canonical = Result->getCanonicalDecl(); 8285 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8286 I != E; ++I) 8287 if ((*I)->getCanonicalDecl() == Canonical) 8288 Correction.setCorrectionDecl(*I); 8289 8290 // Let Sema know about the correction. 8291 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8292 SemaRef.diagnoseTypo( 8293 Correction, 8294 SemaRef.PDiag(IsLocalFriend 8295 ? diag::err_no_matching_local_friend_suggest 8296 : diag::err_member_decl_does_not_match_suggest) 8297 << Name << NewDC << IsDefinition); 8298 return Result; 8299 } 8300 8301 // Pretend the typo correction never occurred 8302 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8303 ExtraArgs.D.getIdentifierLoc()); 8304 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8305 Previous.clear(); 8306 Previous.setLookupName(Name); 8307 } 8308 8309 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8310 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8311 8312 bool NewFDisConst = false; 8313 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8314 NewFDisConst = NewMD->isConst(); 8315 8316 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8317 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8318 NearMatch != NearMatchEnd; ++NearMatch) { 8319 FunctionDecl *FD = NearMatch->first; 8320 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8321 bool FDisConst = MD && MD->isConst(); 8322 bool IsMember = MD || !IsLocalFriend; 8323 8324 // FIXME: These notes are poorly worded for the local friend case. 8325 if (unsigned Idx = NearMatch->second) { 8326 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8327 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8328 if (Loc.isInvalid()) Loc = FD->getLocation(); 8329 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8330 : diag::note_local_decl_close_param_match) 8331 << Idx << FDParam->getType() 8332 << NewFD->getParamDecl(Idx - 1)->getType(); 8333 } else if (FDisConst != NewFDisConst) { 8334 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8335 << NewFDisConst << FD->getSourceRange().getEnd(); 8336 } else 8337 SemaRef.Diag(FD->getLocation(), 8338 IsMember ? diag::note_member_def_close_match 8339 : diag::note_local_decl_close_match); 8340 } 8341 return nullptr; 8342 } 8343 8344 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8345 switch (D.getDeclSpec().getStorageClassSpec()) { 8346 default: llvm_unreachable("Unknown storage class!"); 8347 case DeclSpec::SCS_auto: 8348 case DeclSpec::SCS_register: 8349 case DeclSpec::SCS_mutable: 8350 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8351 diag::err_typecheck_sclass_func); 8352 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8353 D.setInvalidType(); 8354 break; 8355 case DeclSpec::SCS_unspecified: break; 8356 case DeclSpec::SCS_extern: 8357 if (D.getDeclSpec().isExternInLinkageSpec()) 8358 return SC_None; 8359 return SC_Extern; 8360 case DeclSpec::SCS_static: { 8361 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8362 // C99 6.7.1p5: 8363 // The declaration of an identifier for a function that has 8364 // block scope shall have no explicit storage-class specifier 8365 // other than extern 8366 // See also (C++ [dcl.stc]p4). 8367 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8368 diag::err_static_block_func); 8369 break; 8370 } else 8371 return SC_Static; 8372 } 8373 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8374 } 8375 8376 // No explicit storage class has already been returned 8377 return SC_None; 8378 } 8379 8380 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8381 DeclContext *DC, QualType &R, 8382 TypeSourceInfo *TInfo, 8383 StorageClass SC, 8384 bool &IsVirtualOkay) { 8385 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8386 DeclarationName Name = NameInfo.getName(); 8387 8388 FunctionDecl *NewFD = nullptr; 8389 bool isInline = D.getDeclSpec().isInlineSpecified(); 8390 8391 if (!SemaRef.getLangOpts().CPlusPlus) { 8392 // Determine whether the function was written with a 8393 // prototype. This true when: 8394 // - there is a prototype in the declarator, or 8395 // - the type R of the function is some kind of typedef or other non- 8396 // attributed reference to a type name (which eventually refers to a 8397 // function type). 8398 bool HasPrototype = 8399 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8400 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8401 8402 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8403 R, TInfo, SC, isInline, HasPrototype, 8404 CSK_unspecified, 8405 /*TrailingRequiresClause=*/nullptr); 8406 if (D.isInvalidType()) 8407 NewFD->setInvalidDecl(); 8408 8409 return NewFD; 8410 } 8411 8412 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8413 8414 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8415 if (ConstexprKind == CSK_constinit) { 8416 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8417 diag::err_constexpr_wrong_decl_kind) 8418 << ConstexprKind; 8419 ConstexprKind = CSK_unspecified; 8420 D.getMutableDeclSpec().ClearConstexprSpec(); 8421 } 8422 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8423 8424 // Check that the return type is not an abstract class type. 8425 // For record types, this is done by the AbstractClassUsageDiagnoser once 8426 // the class has been completely parsed. 8427 if (!DC->isRecord() && 8428 SemaRef.RequireNonAbstractType( 8429 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8430 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8431 D.setInvalidType(); 8432 8433 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8434 // This is a C++ constructor declaration. 8435 assert(DC->isRecord() && 8436 "Constructors can only be declared in a member context"); 8437 8438 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8439 return CXXConstructorDecl::Create( 8440 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8441 TInfo, ExplicitSpecifier, isInline, 8442 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8443 TrailingRequiresClause); 8444 8445 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8446 // This is a C++ destructor declaration. 8447 if (DC->isRecord()) { 8448 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8449 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8450 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8451 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8452 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8453 TrailingRequiresClause); 8454 8455 // If the destructor needs an implicit exception specification, set it 8456 // now. FIXME: It'd be nice to be able to create the right type to start 8457 // with, but the type needs to reference the destructor declaration. 8458 if (SemaRef.getLangOpts().CPlusPlus11) 8459 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8460 8461 IsVirtualOkay = true; 8462 return NewDD; 8463 8464 } else { 8465 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8466 D.setInvalidType(); 8467 8468 // Create a FunctionDecl to satisfy the function definition parsing 8469 // code path. 8470 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8471 D.getIdentifierLoc(), Name, R, TInfo, SC, 8472 isInline, 8473 /*hasPrototype=*/true, ConstexprKind, 8474 TrailingRequiresClause); 8475 } 8476 8477 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8478 if (!DC->isRecord()) { 8479 SemaRef.Diag(D.getIdentifierLoc(), 8480 diag::err_conv_function_not_member); 8481 return nullptr; 8482 } 8483 8484 SemaRef.CheckConversionDeclarator(D, R, SC); 8485 if (D.isInvalidType()) 8486 return nullptr; 8487 8488 IsVirtualOkay = true; 8489 return CXXConversionDecl::Create( 8490 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8491 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8492 TrailingRequiresClause); 8493 8494 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8495 if (TrailingRequiresClause) 8496 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8497 diag::err_trailing_requires_clause_on_deduction_guide) 8498 << TrailingRequiresClause->getSourceRange(); 8499 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8500 8501 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8502 ExplicitSpecifier, NameInfo, R, TInfo, 8503 D.getEndLoc()); 8504 } else if (DC->isRecord()) { 8505 // If the name of the function is the same as the name of the record, 8506 // then this must be an invalid constructor that has a return type. 8507 // (The parser checks for a return type and makes the declarator a 8508 // constructor if it has no return type). 8509 if (Name.getAsIdentifierInfo() && 8510 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8511 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8512 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8513 << SourceRange(D.getIdentifierLoc()); 8514 return nullptr; 8515 } 8516 8517 // This is a C++ method declaration. 8518 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8519 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8520 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8521 TrailingRequiresClause); 8522 IsVirtualOkay = !Ret->isStatic(); 8523 return Ret; 8524 } else { 8525 bool isFriend = 8526 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8527 if (!isFriend && SemaRef.CurContext->isRecord()) 8528 return nullptr; 8529 8530 // Determine whether the function was written with a 8531 // prototype. This true when: 8532 // - we're in C++ (where every function has a prototype), 8533 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8534 R, TInfo, SC, isInline, true /*HasPrototype*/, 8535 ConstexprKind, TrailingRequiresClause); 8536 } 8537 } 8538 8539 enum OpenCLParamType { 8540 ValidKernelParam, 8541 PtrPtrKernelParam, 8542 PtrKernelParam, 8543 InvalidAddrSpacePtrKernelParam, 8544 InvalidKernelParam, 8545 RecordKernelParam 8546 }; 8547 8548 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8549 // Size dependent types are just typedefs to normal integer types 8550 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8551 // integers other than by their names. 8552 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8553 8554 // Remove typedefs one by one until we reach a typedef 8555 // for a size dependent type. 8556 QualType DesugaredTy = Ty; 8557 do { 8558 ArrayRef<StringRef> Names(SizeTypeNames); 8559 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8560 if (Names.end() != Match) 8561 return true; 8562 8563 Ty = DesugaredTy; 8564 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8565 } while (DesugaredTy != Ty); 8566 8567 return false; 8568 } 8569 8570 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8571 if (PT->isPointerType()) { 8572 QualType PointeeType = PT->getPointeeType(); 8573 if (PointeeType->isPointerType()) 8574 return PtrPtrKernelParam; 8575 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8576 PointeeType.getAddressSpace() == LangAS::opencl_private || 8577 PointeeType.getAddressSpace() == LangAS::Default) 8578 return InvalidAddrSpacePtrKernelParam; 8579 return PtrKernelParam; 8580 } 8581 8582 // OpenCL v1.2 s6.9.k: 8583 // Arguments to kernel functions in a program cannot be declared with the 8584 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8585 // uintptr_t or a struct and/or union that contain fields declared to be one 8586 // of these built-in scalar types. 8587 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8588 return InvalidKernelParam; 8589 8590 if (PT->isImageType()) 8591 return PtrKernelParam; 8592 8593 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8594 return InvalidKernelParam; 8595 8596 // OpenCL extension spec v1.2 s9.5: 8597 // This extension adds support for half scalar and vector types as built-in 8598 // types that can be used for arithmetic operations, conversions etc. 8599 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8600 return InvalidKernelParam; 8601 8602 if (PT->isRecordType()) 8603 return RecordKernelParam; 8604 8605 // Look into an array argument to check if it has a forbidden type. 8606 if (PT->isArrayType()) { 8607 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8608 // Call ourself to check an underlying type of an array. Since the 8609 // getPointeeOrArrayElementType returns an innermost type which is not an 8610 // array, this recursive call only happens once. 8611 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8612 } 8613 8614 return ValidKernelParam; 8615 } 8616 8617 static void checkIsValidOpenCLKernelParameter( 8618 Sema &S, 8619 Declarator &D, 8620 ParmVarDecl *Param, 8621 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8622 QualType PT = Param->getType(); 8623 8624 // Cache the valid types we encounter to avoid rechecking structs that are 8625 // used again 8626 if (ValidTypes.count(PT.getTypePtr())) 8627 return; 8628 8629 switch (getOpenCLKernelParameterType(S, PT)) { 8630 case PtrPtrKernelParam: 8631 // OpenCL v1.2 s6.9.a: 8632 // A kernel function argument cannot be declared as a 8633 // pointer to a pointer type. 8634 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8635 D.setInvalidType(); 8636 return; 8637 8638 case InvalidAddrSpacePtrKernelParam: 8639 // OpenCL v1.0 s6.5: 8640 // __kernel function arguments declared to be a pointer of a type can point 8641 // to one of the following address spaces only : __global, __local or 8642 // __constant. 8643 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8644 D.setInvalidType(); 8645 return; 8646 8647 // OpenCL v1.2 s6.9.k: 8648 // Arguments to kernel functions in a program cannot be declared with the 8649 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8650 // uintptr_t or a struct and/or union that contain fields declared to be 8651 // one of these built-in scalar types. 8652 8653 case InvalidKernelParam: 8654 // OpenCL v1.2 s6.8 n: 8655 // A kernel function argument cannot be declared 8656 // of event_t type. 8657 // Do not diagnose half type since it is diagnosed as invalid argument 8658 // type for any function elsewhere. 8659 if (!PT->isHalfType()) { 8660 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8661 8662 // Explain what typedefs are involved. 8663 const TypedefType *Typedef = nullptr; 8664 while ((Typedef = PT->getAs<TypedefType>())) { 8665 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8666 // SourceLocation may be invalid for a built-in type. 8667 if (Loc.isValid()) 8668 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8669 PT = Typedef->desugar(); 8670 } 8671 } 8672 8673 D.setInvalidType(); 8674 return; 8675 8676 case PtrKernelParam: 8677 case ValidKernelParam: 8678 ValidTypes.insert(PT.getTypePtr()); 8679 return; 8680 8681 case RecordKernelParam: 8682 break; 8683 } 8684 8685 // Track nested structs we will inspect 8686 SmallVector<const Decl *, 4> VisitStack; 8687 8688 // Track where we are in the nested structs. Items will migrate from 8689 // VisitStack to HistoryStack as we do the DFS for bad field. 8690 SmallVector<const FieldDecl *, 4> HistoryStack; 8691 HistoryStack.push_back(nullptr); 8692 8693 // At this point we already handled everything except of a RecordType or 8694 // an ArrayType of a RecordType. 8695 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8696 const RecordType *RecTy = 8697 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8698 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8699 8700 VisitStack.push_back(RecTy->getDecl()); 8701 assert(VisitStack.back() && "First decl null?"); 8702 8703 do { 8704 const Decl *Next = VisitStack.pop_back_val(); 8705 if (!Next) { 8706 assert(!HistoryStack.empty()); 8707 // Found a marker, we have gone up a level 8708 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8709 ValidTypes.insert(Hist->getType().getTypePtr()); 8710 8711 continue; 8712 } 8713 8714 // Adds everything except the original parameter declaration (which is not a 8715 // field itself) to the history stack. 8716 const RecordDecl *RD; 8717 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8718 HistoryStack.push_back(Field); 8719 8720 QualType FieldTy = Field->getType(); 8721 // Other field types (known to be valid or invalid) are handled while we 8722 // walk around RecordDecl::fields(). 8723 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8724 "Unexpected type."); 8725 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8726 8727 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8728 } else { 8729 RD = cast<RecordDecl>(Next); 8730 } 8731 8732 // Add a null marker so we know when we've gone back up a level 8733 VisitStack.push_back(nullptr); 8734 8735 for (const auto *FD : RD->fields()) { 8736 QualType QT = FD->getType(); 8737 8738 if (ValidTypes.count(QT.getTypePtr())) 8739 continue; 8740 8741 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8742 if (ParamType == ValidKernelParam) 8743 continue; 8744 8745 if (ParamType == RecordKernelParam) { 8746 VisitStack.push_back(FD); 8747 continue; 8748 } 8749 8750 // OpenCL v1.2 s6.9.p: 8751 // Arguments to kernel functions that are declared to be a struct or union 8752 // do not allow OpenCL objects to be passed as elements of the struct or 8753 // union. 8754 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8755 ParamType == InvalidAddrSpacePtrKernelParam) { 8756 S.Diag(Param->getLocation(), 8757 diag::err_record_with_pointers_kernel_param) 8758 << PT->isUnionType() 8759 << PT; 8760 } else { 8761 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8762 } 8763 8764 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8765 << OrigRecDecl->getDeclName(); 8766 8767 // We have an error, now let's go back up through history and show where 8768 // the offending field came from 8769 for (ArrayRef<const FieldDecl *>::const_iterator 8770 I = HistoryStack.begin() + 1, 8771 E = HistoryStack.end(); 8772 I != E; ++I) { 8773 const FieldDecl *OuterField = *I; 8774 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8775 << OuterField->getType(); 8776 } 8777 8778 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8779 << QT->isPointerType() 8780 << QT; 8781 D.setInvalidType(); 8782 return; 8783 } 8784 } while (!VisitStack.empty()); 8785 } 8786 8787 /// Find the DeclContext in which a tag is implicitly declared if we see an 8788 /// elaborated type specifier in the specified context, and lookup finds 8789 /// nothing. 8790 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8791 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8792 DC = DC->getParent(); 8793 return DC; 8794 } 8795 8796 /// Find the Scope in which a tag is implicitly declared if we see an 8797 /// elaborated type specifier in the specified context, and lookup finds 8798 /// nothing. 8799 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8800 while (S->isClassScope() || 8801 (LangOpts.CPlusPlus && 8802 S->isFunctionPrototypeScope()) || 8803 ((S->getFlags() & Scope::DeclScope) == 0) || 8804 (S->getEntity() && S->getEntity()->isTransparentContext())) 8805 S = S->getParent(); 8806 return S; 8807 } 8808 8809 NamedDecl* 8810 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8811 TypeSourceInfo *TInfo, LookupResult &Previous, 8812 MultiTemplateParamsArg TemplateParamListsRef, 8813 bool &AddToScope) { 8814 QualType R = TInfo->getType(); 8815 8816 assert(R->isFunctionType()); 8817 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8818 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8819 8820 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8821 for (TemplateParameterList *TPL : TemplateParamListsRef) 8822 TemplateParamLists.push_back(TPL); 8823 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8824 if (!TemplateParamLists.empty() && 8825 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8826 TemplateParamLists.back() = Invented; 8827 else 8828 TemplateParamLists.push_back(Invented); 8829 } 8830 8831 // TODO: consider using NameInfo for diagnostic. 8832 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8833 DeclarationName Name = NameInfo.getName(); 8834 StorageClass SC = getFunctionStorageClass(*this, D); 8835 8836 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8837 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8838 diag::err_invalid_thread) 8839 << DeclSpec::getSpecifierName(TSCS); 8840 8841 if (D.isFirstDeclarationOfMember()) 8842 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8843 D.getIdentifierLoc()); 8844 8845 bool isFriend = false; 8846 FunctionTemplateDecl *FunctionTemplate = nullptr; 8847 bool isMemberSpecialization = false; 8848 bool isFunctionTemplateSpecialization = false; 8849 8850 bool isDependentClassScopeExplicitSpecialization = false; 8851 bool HasExplicitTemplateArgs = false; 8852 TemplateArgumentListInfo TemplateArgs; 8853 8854 bool isVirtualOkay = false; 8855 8856 DeclContext *OriginalDC = DC; 8857 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8858 8859 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8860 isVirtualOkay); 8861 if (!NewFD) return nullptr; 8862 8863 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8864 NewFD->setTopLevelDeclInObjCContainer(); 8865 8866 // Set the lexical context. If this is a function-scope declaration, or has a 8867 // C++ scope specifier, or is the object of a friend declaration, the lexical 8868 // context will be different from the semantic context. 8869 NewFD->setLexicalDeclContext(CurContext); 8870 8871 if (IsLocalExternDecl) 8872 NewFD->setLocalExternDecl(); 8873 8874 if (getLangOpts().CPlusPlus) { 8875 bool isInline = D.getDeclSpec().isInlineSpecified(); 8876 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8877 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8878 isFriend = D.getDeclSpec().isFriendSpecified(); 8879 if (isFriend && !isInline && D.isFunctionDefinition()) { 8880 // C++ [class.friend]p5 8881 // A function can be defined in a friend declaration of a 8882 // class . . . . Such a function is implicitly inline. 8883 NewFD->setImplicitlyInline(); 8884 } 8885 8886 // If this is a method defined in an __interface, and is not a constructor 8887 // or an overloaded operator, then set the pure flag (isVirtual will already 8888 // return true). 8889 if (const CXXRecordDecl *Parent = 8890 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8891 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8892 NewFD->setPure(true); 8893 8894 // C++ [class.union]p2 8895 // A union can have member functions, but not virtual functions. 8896 if (isVirtual && Parent->isUnion()) 8897 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8898 } 8899 8900 SetNestedNameSpecifier(*this, NewFD, D); 8901 isMemberSpecialization = false; 8902 isFunctionTemplateSpecialization = false; 8903 if (D.isInvalidType()) 8904 NewFD->setInvalidDecl(); 8905 8906 // Match up the template parameter lists with the scope specifier, then 8907 // determine whether we have a template or a template specialization. 8908 bool Invalid = false; 8909 TemplateParameterList *TemplateParams = 8910 MatchTemplateParametersToScopeSpecifier( 8911 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8912 D.getCXXScopeSpec(), 8913 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8914 ? D.getName().TemplateId 8915 : nullptr, 8916 TemplateParamLists, isFriend, isMemberSpecialization, 8917 Invalid); 8918 if (TemplateParams) { 8919 // Check that we can declare a template here. 8920 if (CheckTemplateDeclScope(S, TemplateParams)) 8921 NewFD->setInvalidDecl(); 8922 8923 if (TemplateParams->size() > 0) { 8924 // This is a function template 8925 8926 // A destructor cannot be a template. 8927 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8928 Diag(NewFD->getLocation(), diag::err_destructor_template); 8929 NewFD->setInvalidDecl(); 8930 } 8931 8932 // If we're adding a template to a dependent context, we may need to 8933 // rebuilding some of the types used within the template parameter list, 8934 // now that we know what the current instantiation is. 8935 if (DC->isDependentContext()) { 8936 ContextRAII SavedContext(*this, DC); 8937 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8938 Invalid = true; 8939 } 8940 8941 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8942 NewFD->getLocation(), 8943 Name, TemplateParams, 8944 NewFD); 8945 FunctionTemplate->setLexicalDeclContext(CurContext); 8946 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8947 8948 // For source fidelity, store the other template param lists. 8949 if (TemplateParamLists.size() > 1) { 8950 NewFD->setTemplateParameterListsInfo(Context, 8951 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8952 .drop_back(1)); 8953 } 8954 } else { 8955 // This is a function template specialization. 8956 isFunctionTemplateSpecialization = true; 8957 // For source fidelity, store all the template param lists. 8958 if (TemplateParamLists.size() > 0) 8959 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8960 8961 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8962 if (isFriend) { 8963 // We want to remove the "template<>", found here. 8964 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8965 8966 // If we remove the template<> and the name is not a 8967 // template-id, we're actually silently creating a problem: 8968 // the friend declaration will refer to an untemplated decl, 8969 // and clearly the user wants a template specialization. So 8970 // we need to insert '<>' after the name. 8971 SourceLocation InsertLoc; 8972 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8973 InsertLoc = D.getName().getSourceRange().getEnd(); 8974 InsertLoc = getLocForEndOfToken(InsertLoc); 8975 } 8976 8977 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8978 << Name << RemoveRange 8979 << FixItHint::CreateRemoval(RemoveRange) 8980 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8981 } 8982 } 8983 } else { 8984 // Check that we can declare a template here. 8985 if (!TemplateParamLists.empty() && isMemberSpecialization && 8986 CheckTemplateDeclScope(S, TemplateParamLists.back())) 8987 NewFD->setInvalidDecl(); 8988 8989 // All template param lists were matched against the scope specifier: 8990 // this is NOT (an explicit specialization of) a template. 8991 if (TemplateParamLists.size() > 0) 8992 // For source fidelity, store all the template param lists. 8993 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8994 } 8995 8996 if (Invalid) { 8997 NewFD->setInvalidDecl(); 8998 if (FunctionTemplate) 8999 FunctionTemplate->setInvalidDecl(); 9000 } 9001 9002 // C++ [dcl.fct.spec]p5: 9003 // The virtual specifier shall only be used in declarations of 9004 // nonstatic class member functions that appear within a 9005 // member-specification of a class declaration; see 10.3. 9006 // 9007 if (isVirtual && !NewFD->isInvalidDecl()) { 9008 if (!isVirtualOkay) { 9009 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9010 diag::err_virtual_non_function); 9011 } else if (!CurContext->isRecord()) { 9012 // 'virtual' was specified outside of the class. 9013 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9014 diag::err_virtual_out_of_class) 9015 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9016 } else if (NewFD->getDescribedFunctionTemplate()) { 9017 // C++ [temp.mem]p3: 9018 // A member function template shall not be virtual. 9019 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9020 diag::err_virtual_member_function_template) 9021 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9022 } else { 9023 // Okay: Add virtual to the method. 9024 NewFD->setVirtualAsWritten(true); 9025 } 9026 9027 if (getLangOpts().CPlusPlus14 && 9028 NewFD->getReturnType()->isUndeducedType()) 9029 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9030 } 9031 9032 if (getLangOpts().CPlusPlus14 && 9033 (NewFD->isDependentContext() || 9034 (isFriend && CurContext->isDependentContext())) && 9035 NewFD->getReturnType()->isUndeducedType()) { 9036 // If the function template is referenced directly (for instance, as a 9037 // member of the current instantiation), pretend it has a dependent type. 9038 // This is not really justified by the standard, but is the only sane 9039 // thing to do. 9040 // FIXME: For a friend function, we have not marked the function as being 9041 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9042 const FunctionProtoType *FPT = 9043 NewFD->getType()->castAs<FunctionProtoType>(); 9044 QualType Result = 9045 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9046 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9047 FPT->getExtProtoInfo())); 9048 } 9049 9050 // C++ [dcl.fct.spec]p3: 9051 // The inline specifier shall not appear on a block scope function 9052 // declaration. 9053 if (isInline && !NewFD->isInvalidDecl()) { 9054 if (CurContext->isFunctionOrMethod()) { 9055 // 'inline' is not allowed on block scope function declaration. 9056 Diag(D.getDeclSpec().getInlineSpecLoc(), 9057 diag::err_inline_declaration_block_scope) << Name 9058 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9059 } 9060 } 9061 9062 // C++ [dcl.fct.spec]p6: 9063 // The explicit specifier shall be used only in the declaration of a 9064 // constructor or conversion function within its class definition; 9065 // see 12.3.1 and 12.3.2. 9066 if (hasExplicit && !NewFD->isInvalidDecl() && 9067 !isa<CXXDeductionGuideDecl>(NewFD)) { 9068 if (!CurContext->isRecord()) { 9069 // 'explicit' was specified outside of the class. 9070 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9071 diag::err_explicit_out_of_class) 9072 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9073 } else if (!isa<CXXConstructorDecl>(NewFD) && 9074 !isa<CXXConversionDecl>(NewFD)) { 9075 // 'explicit' was specified on a function that wasn't a constructor 9076 // or conversion function. 9077 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9078 diag::err_explicit_non_ctor_or_conv_function) 9079 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9080 } 9081 } 9082 9083 if (ConstexprSpecKind ConstexprKind = 9084 D.getDeclSpec().getConstexprSpecifier()) { 9085 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9086 // are implicitly inline. 9087 NewFD->setImplicitlyInline(); 9088 9089 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9090 // be either constructors or to return a literal type. Therefore, 9091 // destructors cannot be declared constexpr. 9092 if (isa<CXXDestructorDecl>(NewFD) && 9093 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9094 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9095 << ConstexprKind; 9096 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9097 } 9098 // C++20 [dcl.constexpr]p2: An allocation function, or a 9099 // deallocation function shall not be declared with the consteval 9100 // specifier. 9101 if (ConstexprKind == CSK_consteval && 9102 (NewFD->getOverloadedOperator() == OO_New || 9103 NewFD->getOverloadedOperator() == OO_Array_New || 9104 NewFD->getOverloadedOperator() == OO_Delete || 9105 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9106 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9107 diag::err_invalid_consteval_decl_kind) 9108 << NewFD; 9109 NewFD->setConstexprKind(CSK_constexpr); 9110 } 9111 } 9112 9113 // If __module_private__ was specified, mark the function accordingly. 9114 if (D.getDeclSpec().isModulePrivateSpecified()) { 9115 if (isFunctionTemplateSpecialization) { 9116 SourceLocation ModulePrivateLoc 9117 = D.getDeclSpec().getModulePrivateSpecLoc(); 9118 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9119 << 0 9120 << FixItHint::CreateRemoval(ModulePrivateLoc); 9121 } else { 9122 NewFD->setModulePrivate(); 9123 if (FunctionTemplate) 9124 FunctionTemplate->setModulePrivate(); 9125 } 9126 } 9127 9128 if (isFriend) { 9129 if (FunctionTemplate) { 9130 FunctionTemplate->setObjectOfFriendDecl(); 9131 FunctionTemplate->setAccess(AS_public); 9132 } 9133 NewFD->setObjectOfFriendDecl(); 9134 NewFD->setAccess(AS_public); 9135 } 9136 9137 // If a function is defined as defaulted or deleted, mark it as such now. 9138 // We'll do the relevant checks on defaulted / deleted functions later. 9139 switch (D.getFunctionDefinitionKind()) { 9140 case FDK_Declaration: 9141 case FDK_Definition: 9142 break; 9143 9144 case FDK_Defaulted: 9145 NewFD->setDefaulted(); 9146 break; 9147 9148 case FDK_Deleted: 9149 NewFD->setDeletedAsWritten(); 9150 break; 9151 } 9152 9153 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9154 D.isFunctionDefinition()) { 9155 // C++ [class.mfct]p2: 9156 // A member function may be defined (8.4) in its class definition, in 9157 // which case it is an inline member function (7.1.2) 9158 NewFD->setImplicitlyInline(); 9159 } 9160 9161 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9162 !CurContext->isRecord()) { 9163 // C++ [class.static]p1: 9164 // A data or function member of a class may be declared static 9165 // in a class definition, in which case it is a static member of 9166 // the class. 9167 9168 // Complain about the 'static' specifier if it's on an out-of-line 9169 // member function definition. 9170 9171 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9172 // member function template declaration and class member template 9173 // declaration (MSVC versions before 2015), warn about this. 9174 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9175 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9176 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9177 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9178 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9179 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9180 } 9181 9182 // C++11 [except.spec]p15: 9183 // A deallocation function with no exception-specification is treated 9184 // as if it were specified with noexcept(true). 9185 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9186 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9187 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9188 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9189 NewFD->setType(Context.getFunctionType( 9190 FPT->getReturnType(), FPT->getParamTypes(), 9191 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9192 } 9193 9194 // Filter out previous declarations that don't match the scope. 9195 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9196 D.getCXXScopeSpec().isNotEmpty() || 9197 isMemberSpecialization || 9198 isFunctionTemplateSpecialization); 9199 9200 // Handle GNU asm-label extension (encoded as an attribute). 9201 if (Expr *E = (Expr*) D.getAsmLabel()) { 9202 // The parser guarantees this is a string. 9203 StringLiteral *SE = cast<StringLiteral>(E); 9204 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9205 /*IsLiteralLabel=*/true, 9206 SE->getStrTokenLoc(0))); 9207 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9208 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9209 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9210 if (I != ExtnameUndeclaredIdentifiers.end()) { 9211 if (isDeclExternC(NewFD)) { 9212 NewFD->addAttr(I->second); 9213 ExtnameUndeclaredIdentifiers.erase(I); 9214 } else 9215 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9216 << /*Variable*/0 << NewFD; 9217 } 9218 } 9219 9220 // Copy the parameter declarations from the declarator D to the function 9221 // declaration NewFD, if they are available. First scavenge them into Params. 9222 SmallVector<ParmVarDecl*, 16> Params; 9223 unsigned FTIIdx; 9224 if (D.isFunctionDeclarator(FTIIdx)) { 9225 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9226 9227 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9228 // function that takes no arguments, not a function that takes a 9229 // single void argument. 9230 // We let through "const void" here because Sema::GetTypeForDeclarator 9231 // already checks for that case. 9232 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9233 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9234 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9235 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9236 Param->setDeclContext(NewFD); 9237 Params.push_back(Param); 9238 9239 if (Param->isInvalidDecl()) 9240 NewFD->setInvalidDecl(); 9241 } 9242 } 9243 9244 if (!getLangOpts().CPlusPlus) { 9245 // In C, find all the tag declarations from the prototype and move them 9246 // into the function DeclContext. Remove them from the surrounding tag 9247 // injection context of the function, which is typically but not always 9248 // the TU. 9249 DeclContext *PrototypeTagContext = 9250 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9251 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9252 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9253 9254 // We don't want to reparent enumerators. Look at their parent enum 9255 // instead. 9256 if (!TD) { 9257 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9258 TD = cast<EnumDecl>(ECD->getDeclContext()); 9259 } 9260 if (!TD) 9261 continue; 9262 DeclContext *TagDC = TD->getLexicalDeclContext(); 9263 if (!TagDC->containsDecl(TD)) 9264 continue; 9265 TagDC->removeDecl(TD); 9266 TD->setDeclContext(NewFD); 9267 NewFD->addDecl(TD); 9268 9269 // Preserve the lexical DeclContext if it is not the surrounding tag 9270 // injection context of the FD. In this example, the semantic context of 9271 // E will be f and the lexical context will be S, while both the 9272 // semantic and lexical contexts of S will be f: 9273 // void f(struct S { enum E { a } f; } s); 9274 if (TagDC != PrototypeTagContext) 9275 TD->setLexicalDeclContext(TagDC); 9276 } 9277 } 9278 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9279 // When we're declaring a function with a typedef, typeof, etc as in the 9280 // following example, we'll need to synthesize (unnamed) 9281 // parameters for use in the declaration. 9282 // 9283 // @code 9284 // typedef void fn(int); 9285 // fn f; 9286 // @endcode 9287 9288 // Synthesize a parameter for each argument type. 9289 for (const auto &AI : FT->param_types()) { 9290 ParmVarDecl *Param = 9291 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9292 Param->setScopeInfo(0, Params.size()); 9293 Params.push_back(Param); 9294 } 9295 } else { 9296 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9297 "Should not need args for typedef of non-prototype fn"); 9298 } 9299 9300 // Finally, we know we have the right number of parameters, install them. 9301 NewFD->setParams(Params); 9302 9303 if (D.getDeclSpec().isNoreturnSpecified()) 9304 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9305 D.getDeclSpec().getNoreturnSpecLoc(), 9306 AttributeCommonInfo::AS_Keyword)); 9307 9308 // Functions returning a variably modified type violate C99 6.7.5.2p2 9309 // because all functions have linkage. 9310 if (!NewFD->isInvalidDecl() && 9311 NewFD->getReturnType()->isVariablyModifiedType()) { 9312 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9313 NewFD->setInvalidDecl(); 9314 } 9315 9316 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9317 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9318 !NewFD->hasAttr<SectionAttr>()) 9319 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9320 Context, PragmaClangTextSection.SectionName, 9321 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9322 9323 // Apply an implicit SectionAttr if #pragma code_seg is active. 9324 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9325 !NewFD->hasAttr<SectionAttr>()) { 9326 NewFD->addAttr(SectionAttr::CreateImplicit( 9327 Context, CodeSegStack.CurrentValue->getString(), 9328 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9329 SectionAttr::Declspec_allocate)); 9330 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9331 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9332 ASTContext::PSF_Read, 9333 NewFD)) 9334 NewFD->dropAttr<SectionAttr>(); 9335 } 9336 9337 // Apply an implicit CodeSegAttr from class declspec or 9338 // apply an implicit SectionAttr from #pragma code_seg if active. 9339 if (!NewFD->hasAttr<CodeSegAttr>()) { 9340 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9341 D.isFunctionDefinition())) { 9342 NewFD->addAttr(SAttr); 9343 } 9344 } 9345 9346 // Handle attributes. 9347 ProcessDeclAttributes(S, NewFD, D); 9348 9349 if (getLangOpts().OpenCL) { 9350 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9351 // type declaration will generate a compilation error. 9352 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9353 if (AddressSpace != LangAS::Default) { 9354 Diag(NewFD->getLocation(), 9355 diag::err_opencl_return_value_with_address_space); 9356 NewFD->setInvalidDecl(); 9357 } 9358 } 9359 9360 if (!getLangOpts().CPlusPlus) { 9361 // Perform semantic checking on the function declaration. 9362 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9363 CheckMain(NewFD, D.getDeclSpec()); 9364 9365 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9366 CheckMSVCRTEntryPoint(NewFD); 9367 9368 if (!NewFD->isInvalidDecl()) 9369 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9370 isMemberSpecialization)); 9371 else if (!Previous.empty()) 9372 // Recover gracefully from an invalid redeclaration. 9373 D.setRedeclaration(true); 9374 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9375 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9376 "previous declaration set still overloaded"); 9377 9378 // Diagnose no-prototype function declarations with calling conventions that 9379 // don't support variadic calls. Only do this in C and do it after merging 9380 // possibly prototyped redeclarations. 9381 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9382 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9383 CallingConv CC = FT->getExtInfo().getCC(); 9384 if (!supportsVariadicCall(CC)) { 9385 // Windows system headers sometimes accidentally use stdcall without 9386 // (void) parameters, so we relax this to a warning. 9387 int DiagID = 9388 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9389 Diag(NewFD->getLocation(), DiagID) 9390 << FunctionType::getNameForCallConv(CC); 9391 } 9392 } 9393 9394 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9395 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9396 checkNonTrivialCUnion(NewFD->getReturnType(), 9397 NewFD->getReturnTypeSourceRange().getBegin(), 9398 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9399 } else { 9400 // C++11 [replacement.functions]p3: 9401 // The program's definitions shall not be specified as inline. 9402 // 9403 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9404 // 9405 // Suppress the diagnostic if the function is __attribute__((used)), since 9406 // that forces an external definition to be emitted. 9407 if (D.getDeclSpec().isInlineSpecified() && 9408 NewFD->isReplaceableGlobalAllocationFunction() && 9409 !NewFD->hasAttr<UsedAttr>()) 9410 Diag(D.getDeclSpec().getInlineSpecLoc(), 9411 diag::ext_operator_new_delete_declared_inline) 9412 << NewFD->getDeclName(); 9413 9414 // If the declarator is a template-id, translate the parser's template 9415 // argument list into our AST format. 9416 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9417 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9418 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9419 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9420 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9421 TemplateId->NumArgs); 9422 translateTemplateArguments(TemplateArgsPtr, 9423 TemplateArgs); 9424 9425 HasExplicitTemplateArgs = true; 9426 9427 if (NewFD->isInvalidDecl()) { 9428 HasExplicitTemplateArgs = false; 9429 } else if (FunctionTemplate) { 9430 // Function template with explicit template arguments. 9431 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9432 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9433 9434 HasExplicitTemplateArgs = false; 9435 } else { 9436 assert((isFunctionTemplateSpecialization || 9437 D.getDeclSpec().isFriendSpecified()) && 9438 "should have a 'template<>' for this decl"); 9439 // "friend void foo<>(int);" is an implicit specialization decl. 9440 isFunctionTemplateSpecialization = true; 9441 } 9442 } else if (isFriend && isFunctionTemplateSpecialization) { 9443 // This combination is only possible in a recovery case; the user 9444 // wrote something like: 9445 // template <> friend void foo(int); 9446 // which we're recovering from as if the user had written: 9447 // friend void foo<>(int); 9448 // Go ahead and fake up a template id. 9449 HasExplicitTemplateArgs = true; 9450 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9451 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9452 } 9453 9454 // We do not add HD attributes to specializations here because 9455 // they may have different constexpr-ness compared to their 9456 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9457 // may end up with different effective targets. Instead, a 9458 // specialization inherits its target attributes from its template 9459 // in the CheckFunctionTemplateSpecialization() call below. 9460 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9461 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9462 9463 // If it's a friend (and only if it's a friend), it's possible 9464 // that either the specialized function type or the specialized 9465 // template is dependent, and therefore matching will fail. In 9466 // this case, don't check the specialization yet. 9467 bool InstantiationDependent = false; 9468 if (isFunctionTemplateSpecialization && isFriend && 9469 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9470 TemplateSpecializationType::anyDependentTemplateArguments( 9471 TemplateArgs, 9472 InstantiationDependent))) { 9473 assert(HasExplicitTemplateArgs && 9474 "friend function specialization without template args"); 9475 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9476 Previous)) 9477 NewFD->setInvalidDecl(); 9478 } else if (isFunctionTemplateSpecialization) { 9479 if (CurContext->isDependentContext() && CurContext->isRecord() 9480 && !isFriend) { 9481 isDependentClassScopeExplicitSpecialization = true; 9482 } else if (!NewFD->isInvalidDecl() && 9483 CheckFunctionTemplateSpecialization( 9484 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9485 Previous)) 9486 NewFD->setInvalidDecl(); 9487 9488 // C++ [dcl.stc]p1: 9489 // A storage-class-specifier shall not be specified in an explicit 9490 // specialization (14.7.3) 9491 FunctionTemplateSpecializationInfo *Info = 9492 NewFD->getTemplateSpecializationInfo(); 9493 if (Info && SC != SC_None) { 9494 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9495 Diag(NewFD->getLocation(), 9496 diag::err_explicit_specialization_inconsistent_storage_class) 9497 << SC 9498 << FixItHint::CreateRemoval( 9499 D.getDeclSpec().getStorageClassSpecLoc()); 9500 9501 else 9502 Diag(NewFD->getLocation(), 9503 diag::ext_explicit_specialization_storage_class) 9504 << FixItHint::CreateRemoval( 9505 D.getDeclSpec().getStorageClassSpecLoc()); 9506 } 9507 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9508 if (CheckMemberSpecialization(NewFD, Previous)) 9509 NewFD->setInvalidDecl(); 9510 } 9511 9512 // Perform semantic checking on the function declaration. 9513 if (!isDependentClassScopeExplicitSpecialization) { 9514 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9515 CheckMain(NewFD, D.getDeclSpec()); 9516 9517 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9518 CheckMSVCRTEntryPoint(NewFD); 9519 9520 if (!NewFD->isInvalidDecl()) 9521 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9522 isMemberSpecialization)); 9523 else if (!Previous.empty()) 9524 // Recover gracefully from an invalid redeclaration. 9525 D.setRedeclaration(true); 9526 } 9527 9528 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9529 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9530 "previous declaration set still overloaded"); 9531 9532 NamedDecl *PrincipalDecl = (FunctionTemplate 9533 ? cast<NamedDecl>(FunctionTemplate) 9534 : NewFD); 9535 9536 if (isFriend && NewFD->getPreviousDecl()) { 9537 AccessSpecifier Access = AS_public; 9538 if (!NewFD->isInvalidDecl()) 9539 Access = NewFD->getPreviousDecl()->getAccess(); 9540 9541 NewFD->setAccess(Access); 9542 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9543 } 9544 9545 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9546 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9547 PrincipalDecl->setNonMemberOperator(); 9548 9549 // If we have a function template, check the template parameter 9550 // list. This will check and merge default template arguments. 9551 if (FunctionTemplate) { 9552 FunctionTemplateDecl *PrevTemplate = 9553 FunctionTemplate->getPreviousDecl(); 9554 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9555 PrevTemplate ? PrevTemplate->getTemplateParameters() 9556 : nullptr, 9557 D.getDeclSpec().isFriendSpecified() 9558 ? (D.isFunctionDefinition() 9559 ? TPC_FriendFunctionTemplateDefinition 9560 : TPC_FriendFunctionTemplate) 9561 : (D.getCXXScopeSpec().isSet() && 9562 DC && DC->isRecord() && 9563 DC->isDependentContext()) 9564 ? TPC_ClassTemplateMember 9565 : TPC_FunctionTemplate); 9566 } 9567 9568 if (NewFD->isInvalidDecl()) { 9569 // Ignore all the rest of this. 9570 } else if (!D.isRedeclaration()) { 9571 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9572 AddToScope }; 9573 // Fake up an access specifier if it's supposed to be a class member. 9574 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9575 NewFD->setAccess(AS_public); 9576 9577 // Qualified decls generally require a previous declaration. 9578 if (D.getCXXScopeSpec().isSet()) { 9579 // ...with the major exception of templated-scope or 9580 // dependent-scope friend declarations. 9581 9582 // TODO: we currently also suppress this check in dependent 9583 // contexts because (1) the parameter depth will be off when 9584 // matching friend templates and (2) we might actually be 9585 // selecting a friend based on a dependent factor. But there 9586 // are situations where these conditions don't apply and we 9587 // can actually do this check immediately. 9588 // 9589 // Unless the scope is dependent, it's always an error if qualified 9590 // redeclaration lookup found nothing at all. Diagnose that now; 9591 // nothing will diagnose that error later. 9592 if (isFriend && 9593 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9594 (!Previous.empty() && CurContext->isDependentContext()))) { 9595 // ignore these 9596 } else { 9597 // The user tried to provide an out-of-line definition for a 9598 // function that is a member of a class or namespace, but there 9599 // was no such member function declared (C++ [class.mfct]p2, 9600 // C++ [namespace.memdef]p2). For example: 9601 // 9602 // class X { 9603 // void f() const; 9604 // }; 9605 // 9606 // void X::f() { } // ill-formed 9607 // 9608 // Complain about this problem, and attempt to suggest close 9609 // matches (e.g., those that differ only in cv-qualifiers and 9610 // whether the parameter types are references). 9611 9612 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9613 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9614 AddToScope = ExtraArgs.AddToScope; 9615 return Result; 9616 } 9617 } 9618 9619 // Unqualified local friend declarations are required to resolve 9620 // to something. 9621 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9622 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9623 *this, Previous, NewFD, ExtraArgs, true, S)) { 9624 AddToScope = ExtraArgs.AddToScope; 9625 return Result; 9626 } 9627 } 9628 } else if (!D.isFunctionDefinition() && 9629 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9630 !isFriend && !isFunctionTemplateSpecialization && 9631 !isMemberSpecialization) { 9632 // An out-of-line member function declaration must also be a 9633 // definition (C++ [class.mfct]p2). 9634 // Note that this is not the case for explicit specializations of 9635 // function templates or member functions of class templates, per 9636 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9637 // extension for compatibility with old SWIG code which likes to 9638 // generate them. 9639 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9640 << D.getCXXScopeSpec().getRange(); 9641 } 9642 } 9643 9644 // If this is the first declaration of a library builtin function, add 9645 // attributes as appropriate. 9646 if (!D.isRedeclaration() && 9647 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9648 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9649 if (unsigned BuiltinID = II->getBuiltinID()) { 9650 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9651 // Validate the type matches unless this builtin is specified as 9652 // matching regardless of its declared type. 9653 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9654 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9655 } else { 9656 ASTContext::GetBuiltinTypeError Error; 9657 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9658 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9659 9660 if (!Error && !BuiltinType.isNull() && 9661 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9662 NewFD->getType(), BuiltinType)) 9663 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9664 } 9665 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9666 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9667 // FIXME: We should consider this a builtin only in the std namespace. 9668 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9669 } 9670 } 9671 } 9672 } 9673 9674 ProcessPragmaWeak(S, NewFD); 9675 checkAttributesAfterMerging(*this, *NewFD); 9676 9677 AddKnownFunctionAttributes(NewFD); 9678 9679 if (NewFD->hasAttr<OverloadableAttr>() && 9680 !NewFD->getType()->getAs<FunctionProtoType>()) { 9681 Diag(NewFD->getLocation(), 9682 diag::err_attribute_overloadable_no_prototype) 9683 << NewFD; 9684 9685 // Turn this into a variadic function with no parameters. 9686 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9687 FunctionProtoType::ExtProtoInfo EPI( 9688 Context.getDefaultCallingConvention(true, false)); 9689 EPI.Variadic = true; 9690 EPI.ExtInfo = FT->getExtInfo(); 9691 9692 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9693 NewFD->setType(R); 9694 } 9695 9696 // If there's a #pragma GCC visibility in scope, and this isn't a class 9697 // member, set the visibility of this function. 9698 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9699 AddPushedVisibilityAttribute(NewFD); 9700 9701 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9702 // marking the function. 9703 AddCFAuditedAttribute(NewFD); 9704 9705 // If this is a function definition, check if we have to apply optnone due to 9706 // a pragma. 9707 if(D.isFunctionDefinition()) 9708 AddRangeBasedOptnone(NewFD); 9709 9710 // If this is the first declaration of an extern C variable, update 9711 // the map of such variables. 9712 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9713 isIncompleteDeclExternC(*this, NewFD)) 9714 RegisterLocallyScopedExternCDecl(NewFD, S); 9715 9716 // Set this FunctionDecl's range up to the right paren. 9717 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9718 9719 if (D.isRedeclaration() && !Previous.empty()) { 9720 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9721 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9722 isMemberSpecialization || 9723 isFunctionTemplateSpecialization, 9724 D.isFunctionDefinition()); 9725 } 9726 9727 if (getLangOpts().CUDA) { 9728 IdentifierInfo *II = NewFD->getIdentifier(); 9729 if (II && II->isStr(getCudaConfigureFuncName()) && 9730 !NewFD->isInvalidDecl() && 9731 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9732 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9733 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9734 << getCudaConfigureFuncName(); 9735 Context.setcudaConfigureCallDecl(NewFD); 9736 } 9737 9738 // Variadic functions, other than a *declaration* of printf, are not allowed 9739 // in device-side CUDA code, unless someone passed 9740 // -fcuda-allow-variadic-functions. 9741 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9742 (NewFD->hasAttr<CUDADeviceAttr>() || 9743 NewFD->hasAttr<CUDAGlobalAttr>()) && 9744 !(II && II->isStr("printf") && NewFD->isExternC() && 9745 !D.isFunctionDefinition())) { 9746 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9747 } 9748 } 9749 9750 MarkUnusedFileScopedDecl(NewFD); 9751 9752 9753 9754 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9755 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9756 if ((getLangOpts().OpenCLVersion >= 120) 9757 && (SC == SC_Static)) { 9758 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9759 D.setInvalidType(); 9760 } 9761 9762 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9763 if (!NewFD->getReturnType()->isVoidType()) { 9764 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9765 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9766 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9767 : FixItHint()); 9768 D.setInvalidType(); 9769 } 9770 9771 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9772 for (auto Param : NewFD->parameters()) 9773 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9774 9775 if (getLangOpts().OpenCLCPlusPlus) { 9776 if (DC->isRecord()) { 9777 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9778 D.setInvalidType(); 9779 } 9780 if (FunctionTemplate) { 9781 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9782 D.setInvalidType(); 9783 } 9784 } 9785 } 9786 9787 if (getLangOpts().CPlusPlus) { 9788 if (FunctionTemplate) { 9789 if (NewFD->isInvalidDecl()) 9790 FunctionTemplate->setInvalidDecl(); 9791 return FunctionTemplate; 9792 } 9793 9794 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9795 CompleteMemberSpecialization(NewFD, Previous); 9796 } 9797 9798 for (const ParmVarDecl *Param : NewFD->parameters()) { 9799 QualType PT = Param->getType(); 9800 9801 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9802 // types. 9803 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9804 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9805 QualType ElemTy = PipeTy->getElementType(); 9806 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9807 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9808 D.setInvalidType(); 9809 } 9810 } 9811 } 9812 } 9813 9814 // Here we have an function template explicit specialization at class scope. 9815 // The actual specialization will be postponed to template instatiation 9816 // time via the ClassScopeFunctionSpecializationDecl node. 9817 if (isDependentClassScopeExplicitSpecialization) { 9818 ClassScopeFunctionSpecializationDecl *NewSpec = 9819 ClassScopeFunctionSpecializationDecl::Create( 9820 Context, CurContext, NewFD->getLocation(), 9821 cast<CXXMethodDecl>(NewFD), 9822 HasExplicitTemplateArgs, TemplateArgs); 9823 CurContext->addDecl(NewSpec); 9824 AddToScope = false; 9825 } 9826 9827 // Diagnose availability attributes. Availability cannot be used on functions 9828 // that are run during load/unload. 9829 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9830 if (NewFD->hasAttr<ConstructorAttr>()) { 9831 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9832 << 1; 9833 NewFD->dropAttr<AvailabilityAttr>(); 9834 } 9835 if (NewFD->hasAttr<DestructorAttr>()) { 9836 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9837 << 2; 9838 NewFD->dropAttr<AvailabilityAttr>(); 9839 } 9840 } 9841 9842 // Diagnose no_builtin attribute on function declaration that are not a 9843 // definition. 9844 // FIXME: We should really be doing this in 9845 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9846 // the FunctionDecl and at this point of the code 9847 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9848 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9849 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9850 switch (D.getFunctionDefinitionKind()) { 9851 case FDK_Defaulted: 9852 case FDK_Deleted: 9853 Diag(NBA->getLocation(), 9854 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9855 << NBA->getSpelling(); 9856 break; 9857 case FDK_Declaration: 9858 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9859 << NBA->getSpelling(); 9860 break; 9861 case FDK_Definition: 9862 break; 9863 } 9864 9865 return NewFD; 9866 } 9867 9868 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9869 /// when __declspec(code_seg) "is applied to a class, all member functions of 9870 /// the class and nested classes -- this includes compiler-generated special 9871 /// member functions -- are put in the specified segment." 9872 /// The actual behavior is a little more complicated. The Microsoft compiler 9873 /// won't check outer classes if there is an active value from #pragma code_seg. 9874 /// The CodeSeg is always applied from the direct parent but only from outer 9875 /// classes when the #pragma code_seg stack is empty. See: 9876 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9877 /// available since MS has removed the page. 9878 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9879 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9880 if (!Method) 9881 return nullptr; 9882 const CXXRecordDecl *Parent = Method->getParent(); 9883 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9884 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9885 NewAttr->setImplicit(true); 9886 return NewAttr; 9887 } 9888 9889 // The Microsoft compiler won't check outer classes for the CodeSeg 9890 // when the #pragma code_seg stack is active. 9891 if (S.CodeSegStack.CurrentValue) 9892 return nullptr; 9893 9894 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9895 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9896 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9897 NewAttr->setImplicit(true); 9898 return NewAttr; 9899 } 9900 } 9901 return nullptr; 9902 } 9903 9904 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9905 /// containing class. Otherwise it will return implicit SectionAttr if the 9906 /// function is a definition and there is an active value on CodeSegStack 9907 /// (from the current #pragma code-seg value). 9908 /// 9909 /// \param FD Function being declared. 9910 /// \param IsDefinition Whether it is a definition or just a declarartion. 9911 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9912 /// nullptr if no attribute should be added. 9913 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9914 bool IsDefinition) { 9915 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9916 return A; 9917 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9918 CodeSegStack.CurrentValue) 9919 return SectionAttr::CreateImplicit( 9920 getASTContext(), CodeSegStack.CurrentValue->getString(), 9921 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9922 SectionAttr::Declspec_allocate); 9923 return nullptr; 9924 } 9925 9926 /// Determines if we can perform a correct type check for \p D as a 9927 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9928 /// best-effort check. 9929 /// 9930 /// \param NewD The new declaration. 9931 /// \param OldD The old declaration. 9932 /// \param NewT The portion of the type of the new declaration to check. 9933 /// \param OldT The portion of the type of the old declaration to check. 9934 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9935 QualType NewT, QualType OldT) { 9936 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9937 return true; 9938 9939 // For dependently-typed local extern declarations and friends, we can't 9940 // perform a correct type check in general until instantiation: 9941 // 9942 // int f(); 9943 // template<typename T> void g() { T f(); } 9944 // 9945 // (valid if g() is only instantiated with T = int). 9946 if (NewT->isDependentType() && 9947 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9948 return false; 9949 9950 // Similarly, if the previous declaration was a dependent local extern 9951 // declaration, we don't really know its type yet. 9952 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9953 return false; 9954 9955 return true; 9956 } 9957 9958 /// Checks if the new declaration declared in dependent context must be 9959 /// put in the same redeclaration chain as the specified declaration. 9960 /// 9961 /// \param D Declaration that is checked. 9962 /// \param PrevDecl Previous declaration found with proper lookup method for the 9963 /// same declaration name. 9964 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9965 /// belongs to. 9966 /// 9967 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9968 if (!D->getLexicalDeclContext()->isDependentContext()) 9969 return true; 9970 9971 // Don't chain dependent friend function definitions until instantiation, to 9972 // permit cases like 9973 // 9974 // void func(); 9975 // template<typename T> class C1 { friend void func() {} }; 9976 // template<typename T> class C2 { friend void func() {} }; 9977 // 9978 // ... which is valid if only one of C1 and C2 is ever instantiated. 9979 // 9980 // FIXME: This need only apply to function definitions. For now, we proxy 9981 // this by checking for a file-scope function. We do not want this to apply 9982 // to friend declarations nominating member functions, because that gets in 9983 // the way of access checks. 9984 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9985 return false; 9986 9987 auto *VD = dyn_cast<ValueDecl>(D); 9988 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9989 return !VD || !PrevVD || 9990 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9991 PrevVD->getType()); 9992 } 9993 9994 /// Check the target attribute of the function for MultiVersion 9995 /// validity. 9996 /// 9997 /// Returns true if there was an error, false otherwise. 9998 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9999 const auto *TA = FD->getAttr<TargetAttr>(); 10000 assert(TA && "MultiVersion Candidate requires a target attribute"); 10001 ParsedTargetAttr ParseInfo = TA->parse(); 10002 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10003 enum ErrType { Feature = 0, Architecture = 1 }; 10004 10005 if (!ParseInfo.Architecture.empty() && 10006 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10007 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10008 << Architecture << ParseInfo.Architecture; 10009 return true; 10010 } 10011 10012 for (const auto &Feat : ParseInfo.Features) { 10013 auto BareFeat = StringRef{Feat}.substr(1); 10014 if (Feat[0] == '-') { 10015 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10016 << Feature << ("no-" + BareFeat).str(); 10017 return true; 10018 } 10019 10020 if (!TargetInfo.validateCpuSupports(BareFeat) || 10021 !TargetInfo.isValidFeatureName(BareFeat)) { 10022 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10023 << Feature << BareFeat; 10024 return true; 10025 } 10026 } 10027 return false; 10028 } 10029 10030 // Provide a white-list of attributes that are allowed to be combined with 10031 // multiversion functions. 10032 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10033 MultiVersionKind MVType) { 10034 // Note: this list/diagnosis must match the list in 10035 // checkMultiversionAttributesAllSame. 10036 switch (Kind) { 10037 default: 10038 return false; 10039 case attr::Used: 10040 return MVType == MultiVersionKind::Target; 10041 case attr::NonNull: 10042 case attr::NoThrow: 10043 return true; 10044 } 10045 } 10046 10047 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10048 const FunctionDecl *FD, 10049 const FunctionDecl *CausedFD, 10050 MultiVersionKind MVType) { 10051 bool IsCPUSpecificCPUDispatchMVType = 10052 MVType == MultiVersionKind::CPUDispatch || 10053 MVType == MultiVersionKind::CPUSpecific; 10054 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10055 Sema &S, const Attr *A) { 10056 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10057 << IsCPUSpecificCPUDispatchMVType << A; 10058 if (CausedFD) 10059 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10060 return true; 10061 }; 10062 10063 for (const Attr *A : FD->attrs()) { 10064 switch (A->getKind()) { 10065 case attr::CPUDispatch: 10066 case attr::CPUSpecific: 10067 if (MVType != MultiVersionKind::CPUDispatch && 10068 MVType != MultiVersionKind::CPUSpecific) 10069 return Diagnose(S, A); 10070 break; 10071 case attr::Target: 10072 if (MVType != MultiVersionKind::Target) 10073 return Diagnose(S, A); 10074 break; 10075 default: 10076 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10077 return Diagnose(S, A); 10078 break; 10079 } 10080 } 10081 return false; 10082 } 10083 10084 bool Sema::areMultiversionVariantFunctionsCompatible( 10085 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10086 const PartialDiagnostic &NoProtoDiagID, 10087 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10088 const PartialDiagnosticAt &NoSupportDiagIDAt, 10089 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10090 bool ConstexprSupported, bool CLinkageMayDiffer) { 10091 enum DoesntSupport { 10092 FuncTemplates = 0, 10093 VirtFuncs = 1, 10094 DeducedReturn = 2, 10095 Constructors = 3, 10096 Destructors = 4, 10097 DeletedFuncs = 5, 10098 DefaultedFuncs = 6, 10099 ConstexprFuncs = 7, 10100 ConstevalFuncs = 8, 10101 }; 10102 enum Different { 10103 CallingConv = 0, 10104 ReturnType = 1, 10105 ConstexprSpec = 2, 10106 InlineSpec = 3, 10107 StorageClass = 4, 10108 Linkage = 5, 10109 }; 10110 10111 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10112 !OldFD->getType()->getAs<FunctionProtoType>()) { 10113 Diag(OldFD->getLocation(), NoProtoDiagID); 10114 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10115 return true; 10116 } 10117 10118 if (NoProtoDiagID.getDiagID() != 0 && 10119 !NewFD->getType()->getAs<FunctionProtoType>()) 10120 return Diag(NewFD->getLocation(), NoProtoDiagID); 10121 10122 if (!TemplatesSupported && 10123 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10124 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10125 << FuncTemplates; 10126 10127 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10128 if (NewCXXFD->isVirtual()) 10129 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10130 << VirtFuncs; 10131 10132 if (isa<CXXConstructorDecl>(NewCXXFD)) 10133 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10134 << Constructors; 10135 10136 if (isa<CXXDestructorDecl>(NewCXXFD)) 10137 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10138 << Destructors; 10139 } 10140 10141 if (NewFD->isDeleted()) 10142 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10143 << DeletedFuncs; 10144 10145 if (NewFD->isDefaulted()) 10146 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10147 << DefaultedFuncs; 10148 10149 if (!ConstexprSupported && NewFD->isConstexpr()) 10150 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10151 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10152 10153 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10154 const auto *NewType = cast<FunctionType>(NewQType); 10155 QualType NewReturnType = NewType->getReturnType(); 10156 10157 if (NewReturnType->isUndeducedType()) 10158 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10159 << DeducedReturn; 10160 10161 // Ensure the return type is identical. 10162 if (OldFD) { 10163 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10164 const auto *OldType = cast<FunctionType>(OldQType); 10165 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10166 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10167 10168 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10169 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10170 10171 QualType OldReturnType = OldType->getReturnType(); 10172 10173 if (OldReturnType != NewReturnType) 10174 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10175 10176 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10177 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10178 10179 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10180 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10181 10182 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10183 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10184 10185 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10186 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10187 10188 if (CheckEquivalentExceptionSpec( 10189 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10190 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10191 return true; 10192 } 10193 return false; 10194 } 10195 10196 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10197 const FunctionDecl *NewFD, 10198 bool CausesMV, 10199 MultiVersionKind MVType) { 10200 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10201 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10202 if (OldFD) 10203 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10204 return true; 10205 } 10206 10207 bool IsCPUSpecificCPUDispatchMVType = 10208 MVType == MultiVersionKind::CPUDispatch || 10209 MVType == MultiVersionKind::CPUSpecific; 10210 10211 if (CausesMV && OldFD && 10212 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10213 return true; 10214 10215 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10216 return true; 10217 10218 // Only allow transition to MultiVersion if it hasn't been used. 10219 if (OldFD && CausesMV && OldFD->isUsed(false)) 10220 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10221 10222 return S.areMultiversionVariantFunctionsCompatible( 10223 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10224 PartialDiagnosticAt(NewFD->getLocation(), 10225 S.PDiag(diag::note_multiversioning_caused_here)), 10226 PartialDiagnosticAt(NewFD->getLocation(), 10227 S.PDiag(diag::err_multiversion_doesnt_support) 10228 << IsCPUSpecificCPUDispatchMVType), 10229 PartialDiagnosticAt(NewFD->getLocation(), 10230 S.PDiag(diag::err_multiversion_diff)), 10231 /*TemplatesSupported=*/false, 10232 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10233 /*CLinkageMayDiffer=*/false); 10234 } 10235 10236 /// Check the validity of a multiversion function declaration that is the 10237 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10238 /// 10239 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10240 /// 10241 /// Returns true if there was an error, false otherwise. 10242 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10243 MultiVersionKind MVType, 10244 const TargetAttr *TA) { 10245 assert(MVType != MultiVersionKind::None && 10246 "Function lacks multiversion attribute"); 10247 10248 // Target only causes MV if it is default, otherwise this is a normal 10249 // function. 10250 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10251 return false; 10252 10253 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10254 FD->setInvalidDecl(); 10255 return true; 10256 } 10257 10258 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10259 FD->setInvalidDecl(); 10260 return true; 10261 } 10262 10263 FD->setIsMultiVersion(); 10264 return false; 10265 } 10266 10267 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10268 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10269 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10270 return true; 10271 } 10272 10273 return false; 10274 } 10275 10276 static bool CheckTargetCausesMultiVersioning( 10277 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10278 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10279 LookupResult &Previous) { 10280 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10281 ParsedTargetAttr NewParsed = NewTA->parse(); 10282 // Sort order doesn't matter, it just needs to be consistent. 10283 llvm::sort(NewParsed.Features); 10284 10285 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10286 // to change, this is a simple redeclaration. 10287 if (!NewTA->isDefaultVersion() && 10288 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10289 return false; 10290 10291 // Otherwise, this decl causes MultiVersioning. 10292 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10293 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10294 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10295 NewFD->setInvalidDecl(); 10296 return true; 10297 } 10298 10299 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10300 MultiVersionKind::Target)) { 10301 NewFD->setInvalidDecl(); 10302 return true; 10303 } 10304 10305 if (CheckMultiVersionValue(S, NewFD)) { 10306 NewFD->setInvalidDecl(); 10307 return true; 10308 } 10309 10310 // If this is 'default', permit the forward declaration. 10311 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10312 Redeclaration = true; 10313 OldDecl = OldFD; 10314 OldFD->setIsMultiVersion(); 10315 NewFD->setIsMultiVersion(); 10316 return false; 10317 } 10318 10319 if (CheckMultiVersionValue(S, OldFD)) { 10320 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10321 NewFD->setInvalidDecl(); 10322 return true; 10323 } 10324 10325 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10326 10327 if (OldParsed == NewParsed) { 10328 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10329 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10330 NewFD->setInvalidDecl(); 10331 return true; 10332 } 10333 10334 for (const auto *FD : OldFD->redecls()) { 10335 const auto *CurTA = FD->getAttr<TargetAttr>(); 10336 // We allow forward declarations before ANY multiversioning attributes, but 10337 // nothing after the fact. 10338 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10339 (!CurTA || CurTA->isInherited())) { 10340 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10341 << 0; 10342 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10343 NewFD->setInvalidDecl(); 10344 return true; 10345 } 10346 } 10347 10348 OldFD->setIsMultiVersion(); 10349 NewFD->setIsMultiVersion(); 10350 Redeclaration = false; 10351 MergeTypeWithPrevious = false; 10352 OldDecl = nullptr; 10353 Previous.clear(); 10354 return false; 10355 } 10356 10357 /// Check the validity of a new function declaration being added to an existing 10358 /// multiversioned declaration collection. 10359 static bool CheckMultiVersionAdditionalDecl( 10360 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10361 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10362 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10363 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10364 LookupResult &Previous) { 10365 10366 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10367 // Disallow mixing of multiversioning types. 10368 if ((OldMVType == MultiVersionKind::Target && 10369 NewMVType != MultiVersionKind::Target) || 10370 (NewMVType == MultiVersionKind::Target && 10371 OldMVType != MultiVersionKind::Target)) { 10372 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10373 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10374 NewFD->setInvalidDecl(); 10375 return true; 10376 } 10377 10378 ParsedTargetAttr NewParsed; 10379 if (NewTA) { 10380 NewParsed = NewTA->parse(); 10381 llvm::sort(NewParsed.Features); 10382 } 10383 10384 bool UseMemberUsingDeclRules = 10385 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10386 10387 // Next, check ALL non-overloads to see if this is a redeclaration of a 10388 // previous member of the MultiVersion set. 10389 for (NamedDecl *ND : Previous) { 10390 FunctionDecl *CurFD = ND->getAsFunction(); 10391 if (!CurFD) 10392 continue; 10393 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10394 continue; 10395 10396 if (NewMVType == MultiVersionKind::Target) { 10397 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10398 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10399 NewFD->setIsMultiVersion(); 10400 Redeclaration = true; 10401 OldDecl = ND; 10402 return false; 10403 } 10404 10405 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10406 if (CurParsed == NewParsed) { 10407 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10408 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10409 NewFD->setInvalidDecl(); 10410 return true; 10411 } 10412 } else { 10413 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10414 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10415 // Handle CPUDispatch/CPUSpecific versions. 10416 // Only 1 CPUDispatch function is allowed, this will make it go through 10417 // the redeclaration errors. 10418 if (NewMVType == MultiVersionKind::CPUDispatch && 10419 CurFD->hasAttr<CPUDispatchAttr>()) { 10420 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10421 std::equal( 10422 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10423 NewCPUDisp->cpus_begin(), 10424 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10425 return Cur->getName() == New->getName(); 10426 })) { 10427 NewFD->setIsMultiVersion(); 10428 Redeclaration = true; 10429 OldDecl = ND; 10430 return false; 10431 } 10432 10433 // If the declarations don't match, this is an error condition. 10434 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10435 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10436 NewFD->setInvalidDecl(); 10437 return true; 10438 } 10439 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10440 10441 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10442 std::equal( 10443 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10444 NewCPUSpec->cpus_begin(), 10445 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10446 return Cur->getName() == New->getName(); 10447 })) { 10448 NewFD->setIsMultiVersion(); 10449 Redeclaration = true; 10450 OldDecl = ND; 10451 return false; 10452 } 10453 10454 // Only 1 version of CPUSpecific is allowed for each CPU. 10455 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10456 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10457 if (CurII == NewII) { 10458 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10459 << NewII; 10460 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10461 NewFD->setInvalidDecl(); 10462 return true; 10463 } 10464 } 10465 } 10466 } 10467 // If the two decls aren't the same MVType, there is no possible error 10468 // condition. 10469 } 10470 } 10471 10472 // Else, this is simply a non-redecl case. Checking the 'value' is only 10473 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10474 // handled in the attribute adding step. 10475 if (NewMVType == MultiVersionKind::Target && 10476 CheckMultiVersionValue(S, NewFD)) { 10477 NewFD->setInvalidDecl(); 10478 return true; 10479 } 10480 10481 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10482 !OldFD->isMultiVersion(), NewMVType)) { 10483 NewFD->setInvalidDecl(); 10484 return true; 10485 } 10486 10487 // Permit forward declarations in the case where these two are compatible. 10488 if (!OldFD->isMultiVersion()) { 10489 OldFD->setIsMultiVersion(); 10490 NewFD->setIsMultiVersion(); 10491 Redeclaration = true; 10492 OldDecl = OldFD; 10493 return false; 10494 } 10495 10496 NewFD->setIsMultiVersion(); 10497 Redeclaration = false; 10498 MergeTypeWithPrevious = false; 10499 OldDecl = nullptr; 10500 Previous.clear(); 10501 return false; 10502 } 10503 10504 10505 /// Check the validity of a mulitversion function declaration. 10506 /// Also sets the multiversion'ness' of the function itself. 10507 /// 10508 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10509 /// 10510 /// Returns true if there was an error, false otherwise. 10511 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10512 bool &Redeclaration, NamedDecl *&OldDecl, 10513 bool &MergeTypeWithPrevious, 10514 LookupResult &Previous) { 10515 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10516 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10517 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10518 10519 // Mixing Multiversioning types is prohibited. 10520 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10521 (NewCPUDisp && NewCPUSpec)) { 10522 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10523 NewFD->setInvalidDecl(); 10524 return true; 10525 } 10526 10527 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10528 10529 // Main isn't allowed to become a multiversion function, however it IS 10530 // permitted to have 'main' be marked with the 'target' optimization hint. 10531 if (NewFD->isMain()) { 10532 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10533 MVType == MultiVersionKind::CPUDispatch || 10534 MVType == MultiVersionKind::CPUSpecific) { 10535 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10536 NewFD->setInvalidDecl(); 10537 return true; 10538 } 10539 return false; 10540 } 10541 10542 if (!OldDecl || !OldDecl->getAsFunction() || 10543 OldDecl->getDeclContext()->getRedeclContext() != 10544 NewFD->getDeclContext()->getRedeclContext()) { 10545 // If there's no previous declaration, AND this isn't attempting to cause 10546 // multiversioning, this isn't an error condition. 10547 if (MVType == MultiVersionKind::None) 10548 return false; 10549 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10550 } 10551 10552 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10553 10554 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10555 return false; 10556 10557 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10558 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10559 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10560 NewFD->setInvalidDecl(); 10561 return true; 10562 } 10563 10564 // Handle the target potentially causes multiversioning case. 10565 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10566 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10567 Redeclaration, OldDecl, 10568 MergeTypeWithPrevious, Previous); 10569 10570 // At this point, we have a multiversion function decl (in OldFD) AND an 10571 // appropriate attribute in the current function decl. Resolve that these are 10572 // still compatible with previous declarations. 10573 return CheckMultiVersionAdditionalDecl( 10574 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10575 OldDecl, MergeTypeWithPrevious, Previous); 10576 } 10577 10578 /// Perform semantic checking of a new function declaration. 10579 /// 10580 /// Performs semantic analysis of the new function declaration 10581 /// NewFD. This routine performs all semantic checking that does not 10582 /// require the actual declarator involved in the declaration, and is 10583 /// used both for the declaration of functions as they are parsed 10584 /// (called via ActOnDeclarator) and for the declaration of functions 10585 /// that have been instantiated via C++ template instantiation (called 10586 /// via InstantiateDecl). 10587 /// 10588 /// \param IsMemberSpecialization whether this new function declaration is 10589 /// a member specialization (that replaces any definition provided by the 10590 /// previous declaration). 10591 /// 10592 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10593 /// 10594 /// \returns true if the function declaration is a redeclaration. 10595 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10596 LookupResult &Previous, 10597 bool IsMemberSpecialization) { 10598 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10599 "Variably modified return types are not handled here"); 10600 10601 // Determine whether the type of this function should be merged with 10602 // a previous visible declaration. This never happens for functions in C++, 10603 // and always happens in C if the previous declaration was visible. 10604 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10605 !Previous.isShadowed(); 10606 10607 bool Redeclaration = false; 10608 NamedDecl *OldDecl = nullptr; 10609 bool MayNeedOverloadableChecks = false; 10610 10611 // Merge or overload the declaration with an existing declaration of 10612 // the same name, if appropriate. 10613 if (!Previous.empty()) { 10614 // Determine whether NewFD is an overload of PrevDecl or 10615 // a declaration that requires merging. If it's an overload, 10616 // there's no more work to do here; we'll just add the new 10617 // function to the scope. 10618 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10619 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10620 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10621 Redeclaration = true; 10622 OldDecl = Candidate; 10623 } 10624 } else { 10625 MayNeedOverloadableChecks = true; 10626 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10627 /*NewIsUsingDecl*/ false)) { 10628 case Ovl_Match: 10629 Redeclaration = true; 10630 break; 10631 10632 case Ovl_NonFunction: 10633 Redeclaration = true; 10634 break; 10635 10636 case Ovl_Overload: 10637 Redeclaration = false; 10638 break; 10639 } 10640 } 10641 } 10642 10643 // Check for a previous extern "C" declaration with this name. 10644 if (!Redeclaration && 10645 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10646 if (!Previous.empty()) { 10647 // This is an extern "C" declaration with the same name as a previous 10648 // declaration, and thus redeclares that entity... 10649 Redeclaration = true; 10650 OldDecl = Previous.getFoundDecl(); 10651 MergeTypeWithPrevious = false; 10652 10653 // ... except in the presence of __attribute__((overloadable)). 10654 if (OldDecl->hasAttr<OverloadableAttr>() || 10655 NewFD->hasAttr<OverloadableAttr>()) { 10656 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10657 MayNeedOverloadableChecks = true; 10658 Redeclaration = false; 10659 OldDecl = nullptr; 10660 } 10661 } 10662 } 10663 } 10664 10665 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10666 MergeTypeWithPrevious, Previous)) 10667 return Redeclaration; 10668 10669 // C++11 [dcl.constexpr]p8: 10670 // A constexpr specifier for a non-static member function that is not 10671 // a constructor declares that member function to be const. 10672 // 10673 // This needs to be delayed until we know whether this is an out-of-line 10674 // definition of a static member function. 10675 // 10676 // This rule is not present in C++1y, so we produce a backwards 10677 // compatibility warning whenever it happens in C++11. 10678 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10679 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10680 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10681 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10682 CXXMethodDecl *OldMD = nullptr; 10683 if (OldDecl) 10684 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10685 if (!OldMD || !OldMD->isStatic()) { 10686 const FunctionProtoType *FPT = 10687 MD->getType()->castAs<FunctionProtoType>(); 10688 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10689 EPI.TypeQuals.addConst(); 10690 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10691 FPT->getParamTypes(), EPI)); 10692 10693 // Warn that we did this, if we're not performing template instantiation. 10694 // In that case, we'll have warned already when the template was defined. 10695 if (!inTemplateInstantiation()) { 10696 SourceLocation AddConstLoc; 10697 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10698 .IgnoreParens().getAs<FunctionTypeLoc>()) 10699 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10700 10701 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10702 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10703 } 10704 } 10705 } 10706 10707 if (Redeclaration) { 10708 // NewFD and OldDecl represent declarations that need to be 10709 // merged. 10710 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10711 NewFD->setInvalidDecl(); 10712 return Redeclaration; 10713 } 10714 10715 Previous.clear(); 10716 Previous.addDecl(OldDecl); 10717 10718 if (FunctionTemplateDecl *OldTemplateDecl = 10719 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10720 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10721 FunctionTemplateDecl *NewTemplateDecl 10722 = NewFD->getDescribedFunctionTemplate(); 10723 assert(NewTemplateDecl && "Template/non-template mismatch"); 10724 10725 // The call to MergeFunctionDecl above may have created some state in 10726 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10727 // can add it as a redeclaration. 10728 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10729 10730 NewFD->setPreviousDeclaration(OldFD); 10731 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10732 if (NewFD->isCXXClassMember()) { 10733 NewFD->setAccess(OldTemplateDecl->getAccess()); 10734 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10735 } 10736 10737 // If this is an explicit specialization of a member that is a function 10738 // template, mark it as a member specialization. 10739 if (IsMemberSpecialization && 10740 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10741 NewTemplateDecl->setMemberSpecialization(); 10742 assert(OldTemplateDecl->isMemberSpecialization()); 10743 // Explicit specializations of a member template do not inherit deleted 10744 // status from the parent member template that they are specializing. 10745 if (OldFD->isDeleted()) { 10746 // FIXME: This assert will not hold in the presence of modules. 10747 assert(OldFD->getCanonicalDecl() == OldFD); 10748 // FIXME: We need an update record for this AST mutation. 10749 OldFD->setDeletedAsWritten(false); 10750 } 10751 } 10752 10753 } else { 10754 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10755 auto *OldFD = cast<FunctionDecl>(OldDecl); 10756 // This needs to happen first so that 'inline' propagates. 10757 NewFD->setPreviousDeclaration(OldFD); 10758 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10759 if (NewFD->isCXXClassMember()) 10760 NewFD->setAccess(OldFD->getAccess()); 10761 } 10762 } 10763 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10764 !NewFD->getAttr<OverloadableAttr>()) { 10765 assert((Previous.empty() || 10766 llvm::any_of(Previous, 10767 [](const NamedDecl *ND) { 10768 return ND->hasAttr<OverloadableAttr>(); 10769 })) && 10770 "Non-redecls shouldn't happen without overloadable present"); 10771 10772 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10773 const auto *FD = dyn_cast<FunctionDecl>(ND); 10774 return FD && !FD->hasAttr<OverloadableAttr>(); 10775 }); 10776 10777 if (OtherUnmarkedIter != Previous.end()) { 10778 Diag(NewFD->getLocation(), 10779 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10780 Diag((*OtherUnmarkedIter)->getLocation(), 10781 diag::note_attribute_overloadable_prev_overload) 10782 << false; 10783 10784 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10785 } 10786 } 10787 10788 // Semantic checking for this function declaration (in isolation). 10789 10790 if (getLangOpts().CPlusPlus) { 10791 // C++-specific checks. 10792 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10793 CheckConstructor(Constructor); 10794 } else if (CXXDestructorDecl *Destructor = 10795 dyn_cast<CXXDestructorDecl>(NewFD)) { 10796 CXXRecordDecl *Record = Destructor->getParent(); 10797 QualType ClassType = Context.getTypeDeclType(Record); 10798 10799 // FIXME: Shouldn't we be able to perform this check even when the class 10800 // type is dependent? Both gcc and edg can handle that. 10801 if (!ClassType->isDependentType()) { 10802 DeclarationName Name 10803 = Context.DeclarationNames.getCXXDestructorName( 10804 Context.getCanonicalType(ClassType)); 10805 if (NewFD->getDeclName() != Name) { 10806 Diag(NewFD->getLocation(), diag::err_destructor_name); 10807 NewFD->setInvalidDecl(); 10808 return Redeclaration; 10809 } 10810 } 10811 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10812 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10813 CheckDeductionGuideTemplate(TD); 10814 10815 // A deduction guide is not on the list of entities that can be 10816 // explicitly specialized. 10817 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10818 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10819 << /*explicit specialization*/ 1; 10820 } 10821 10822 // Find any virtual functions that this function overrides. 10823 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10824 if (!Method->isFunctionTemplateSpecialization() && 10825 !Method->getDescribedFunctionTemplate() && 10826 Method->isCanonicalDecl()) { 10827 AddOverriddenMethods(Method->getParent(), Method); 10828 } 10829 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10830 // C++2a [class.virtual]p6 10831 // A virtual method shall not have a requires-clause. 10832 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10833 diag::err_constrained_virtual_method); 10834 10835 if (Method->isStatic()) 10836 checkThisInStaticMemberFunctionType(Method); 10837 } 10838 10839 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10840 ActOnConversionDeclarator(Conversion); 10841 10842 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10843 if (NewFD->isOverloadedOperator() && 10844 CheckOverloadedOperatorDeclaration(NewFD)) { 10845 NewFD->setInvalidDecl(); 10846 return Redeclaration; 10847 } 10848 10849 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10850 if (NewFD->getLiteralIdentifier() && 10851 CheckLiteralOperatorDeclaration(NewFD)) { 10852 NewFD->setInvalidDecl(); 10853 return Redeclaration; 10854 } 10855 10856 // In C++, check default arguments now that we have merged decls. Unless 10857 // the lexical context is the class, because in this case this is done 10858 // during delayed parsing anyway. 10859 if (!CurContext->isRecord()) 10860 CheckCXXDefaultArguments(NewFD); 10861 10862 // If this function declares a builtin function, check the type of this 10863 // declaration against the expected type for the builtin. 10864 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10865 ASTContext::GetBuiltinTypeError Error; 10866 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10867 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10868 // If the type of the builtin differs only in its exception 10869 // specification, that's OK. 10870 // FIXME: If the types do differ in this way, it would be better to 10871 // retain the 'noexcept' form of the type. 10872 if (!T.isNull() && 10873 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10874 NewFD->getType())) 10875 // The type of this function differs from the type of the builtin, 10876 // so forget about the builtin entirely. 10877 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10878 } 10879 10880 // If this function is declared as being extern "C", then check to see if 10881 // the function returns a UDT (class, struct, or union type) that is not C 10882 // compatible, and if it does, warn the user. 10883 // But, issue any diagnostic on the first declaration only. 10884 if (Previous.empty() && NewFD->isExternC()) { 10885 QualType R = NewFD->getReturnType(); 10886 if (R->isIncompleteType() && !R->isVoidType()) 10887 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10888 << NewFD << R; 10889 else if (!R.isPODType(Context) && !R->isVoidType() && 10890 !R->isObjCObjectPointerType()) 10891 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10892 } 10893 10894 // C++1z [dcl.fct]p6: 10895 // [...] whether the function has a non-throwing exception-specification 10896 // [is] part of the function type 10897 // 10898 // This results in an ABI break between C++14 and C++17 for functions whose 10899 // declared type includes an exception-specification in a parameter or 10900 // return type. (Exception specifications on the function itself are OK in 10901 // most cases, and exception specifications are not permitted in most other 10902 // contexts where they could make it into a mangling.) 10903 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10904 auto HasNoexcept = [&](QualType T) -> bool { 10905 // Strip off declarator chunks that could be between us and a function 10906 // type. We don't need to look far, exception specifications are very 10907 // restricted prior to C++17. 10908 if (auto *RT = T->getAs<ReferenceType>()) 10909 T = RT->getPointeeType(); 10910 else if (T->isAnyPointerType()) 10911 T = T->getPointeeType(); 10912 else if (auto *MPT = T->getAs<MemberPointerType>()) 10913 T = MPT->getPointeeType(); 10914 if (auto *FPT = T->getAs<FunctionProtoType>()) 10915 if (FPT->isNothrow()) 10916 return true; 10917 return false; 10918 }; 10919 10920 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10921 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10922 for (QualType T : FPT->param_types()) 10923 AnyNoexcept |= HasNoexcept(T); 10924 if (AnyNoexcept) 10925 Diag(NewFD->getLocation(), 10926 diag::warn_cxx17_compat_exception_spec_in_signature) 10927 << NewFD; 10928 } 10929 10930 if (!Redeclaration && LangOpts.CUDA) 10931 checkCUDATargetOverload(NewFD, Previous); 10932 } 10933 return Redeclaration; 10934 } 10935 10936 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10937 // C++11 [basic.start.main]p3: 10938 // A program that [...] declares main to be inline, static or 10939 // constexpr is ill-formed. 10940 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10941 // appear in a declaration of main. 10942 // static main is not an error under C99, but we should warn about it. 10943 // We accept _Noreturn main as an extension. 10944 if (FD->getStorageClass() == SC_Static) 10945 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10946 ? diag::err_static_main : diag::warn_static_main) 10947 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10948 if (FD->isInlineSpecified()) 10949 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10950 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10951 if (DS.isNoreturnSpecified()) { 10952 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10953 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10954 Diag(NoreturnLoc, diag::ext_noreturn_main); 10955 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10956 << FixItHint::CreateRemoval(NoreturnRange); 10957 } 10958 if (FD->isConstexpr()) { 10959 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10960 << FD->isConsteval() 10961 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10962 FD->setConstexprKind(CSK_unspecified); 10963 } 10964 10965 if (getLangOpts().OpenCL) { 10966 Diag(FD->getLocation(), diag::err_opencl_no_main) 10967 << FD->hasAttr<OpenCLKernelAttr>(); 10968 FD->setInvalidDecl(); 10969 return; 10970 } 10971 10972 QualType T = FD->getType(); 10973 assert(T->isFunctionType() && "function decl is not of function type"); 10974 const FunctionType* FT = T->castAs<FunctionType>(); 10975 10976 // Set default calling convention for main() 10977 if (FT->getCallConv() != CC_C) { 10978 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10979 FD->setType(QualType(FT, 0)); 10980 T = Context.getCanonicalType(FD->getType()); 10981 } 10982 10983 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10984 // In C with GNU extensions we allow main() to have non-integer return 10985 // type, but we should warn about the extension, and we disable the 10986 // implicit-return-zero rule. 10987 10988 // GCC in C mode accepts qualified 'int'. 10989 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10990 FD->setHasImplicitReturnZero(true); 10991 else { 10992 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10993 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10994 if (RTRange.isValid()) 10995 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10996 << FixItHint::CreateReplacement(RTRange, "int"); 10997 } 10998 } else { 10999 // In C and C++, main magically returns 0 if you fall off the end; 11000 // set the flag which tells us that. 11001 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11002 11003 // All the standards say that main() should return 'int'. 11004 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11005 FD->setHasImplicitReturnZero(true); 11006 else { 11007 // Otherwise, this is just a flat-out error. 11008 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11009 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11010 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11011 : FixItHint()); 11012 FD->setInvalidDecl(true); 11013 } 11014 } 11015 11016 // Treat protoless main() as nullary. 11017 if (isa<FunctionNoProtoType>(FT)) return; 11018 11019 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11020 unsigned nparams = FTP->getNumParams(); 11021 assert(FD->getNumParams() == nparams); 11022 11023 bool HasExtraParameters = (nparams > 3); 11024 11025 if (FTP->isVariadic()) { 11026 Diag(FD->getLocation(), diag::ext_variadic_main); 11027 // FIXME: if we had information about the location of the ellipsis, we 11028 // could add a FixIt hint to remove it as a parameter. 11029 } 11030 11031 // Darwin passes an undocumented fourth argument of type char**. If 11032 // other platforms start sprouting these, the logic below will start 11033 // getting shifty. 11034 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11035 HasExtraParameters = false; 11036 11037 if (HasExtraParameters) { 11038 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11039 FD->setInvalidDecl(true); 11040 nparams = 3; 11041 } 11042 11043 // FIXME: a lot of the following diagnostics would be improved 11044 // if we had some location information about types. 11045 11046 QualType CharPP = 11047 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11048 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11049 11050 for (unsigned i = 0; i < nparams; ++i) { 11051 QualType AT = FTP->getParamType(i); 11052 11053 bool mismatch = true; 11054 11055 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11056 mismatch = false; 11057 else if (Expected[i] == CharPP) { 11058 // As an extension, the following forms are okay: 11059 // char const ** 11060 // char const * const * 11061 // char * const * 11062 11063 QualifierCollector qs; 11064 const PointerType* PT; 11065 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11066 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11067 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11068 Context.CharTy)) { 11069 qs.removeConst(); 11070 mismatch = !qs.empty(); 11071 } 11072 } 11073 11074 if (mismatch) { 11075 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11076 // TODO: suggest replacing given type with expected type 11077 FD->setInvalidDecl(true); 11078 } 11079 } 11080 11081 if (nparams == 1 && !FD->isInvalidDecl()) { 11082 Diag(FD->getLocation(), diag::warn_main_one_arg); 11083 } 11084 11085 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11086 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11087 FD->setInvalidDecl(); 11088 } 11089 } 11090 11091 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11092 QualType T = FD->getType(); 11093 assert(T->isFunctionType() && "function decl is not of function type"); 11094 const FunctionType *FT = T->castAs<FunctionType>(); 11095 11096 // Set an implicit return of 'zero' if the function can return some integral, 11097 // enumeration, pointer or nullptr type. 11098 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11099 FT->getReturnType()->isAnyPointerType() || 11100 FT->getReturnType()->isNullPtrType()) 11101 // DllMain is exempt because a return value of zero means it failed. 11102 if (FD->getName() != "DllMain") 11103 FD->setHasImplicitReturnZero(true); 11104 11105 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11106 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11107 FD->setInvalidDecl(); 11108 } 11109 } 11110 11111 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11112 // FIXME: Need strict checking. In C89, we need to check for 11113 // any assignment, increment, decrement, function-calls, or 11114 // commas outside of a sizeof. In C99, it's the same list, 11115 // except that the aforementioned are allowed in unevaluated 11116 // expressions. Everything else falls under the 11117 // "may accept other forms of constant expressions" exception. 11118 // 11119 // Regular C++ code will not end up here (exceptions: language extensions, 11120 // OpenCL C++ etc), so the constant expression rules there don't matter. 11121 if (Init->isValueDependent()) { 11122 assert(Init->containsErrors() && 11123 "Dependent code should only occur in error-recovery path."); 11124 return true; 11125 } 11126 const Expr *Culprit; 11127 if (Init->isConstantInitializer(Context, false, &Culprit)) 11128 return false; 11129 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11130 << Culprit->getSourceRange(); 11131 return true; 11132 } 11133 11134 namespace { 11135 // Visits an initialization expression to see if OrigDecl is evaluated in 11136 // its own initialization and throws a warning if it does. 11137 class SelfReferenceChecker 11138 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11139 Sema &S; 11140 Decl *OrigDecl; 11141 bool isRecordType; 11142 bool isPODType; 11143 bool isReferenceType; 11144 11145 bool isInitList; 11146 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11147 11148 public: 11149 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11150 11151 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11152 S(S), OrigDecl(OrigDecl) { 11153 isPODType = false; 11154 isRecordType = false; 11155 isReferenceType = false; 11156 isInitList = false; 11157 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11158 isPODType = VD->getType().isPODType(S.Context); 11159 isRecordType = VD->getType()->isRecordType(); 11160 isReferenceType = VD->getType()->isReferenceType(); 11161 } 11162 } 11163 11164 // For most expressions, just call the visitor. For initializer lists, 11165 // track the index of the field being initialized since fields are 11166 // initialized in order allowing use of previously initialized fields. 11167 void CheckExpr(Expr *E) { 11168 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11169 if (!InitList) { 11170 Visit(E); 11171 return; 11172 } 11173 11174 // Track and increment the index here. 11175 isInitList = true; 11176 InitFieldIndex.push_back(0); 11177 for (auto Child : InitList->children()) { 11178 CheckExpr(cast<Expr>(Child)); 11179 ++InitFieldIndex.back(); 11180 } 11181 InitFieldIndex.pop_back(); 11182 } 11183 11184 // Returns true if MemberExpr is checked and no further checking is needed. 11185 // Returns false if additional checking is required. 11186 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11187 llvm::SmallVector<FieldDecl*, 4> Fields; 11188 Expr *Base = E; 11189 bool ReferenceField = false; 11190 11191 // Get the field members used. 11192 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11193 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11194 if (!FD) 11195 return false; 11196 Fields.push_back(FD); 11197 if (FD->getType()->isReferenceType()) 11198 ReferenceField = true; 11199 Base = ME->getBase()->IgnoreParenImpCasts(); 11200 } 11201 11202 // Keep checking only if the base Decl is the same. 11203 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11204 if (!DRE || DRE->getDecl() != OrigDecl) 11205 return false; 11206 11207 // A reference field can be bound to an unininitialized field. 11208 if (CheckReference && !ReferenceField) 11209 return true; 11210 11211 // Convert FieldDecls to their index number. 11212 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11213 for (const FieldDecl *I : llvm::reverse(Fields)) 11214 UsedFieldIndex.push_back(I->getFieldIndex()); 11215 11216 // See if a warning is needed by checking the first difference in index 11217 // numbers. If field being used has index less than the field being 11218 // initialized, then the use is safe. 11219 for (auto UsedIter = UsedFieldIndex.begin(), 11220 UsedEnd = UsedFieldIndex.end(), 11221 OrigIter = InitFieldIndex.begin(), 11222 OrigEnd = InitFieldIndex.end(); 11223 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11224 if (*UsedIter < *OrigIter) 11225 return true; 11226 if (*UsedIter > *OrigIter) 11227 break; 11228 } 11229 11230 // TODO: Add a different warning which will print the field names. 11231 HandleDeclRefExpr(DRE); 11232 return true; 11233 } 11234 11235 // For most expressions, the cast is directly above the DeclRefExpr. 11236 // For conditional operators, the cast can be outside the conditional 11237 // operator if both expressions are DeclRefExpr's. 11238 void HandleValue(Expr *E) { 11239 E = E->IgnoreParens(); 11240 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11241 HandleDeclRefExpr(DRE); 11242 return; 11243 } 11244 11245 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11246 Visit(CO->getCond()); 11247 HandleValue(CO->getTrueExpr()); 11248 HandleValue(CO->getFalseExpr()); 11249 return; 11250 } 11251 11252 if (BinaryConditionalOperator *BCO = 11253 dyn_cast<BinaryConditionalOperator>(E)) { 11254 Visit(BCO->getCond()); 11255 HandleValue(BCO->getFalseExpr()); 11256 return; 11257 } 11258 11259 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11260 HandleValue(OVE->getSourceExpr()); 11261 return; 11262 } 11263 11264 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11265 if (BO->getOpcode() == BO_Comma) { 11266 Visit(BO->getLHS()); 11267 HandleValue(BO->getRHS()); 11268 return; 11269 } 11270 } 11271 11272 if (isa<MemberExpr>(E)) { 11273 if (isInitList) { 11274 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11275 false /*CheckReference*/)) 11276 return; 11277 } 11278 11279 Expr *Base = E->IgnoreParenImpCasts(); 11280 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11281 // Check for static member variables and don't warn on them. 11282 if (!isa<FieldDecl>(ME->getMemberDecl())) 11283 return; 11284 Base = ME->getBase()->IgnoreParenImpCasts(); 11285 } 11286 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11287 HandleDeclRefExpr(DRE); 11288 return; 11289 } 11290 11291 Visit(E); 11292 } 11293 11294 // Reference types not handled in HandleValue are handled here since all 11295 // uses of references are bad, not just r-value uses. 11296 void VisitDeclRefExpr(DeclRefExpr *E) { 11297 if (isReferenceType) 11298 HandleDeclRefExpr(E); 11299 } 11300 11301 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11302 if (E->getCastKind() == CK_LValueToRValue) { 11303 HandleValue(E->getSubExpr()); 11304 return; 11305 } 11306 11307 Inherited::VisitImplicitCastExpr(E); 11308 } 11309 11310 void VisitMemberExpr(MemberExpr *E) { 11311 if (isInitList) { 11312 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11313 return; 11314 } 11315 11316 // Don't warn on arrays since they can be treated as pointers. 11317 if (E->getType()->canDecayToPointerType()) return; 11318 11319 // Warn when a non-static method call is followed by non-static member 11320 // field accesses, which is followed by a DeclRefExpr. 11321 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11322 bool Warn = (MD && !MD->isStatic()); 11323 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11324 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11325 if (!isa<FieldDecl>(ME->getMemberDecl())) 11326 Warn = false; 11327 Base = ME->getBase()->IgnoreParenImpCasts(); 11328 } 11329 11330 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11331 if (Warn) 11332 HandleDeclRefExpr(DRE); 11333 return; 11334 } 11335 11336 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11337 // Visit that expression. 11338 Visit(Base); 11339 } 11340 11341 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11342 Expr *Callee = E->getCallee(); 11343 11344 if (isa<UnresolvedLookupExpr>(Callee)) 11345 return Inherited::VisitCXXOperatorCallExpr(E); 11346 11347 Visit(Callee); 11348 for (auto Arg: E->arguments()) 11349 HandleValue(Arg->IgnoreParenImpCasts()); 11350 } 11351 11352 void VisitUnaryOperator(UnaryOperator *E) { 11353 // For POD record types, addresses of its own members are well-defined. 11354 if (E->getOpcode() == UO_AddrOf && isRecordType && 11355 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11356 if (!isPODType) 11357 HandleValue(E->getSubExpr()); 11358 return; 11359 } 11360 11361 if (E->isIncrementDecrementOp()) { 11362 HandleValue(E->getSubExpr()); 11363 return; 11364 } 11365 11366 Inherited::VisitUnaryOperator(E); 11367 } 11368 11369 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11370 11371 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11372 if (E->getConstructor()->isCopyConstructor()) { 11373 Expr *ArgExpr = E->getArg(0); 11374 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11375 if (ILE->getNumInits() == 1) 11376 ArgExpr = ILE->getInit(0); 11377 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11378 if (ICE->getCastKind() == CK_NoOp) 11379 ArgExpr = ICE->getSubExpr(); 11380 HandleValue(ArgExpr); 11381 return; 11382 } 11383 Inherited::VisitCXXConstructExpr(E); 11384 } 11385 11386 void VisitCallExpr(CallExpr *E) { 11387 // Treat std::move as a use. 11388 if (E->isCallToStdMove()) { 11389 HandleValue(E->getArg(0)); 11390 return; 11391 } 11392 11393 Inherited::VisitCallExpr(E); 11394 } 11395 11396 void VisitBinaryOperator(BinaryOperator *E) { 11397 if (E->isCompoundAssignmentOp()) { 11398 HandleValue(E->getLHS()); 11399 Visit(E->getRHS()); 11400 return; 11401 } 11402 11403 Inherited::VisitBinaryOperator(E); 11404 } 11405 11406 // A custom visitor for BinaryConditionalOperator is needed because the 11407 // regular visitor would check the condition and true expression separately 11408 // but both point to the same place giving duplicate diagnostics. 11409 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11410 Visit(E->getCond()); 11411 Visit(E->getFalseExpr()); 11412 } 11413 11414 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11415 Decl* ReferenceDecl = DRE->getDecl(); 11416 if (OrigDecl != ReferenceDecl) return; 11417 unsigned diag; 11418 if (isReferenceType) { 11419 diag = diag::warn_uninit_self_reference_in_reference_init; 11420 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11421 diag = diag::warn_static_self_reference_in_init; 11422 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11423 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11424 DRE->getDecl()->getType()->isRecordType()) { 11425 diag = diag::warn_uninit_self_reference_in_init; 11426 } else { 11427 // Local variables will be handled by the CFG analysis. 11428 return; 11429 } 11430 11431 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11432 S.PDiag(diag) 11433 << DRE->getDecl() << OrigDecl->getLocation() 11434 << DRE->getSourceRange()); 11435 } 11436 }; 11437 11438 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11439 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11440 bool DirectInit) { 11441 // Parameters arguments are occassionially constructed with itself, 11442 // for instance, in recursive functions. Skip them. 11443 if (isa<ParmVarDecl>(OrigDecl)) 11444 return; 11445 11446 E = E->IgnoreParens(); 11447 11448 // Skip checking T a = a where T is not a record or reference type. 11449 // Doing so is a way to silence uninitialized warnings. 11450 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11451 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11452 if (ICE->getCastKind() == CK_LValueToRValue) 11453 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11454 if (DRE->getDecl() == OrigDecl) 11455 return; 11456 11457 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11458 } 11459 } // end anonymous namespace 11460 11461 namespace { 11462 // Simple wrapper to add the name of a variable or (if no variable is 11463 // available) a DeclarationName into a diagnostic. 11464 struct VarDeclOrName { 11465 VarDecl *VDecl; 11466 DeclarationName Name; 11467 11468 friend const Sema::SemaDiagnosticBuilder & 11469 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11470 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11471 } 11472 }; 11473 } // end anonymous namespace 11474 11475 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11476 DeclarationName Name, QualType Type, 11477 TypeSourceInfo *TSI, 11478 SourceRange Range, bool DirectInit, 11479 Expr *Init) { 11480 bool IsInitCapture = !VDecl; 11481 assert((!VDecl || !VDecl->isInitCapture()) && 11482 "init captures are expected to be deduced prior to initialization"); 11483 11484 VarDeclOrName VN{VDecl, Name}; 11485 11486 DeducedType *Deduced = Type->getContainedDeducedType(); 11487 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11488 11489 // C++11 [dcl.spec.auto]p3 11490 if (!Init) { 11491 assert(VDecl && "no init for init capture deduction?"); 11492 11493 // Except for class argument deduction, and then for an initializing 11494 // declaration only, i.e. no static at class scope or extern. 11495 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11496 VDecl->hasExternalStorage() || 11497 VDecl->isStaticDataMember()) { 11498 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11499 << VDecl->getDeclName() << Type; 11500 return QualType(); 11501 } 11502 } 11503 11504 ArrayRef<Expr*> DeduceInits; 11505 if (Init) 11506 DeduceInits = Init; 11507 11508 if (DirectInit) { 11509 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11510 DeduceInits = PL->exprs(); 11511 } 11512 11513 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11514 assert(VDecl && "non-auto type for init capture deduction?"); 11515 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11516 InitializationKind Kind = InitializationKind::CreateForInit( 11517 VDecl->getLocation(), DirectInit, Init); 11518 // FIXME: Initialization should not be taking a mutable list of inits. 11519 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11520 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11521 InitsCopy); 11522 } 11523 11524 if (DirectInit) { 11525 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11526 DeduceInits = IL->inits(); 11527 } 11528 11529 // Deduction only works if we have exactly one source expression. 11530 if (DeduceInits.empty()) { 11531 // It isn't possible to write this directly, but it is possible to 11532 // end up in this situation with "auto x(some_pack...);" 11533 Diag(Init->getBeginLoc(), IsInitCapture 11534 ? diag::err_init_capture_no_expression 11535 : diag::err_auto_var_init_no_expression) 11536 << VN << Type << Range; 11537 return QualType(); 11538 } 11539 11540 if (DeduceInits.size() > 1) { 11541 Diag(DeduceInits[1]->getBeginLoc(), 11542 IsInitCapture ? diag::err_init_capture_multiple_expressions 11543 : diag::err_auto_var_init_multiple_expressions) 11544 << VN << Type << Range; 11545 return QualType(); 11546 } 11547 11548 Expr *DeduceInit = DeduceInits[0]; 11549 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11550 Diag(Init->getBeginLoc(), IsInitCapture 11551 ? diag::err_init_capture_paren_braces 11552 : diag::err_auto_var_init_paren_braces) 11553 << isa<InitListExpr>(Init) << VN << Type << Range; 11554 return QualType(); 11555 } 11556 11557 // Expressions default to 'id' when we're in a debugger. 11558 bool DefaultedAnyToId = false; 11559 if (getLangOpts().DebuggerCastResultToId && 11560 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11561 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11562 if (Result.isInvalid()) { 11563 return QualType(); 11564 } 11565 Init = Result.get(); 11566 DefaultedAnyToId = true; 11567 } 11568 11569 // C++ [dcl.decomp]p1: 11570 // If the assignment-expression [...] has array type A and no ref-qualifier 11571 // is present, e has type cv A 11572 if (VDecl && isa<DecompositionDecl>(VDecl) && 11573 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11574 DeduceInit->getType()->isConstantArrayType()) 11575 return Context.getQualifiedType(DeduceInit->getType(), 11576 Type.getQualifiers()); 11577 11578 QualType DeducedType; 11579 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11580 if (!IsInitCapture) 11581 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11582 else if (isa<InitListExpr>(Init)) 11583 Diag(Range.getBegin(), 11584 diag::err_init_capture_deduction_failure_from_init_list) 11585 << VN 11586 << (DeduceInit->getType().isNull() ? TSI->getType() 11587 : DeduceInit->getType()) 11588 << DeduceInit->getSourceRange(); 11589 else 11590 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11591 << VN << TSI->getType() 11592 << (DeduceInit->getType().isNull() ? TSI->getType() 11593 : DeduceInit->getType()) 11594 << DeduceInit->getSourceRange(); 11595 } 11596 11597 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11598 // 'id' instead of a specific object type prevents most of our usual 11599 // checks. 11600 // We only want to warn outside of template instantiations, though: 11601 // inside a template, the 'id' could have come from a parameter. 11602 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11603 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11604 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11605 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11606 } 11607 11608 return DeducedType; 11609 } 11610 11611 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11612 Expr *Init) { 11613 assert(!Init || !Init->containsErrors()); 11614 QualType DeducedType = deduceVarTypeFromInitializer( 11615 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11616 VDecl->getSourceRange(), DirectInit, Init); 11617 if (DeducedType.isNull()) { 11618 VDecl->setInvalidDecl(); 11619 return true; 11620 } 11621 11622 VDecl->setType(DeducedType); 11623 assert(VDecl->isLinkageValid()); 11624 11625 // In ARC, infer lifetime. 11626 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11627 VDecl->setInvalidDecl(); 11628 11629 if (getLangOpts().OpenCL) 11630 deduceOpenCLAddressSpace(VDecl); 11631 11632 // If this is a redeclaration, check that the type we just deduced matches 11633 // the previously declared type. 11634 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11635 // We never need to merge the type, because we cannot form an incomplete 11636 // array of auto, nor deduce such a type. 11637 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11638 } 11639 11640 // Check the deduced type is valid for a variable declaration. 11641 CheckVariableDeclarationType(VDecl); 11642 return VDecl->isInvalidDecl(); 11643 } 11644 11645 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11646 SourceLocation Loc) { 11647 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11648 Init = EWC->getSubExpr(); 11649 11650 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11651 Init = CE->getSubExpr(); 11652 11653 QualType InitType = Init->getType(); 11654 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11655 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11656 "shouldn't be called if type doesn't have a non-trivial C struct"); 11657 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11658 for (auto I : ILE->inits()) { 11659 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11660 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11661 continue; 11662 SourceLocation SL = I->getExprLoc(); 11663 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11664 } 11665 return; 11666 } 11667 11668 if (isa<ImplicitValueInitExpr>(Init)) { 11669 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11670 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11671 NTCUK_Init); 11672 } else { 11673 // Assume all other explicit initializers involving copying some existing 11674 // object. 11675 // TODO: ignore any explicit initializers where we can guarantee 11676 // copy-elision. 11677 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11678 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11679 } 11680 } 11681 11682 namespace { 11683 11684 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11685 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11686 // in the source code or implicitly by the compiler if it is in a union 11687 // defined in a system header and has non-trivial ObjC ownership 11688 // qualifications. We don't want those fields to participate in determining 11689 // whether the containing union is non-trivial. 11690 return FD->hasAttr<UnavailableAttr>(); 11691 } 11692 11693 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11694 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11695 void> { 11696 using Super = 11697 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11698 void>; 11699 11700 DiagNonTrivalCUnionDefaultInitializeVisitor( 11701 QualType OrigTy, SourceLocation OrigLoc, 11702 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11703 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11704 11705 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11706 const FieldDecl *FD, bool InNonTrivialUnion) { 11707 if (const auto *AT = S.Context.getAsArrayType(QT)) 11708 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11709 InNonTrivialUnion); 11710 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11711 } 11712 11713 void visitARCStrong(QualType QT, const FieldDecl *FD, 11714 bool InNonTrivialUnion) { 11715 if (InNonTrivialUnion) 11716 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11717 << 1 << 0 << QT << FD->getName(); 11718 } 11719 11720 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11721 if (InNonTrivialUnion) 11722 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11723 << 1 << 0 << QT << FD->getName(); 11724 } 11725 11726 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11727 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11728 if (RD->isUnion()) { 11729 if (OrigLoc.isValid()) { 11730 bool IsUnion = false; 11731 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11732 IsUnion = OrigRD->isUnion(); 11733 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11734 << 0 << OrigTy << IsUnion << UseContext; 11735 // Reset OrigLoc so that this diagnostic is emitted only once. 11736 OrigLoc = SourceLocation(); 11737 } 11738 InNonTrivialUnion = true; 11739 } 11740 11741 if (InNonTrivialUnion) 11742 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11743 << 0 << 0 << QT.getUnqualifiedType() << ""; 11744 11745 for (const FieldDecl *FD : RD->fields()) 11746 if (!shouldIgnoreForRecordTriviality(FD)) 11747 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11748 } 11749 11750 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11751 11752 // The non-trivial C union type or the struct/union type that contains a 11753 // non-trivial C union. 11754 QualType OrigTy; 11755 SourceLocation OrigLoc; 11756 Sema::NonTrivialCUnionContext UseContext; 11757 Sema &S; 11758 }; 11759 11760 struct DiagNonTrivalCUnionDestructedTypeVisitor 11761 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11762 using Super = 11763 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11764 11765 DiagNonTrivalCUnionDestructedTypeVisitor( 11766 QualType OrigTy, SourceLocation OrigLoc, 11767 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11768 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11769 11770 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11771 const FieldDecl *FD, bool InNonTrivialUnion) { 11772 if (const auto *AT = S.Context.getAsArrayType(QT)) 11773 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11774 InNonTrivialUnion); 11775 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11776 } 11777 11778 void visitARCStrong(QualType QT, const FieldDecl *FD, 11779 bool InNonTrivialUnion) { 11780 if (InNonTrivialUnion) 11781 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11782 << 1 << 1 << QT << FD->getName(); 11783 } 11784 11785 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11786 if (InNonTrivialUnion) 11787 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11788 << 1 << 1 << QT << FD->getName(); 11789 } 11790 11791 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11792 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11793 if (RD->isUnion()) { 11794 if (OrigLoc.isValid()) { 11795 bool IsUnion = false; 11796 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11797 IsUnion = OrigRD->isUnion(); 11798 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11799 << 1 << OrigTy << IsUnion << UseContext; 11800 // Reset OrigLoc so that this diagnostic is emitted only once. 11801 OrigLoc = SourceLocation(); 11802 } 11803 InNonTrivialUnion = true; 11804 } 11805 11806 if (InNonTrivialUnion) 11807 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11808 << 0 << 1 << QT.getUnqualifiedType() << ""; 11809 11810 for (const FieldDecl *FD : RD->fields()) 11811 if (!shouldIgnoreForRecordTriviality(FD)) 11812 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11813 } 11814 11815 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11816 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11817 bool InNonTrivialUnion) {} 11818 11819 // The non-trivial C union type or the struct/union type that contains a 11820 // non-trivial C union. 11821 QualType OrigTy; 11822 SourceLocation OrigLoc; 11823 Sema::NonTrivialCUnionContext UseContext; 11824 Sema &S; 11825 }; 11826 11827 struct DiagNonTrivalCUnionCopyVisitor 11828 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11829 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11830 11831 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11832 Sema::NonTrivialCUnionContext UseContext, 11833 Sema &S) 11834 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11835 11836 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11837 const FieldDecl *FD, bool InNonTrivialUnion) { 11838 if (const auto *AT = S.Context.getAsArrayType(QT)) 11839 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11840 InNonTrivialUnion); 11841 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11842 } 11843 11844 void visitARCStrong(QualType QT, const FieldDecl *FD, 11845 bool InNonTrivialUnion) { 11846 if (InNonTrivialUnion) 11847 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11848 << 1 << 2 << QT << FD->getName(); 11849 } 11850 11851 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11852 if (InNonTrivialUnion) 11853 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11854 << 1 << 2 << QT << FD->getName(); 11855 } 11856 11857 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11858 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11859 if (RD->isUnion()) { 11860 if (OrigLoc.isValid()) { 11861 bool IsUnion = false; 11862 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11863 IsUnion = OrigRD->isUnion(); 11864 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11865 << 2 << OrigTy << IsUnion << UseContext; 11866 // Reset OrigLoc so that this diagnostic is emitted only once. 11867 OrigLoc = SourceLocation(); 11868 } 11869 InNonTrivialUnion = true; 11870 } 11871 11872 if (InNonTrivialUnion) 11873 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11874 << 0 << 2 << QT.getUnqualifiedType() << ""; 11875 11876 for (const FieldDecl *FD : RD->fields()) 11877 if (!shouldIgnoreForRecordTriviality(FD)) 11878 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11879 } 11880 11881 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11882 const FieldDecl *FD, bool InNonTrivialUnion) {} 11883 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11884 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11885 bool InNonTrivialUnion) {} 11886 11887 // The non-trivial C union type or the struct/union type that contains a 11888 // non-trivial C union. 11889 QualType OrigTy; 11890 SourceLocation OrigLoc; 11891 Sema::NonTrivialCUnionContext UseContext; 11892 Sema &S; 11893 }; 11894 11895 } // namespace 11896 11897 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11898 NonTrivialCUnionContext UseContext, 11899 unsigned NonTrivialKind) { 11900 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11901 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11902 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11903 "shouldn't be called if type doesn't have a non-trivial C union"); 11904 11905 if ((NonTrivialKind & NTCUK_Init) && 11906 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11907 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11908 .visit(QT, nullptr, false); 11909 if ((NonTrivialKind & NTCUK_Destruct) && 11910 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11911 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11912 .visit(QT, nullptr, false); 11913 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11914 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11915 .visit(QT, nullptr, false); 11916 } 11917 11918 /// AddInitializerToDecl - Adds the initializer Init to the 11919 /// declaration dcl. If DirectInit is true, this is C++ direct 11920 /// initialization rather than copy initialization. 11921 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11922 // If there is no declaration, there was an error parsing it. Just ignore 11923 // the initializer. 11924 if (!RealDecl || RealDecl->isInvalidDecl()) { 11925 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11926 return; 11927 } 11928 11929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11930 // Pure-specifiers are handled in ActOnPureSpecifier. 11931 Diag(Method->getLocation(), diag::err_member_function_initialization) 11932 << Method->getDeclName() << Init->getSourceRange(); 11933 Method->setInvalidDecl(); 11934 return; 11935 } 11936 11937 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11938 if (!VDecl) { 11939 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11940 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11941 RealDecl->setInvalidDecl(); 11942 return; 11943 } 11944 11945 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11946 if (VDecl->getType()->isUndeducedType()) { 11947 // Attempt typo correction early so that the type of the init expression can 11948 // be deduced based on the chosen correction if the original init contains a 11949 // TypoExpr. 11950 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11951 if (!Res.isUsable()) { 11952 // There are unresolved typos in Init, just drop them. 11953 // FIXME: improve the recovery strategy to preserve the Init. 11954 RealDecl->setInvalidDecl(); 11955 return; 11956 } 11957 if (Res.get()->containsErrors()) { 11958 // Invalidate the decl as we don't know the type for recovery-expr yet. 11959 RealDecl->setInvalidDecl(); 11960 VDecl->setInit(Res.get()); 11961 return; 11962 } 11963 Init = Res.get(); 11964 11965 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11966 return; 11967 } 11968 11969 // dllimport cannot be used on variable definitions. 11970 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11971 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11972 VDecl->setInvalidDecl(); 11973 return; 11974 } 11975 11976 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11977 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11978 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11979 VDecl->setInvalidDecl(); 11980 return; 11981 } 11982 11983 if (!VDecl->getType()->isDependentType()) { 11984 // A definition must end up with a complete type, which means it must be 11985 // complete with the restriction that an array type might be completed by 11986 // the initializer; note that later code assumes this restriction. 11987 QualType BaseDeclType = VDecl->getType(); 11988 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11989 BaseDeclType = Array->getElementType(); 11990 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11991 diag::err_typecheck_decl_incomplete_type)) { 11992 RealDecl->setInvalidDecl(); 11993 return; 11994 } 11995 11996 // The variable can not have an abstract class type. 11997 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11998 diag::err_abstract_type_in_decl, 11999 AbstractVariableType)) 12000 VDecl->setInvalidDecl(); 12001 } 12002 12003 // If adding the initializer will turn this declaration into a definition, 12004 // and we already have a definition for this variable, diagnose or otherwise 12005 // handle the situation. 12006 VarDecl *Def; 12007 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12008 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12009 !VDecl->isThisDeclarationADemotedDefinition() && 12010 checkVarDeclRedefinition(Def, VDecl)) 12011 return; 12012 12013 if (getLangOpts().CPlusPlus) { 12014 // C++ [class.static.data]p4 12015 // If a static data member is of const integral or const 12016 // enumeration type, its declaration in the class definition can 12017 // specify a constant-initializer which shall be an integral 12018 // constant expression (5.19). In that case, the member can appear 12019 // in integral constant expressions. The member shall still be 12020 // defined in a namespace scope if it is used in the program and the 12021 // namespace scope definition shall not contain an initializer. 12022 // 12023 // We already performed a redefinition check above, but for static 12024 // data members we also need to check whether there was an in-class 12025 // declaration with an initializer. 12026 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12027 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12028 << VDecl->getDeclName(); 12029 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12030 diag::note_previous_initializer) 12031 << 0; 12032 return; 12033 } 12034 12035 if (VDecl->hasLocalStorage()) 12036 setFunctionHasBranchProtectedScope(); 12037 12038 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12039 VDecl->setInvalidDecl(); 12040 return; 12041 } 12042 } 12043 12044 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12045 // a kernel function cannot be initialized." 12046 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12047 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12048 VDecl->setInvalidDecl(); 12049 return; 12050 } 12051 12052 // The LoaderUninitialized attribute acts as a definition (of undef). 12053 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12054 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12055 VDecl->setInvalidDecl(); 12056 return; 12057 } 12058 12059 // Get the decls type and save a reference for later, since 12060 // CheckInitializerTypes may change it. 12061 QualType DclT = VDecl->getType(), SavT = DclT; 12062 12063 // Expressions default to 'id' when we're in a debugger 12064 // and we are assigning it to a variable of Objective-C pointer type. 12065 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12066 Init->getType() == Context.UnknownAnyTy) { 12067 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12068 if (Result.isInvalid()) { 12069 VDecl->setInvalidDecl(); 12070 return; 12071 } 12072 Init = Result.get(); 12073 } 12074 12075 // Perform the initialization. 12076 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12077 if (!VDecl->isInvalidDecl()) { 12078 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12079 InitializationKind Kind = InitializationKind::CreateForInit( 12080 VDecl->getLocation(), DirectInit, Init); 12081 12082 MultiExprArg Args = Init; 12083 if (CXXDirectInit) 12084 Args = MultiExprArg(CXXDirectInit->getExprs(), 12085 CXXDirectInit->getNumExprs()); 12086 12087 // Try to correct any TypoExprs in the initialization arguments. 12088 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12089 ExprResult Res = CorrectDelayedTyposInExpr( 12090 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12091 [this, Entity, Kind](Expr *E) { 12092 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12093 return Init.Failed() ? ExprError() : E; 12094 }); 12095 if (Res.isInvalid()) { 12096 VDecl->setInvalidDecl(); 12097 } else if (Res.get() != Args[Idx]) { 12098 Args[Idx] = Res.get(); 12099 } 12100 } 12101 if (VDecl->isInvalidDecl()) 12102 return; 12103 12104 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12105 /*TopLevelOfInitList=*/false, 12106 /*TreatUnavailableAsInvalid=*/false); 12107 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12108 if (Result.isInvalid()) { 12109 // If the provied initializer fails to initialize the var decl, 12110 // we attach a recovery expr for better recovery. 12111 auto RecoveryExpr = 12112 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12113 if (RecoveryExpr.get()) 12114 VDecl->setInit(RecoveryExpr.get()); 12115 return; 12116 } 12117 12118 Init = Result.getAs<Expr>(); 12119 } 12120 12121 // Check for self-references within variable initializers. 12122 // Variables declared within a function/method body (except for references) 12123 // are handled by a dataflow analysis. 12124 // This is undefined behavior in C++, but valid in C. 12125 if (getLangOpts().CPlusPlus) { 12126 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12127 VDecl->getType()->isReferenceType()) { 12128 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12129 } 12130 } 12131 12132 // If the type changed, it means we had an incomplete type that was 12133 // completed by the initializer. For example: 12134 // int ary[] = { 1, 3, 5 }; 12135 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12136 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12137 VDecl->setType(DclT); 12138 12139 if (!VDecl->isInvalidDecl()) { 12140 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12141 12142 if (VDecl->hasAttr<BlocksAttr>()) 12143 checkRetainCycles(VDecl, Init); 12144 12145 // It is safe to assign a weak reference into a strong variable. 12146 // Although this code can still have problems: 12147 // id x = self.weakProp; 12148 // id y = self.weakProp; 12149 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12150 // paths through the function. This should be revisited if 12151 // -Wrepeated-use-of-weak is made flow-sensitive. 12152 if (FunctionScopeInfo *FSI = getCurFunction()) 12153 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12154 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12155 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12156 Init->getBeginLoc())) 12157 FSI->markSafeWeakUse(Init); 12158 } 12159 12160 // The initialization is usually a full-expression. 12161 // 12162 // FIXME: If this is a braced initialization of an aggregate, it is not 12163 // an expression, and each individual field initializer is a separate 12164 // full-expression. For instance, in: 12165 // 12166 // struct Temp { ~Temp(); }; 12167 // struct S { S(Temp); }; 12168 // struct T { S a, b; } t = { Temp(), Temp() } 12169 // 12170 // we should destroy the first Temp before constructing the second. 12171 ExprResult Result = 12172 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12173 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12174 if (Result.isInvalid()) { 12175 VDecl->setInvalidDecl(); 12176 return; 12177 } 12178 Init = Result.get(); 12179 12180 // Attach the initializer to the decl. 12181 VDecl->setInit(Init); 12182 12183 if (VDecl->isLocalVarDecl()) { 12184 // Don't check the initializer if the declaration is malformed. 12185 if (VDecl->isInvalidDecl()) { 12186 // do nothing 12187 12188 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12189 // This is true even in C++ for OpenCL. 12190 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12191 CheckForConstantInitializer(Init, DclT); 12192 12193 // Otherwise, C++ does not restrict the initializer. 12194 } else if (getLangOpts().CPlusPlus) { 12195 // do nothing 12196 12197 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12198 // static storage duration shall be constant expressions or string literals. 12199 } else if (VDecl->getStorageClass() == SC_Static) { 12200 CheckForConstantInitializer(Init, DclT); 12201 12202 // C89 is stricter than C99 for aggregate initializers. 12203 // C89 6.5.7p3: All the expressions [...] in an initializer list 12204 // for an object that has aggregate or union type shall be 12205 // constant expressions. 12206 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12207 isa<InitListExpr>(Init)) { 12208 const Expr *Culprit; 12209 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12210 Diag(Culprit->getExprLoc(), 12211 diag::ext_aggregate_init_not_constant) 12212 << Culprit->getSourceRange(); 12213 } 12214 } 12215 12216 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12217 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12218 if (VDecl->hasLocalStorage()) 12219 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12220 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12221 VDecl->getLexicalDeclContext()->isRecord()) { 12222 // This is an in-class initialization for a static data member, e.g., 12223 // 12224 // struct S { 12225 // static const int value = 17; 12226 // }; 12227 12228 // C++ [class.mem]p4: 12229 // A member-declarator can contain a constant-initializer only 12230 // if it declares a static member (9.4) of const integral or 12231 // const enumeration type, see 9.4.2. 12232 // 12233 // C++11 [class.static.data]p3: 12234 // If a non-volatile non-inline const static data member is of integral 12235 // or enumeration type, its declaration in the class definition can 12236 // specify a brace-or-equal-initializer in which every initializer-clause 12237 // that is an assignment-expression is a constant expression. A static 12238 // data member of literal type can be declared in the class definition 12239 // with the constexpr specifier; if so, its declaration shall specify a 12240 // brace-or-equal-initializer in which every initializer-clause that is 12241 // an assignment-expression is a constant expression. 12242 12243 // Do nothing on dependent types. 12244 if (DclT->isDependentType()) { 12245 12246 // Allow any 'static constexpr' members, whether or not they are of literal 12247 // type. We separately check that every constexpr variable is of literal 12248 // type. 12249 } else if (VDecl->isConstexpr()) { 12250 12251 // Require constness. 12252 } else if (!DclT.isConstQualified()) { 12253 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12254 << Init->getSourceRange(); 12255 VDecl->setInvalidDecl(); 12256 12257 // We allow integer constant expressions in all cases. 12258 } else if (DclT->isIntegralOrEnumerationType()) { 12259 // Check whether the expression is a constant expression. 12260 SourceLocation Loc; 12261 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12262 // In C++11, a non-constexpr const static data member with an 12263 // in-class initializer cannot be volatile. 12264 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12265 else if (Init->isValueDependent()) 12266 ; // Nothing to check. 12267 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12268 ; // Ok, it's an ICE! 12269 else if (Init->getType()->isScopedEnumeralType() && 12270 Init->isCXX11ConstantExpr(Context)) 12271 ; // Ok, it is a scoped-enum constant expression. 12272 else if (Init->isEvaluatable(Context)) { 12273 // If we can constant fold the initializer through heroics, accept it, 12274 // but report this as a use of an extension for -pedantic. 12275 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12276 << Init->getSourceRange(); 12277 } else { 12278 // Otherwise, this is some crazy unknown case. Report the issue at the 12279 // location provided by the isIntegerConstantExpr failed check. 12280 Diag(Loc, diag::err_in_class_initializer_non_constant) 12281 << Init->getSourceRange(); 12282 VDecl->setInvalidDecl(); 12283 } 12284 12285 // We allow foldable floating-point constants as an extension. 12286 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12287 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12288 // it anyway and provide a fixit to add the 'constexpr'. 12289 if (getLangOpts().CPlusPlus11) { 12290 Diag(VDecl->getLocation(), 12291 diag::ext_in_class_initializer_float_type_cxx11) 12292 << DclT << Init->getSourceRange(); 12293 Diag(VDecl->getBeginLoc(), 12294 diag::note_in_class_initializer_float_type_cxx11) 12295 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12296 } else { 12297 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12298 << DclT << Init->getSourceRange(); 12299 12300 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12301 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12302 << Init->getSourceRange(); 12303 VDecl->setInvalidDecl(); 12304 } 12305 } 12306 12307 // Suggest adding 'constexpr' in C++11 for literal types. 12308 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12309 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12310 << DclT << Init->getSourceRange() 12311 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12312 VDecl->setConstexpr(true); 12313 12314 } else { 12315 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12316 << DclT << Init->getSourceRange(); 12317 VDecl->setInvalidDecl(); 12318 } 12319 } else if (VDecl->isFileVarDecl()) { 12320 // In C, extern is typically used to avoid tentative definitions when 12321 // declaring variables in headers, but adding an intializer makes it a 12322 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12323 // In C++, extern is often used to give implictly static const variables 12324 // external linkage, so don't warn in that case. If selectany is present, 12325 // this might be header code intended for C and C++ inclusion, so apply the 12326 // C++ rules. 12327 if (VDecl->getStorageClass() == SC_Extern && 12328 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12329 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12330 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12331 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12332 Diag(VDecl->getLocation(), diag::warn_extern_init); 12333 12334 // In Microsoft C++ mode, a const variable defined in namespace scope has 12335 // external linkage by default if the variable is declared with 12336 // __declspec(dllexport). 12337 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12338 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12339 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12340 VDecl->setStorageClass(SC_Extern); 12341 12342 // C99 6.7.8p4. All file scoped initializers need to be constant. 12343 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12344 CheckForConstantInitializer(Init, DclT); 12345 } 12346 12347 QualType InitType = Init->getType(); 12348 if (!InitType.isNull() && 12349 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12350 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12351 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12352 12353 // We will represent direct-initialization similarly to copy-initialization: 12354 // int x(1); -as-> int x = 1; 12355 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12356 // 12357 // Clients that want to distinguish between the two forms, can check for 12358 // direct initializer using VarDecl::getInitStyle(). 12359 // A major benefit is that clients that don't particularly care about which 12360 // exactly form was it (like the CodeGen) can handle both cases without 12361 // special case code. 12362 12363 // C++ 8.5p11: 12364 // The form of initialization (using parentheses or '=') is generally 12365 // insignificant, but does matter when the entity being initialized has a 12366 // class type. 12367 if (CXXDirectInit) { 12368 assert(DirectInit && "Call-style initializer must be direct init."); 12369 VDecl->setInitStyle(VarDecl::CallInit); 12370 } else if (DirectInit) { 12371 // This must be list-initialization. No other way is direct-initialization. 12372 VDecl->setInitStyle(VarDecl::ListInit); 12373 } 12374 12375 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12376 DeclsToCheckForDeferredDiags.push_back(VDecl); 12377 CheckCompleteVariableDeclaration(VDecl); 12378 } 12379 12380 /// ActOnInitializerError - Given that there was an error parsing an 12381 /// initializer for the given declaration, try to return to some form 12382 /// of sanity. 12383 void Sema::ActOnInitializerError(Decl *D) { 12384 // Our main concern here is re-establishing invariants like "a 12385 // variable's type is either dependent or complete". 12386 if (!D || D->isInvalidDecl()) return; 12387 12388 VarDecl *VD = dyn_cast<VarDecl>(D); 12389 if (!VD) return; 12390 12391 // Bindings are not usable if we can't make sense of the initializer. 12392 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12393 for (auto *BD : DD->bindings()) 12394 BD->setInvalidDecl(); 12395 12396 // Auto types are meaningless if we can't make sense of the initializer. 12397 if (VD->getType()->isUndeducedType()) { 12398 D->setInvalidDecl(); 12399 return; 12400 } 12401 12402 QualType Ty = VD->getType(); 12403 if (Ty->isDependentType()) return; 12404 12405 // Require a complete type. 12406 if (RequireCompleteType(VD->getLocation(), 12407 Context.getBaseElementType(Ty), 12408 diag::err_typecheck_decl_incomplete_type)) { 12409 VD->setInvalidDecl(); 12410 return; 12411 } 12412 12413 // Require a non-abstract type. 12414 if (RequireNonAbstractType(VD->getLocation(), Ty, 12415 diag::err_abstract_type_in_decl, 12416 AbstractVariableType)) { 12417 VD->setInvalidDecl(); 12418 return; 12419 } 12420 12421 // Don't bother complaining about constructors or destructors, 12422 // though. 12423 } 12424 12425 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12426 // If there is no declaration, there was an error parsing it. Just ignore it. 12427 if (!RealDecl) 12428 return; 12429 12430 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12431 QualType Type = Var->getType(); 12432 12433 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12434 if (isa<DecompositionDecl>(RealDecl)) { 12435 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12436 Var->setInvalidDecl(); 12437 return; 12438 } 12439 12440 if (Type->isUndeducedType() && 12441 DeduceVariableDeclarationType(Var, false, nullptr)) 12442 return; 12443 12444 // C++11 [class.static.data]p3: A static data member can be declared with 12445 // the constexpr specifier; if so, its declaration shall specify 12446 // a brace-or-equal-initializer. 12447 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12448 // the definition of a variable [...] or the declaration of a static data 12449 // member. 12450 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12451 !Var->isThisDeclarationADemotedDefinition()) { 12452 if (Var->isStaticDataMember()) { 12453 // C++1z removes the relevant rule; the in-class declaration is always 12454 // a definition there. 12455 if (!getLangOpts().CPlusPlus17 && 12456 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12457 Diag(Var->getLocation(), 12458 diag::err_constexpr_static_mem_var_requires_init) 12459 << Var; 12460 Var->setInvalidDecl(); 12461 return; 12462 } 12463 } else { 12464 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12465 Var->setInvalidDecl(); 12466 return; 12467 } 12468 } 12469 12470 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12471 // be initialized. 12472 if (!Var->isInvalidDecl() && 12473 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12474 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12475 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12476 Var->setInvalidDecl(); 12477 return; 12478 } 12479 12480 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12481 if (Var->getStorageClass() == SC_Extern) { 12482 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12483 << Var; 12484 Var->setInvalidDecl(); 12485 return; 12486 } 12487 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12488 diag::err_typecheck_decl_incomplete_type)) { 12489 Var->setInvalidDecl(); 12490 return; 12491 } 12492 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12493 if (!RD->hasTrivialDefaultConstructor()) { 12494 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12495 Var->setInvalidDecl(); 12496 return; 12497 } 12498 } 12499 } 12500 12501 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12502 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12503 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12504 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12505 NTCUC_DefaultInitializedObject, NTCUK_Init); 12506 12507 12508 switch (DefKind) { 12509 case VarDecl::Definition: 12510 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12511 break; 12512 12513 // We have an out-of-line definition of a static data member 12514 // that has an in-class initializer, so we type-check this like 12515 // a declaration. 12516 // 12517 LLVM_FALLTHROUGH; 12518 12519 case VarDecl::DeclarationOnly: 12520 // It's only a declaration. 12521 12522 // Block scope. C99 6.7p7: If an identifier for an object is 12523 // declared with no linkage (C99 6.2.2p6), the type for the 12524 // object shall be complete. 12525 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12526 !Var->hasLinkage() && !Var->isInvalidDecl() && 12527 RequireCompleteType(Var->getLocation(), Type, 12528 diag::err_typecheck_decl_incomplete_type)) 12529 Var->setInvalidDecl(); 12530 12531 // Make sure that the type is not abstract. 12532 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12533 RequireNonAbstractType(Var->getLocation(), Type, 12534 diag::err_abstract_type_in_decl, 12535 AbstractVariableType)) 12536 Var->setInvalidDecl(); 12537 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12538 Var->getStorageClass() == SC_PrivateExtern) { 12539 Diag(Var->getLocation(), diag::warn_private_extern); 12540 Diag(Var->getLocation(), diag::note_private_extern); 12541 } 12542 12543 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12544 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12545 ExternalDeclarations.push_back(Var); 12546 12547 return; 12548 12549 case VarDecl::TentativeDefinition: 12550 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12551 // object that has file scope without an initializer, and without a 12552 // storage-class specifier or with the storage-class specifier "static", 12553 // constitutes a tentative definition. Note: A tentative definition with 12554 // external linkage is valid (C99 6.2.2p5). 12555 if (!Var->isInvalidDecl()) { 12556 if (const IncompleteArrayType *ArrayT 12557 = Context.getAsIncompleteArrayType(Type)) { 12558 if (RequireCompleteSizedType( 12559 Var->getLocation(), ArrayT->getElementType(), 12560 diag::err_array_incomplete_or_sizeless_type)) 12561 Var->setInvalidDecl(); 12562 } else if (Var->getStorageClass() == SC_Static) { 12563 // C99 6.9.2p3: If the declaration of an identifier for an object is 12564 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12565 // declared type shall not be an incomplete type. 12566 // NOTE: code such as the following 12567 // static struct s; 12568 // struct s { int a; }; 12569 // is accepted by gcc. Hence here we issue a warning instead of 12570 // an error and we do not invalidate the static declaration. 12571 // NOTE: to avoid multiple warnings, only check the first declaration. 12572 if (Var->isFirstDecl()) 12573 RequireCompleteType(Var->getLocation(), Type, 12574 diag::ext_typecheck_decl_incomplete_type); 12575 } 12576 } 12577 12578 // Record the tentative definition; we're done. 12579 if (!Var->isInvalidDecl()) 12580 TentativeDefinitions.push_back(Var); 12581 return; 12582 } 12583 12584 // Provide a specific diagnostic for uninitialized variable 12585 // definitions with incomplete array type. 12586 if (Type->isIncompleteArrayType()) { 12587 Diag(Var->getLocation(), 12588 diag::err_typecheck_incomplete_array_needs_initializer); 12589 Var->setInvalidDecl(); 12590 return; 12591 } 12592 12593 // Provide a specific diagnostic for uninitialized variable 12594 // definitions with reference type. 12595 if (Type->isReferenceType()) { 12596 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12597 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12598 Var->setInvalidDecl(); 12599 return; 12600 } 12601 12602 // Do not attempt to type-check the default initializer for a 12603 // variable with dependent type. 12604 if (Type->isDependentType()) 12605 return; 12606 12607 if (Var->isInvalidDecl()) 12608 return; 12609 12610 if (!Var->hasAttr<AliasAttr>()) { 12611 if (RequireCompleteType(Var->getLocation(), 12612 Context.getBaseElementType(Type), 12613 diag::err_typecheck_decl_incomplete_type)) { 12614 Var->setInvalidDecl(); 12615 return; 12616 } 12617 } else { 12618 return; 12619 } 12620 12621 // The variable can not have an abstract class type. 12622 if (RequireNonAbstractType(Var->getLocation(), Type, 12623 diag::err_abstract_type_in_decl, 12624 AbstractVariableType)) { 12625 Var->setInvalidDecl(); 12626 return; 12627 } 12628 12629 // Check for jumps past the implicit initializer. C++0x 12630 // clarifies that this applies to a "variable with automatic 12631 // storage duration", not a "local variable". 12632 // C++11 [stmt.dcl]p3 12633 // A program that jumps from a point where a variable with automatic 12634 // storage duration is not in scope to a point where it is in scope is 12635 // ill-formed unless the variable has scalar type, class type with a 12636 // trivial default constructor and a trivial destructor, a cv-qualified 12637 // version of one of these types, or an array of one of the preceding 12638 // types and is declared without an initializer. 12639 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12640 if (const RecordType *Record 12641 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12642 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12643 // Mark the function (if we're in one) for further checking even if the 12644 // looser rules of C++11 do not require such checks, so that we can 12645 // diagnose incompatibilities with C++98. 12646 if (!CXXRecord->isPOD()) 12647 setFunctionHasBranchProtectedScope(); 12648 } 12649 } 12650 // In OpenCL, we can't initialize objects in the __local address space, 12651 // even implicitly, so don't synthesize an implicit initializer. 12652 if (getLangOpts().OpenCL && 12653 Var->getType().getAddressSpace() == LangAS::opencl_local) 12654 return; 12655 // C++03 [dcl.init]p9: 12656 // If no initializer is specified for an object, and the 12657 // object is of (possibly cv-qualified) non-POD class type (or 12658 // array thereof), the object shall be default-initialized; if 12659 // the object is of const-qualified type, the underlying class 12660 // type shall have a user-declared default 12661 // constructor. Otherwise, if no initializer is specified for 12662 // a non- static object, the object and its subobjects, if 12663 // any, have an indeterminate initial value); if the object 12664 // or any of its subobjects are of const-qualified type, the 12665 // program is ill-formed. 12666 // C++0x [dcl.init]p11: 12667 // If no initializer is specified for an object, the object is 12668 // default-initialized; [...]. 12669 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12670 InitializationKind Kind 12671 = InitializationKind::CreateDefault(Var->getLocation()); 12672 12673 InitializationSequence InitSeq(*this, Entity, Kind, None); 12674 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12675 12676 if (Init.get()) { 12677 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12678 // This is important for template substitution. 12679 Var->setInitStyle(VarDecl::CallInit); 12680 } else if (Init.isInvalid()) { 12681 // If default-init fails, attach a recovery-expr initializer to track 12682 // that initialization was attempted and failed. 12683 auto RecoveryExpr = 12684 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12685 if (RecoveryExpr.get()) 12686 Var->setInit(RecoveryExpr.get()); 12687 } 12688 12689 CheckCompleteVariableDeclaration(Var); 12690 } 12691 } 12692 12693 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12694 // If there is no declaration, there was an error parsing it. Ignore it. 12695 if (!D) 12696 return; 12697 12698 VarDecl *VD = dyn_cast<VarDecl>(D); 12699 if (!VD) { 12700 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12701 D->setInvalidDecl(); 12702 return; 12703 } 12704 12705 VD->setCXXForRangeDecl(true); 12706 12707 // for-range-declaration cannot be given a storage class specifier. 12708 int Error = -1; 12709 switch (VD->getStorageClass()) { 12710 case SC_None: 12711 break; 12712 case SC_Extern: 12713 Error = 0; 12714 break; 12715 case SC_Static: 12716 Error = 1; 12717 break; 12718 case SC_PrivateExtern: 12719 Error = 2; 12720 break; 12721 case SC_Auto: 12722 Error = 3; 12723 break; 12724 case SC_Register: 12725 Error = 4; 12726 break; 12727 } 12728 if (Error != -1) { 12729 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12730 << VD << Error; 12731 D->setInvalidDecl(); 12732 } 12733 } 12734 12735 StmtResult 12736 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12737 IdentifierInfo *Ident, 12738 ParsedAttributes &Attrs, 12739 SourceLocation AttrEnd) { 12740 // C++1y [stmt.iter]p1: 12741 // A range-based for statement of the form 12742 // for ( for-range-identifier : for-range-initializer ) statement 12743 // is equivalent to 12744 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12745 DeclSpec DS(Attrs.getPool().getFactory()); 12746 12747 const char *PrevSpec; 12748 unsigned DiagID; 12749 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12750 getPrintingPolicy()); 12751 12752 Declarator D(DS, DeclaratorContext::ForContext); 12753 D.SetIdentifier(Ident, IdentLoc); 12754 D.takeAttributes(Attrs, AttrEnd); 12755 12756 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12757 IdentLoc); 12758 Decl *Var = ActOnDeclarator(S, D); 12759 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12760 FinalizeDeclaration(Var); 12761 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12762 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12763 } 12764 12765 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12766 if (var->isInvalidDecl()) return; 12767 12768 if (getLangOpts().OpenCL) { 12769 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12770 // initialiser 12771 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12772 !var->hasInit()) { 12773 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12774 << 1 /*Init*/; 12775 var->setInvalidDecl(); 12776 return; 12777 } 12778 } 12779 12780 // In Objective-C, don't allow jumps past the implicit initialization of a 12781 // local retaining variable. 12782 if (getLangOpts().ObjC && 12783 var->hasLocalStorage()) { 12784 switch (var->getType().getObjCLifetime()) { 12785 case Qualifiers::OCL_None: 12786 case Qualifiers::OCL_ExplicitNone: 12787 case Qualifiers::OCL_Autoreleasing: 12788 break; 12789 12790 case Qualifiers::OCL_Weak: 12791 case Qualifiers::OCL_Strong: 12792 setFunctionHasBranchProtectedScope(); 12793 break; 12794 } 12795 } 12796 12797 if (var->hasLocalStorage() && 12798 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12799 setFunctionHasBranchProtectedScope(); 12800 12801 // Warn about externally-visible variables being defined without a 12802 // prior declaration. We only want to do this for global 12803 // declarations, but we also specifically need to avoid doing it for 12804 // class members because the linkage of an anonymous class can 12805 // change if it's later given a typedef name. 12806 if (var->isThisDeclarationADefinition() && 12807 var->getDeclContext()->getRedeclContext()->isFileContext() && 12808 var->isExternallyVisible() && var->hasLinkage() && 12809 !var->isInline() && !var->getDescribedVarTemplate() && 12810 !isa<VarTemplatePartialSpecializationDecl>(var) && 12811 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12812 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12813 var->getLocation())) { 12814 // Find a previous declaration that's not a definition. 12815 VarDecl *prev = var->getPreviousDecl(); 12816 while (prev && prev->isThisDeclarationADefinition()) 12817 prev = prev->getPreviousDecl(); 12818 12819 if (!prev) { 12820 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12821 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12822 << /* variable */ 0; 12823 } 12824 } 12825 12826 // Cache the result of checking for constant initialization. 12827 Optional<bool> CacheHasConstInit; 12828 const Expr *CacheCulprit = nullptr; 12829 auto checkConstInit = [&]() mutable { 12830 if (!CacheHasConstInit) 12831 CacheHasConstInit = var->getInit()->isConstantInitializer( 12832 Context, var->getType()->isReferenceType(), &CacheCulprit); 12833 return *CacheHasConstInit; 12834 }; 12835 12836 if (var->getTLSKind() == VarDecl::TLS_Static) { 12837 if (var->getType().isDestructedType()) { 12838 // GNU C++98 edits for __thread, [basic.start.term]p3: 12839 // The type of an object with thread storage duration shall not 12840 // have a non-trivial destructor. 12841 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12842 if (getLangOpts().CPlusPlus11) 12843 Diag(var->getLocation(), diag::note_use_thread_local); 12844 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12845 if (!checkConstInit()) { 12846 // GNU C++98 edits for __thread, [basic.start.init]p4: 12847 // An object of thread storage duration shall not require dynamic 12848 // initialization. 12849 // FIXME: Need strict checking here. 12850 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12851 << CacheCulprit->getSourceRange(); 12852 if (getLangOpts().CPlusPlus11) 12853 Diag(var->getLocation(), diag::note_use_thread_local); 12854 } 12855 } 12856 } 12857 12858 // Apply section attributes and pragmas to global variables. 12859 bool GlobalStorage = var->hasGlobalStorage(); 12860 if (GlobalStorage && var->isThisDeclarationADefinition() && 12861 !inTemplateInstantiation()) { 12862 PragmaStack<StringLiteral *> *Stack = nullptr; 12863 int SectionFlags = ASTContext::PSF_Read; 12864 if (var->getType().isConstQualified()) 12865 Stack = &ConstSegStack; 12866 else if (!var->getInit()) { 12867 Stack = &BSSSegStack; 12868 SectionFlags |= ASTContext::PSF_Write; 12869 } else { 12870 Stack = &DataSegStack; 12871 SectionFlags |= ASTContext::PSF_Write; 12872 } 12873 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12874 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12875 SectionFlags |= ASTContext::PSF_Implicit; 12876 UnifySection(SA->getName(), SectionFlags, var); 12877 } else if (Stack->CurrentValue) { 12878 SectionFlags |= ASTContext::PSF_Implicit; 12879 auto SectionName = Stack->CurrentValue->getString(); 12880 var->addAttr(SectionAttr::CreateImplicit( 12881 Context, SectionName, Stack->CurrentPragmaLocation, 12882 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12883 if (UnifySection(SectionName, SectionFlags, var)) 12884 var->dropAttr<SectionAttr>(); 12885 } 12886 12887 // Apply the init_seg attribute if this has an initializer. If the 12888 // initializer turns out to not be dynamic, we'll end up ignoring this 12889 // attribute. 12890 if (CurInitSeg && var->getInit()) 12891 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12892 CurInitSegLoc, 12893 AttributeCommonInfo::AS_Pragma)); 12894 } 12895 12896 if (!var->getType()->isStructureType() && var->hasInit() && 12897 isa<InitListExpr>(var->getInit())) { 12898 const auto *ILE = cast<InitListExpr>(var->getInit()); 12899 unsigned NumInits = ILE->getNumInits(); 12900 if (NumInits > 2) 12901 for (unsigned I = 0; I < NumInits; ++I) { 12902 const auto *Init = ILE->getInit(I); 12903 if (!Init) 12904 break; 12905 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12906 if (!SL) 12907 break; 12908 12909 unsigned NumConcat = SL->getNumConcatenated(); 12910 // Diagnose missing comma in string array initialization. 12911 // Do not warn when all the elements in the initializer are concatenated 12912 // together. Do not warn for macros too. 12913 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 12914 bool OnlyOneMissingComma = true; 12915 for (unsigned J = I + 1; J < NumInits; ++J) { 12916 const auto *Init = ILE->getInit(J); 12917 if (!Init) 12918 break; 12919 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12920 if (!SLJ || SLJ->getNumConcatenated() > 1) { 12921 OnlyOneMissingComma = false; 12922 break; 12923 } 12924 } 12925 12926 if (OnlyOneMissingComma) { 12927 SmallVector<FixItHint, 1> Hints; 12928 for (unsigned i = 0; i < NumConcat - 1; ++i) 12929 Hints.push_back(FixItHint::CreateInsertion( 12930 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 12931 12932 Diag(SL->getStrTokenLoc(1), 12933 diag::warn_concatenated_literal_array_init) 12934 << Hints; 12935 Diag(SL->getBeginLoc(), 12936 diag::note_concatenated_string_literal_silence); 12937 } 12938 // In any case, stop now. 12939 break; 12940 } 12941 } 12942 } 12943 12944 // All the following checks are C++ only. 12945 if (!getLangOpts().CPlusPlus) { 12946 // If this variable must be emitted, add it as an initializer for the 12947 // current module. 12948 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12949 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12950 return; 12951 } 12952 12953 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12954 CheckCompleteDecompositionDeclaration(DD); 12955 12956 QualType type = var->getType(); 12957 if (type->isDependentType()) return; 12958 12959 if (var->hasAttr<BlocksAttr>()) 12960 getCurFunction()->addByrefBlockVar(var); 12961 12962 Expr *Init = var->getInit(); 12963 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12964 QualType baseType = Context.getBaseElementType(type); 12965 12966 if (Init && !Init->isValueDependent()) { 12967 if (var->isConstexpr()) { 12968 SmallVector<PartialDiagnosticAt, 8> Notes; 12969 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12970 SourceLocation DiagLoc = var->getLocation(); 12971 // If the note doesn't add any useful information other than a source 12972 // location, fold it into the primary diagnostic. 12973 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12974 diag::note_invalid_subexpr_in_const_expr) { 12975 DiagLoc = Notes[0].first; 12976 Notes.clear(); 12977 } 12978 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12979 << var << Init->getSourceRange(); 12980 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12981 Diag(Notes[I].first, Notes[I].second); 12982 } 12983 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12984 // Check whether the initializer of a const variable of integral or 12985 // enumeration type is an ICE now, since we can't tell whether it was 12986 // initialized by a constant expression if we check later. 12987 var->checkInitIsICE(); 12988 } 12989 12990 // Don't emit further diagnostics about constexpr globals since they 12991 // were just diagnosed. 12992 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12993 // FIXME: Need strict checking in C++03 here. 12994 bool DiagErr = getLangOpts().CPlusPlus11 12995 ? !var->checkInitIsICE() : !checkConstInit(); 12996 if (DiagErr) { 12997 auto *Attr = var->getAttr<ConstInitAttr>(); 12998 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12999 << Init->getSourceRange(); 13000 Diag(Attr->getLocation(), 13001 diag::note_declared_required_constant_init_here) 13002 << Attr->getRange() << Attr->isConstinit(); 13003 if (getLangOpts().CPlusPlus11) { 13004 APValue Value; 13005 SmallVector<PartialDiagnosticAt, 8> Notes; 13006 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 13007 for (auto &it : Notes) 13008 Diag(it.first, it.second); 13009 } else { 13010 Diag(CacheCulprit->getExprLoc(), 13011 diag::note_invalid_subexpr_in_const_expr) 13012 << CacheCulprit->getSourceRange(); 13013 } 13014 } 13015 } 13016 else if (!var->isConstexpr() && IsGlobal && 13017 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13018 var->getLocation())) { 13019 // Warn about globals which don't have a constant initializer. Don't 13020 // warn about globals with a non-trivial destructor because we already 13021 // warned about them. 13022 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13023 if (!(RD && !RD->hasTrivialDestructor())) { 13024 if (!checkConstInit()) 13025 Diag(var->getLocation(), diag::warn_global_constructor) 13026 << Init->getSourceRange(); 13027 } 13028 } 13029 } 13030 13031 // Require the destructor. 13032 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13033 FinalizeVarWithDestructor(var, recordType); 13034 13035 // If this variable must be emitted, add it as an initializer for the current 13036 // module. 13037 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13038 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13039 } 13040 13041 /// Determines if a variable's alignment is dependent. 13042 static bool hasDependentAlignment(VarDecl *VD) { 13043 if (VD->getType()->isDependentType()) 13044 return true; 13045 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13046 if (I->isAlignmentDependent()) 13047 return true; 13048 return false; 13049 } 13050 13051 /// Check if VD needs to be dllexport/dllimport due to being in a 13052 /// dllexport/import function. 13053 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13054 assert(VD->isStaticLocal()); 13055 13056 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13057 13058 // Find outermost function when VD is in lambda function. 13059 while (FD && !getDLLAttr(FD) && 13060 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13061 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13062 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13063 } 13064 13065 if (!FD) 13066 return; 13067 13068 // Static locals inherit dll attributes from their function. 13069 if (Attr *A = getDLLAttr(FD)) { 13070 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13071 NewAttr->setInherited(true); 13072 VD->addAttr(NewAttr); 13073 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13074 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13075 NewAttr->setInherited(true); 13076 VD->addAttr(NewAttr); 13077 13078 // Export this function to enforce exporting this static variable even 13079 // if it is not used in this compilation unit. 13080 if (!FD->hasAttr<DLLExportAttr>()) 13081 FD->addAttr(NewAttr); 13082 13083 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13084 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13085 NewAttr->setInherited(true); 13086 VD->addAttr(NewAttr); 13087 } 13088 } 13089 13090 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13091 /// any semantic actions necessary after any initializer has been attached. 13092 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13093 // Note that we are no longer parsing the initializer for this declaration. 13094 ParsingInitForAutoVars.erase(ThisDecl); 13095 13096 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13097 if (!VD) 13098 return; 13099 13100 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13101 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13102 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13103 if (PragmaClangBSSSection.Valid) 13104 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13105 Context, PragmaClangBSSSection.SectionName, 13106 PragmaClangBSSSection.PragmaLocation, 13107 AttributeCommonInfo::AS_Pragma)); 13108 if (PragmaClangDataSection.Valid) 13109 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13110 Context, PragmaClangDataSection.SectionName, 13111 PragmaClangDataSection.PragmaLocation, 13112 AttributeCommonInfo::AS_Pragma)); 13113 if (PragmaClangRodataSection.Valid) 13114 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13115 Context, PragmaClangRodataSection.SectionName, 13116 PragmaClangRodataSection.PragmaLocation, 13117 AttributeCommonInfo::AS_Pragma)); 13118 if (PragmaClangRelroSection.Valid) 13119 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13120 Context, PragmaClangRelroSection.SectionName, 13121 PragmaClangRelroSection.PragmaLocation, 13122 AttributeCommonInfo::AS_Pragma)); 13123 } 13124 13125 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13126 for (auto *BD : DD->bindings()) { 13127 FinalizeDeclaration(BD); 13128 } 13129 } 13130 13131 checkAttributesAfterMerging(*this, *VD); 13132 13133 // Perform TLS alignment check here after attributes attached to the variable 13134 // which may affect the alignment have been processed. Only perform the check 13135 // if the target has a maximum TLS alignment (zero means no constraints). 13136 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13137 // Protect the check so that it's not performed on dependent types and 13138 // dependent alignments (we can't determine the alignment in that case). 13139 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13140 !VD->isInvalidDecl()) { 13141 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13142 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13143 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13144 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13145 << (unsigned)MaxAlignChars.getQuantity(); 13146 } 13147 } 13148 } 13149 13150 if (VD->isStaticLocal()) { 13151 CheckStaticLocalForDllExport(VD); 13152 13153 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 13154 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 13155 // function, only __shared__ variables or variables without any device 13156 // memory qualifiers may be declared with static storage class. 13157 // Note: It is unclear how a function-scope non-const static variable 13158 // without device memory qualifier is implemented, therefore only static 13159 // const variable without device memory qualifier is allowed. 13160 [&]() { 13161 if (!getLangOpts().CUDA) 13162 return; 13163 if (VD->hasAttr<CUDASharedAttr>()) 13164 return; 13165 if (VD->getType().isConstQualified() && 13166 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13167 return; 13168 if (CUDADiagIfDeviceCode(VD->getLocation(), 13169 diag::err_device_static_local_var) 13170 << CurrentCUDATarget()) 13171 VD->setInvalidDecl(); 13172 }(); 13173 } 13174 } 13175 13176 // Perform check for initializers of device-side global variables. 13177 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13178 // 7.5). We must also apply the same checks to all __shared__ 13179 // variables whether they are local or not. CUDA also allows 13180 // constant initializers for __constant__ and __device__ variables. 13181 if (getLangOpts().CUDA) 13182 checkAllowedCUDAInitializer(VD); 13183 13184 // Grab the dllimport or dllexport attribute off of the VarDecl. 13185 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13186 13187 // Imported static data members cannot be defined out-of-line. 13188 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13189 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13190 VD->isThisDeclarationADefinition()) { 13191 // We allow definitions of dllimport class template static data members 13192 // with a warning. 13193 CXXRecordDecl *Context = 13194 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13195 bool IsClassTemplateMember = 13196 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13197 Context->getDescribedClassTemplate(); 13198 13199 Diag(VD->getLocation(), 13200 IsClassTemplateMember 13201 ? diag::warn_attribute_dllimport_static_field_definition 13202 : diag::err_attribute_dllimport_static_field_definition); 13203 Diag(IA->getLocation(), diag::note_attribute); 13204 if (!IsClassTemplateMember) 13205 VD->setInvalidDecl(); 13206 } 13207 } 13208 13209 // dllimport/dllexport variables cannot be thread local, their TLS index 13210 // isn't exported with the variable. 13211 if (DLLAttr && VD->getTLSKind()) { 13212 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13213 if (F && getDLLAttr(F)) { 13214 assert(VD->isStaticLocal()); 13215 // But if this is a static local in a dlimport/dllexport function, the 13216 // function will never be inlined, which means the var would never be 13217 // imported, so having it marked import/export is safe. 13218 } else { 13219 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13220 << DLLAttr; 13221 VD->setInvalidDecl(); 13222 } 13223 } 13224 13225 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13226 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13227 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13228 VD->dropAttr<UsedAttr>(); 13229 } 13230 } 13231 13232 const DeclContext *DC = VD->getDeclContext(); 13233 // If there's a #pragma GCC visibility in scope, and this isn't a class 13234 // member, set the visibility of this variable. 13235 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13236 AddPushedVisibilityAttribute(VD); 13237 13238 // FIXME: Warn on unused var template partial specializations. 13239 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13240 MarkUnusedFileScopedDecl(VD); 13241 13242 // Now we have parsed the initializer and can update the table of magic 13243 // tag values. 13244 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13245 !VD->getType()->isIntegralOrEnumerationType()) 13246 return; 13247 13248 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13249 const Expr *MagicValueExpr = VD->getInit(); 13250 if (!MagicValueExpr) { 13251 continue; 13252 } 13253 Optional<llvm::APSInt> MagicValueInt; 13254 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13255 Diag(I->getRange().getBegin(), 13256 diag::err_type_tag_for_datatype_not_ice) 13257 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13258 continue; 13259 } 13260 if (MagicValueInt->getActiveBits() > 64) { 13261 Diag(I->getRange().getBegin(), 13262 diag::err_type_tag_for_datatype_too_large) 13263 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13264 continue; 13265 } 13266 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13267 RegisterTypeTagForDatatype(I->getArgumentKind(), 13268 MagicValue, 13269 I->getMatchingCType(), 13270 I->getLayoutCompatible(), 13271 I->getMustBeNull()); 13272 } 13273 } 13274 13275 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13276 auto *VD = dyn_cast<VarDecl>(DD); 13277 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13278 } 13279 13280 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13281 ArrayRef<Decl *> Group) { 13282 SmallVector<Decl*, 8> Decls; 13283 13284 if (DS.isTypeSpecOwned()) 13285 Decls.push_back(DS.getRepAsDecl()); 13286 13287 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13288 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13289 bool DiagnosedMultipleDecomps = false; 13290 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13291 bool DiagnosedNonDeducedAuto = false; 13292 13293 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13294 if (Decl *D = Group[i]) { 13295 // For declarators, there are some additional syntactic-ish checks we need 13296 // to perform. 13297 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13298 if (!FirstDeclaratorInGroup) 13299 FirstDeclaratorInGroup = DD; 13300 if (!FirstDecompDeclaratorInGroup) 13301 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13302 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13303 !hasDeducedAuto(DD)) 13304 FirstNonDeducedAutoInGroup = DD; 13305 13306 if (FirstDeclaratorInGroup != DD) { 13307 // A decomposition declaration cannot be combined with any other 13308 // declaration in the same group. 13309 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13310 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13311 diag::err_decomp_decl_not_alone) 13312 << FirstDeclaratorInGroup->getSourceRange() 13313 << DD->getSourceRange(); 13314 DiagnosedMultipleDecomps = true; 13315 } 13316 13317 // A declarator that uses 'auto' in any way other than to declare a 13318 // variable with a deduced type cannot be combined with any other 13319 // declarator in the same group. 13320 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13321 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13322 diag::err_auto_non_deduced_not_alone) 13323 << FirstNonDeducedAutoInGroup->getType() 13324 ->hasAutoForTrailingReturnType() 13325 << FirstDeclaratorInGroup->getSourceRange() 13326 << DD->getSourceRange(); 13327 DiagnosedNonDeducedAuto = true; 13328 } 13329 } 13330 } 13331 13332 Decls.push_back(D); 13333 } 13334 } 13335 13336 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13337 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13338 handleTagNumbering(Tag, S); 13339 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13340 getLangOpts().CPlusPlus) 13341 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13342 } 13343 } 13344 13345 return BuildDeclaratorGroup(Decls); 13346 } 13347 13348 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13349 /// group, performing any necessary semantic checking. 13350 Sema::DeclGroupPtrTy 13351 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13352 // C++14 [dcl.spec.auto]p7: (DR1347) 13353 // If the type that replaces the placeholder type is not the same in each 13354 // deduction, the program is ill-formed. 13355 if (Group.size() > 1) { 13356 QualType Deduced; 13357 VarDecl *DeducedDecl = nullptr; 13358 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13359 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13360 if (!D || D->isInvalidDecl()) 13361 break; 13362 DeducedType *DT = D->getType()->getContainedDeducedType(); 13363 if (!DT || DT->getDeducedType().isNull()) 13364 continue; 13365 if (Deduced.isNull()) { 13366 Deduced = DT->getDeducedType(); 13367 DeducedDecl = D; 13368 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13369 auto *AT = dyn_cast<AutoType>(DT); 13370 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13371 diag::err_auto_different_deductions) 13372 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13373 << DeducedDecl->getDeclName() << DT->getDeducedType() 13374 << D->getDeclName(); 13375 if (DeducedDecl->hasInit()) 13376 Dia << DeducedDecl->getInit()->getSourceRange(); 13377 if (D->getInit()) 13378 Dia << D->getInit()->getSourceRange(); 13379 D->setInvalidDecl(); 13380 break; 13381 } 13382 } 13383 } 13384 13385 ActOnDocumentableDecls(Group); 13386 13387 return DeclGroupPtrTy::make( 13388 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13389 } 13390 13391 void Sema::ActOnDocumentableDecl(Decl *D) { 13392 ActOnDocumentableDecls(D); 13393 } 13394 13395 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13396 // Don't parse the comment if Doxygen diagnostics are ignored. 13397 if (Group.empty() || !Group[0]) 13398 return; 13399 13400 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13401 Group[0]->getLocation()) && 13402 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13403 Group[0]->getLocation())) 13404 return; 13405 13406 if (Group.size() >= 2) { 13407 // This is a decl group. Normally it will contain only declarations 13408 // produced from declarator list. But in case we have any definitions or 13409 // additional declaration references: 13410 // 'typedef struct S {} S;' 13411 // 'typedef struct S *S;' 13412 // 'struct S *pS;' 13413 // FinalizeDeclaratorGroup adds these as separate declarations. 13414 Decl *MaybeTagDecl = Group[0]; 13415 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13416 Group = Group.slice(1); 13417 } 13418 } 13419 13420 // FIMXE: We assume every Decl in the group is in the same file. 13421 // This is false when preprocessor constructs the group from decls in 13422 // different files (e. g. macros or #include). 13423 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13424 } 13425 13426 /// Common checks for a parameter-declaration that should apply to both function 13427 /// parameters and non-type template parameters. 13428 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13429 // Check that there are no default arguments inside the type of this 13430 // parameter. 13431 if (getLangOpts().CPlusPlus) 13432 CheckExtraCXXDefaultArguments(D); 13433 13434 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13435 if (D.getCXXScopeSpec().isSet()) { 13436 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13437 << D.getCXXScopeSpec().getRange(); 13438 } 13439 13440 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13441 // simple identifier except [...irrelevant cases...]. 13442 switch (D.getName().getKind()) { 13443 case UnqualifiedIdKind::IK_Identifier: 13444 break; 13445 13446 case UnqualifiedIdKind::IK_OperatorFunctionId: 13447 case UnqualifiedIdKind::IK_ConversionFunctionId: 13448 case UnqualifiedIdKind::IK_LiteralOperatorId: 13449 case UnqualifiedIdKind::IK_ConstructorName: 13450 case UnqualifiedIdKind::IK_DestructorName: 13451 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13452 case UnqualifiedIdKind::IK_DeductionGuideName: 13453 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13454 << GetNameForDeclarator(D).getName(); 13455 break; 13456 13457 case UnqualifiedIdKind::IK_TemplateId: 13458 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13459 // GetNameForDeclarator would not produce a useful name in this case. 13460 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13461 break; 13462 } 13463 } 13464 13465 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13466 /// to introduce parameters into function prototype scope. 13467 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13468 const DeclSpec &DS = D.getDeclSpec(); 13469 13470 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13471 13472 // C++03 [dcl.stc]p2 also permits 'auto'. 13473 StorageClass SC = SC_None; 13474 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13475 SC = SC_Register; 13476 // In C++11, the 'register' storage class specifier is deprecated. 13477 // In C++17, it is not allowed, but we tolerate it as an extension. 13478 if (getLangOpts().CPlusPlus11) { 13479 Diag(DS.getStorageClassSpecLoc(), 13480 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13481 : diag::warn_deprecated_register) 13482 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13483 } 13484 } else if (getLangOpts().CPlusPlus && 13485 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13486 SC = SC_Auto; 13487 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13488 Diag(DS.getStorageClassSpecLoc(), 13489 diag::err_invalid_storage_class_in_func_decl); 13490 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13491 } 13492 13493 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13494 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13495 << DeclSpec::getSpecifierName(TSCS); 13496 if (DS.isInlineSpecified()) 13497 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13498 << getLangOpts().CPlusPlus17; 13499 if (DS.hasConstexprSpecifier()) 13500 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13501 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13502 13503 DiagnoseFunctionSpecifiers(DS); 13504 13505 CheckFunctionOrTemplateParamDeclarator(S, D); 13506 13507 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13508 QualType parmDeclType = TInfo->getType(); 13509 13510 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13511 IdentifierInfo *II = D.getIdentifier(); 13512 if (II) { 13513 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13514 ForVisibleRedeclaration); 13515 LookupName(R, S); 13516 if (R.isSingleResult()) { 13517 NamedDecl *PrevDecl = R.getFoundDecl(); 13518 if (PrevDecl->isTemplateParameter()) { 13519 // Maybe we will complain about the shadowed template parameter. 13520 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13521 // Just pretend that we didn't see the previous declaration. 13522 PrevDecl = nullptr; 13523 } else if (S->isDeclScope(PrevDecl)) { 13524 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13525 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13526 13527 // Recover by removing the name 13528 II = nullptr; 13529 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13530 D.setInvalidType(true); 13531 } 13532 } 13533 } 13534 13535 // Temporarily put parameter variables in the translation unit, not 13536 // the enclosing context. This prevents them from accidentally 13537 // looking like class members in C++. 13538 ParmVarDecl *New = 13539 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13540 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13541 13542 if (D.isInvalidType()) 13543 New->setInvalidDecl(); 13544 13545 assert(S->isFunctionPrototypeScope()); 13546 assert(S->getFunctionPrototypeDepth() >= 1); 13547 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13548 S->getNextFunctionPrototypeIndex()); 13549 13550 // Add the parameter declaration into this scope. 13551 S->AddDecl(New); 13552 if (II) 13553 IdResolver.AddDecl(New); 13554 13555 ProcessDeclAttributes(S, New, D); 13556 13557 if (D.getDeclSpec().isModulePrivateSpecified()) 13558 Diag(New->getLocation(), diag::err_module_private_local) 13559 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13560 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13561 13562 if (New->hasAttr<BlocksAttr>()) { 13563 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13564 } 13565 13566 if (getLangOpts().OpenCL) 13567 deduceOpenCLAddressSpace(New); 13568 13569 return New; 13570 } 13571 13572 /// Synthesizes a variable for a parameter arising from a 13573 /// typedef. 13574 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13575 SourceLocation Loc, 13576 QualType T) { 13577 /* FIXME: setting StartLoc == Loc. 13578 Would it be worth to modify callers so as to provide proper source 13579 location for the unnamed parameters, embedding the parameter's type? */ 13580 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13581 T, Context.getTrivialTypeSourceInfo(T, Loc), 13582 SC_None, nullptr); 13583 Param->setImplicit(); 13584 return Param; 13585 } 13586 13587 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13588 // Don't diagnose unused-parameter errors in template instantiations; we 13589 // will already have done so in the template itself. 13590 if (inTemplateInstantiation()) 13591 return; 13592 13593 for (const ParmVarDecl *Parameter : Parameters) { 13594 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13595 !Parameter->hasAttr<UnusedAttr>()) { 13596 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13597 << Parameter->getDeclName(); 13598 } 13599 } 13600 } 13601 13602 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13603 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13604 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13605 return; 13606 13607 // Warn if the return value is pass-by-value and larger than the specified 13608 // threshold. 13609 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13610 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13611 if (Size > LangOpts.NumLargeByValueCopy) 13612 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13613 } 13614 13615 // Warn if any parameter is pass-by-value and larger than the specified 13616 // threshold. 13617 for (const ParmVarDecl *Parameter : Parameters) { 13618 QualType T = Parameter->getType(); 13619 if (T->isDependentType() || !T.isPODType(Context)) 13620 continue; 13621 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13622 if (Size > LangOpts.NumLargeByValueCopy) 13623 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13624 << Parameter << Size; 13625 } 13626 } 13627 13628 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13629 SourceLocation NameLoc, IdentifierInfo *Name, 13630 QualType T, TypeSourceInfo *TSInfo, 13631 StorageClass SC) { 13632 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13633 if (getLangOpts().ObjCAutoRefCount && 13634 T.getObjCLifetime() == Qualifiers::OCL_None && 13635 T->isObjCLifetimeType()) { 13636 13637 Qualifiers::ObjCLifetime lifetime; 13638 13639 // Special cases for arrays: 13640 // - if it's const, use __unsafe_unretained 13641 // - otherwise, it's an error 13642 if (T->isArrayType()) { 13643 if (!T.isConstQualified()) { 13644 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13645 DelayedDiagnostics.add( 13646 sema::DelayedDiagnostic::makeForbiddenType( 13647 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13648 else 13649 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13650 << TSInfo->getTypeLoc().getSourceRange(); 13651 } 13652 lifetime = Qualifiers::OCL_ExplicitNone; 13653 } else { 13654 lifetime = T->getObjCARCImplicitLifetime(); 13655 } 13656 T = Context.getLifetimeQualifiedType(T, lifetime); 13657 } 13658 13659 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13660 Context.getAdjustedParameterType(T), 13661 TSInfo, SC, nullptr); 13662 13663 // Make a note if we created a new pack in the scope of a lambda, so that 13664 // we know that references to that pack must also be expanded within the 13665 // lambda scope. 13666 if (New->isParameterPack()) 13667 if (auto *LSI = getEnclosingLambda()) 13668 LSI->LocalPacks.push_back(New); 13669 13670 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13671 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13672 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13673 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13674 13675 // Parameters can not be abstract class types. 13676 // For record types, this is done by the AbstractClassUsageDiagnoser once 13677 // the class has been completely parsed. 13678 if (!CurContext->isRecord() && 13679 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13680 AbstractParamType)) 13681 New->setInvalidDecl(); 13682 13683 // Parameter declarators cannot be interface types. All ObjC objects are 13684 // passed by reference. 13685 if (T->isObjCObjectType()) { 13686 SourceLocation TypeEndLoc = 13687 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13688 Diag(NameLoc, 13689 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13690 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13691 T = Context.getObjCObjectPointerType(T); 13692 New->setType(T); 13693 } 13694 13695 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13696 // duration shall not be qualified by an address-space qualifier." 13697 // Since all parameters have automatic store duration, they can not have 13698 // an address space. 13699 if (T.getAddressSpace() != LangAS::Default && 13700 // OpenCL allows function arguments declared to be an array of a type 13701 // to be qualified with an address space. 13702 !(getLangOpts().OpenCL && 13703 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13704 Diag(NameLoc, diag::err_arg_with_address_space); 13705 New->setInvalidDecl(); 13706 } 13707 13708 return New; 13709 } 13710 13711 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13712 SourceLocation LocAfterDecls) { 13713 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13714 13715 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13716 // for a K&R function. 13717 if (!FTI.hasPrototype) { 13718 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13719 --i; 13720 if (FTI.Params[i].Param == nullptr) { 13721 SmallString<256> Code; 13722 llvm::raw_svector_ostream(Code) 13723 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13724 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13725 << FTI.Params[i].Ident 13726 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13727 13728 // Implicitly declare the argument as type 'int' for lack of a better 13729 // type. 13730 AttributeFactory attrs; 13731 DeclSpec DS(attrs); 13732 const char* PrevSpec; // unused 13733 unsigned DiagID; // unused 13734 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13735 DiagID, Context.getPrintingPolicy()); 13736 // Use the identifier location for the type source range. 13737 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13738 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13739 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13740 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13741 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13742 } 13743 } 13744 } 13745 } 13746 13747 Decl * 13748 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13749 MultiTemplateParamsArg TemplateParameterLists, 13750 SkipBodyInfo *SkipBody) { 13751 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13752 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13753 Scope *ParentScope = FnBodyScope->getParent(); 13754 13755 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13756 // we define a non-templated function definition, we will create a declaration 13757 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13758 // The base function declaration will have the equivalent of an `omp declare 13759 // variant` annotation which specifies the mangled definition as a 13760 // specialization function under the OpenMP context defined as part of the 13761 // `omp begin declare variant`. 13762 SmallVector<FunctionDecl *, 4> Bases; 13763 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13764 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13765 ParentScope, D, TemplateParameterLists, Bases); 13766 13767 D.setFunctionDefinitionKind(FDK_Definition); 13768 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13769 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13770 13771 if (!Bases.empty()) 13772 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13773 13774 return Dcl; 13775 } 13776 13777 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13778 Consumer.HandleInlineFunctionDefinition(D); 13779 } 13780 13781 static bool 13782 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13783 const FunctionDecl *&PossiblePrototype) { 13784 // Don't warn about invalid declarations. 13785 if (FD->isInvalidDecl()) 13786 return false; 13787 13788 // Or declarations that aren't global. 13789 if (!FD->isGlobal()) 13790 return false; 13791 13792 // Don't warn about C++ member functions. 13793 if (isa<CXXMethodDecl>(FD)) 13794 return false; 13795 13796 // Don't warn about 'main'. 13797 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13798 if (IdentifierInfo *II = FD->getIdentifier()) 13799 if (II->isStr("main")) 13800 return false; 13801 13802 // Don't warn about inline functions. 13803 if (FD->isInlined()) 13804 return false; 13805 13806 // Don't warn about function templates. 13807 if (FD->getDescribedFunctionTemplate()) 13808 return false; 13809 13810 // Don't warn about function template specializations. 13811 if (FD->isFunctionTemplateSpecialization()) 13812 return false; 13813 13814 // Don't warn for OpenCL kernels. 13815 if (FD->hasAttr<OpenCLKernelAttr>()) 13816 return false; 13817 13818 // Don't warn on explicitly deleted functions. 13819 if (FD->isDeleted()) 13820 return false; 13821 13822 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13823 Prev; Prev = Prev->getPreviousDecl()) { 13824 // Ignore any declarations that occur in function or method 13825 // scope, because they aren't visible from the header. 13826 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13827 continue; 13828 13829 PossiblePrototype = Prev; 13830 return Prev->getType()->isFunctionNoProtoType(); 13831 } 13832 13833 return true; 13834 } 13835 13836 void 13837 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13838 const FunctionDecl *EffectiveDefinition, 13839 SkipBodyInfo *SkipBody) { 13840 const FunctionDecl *Definition = EffectiveDefinition; 13841 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13842 // If this is a friend function defined in a class template, it does not 13843 // have a body until it is used, nevertheless it is a definition, see 13844 // [temp.inst]p2: 13845 // 13846 // ... for the purpose of determining whether an instantiated redeclaration 13847 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13848 // corresponds to a definition in the template is considered to be a 13849 // definition. 13850 // 13851 // The following code must produce redefinition error: 13852 // 13853 // template<typename T> struct C20 { friend void func_20() {} }; 13854 // C20<int> c20i; 13855 // void func_20() {} 13856 // 13857 for (auto I : FD->redecls()) { 13858 if (I != FD && !I->isInvalidDecl() && 13859 I->getFriendObjectKind() != Decl::FOK_None) { 13860 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13861 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13862 // A merged copy of the same function, instantiated as a member of 13863 // the same class, is OK. 13864 if (declaresSameEntity(OrigFD, Original) && 13865 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13866 cast<Decl>(FD->getLexicalDeclContext()))) 13867 continue; 13868 } 13869 13870 if (Original->isThisDeclarationADefinition()) { 13871 Definition = I; 13872 break; 13873 } 13874 } 13875 } 13876 } 13877 } 13878 13879 if (!Definition) 13880 // Similar to friend functions a friend function template may be a 13881 // definition and do not have a body if it is instantiated in a class 13882 // template. 13883 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13884 for (auto I : FTD->redecls()) { 13885 auto D = cast<FunctionTemplateDecl>(I); 13886 if (D != FTD) { 13887 assert(!D->isThisDeclarationADefinition() && 13888 "More than one definition in redeclaration chain"); 13889 if (D->getFriendObjectKind() != Decl::FOK_None) 13890 if (FunctionTemplateDecl *FT = 13891 D->getInstantiatedFromMemberTemplate()) { 13892 if (FT->isThisDeclarationADefinition()) { 13893 Definition = D->getTemplatedDecl(); 13894 break; 13895 } 13896 } 13897 } 13898 } 13899 } 13900 13901 if (!Definition) 13902 return; 13903 13904 if (canRedefineFunction(Definition, getLangOpts())) 13905 return; 13906 13907 // Don't emit an error when this is redefinition of a typo-corrected 13908 // definition. 13909 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13910 return; 13911 13912 // If we don't have a visible definition of the function, and it's inline or 13913 // a template, skip the new definition. 13914 if (SkipBody && !hasVisibleDefinition(Definition) && 13915 (Definition->getFormalLinkage() == InternalLinkage || 13916 Definition->isInlined() || 13917 Definition->getDescribedFunctionTemplate() || 13918 Definition->getNumTemplateParameterLists())) { 13919 SkipBody->ShouldSkip = true; 13920 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13921 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13922 makeMergedDefinitionVisible(TD); 13923 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13924 return; 13925 } 13926 13927 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13928 Definition->getStorageClass() == SC_Extern) 13929 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13930 << FD << getLangOpts().CPlusPlus; 13931 else 13932 Diag(FD->getLocation(), diag::err_redefinition) << FD; 13933 13934 Diag(Definition->getLocation(), diag::note_previous_definition); 13935 FD->setInvalidDecl(); 13936 } 13937 13938 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13939 Sema &S) { 13940 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13941 13942 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13943 LSI->CallOperator = CallOperator; 13944 LSI->Lambda = LambdaClass; 13945 LSI->ReturnType = CallOperator->getReturnType(); 13946 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13947 13948 if (LCD == LCD_None) 13949 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13950 else if (LCD == LCD_ByCopy) 13951 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13952 else if (LCD == LCD_ByRef) 13953 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13954 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13955 13956 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13957 LSI->Mutable = !CallOperator->isConst(); 13958 13959 // Add the captures to the LSI so they can be noted as already 13960 // captured within tryCaptureVar. 13961 auto I = LambdaClass->field_begin(); 13962 for (const auto &C : LambdaClass->captures()) { 13963 if (C.capturesVariable()) { 13964 VarDecl *VD = C.getCapturedVar(); 13965 if (VD->isInitCapture()) 13966 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13967 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13968 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13969 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13970 /*EllipsisLoc*/C.isPackExpansion() 13971 ? C.getEllipsisLoc() : SourceLocation(), 13972 I->getType(), /*Invalid*/false); 13973 13974 } else if (C.capturesThis()) { 13975 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13976 C.getCaptureKind() == LCK_StarThis); 13977 } else { 13978 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13979 I->getType()); 13980 } 13981 ++I; 13982 } 13983 } 13984 13985 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13986 SkipBodyInfo *SkipBody) { 13987 if (!D) { 13988 // Parsing the function declaration failed in some way. Push on a fake scope 13989 // anyway so we can try to parse the function body. 13990 PushFunctionScope(); 13991 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13992 return D; 13993 } 13994 13995 FunctionDecl *FD = nullptr; 13996 13997 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13998 FD = FunTmpl->getTemplatedDecl(); 13999 else 14000 FD = cast<FunctionDecl>(D); 14001 14002 // Do not push if it is a lambda because one is already pushed when building 14003 // the lambda in ActOnStartOfLambdaDefinition(). 14004 if (!isLambdaCallOperator(FD)) 14005 PushExpressionEvaluationContext( 14006 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14007 : ExprEvalContexts.back().Context); 14008 14009 // Check for defining attributes before the check for redefinition. 14010 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14011 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14012 FD->dropAttr<AliasAttr>(); 14013 FD->setInvalidDecl(); 14014 } 14015 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14016 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14017 FD->dropAttr<IFuncAttr>(); 14018 FD->setInvalidDecl(); 14019 } 14020 14021 // See if this is a redefinition. If 'will have body' is already set, then 14022 // these checks were already performed when it was set. 14023 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 14024 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14025 14026 // If we're skipping the body, we're done. Don't enter the scope. 14027 if (SkipBody && SkipBody->ShouldSkip) 14028 return D; 14029 } 14030 14031 // Mark this function as "will have a body eventually". This lets users to 14032 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14033 // this function. 14034 FD->setWillHaveBody(); 14035 14036 // If we are instantiating a generic lambda call operator, push 14037 // a LambdaScopeInfo onto the function stack. But use the information 14038 // that's already been calculated (ActOnLambdaExpr) to prime the current 14039 // LambdaScopeInfo. 14040 // When the template operator is being specialized, the LambdaScopeInfo, 14041 // has to be properly restored so that tryCaptureVariable doesn't try 14042 // and capture any new variables. In addition when calculating potential 14043 // captures during transformation of nested lambdas, it is necessary to 14044 // have the LSI properly restored. 14045 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14046 assert(inTemplateInstantiation() && 14047 "There should be an active template instantiation on the stack " 14048 "when instantiating a generic lambda!"); 14049 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14050 } else { 14051 // Enter a new function scope 14052 PushFunctionScope(); 14053 } 14054 14055 // Builtin functions cannot be defined. 14056 if (unsigned BuiltinID = FD->getBuiltinID()) { 14057 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14058 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14059 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14060 FD->setInvalidDecl(); 14061 } 14062 } 14063 14064 // The return type of a function definition must be complete 14065 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14066 QualType ResultType = FD->getReturnType(); 14067 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14068 !FD->isInvalidDecl() && 14069 RequireCompleteType(FD->getLocation(), ResultType, 14070 diag::err_func_def_incomplete_result)) 14071 FD->setInvalidDecl(); 14072 14073 if (FnBodyScope) 14074 PushDeclContext(FnBodyScope, FD); 14075 14076 // Check the validity of our function parameters 14077 CheckParmsForFunctionDef(FD->parameters(), 14078 /*CheckParameterNames=*/true); 14079 14080 // Add non-parameter declarations already in the function to the current 14081 // scope. 14082 if (FnBodyScope) { 14083 for (Decl *NPD : FD->decls()) { 14084 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14085 if (!NonParmDecl) 14086 continue; 14087 assert(!isa<ParmVarDecl>(NonParmDecl) && 14088 "parameters should not be in newly created FD yet"); 14089 14090 // If the decl has a name, make it accessible in the current scope. 14091 if (NonParmDecl->getDeclName()) 14092 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14093 14094 // Similarly, dive into enums and fish their constants out, making them 14095 // accessible in this scope. 14096 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14097 for (auto *EI : ED->enumerators()) 14098 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14099 } 14100 } 14101 } 14102 14103 // Introduce our parameters into the function scope 14104 for (auto Param : FD->parameters()) { 14105 Param->setOwningFunction(FD); 14106 14107 // If this has an identifier, add it to the scope stack. 14108 if (Param->getIdentifier() && FnBodyScope) { 14109 CheckShadow(FnBodyScope, Param); 14110 14111 PushOnScopeChains(Param, FnBodyScope); 14112 } 14113 } 14114 14115 // Ensure that the function's exception specification is instantiated. 14116 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14117 ResolveExceptionSpec(D->getLocation(), FPT); 14118 14119 // dllimport cannot be applied to non-inline function definitions. 14120 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14121 !FD->isTemplateInstantiation()) { 14122 assert(!FD->hasAttr<DLLExportAttr>()); 14123 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14124 FD->setInvalidDecl(); 14125 return D; 14126 } 14127 // We want to attach documentation to original Decl (which might be 14128 // a function template). 14129 ActOnDocumentableDecl(D); 14130 if (getCurLexicalContext()->isObjCContainer() && 14131 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14132 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14133 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14134 14135 return D; 14136 } 14137 14138 /// Given the set of return statements within a function body, 14139 /// compute the variables that are subject to the named return value 14140 /// optimization. 14141 /// 14142 /// Each of the variables that is subject to the named return value 14143 /// optimization will be marked as NRVO variables in the AST, and any 14144 /// return statement that has a marked NRVO variable as its NRVO candidate can 14145 /// use the named return value optimization. 14146 /// 14147 /// This function applies a very simplistic algorithm for NRVO: if every return 14148 /// statement in the scope of a variable has the same NRVO candidate, that 14149 /// candidate is an NRVO variable. 14150 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14151 ReturnStmt **Returns = Scope->Returns.data(); 14152 14153 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14154 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14155 if (!NRVOCandidate->isNRVOVariable()) 14156 Returns[I]->setNRVOCandidate(nullptr); 14157 } 14158 } 14159 } 14160 14161 bool Sema::canDelayFunctionBody(const Declarator &D) { 14162 // We can't delay parsing the body of a constexpr function template (yet). 14163 if (D.getDeclSpec().hasConstexprSpecifier()) 14164 return false; 14165 14166 // We can't delay parsing the body of a function template with a deduced 14167 // return type (yet). 14168 if (D.getDeclSpec().hasAutoTypeSpec()) { 14169 // If the placeholder introduces a non-deduced trailing return type, 14170 // we can still delay parsing it. 14171 if (D.getNumTypeObjects()) { 14172 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14173 if (Outer.Kind == DeclaratorChunk::Function && 14174 Outer.Fun.hasTrailingReturnType()) { 14175 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14176 return Ty.isNull() || !Ty->isUndeducedType(); 14177 } 14178 } 14179 return false; 14180 } 14181 14182 return true; 14183 } 14184 14185 bool Sema::canSkipFunctionBody(Decl *D) { 14186 // We cannot skip the body of a function (or function template) which is 14187 // constexpr, since we may need to evaluate its body in order to parse the 14188 // rest of the file. 14189 // We cannot skip the body of a function with an undeduced return type, 14190 // because any callers of that function need to know the type. 14191 if (const FunctionDecl *FD = D->getAsFunction()) { 14192 if (FD->isConstexpr()) 14193 return false; 14194 // We can't simply call Type::isUndeducedType here, because inside template 14195 // auto can be deduced to a dependent type, which is not considered 14196 // "undeduced". 14197 if (FD->getReturnType()->getContainedDeducedType()) 14198 return false; 14199 } 14200 return Consumer.shouldSkipFunctionBody(D); 14201 } 14202 14203 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14204 if (!Decl) 14205 return nullptr; 14206 if (FunctionDecl *FD = Decl->getAsFunction()) 14207 FD->setHasSkippedBody(); 14208 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14209 MD->setHasSkippedBody(); 14210 return Decl; 14211 } 14212 14213 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14214 return ActOnFinishFunctionBody(D, BodyArg, false); 14215 } 14216 14217 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14218 /// body. 14219 class ExitFunctionBodyRAII { 14220 public: 14221 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14222 ~ExitFunctionBodyRAII() { 14223 if (!IsLambda) 14224 S.PopExpressionEvaluationContext(); 14225 } 14226 14227 private: 14228 Sema &S; 14229 bool IsLambda = false; 14230 }; 14231 14232 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14233 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14234 14235 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14236 if (EscapeInfo.count(BD)) 14237 return EscapeInfo[BD]; 14238 14239 bool R = false; 14240 const BlockDecl *CurBD = BD; 14241 14242 do { 14243 R = !CurBD->doesNotEscape(); 14244 if (R) 14245 break; 14246 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14247 } while (CurBD); 14248 14249 return EscapeInfo[BD] = R; 14250 }; 14251 14252 // If the location where 'self' is implicitly retained is inside a escaping 14253 // block, emit a diagnostic. 14254 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14255 S.ImplicitlyRetainedSelfLocs) 14256 if (IsOrNestedInEscapingBlock(P.second)) 14257 S.Diag(P.first, diag::warn_implicitly_retains_self) 14258 << FixItHint::CreateInsertion(P.first, "self->"); 14259 } 14260 14261 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14262 bool IsInstantiation) { 14263 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14264 14265 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14266 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14267 14268 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14269 CheckCompletedCoroutineBody(FD, Body); 14270 14271 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14272 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14273 // meant to pop the context added in ActOnStartOfFunctionDef(). 14274 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14275 14276 if (FD) { 14277 FD->setBody(Body); 14278 FD->setWillHaveBody(false); 14279 14280 if (getLangOpts().CPlusPlus14) { 14281 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14282 FD->getReturnType()->isUndeducedType()) { 14283 // If the function has a deduced result type but contains no 'return' 14284 // statements, the result type as written must be exactly 'auto', and 14285 // the deduced result type is 'void'. 14286 if (!FD->getReturnType()->getAs<AutoType>()) { 14287 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14288 << FD->getReturnType(); 14289 FD->setInvalidDecl(); 14290 } else { 14291 // Substitute 'void' for the 'auto' in the type. 14292 TypeLoc ResultType = getReturnTypeLoc(FD); 14293 Context.adjustDeducedFunctionResultType( 14294 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14295 } 14296 } 14297 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14298 // In C++11, we don't use 'auto' deduction rules for lambda call 14299 // operators because we don't support return type deduction. 14300 auto *LSI = getCurLambda(); 14301 if (LSI->HasImplicitReturnType) { 14302 deduceClosureReturnType(*LSI); 14303 14304 // C++11 [expr.prim.lambda]p4: 14305 // [...] if there are no return statements in the compound-statement 14306 // [the deduced type is] the type void 14307 QualType RetType = 14308 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14309 14310 // Update the return type to the deduced type. 14311 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14312 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14313 Proto->getExtProtoInfo())); 14314 } 14315 } 14316 14317 // If the function implicitly returns zero (like 'main') or is naked, 14318 // don't complain about missing return statements. 14319 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14320 WP.disableCheckFallThrough(); 14321 14322 // MSVC permits the use of pure specifier (=0) on function definition, 14323 // defined at class scope, warn about this non-standard construct. 14324 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14325 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14326 14327 if (!FD->isInvalidDecl()) { 14328 // Don't diagnose unused parameters of defaulted or deleted functions. 14329 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14330 DiagnoseUnusedParameters(FD->parameters()); 14331 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14332 FD->getReturnType(), FD); 14333 14334 // If this is a structor, we need a vtable. 14335 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14336 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14337 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14338 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14339 14340 // Try to apply the named return value optimization. We have to check 14341 // if we can do this here because lambdas keep return statements around 14342 // to deduce an implicit return type. 14343 if (FD->getReturnType()->isRecordType() && 14344 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14345 computeNRVO(Body, getCurFunction()); 14346 } 14347 14348 // GNU warning -Wmissing-prototypes: 14349 // Warn if a global function is defined without a previous 14350 // prototype declaration. This warning is issued even if the 14351 // definition itself provides a prototype. The aim is to detect 14352 // global functions that fail to be declared in header files. 14353 const FunctionDecl *PossiblePrototype = nullptr; 14354 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14355 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14356 14357 if (PossiblePrototype) { 14358 // We found a declaration that is not a prototype, 14359 // but that could be a zero-parameter prototype 14360 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14361 TypeLoc TL = TI->getTypeLoc(); 14362 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14363 Diag(PossiblePrototype->getLocation(), 14364 diag::note_declaration_not_a_prototype) 14365 << (FD->getNumParams() != 0) 14366 << (FD->getNumParams() == 0 14367 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14368 : FixItHint{}); 14369 } 14370 } else { 14371 // Returns true if the token beginning at this Loc is `const`. 14372 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14373 const LangOptions &LangOpts) { 14374 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14375 if (LocInfo.first.isInvalid()) 14376 return false; 14377 14378 bool Invalid = false; 14379 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14380 if (Invalid) 14381 return false; 14382 14383 if (LocInfo.second > Buffer.size()) 14384 return false; 14385 14386 const char *LexStart = Buffer.data() + LocInfo.second; 14387 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14388 14389 return StartTok.consume_front("const") && 14390 (StartTok.empty() || isWhitespace(StartTok[0]) || 14391 StartTok.startswith("/*") || StartTok.startswith("//")); 14392 }; 14393 14394 auto findBeginLoc = [&]() { 14395 // If the return type has `const` qualifier, we want to insert 14396 // `static` before `const` (and not before the typename). 14397 if ((FD->getReturnType()->isAnyPointerType() && 14398 FD->getReturnType()->getPointeeType().isConstQualified()) || 14399 FD->getReturnType().isConstQualified()) { 14400 // But only do this if we can determine where the `const` is. 14401 14402 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14403 getLangOpts())) 14404 14405 return FD->getBeginLoc(); 14406 } 14407 return FD->getTypeSpecStartLoc(); 14408 }; 14409 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14410 << /* function */ 1 14411 << (FD->getStorageClass() == SC_None 14412 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14413 : FixItHint{}); 14414 } 14415 14416 // GNU warning -Wstrict-prototypes 14417 // Warn if K&R function is defined without a previous declaration. 14418 // This warning is issued only if the definition itself does not provide 14419 // a prototype. Only K&R definitions do not provide a prototype. 14420 if (!FD->hasWrittenPrototype()) { 14421 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14422 TypeLoc TL = TI->getTypeLoc(); 14423 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14424 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14425 } 14426 } 14427 14428 // Warn on CPUDispatch with an actual body. 14429 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14430 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14431 if (!CmpndBody->body_empty()) 14432 Diag(CmpndBody->body_front()->getBeginLoc(), 14433 diag::warn_dispatch_body_ignored); 14434 14435 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14436 const CXXMethodDecl *KeyFunction; 14437 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14438 MD->isVirtual() && 14439 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14440 MD == KeyFunction->getCanonicalDecl()) { 14441 // Update the key-function state if necessary for this ABI. 14442 if (FD->isInlined() && 14443 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14444 Context.setNonKeyFunction(MD); 14445 14446 // If the newly-chosen key function is already defined, then we 14447 // need to mark the vtable as used retroactively. 14448 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14449 const FunctionDecl *Definition; 14450 if (KeyFunction && KeyFunction->isDefined(Definition)) 14451 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14452 } else { 14453 // We just defined they key function; mark the vtable as used. 14454 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14455 } 14456 } 14457 } 14458 14459 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14460 "Function parsing confused"); 14461 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14462 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14463 MD->setBody(Body); 14464 if (!MD->isInvalidDecl()) { 14465 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14466 MD->getReturnType(), MD); 14467 14468 if (Body) 14469 computeNRVO(Body, getCurFunction()); 14470 } 14471 if (getCurFunction()->ObjCShouldCallSuper) { 14472 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14473 << MD->getSelector().getAsString(); 14474 getCurFunction()->ObjCShouldCallSuper = false; 14475 } 14476 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14477 const ObjCMethodDecl *InitMethod = nullptr; 14478 bool isDesignated = 14479 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14480 assert(isDesignated && InitMethod); 14481 (void)isDesignated; 14482 14483 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14484 auto IFace = MD->getClassInterface(); 14485 if (!IFace) 14486 return false; 14487 auto SuperD = IFace->getSuperClass(); 14488 if (!SuperD) 14489 return false; 14490 return SuperD->getIdentifier() == 14491 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14492 }; 14493 // Don't issue this warning for unavailable inits or direct subclasses 14494 // of NSObject. 14495 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14496 Diag(MD->getLocation(), 14497 diag::warn_objc_designated_init_missing_super_call); 14498 Diag(InitMethod->getLocation(), 14499 diag::note_objc_designated_init_marked_here); 14500 } 14501 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14502 } 14503 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14504 // Don't issue this warning for unavaialable inits. 14505 if (!MD->isUnavailable()) 14506 Diag(MD->getLocation(), 14507 diag::warn_objc_secondary_init_missing_init_call); 14508 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14509 } 14510 14511 diagnoseImplicitlyRetainedSelf(*this); 14512 } else { 14513 // Parsing the function declaration failed in some way. Pop the fake scope 14514 // we pushed on. 14515 PopFunctionScopeInfo(ActivePolicy, dcl); 14516 return nullptr; 14517 } 14518 14519 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14520 DiagnoseUnguardedAvailabilityViolations(dcl); 14521 14522 assert(!getCurFunction()->ObjCShouldCallSuper && 14523 "This should only be set for ObjC methods, which should have been " 14524 "handled in the block above."); 14525 14526 // Verify and clean out per-function state. 14527 if (Body && (!FD || !FD->isDefaulted())) { 14528 // C++ constructors that have function-try-blocks can't have return 14529 // statements in the handlers of that block. (C++ [except.handle]p14) 14530 // Verify this. 14531 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14532 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14533 14534 // Verify that gotos and switch cases don't jump into scopes illegally. 14535 if (getCurFunction()->NeedsScopeChecking() && 14536 !PP.isCodeCompletionEnabled()) 14537 DiagnoseInvalidJumps(Body); 14538 14539 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14540 if (!Destructor->getParent()->isDependentType()) 14541 CheckDestructor(Destructor); 14542 14543 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14544 Destructor->getParent()); 14545 } 14546 14547 // If any errors have occurred, clear out any temporaries that may have 14548 // been leftover. This ensures that these temporaries won't be picked up for 14549 // deletion in some later function. 14550 if (getDiagnostics().hasUncompilableErrorOccurred() || 14551 getDiagnostics().getSuppressAllDiagnostics()) { 14552 DiscardCleanupsInEvaluationContext(); 14553 } 14554 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14555 !isa<FunctionTemplateDecl>(dcl)) { 14556 // Since the body is valid, issue any analysis-based warnings that are 14557 // enabled. 14558 ActivePolicy = &WP; 14559 } 14560 14561 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14562 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14563 FD->setInvalidDecl(); 14564 14565 if (FD && FD->hasAttr<NakedAttr>()) { 14566 for (const Stmt *S : Body->children()) { 14567 // Allow local register variables without initializer as they don't 14568 // require prologue. 14569 bool RegisterVariables = false; 14570 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14571 for (const auto *Decl : DS->decls()) { 14572 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14573 RegisterVariables = 14574 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14575 if (!RegisterVariables) 14576 break; 14577 } 14578 } 14579 } 14580 if (RegisterVariables) 14581 continue; 14582 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14583 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14584 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14585 FD->setInvalidDecl(); 14586 break; 14587 } 14588 } 14589 } 14590 14591 assert(ExprCleanupObjects.size() == 14592 ExprEvalContexts.back().NumCleanupObjects && 14593 "Leftover temporaries in function"); 14594 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14595 assert(MaybeODRUseExprs.empty() && 14596 "Leftover expressions for odr-use checking"); 14597 } 14598 14599 if (!IsInstantiation) 14600 PopDeclContext(); 14601 14602 PopFunctionScopeInfo(ActivePolicy, dcl); 14603 // If any errors have occurred, clear out any temporaries that may have 14604 // been leftover. This ensures that these temporaries won't be picked up for 14605 // deletion in some later function. 14606 if (getDiagnostics().hasUncompilableErrorOccurred()) { 14607 DiscardCleanupsInEvaluationContext(); 14608 } 14609 14610 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { 14611 auto ES = getEmissionStatus(FD); 14612 if (ES == Sema::FunctionEmissionStatus::Emitted || 14613 ES == Sema::FunctionEmissionStatus::Unknown) 14614 DeclsToCheckForDeferredDiags.push_back(FD); 14615 } 14616 14617 return dcl; 14618 } 14619 14620 /// When we finish delayed parsing of an attribute, we must attach it to the 14621 /// relevant Decl. 14622 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14623 ParsedAttributes &Attrs) { 14624 // Always attach attributes to the underlying decl. 14625 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14626 D = TD->getTemplatedDecl(); 14627 ProcessDeclAttributeList(S, D, Attrs); 14628 14629 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14630 if (Method->isStatic()) 14631 checkThisInStaticMemberFunctionAttributes(Method); 14632 } 14633 14634 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14635 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14636 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14637 IdentifierInfo &II, Scope *S) { 14638 // Find the scope in which the identifier is injected and the corresponding 14639 // DeclContext. 14640 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14641 // In that case, we inject the declaration into the translation unit scope 14642 // instead. 14643 Scope *BlockScope = S; 14644 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14645 BlockScope = BlockScope->getParent(); 14646 14647 Scope *ContextScope = BlockScope; 14648 while (!ContextScope->getEntity()) 14649 ContextScope = ContextScope->getParent(); 14650 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14651 14652 // Before we produce a declaration for an implicitly defined 14653 // function, see whether there was a locally-scoped declaration of 14654 // this name as a function or variable. If so, use that 14655 // (non-visible) declaration, and complain about it. 14656 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14657 if (ExternCPrev) { 14658 // We still need to inject the function into the enclosing block scope so 14659 // that later (non-call) uses can see it. 14660 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14661 14662 // C89 footnote 38: 14663 // If in fact it is not defined as having type "function returning int", 14664 // the behavior is undefined. 14665 if (!isa<FunctionDecl>(ExternCPrev) || 14666 !Context.typesAreCompatible( 14667 cast<FunctionDecl>(ExternCPrev)->getType(), 14668 Context.getFunctionNoProtoType(Context.IntTy))) { 14669 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14670 << ExternCPrev << !getLangOpts().C99; 14671 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14672 return ExternCPrev; 14673 } 14674 } 14675 14676 // Extension in C99. Legal in C90, but warn about it. 14677 unsigned diag_id; 14678 if (II.getName().startswith("__builtin_")) 14679 diag_id = diag::warn_builtin_unknown; 14680 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14681 else if (getLangOpts().OpenCL) 14682 diag_id = diag::err_opencl_implicit_function_decl; 14683 else if (getLangOpts().C99) 14684 diag_id = diag::ext_implicit_function_decl; 14685 else 14686 diag_id = diag::warn_implicit_function_decl; 14687 Diag(Loc, diag_id) << &II; 14688 14689 // If we found a prior declaration of this function, don't bother building 14690 // another one. We've already pushed that one into scope, so there's nothing 14691 // more to do. 14692 if (ExternCPrev) 14693 return ExternCPrev; 14694 14695 // Because typo correction is expensive, only do it if the implicit 14696 // function declaration is going to be treated as an error. 14697 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14698 TypoCorrection Corrected; 14699 DeclFilterCCC<FunctionDecl> CCC{}; 14700 if (S && (Corrected = 14701 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14702 S, nullptr, CCC, CTK_NonError))) 14703 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14704 /*ErrorRecovery*/false); 14705 } 14706 14707 // Set a Declarator for the implicit definition: int foo(); 14708 const char *Dummy; 14709 AttributeFactory attrFactory; 14710 DeclSpec DS(attrFactory); 14711 unsigned DiagID; 14712 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14713 Context.getPrintingPolicy()); 14714 (void)Error; // Silence warning. 14715 assert(!Error && "Error setting up implicit decl!"); 14716 SourceLocation NoLoc; 14717 Declarator D(DS, DeclaratorContext::BlockContext); 14718 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14719 /*IsAmbiguous=*/false, 14720 /*LParenLoc=*/NoLoc, 14721 /*Params=*/nullptr, 14722 /*NumParams=*/0, 14723 /*EllipsisLoc=*/NoLoc, 14724 /*RParenLoc=*/NoLoc, 14725 /*RefQualifierIsLvalueRef=*/true, 14726 /*RefQualifierLoc=*/NoLoc, 14727 /*MutableLoc=*/NoLoc, EST_None, 14728 /*ESpecRange=*/SourceRange(), 14729 /*Exceptions=*/nullptr, 14730 /*ExceptionRanges=*/nullptr, 14731 /*NumExceptions=*/0, 14732 /*NoexceptExpr=*/nullptr, 14733 /*ExceptionSpecTokens=*/nullptr, 14734 /*DeclsInPrototype=*/None, Loc, 14735 Loc, D), 14736 std::move(DS.getAttributes()), SourceLocation()); 14737 D.SetIdentifier(&II, Loc); 14738 14739 // Insert this function into the enclosing block scope. 14740 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14741 FD->setImplicit(); 14742 14743 AddKnownFunctionAttributes(FD); 14744 14745 return FD; 14746 } 14747 14748 /// If this function is a C++ replaceable global allocation function 14749 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14750 /// adds any function attributes that we know a priori based on the standard. 14751 /// 14752 /// We need to check for duplicate attributes both here and where user-written 14753 /// attributes are applied to declarations. 14754 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14755 FunctionDecl *FD) { 14756 if (FD->isInvalidDecl()) 14757 return; 14758 14759 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14760 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14761 return; 14762 14763 Optional<unsigned> AlignmentParam; 14764 bool IsNothrow = false; 14765 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14766 return; 14767 14768 // C++2a [basic.stc.dynamic.allocation]p4: 14769 // An allocation function that has a non-throwing exception specification 14770 // indicates failure by returning a null pointer value. Any other allocation 14771 // function never returns a null pointer value and indicates failure only by 14772 // throwing an exception [...] 14773 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14774 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14775 14776 // C++2a [basic.stc.dynamic.allocation]p2: 14777 // An allocation function attempts to allocate the requested amount of 14778 // storage. [...] If the request succeeds, the value returned by a 14779 // replaceable allocation function is a [...] pointer value p0 different 14780 // from any previously returned value p1 [...] 14781 // 14782 // However, this particular information is being added in codegen, 14783 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14784 14785 // C++2a [basic.stc.dynamic.allocation]p2: 14786 // An allocation function attempts to allocate the requested amount of 14787 // storage. If it is successful, it returns the address of the start of a 14788 // block of storage whose length in bytes is at least as large as the 14789 // requested size. 14790 if (!FD->hasAttr<AllocSizeAttr>()) { 14791 FD->addAttr(AllocSizeAttr::CreateImplicit( 14792 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14793 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14794 } 14795 14796 // C++2a [basic.stc.dynamic.allocation]p3: 14797 // For an allocation function [...], the pointer returned on a successful 14798 // call shall represent the address of storage that is aligned as follows: 14799 // (3.1) If the allocation function takes an argument of type 14800 // std::align_val_t, the storage will have the alignment 14801 // specified by the value of this argument. 14802 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14803 FD->addAttr(AllocAlignAttr::CreateImplicit( 14804 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14805 } 14806 14807 // FIXME: 14808 // C++2a [basic.stc.dynamic.allocation]p3: 14809 // For an allocation function [...], the pointer returned on a successful 14810 // call shall represent the address of storage that is aligned as follows: 14811 // (3.2) Otherwise, if the allocation function is named operator new[], 14812 // the storage is aligned for any object that does not have 14813 // new-extended alignment ([basic.align]) and is no larger than the 14814 // requested size. 14815 // (3.3) Otherwise, the storage is aligned for any object that does not 14816 // have new-extended alignment and is of the requested size. 14817 } 14818 14819 /// Adds any function attributes that we know a priori based on 14820 /// the declaration of this function. 14821 /// 14822 /// These attributes can apply both to implicitly-declared builtins 14823 /// (like __builtin___printf_chk) or to library-declared functions 14824 /// like NSLog or printf. 14825 /// 14826 /// We need to check for duplicate attributes both here and where user-written 14827 /// attributes are applied to declarations. 14828 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14829 if (FD->isInvalidDecl()) 14830 return; 14831 14832 // If this is a built-in function, map its builtin attributes to 14833 // actual attributes. 14834 if (unsigned BuiltinID = FD->getBuiltinID()) { 14835 // Handle printf-formatting attributes. 14836 unsigned FormatIdx; 14837 bool HasVAListArg; 14838 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14839 if (!FD->hasAttr<FormatAttr>()) { 14840 const char *fmt = "printf"; 14841 unsigned int NumParams = FD->getNumParams(); 14842 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14843 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14844 fmt = "NSString"; 14845 FD->addAttr(FormatAttr::CreateImplicit(Context, 14846 &Context.Idents.get(fmt), 14847 FormatIdx+1, 14848 HasVAListArg ? 0 : FormatIdx+2, 14849 FD->getLocation())); 14850 } 14851 } 14852 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14853 HasVAListArg)) { 14854 if (!FD->hasAttr<FormatAttr>()) 14855 FD->addAttr(FormatAttr::CreateImplicit(Context, 14856 &Context.Idents.get("scanf"), 14857 FormatIdx+1, 14858 HasVAListArg ? 0 : FormatIdx+2, 14859 FD->getLocation())); 14860 } 14861 14862 // Handle automatically recognized callbacks. 14863 SmallVector<int, 4> Encoding; 14864 if (!FD->hasAttr<CallbackAttr>() && 14865 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14866 FD->addAttr(CallbackAttr::CreateImplicit( 14867 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14868 14869 // Mark const if we don't care about errno and that is the only thing 14870 // preventing the function from being const. This allows IRgen to use LLVM 14871 // intrinsics for such functions. 14872 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14873 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14874 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14875 14876 // We make "fma" on some platforms const because we know it does not set 14877 // errno in those environments even though it could set errno based on the 14878 // C standard. 14879 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14880 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14881 !FD->hasAttr<ConstAttr>()) { 14882 switch (BuiltinID) { 14883 case Builtin::BI__builtin_fma: 14884 case Builtin::BI__builtin_fmaf: 14885 case Builtin::BI__builtin_fmal: 14886 case Builtin::BIfma: 14887 case Builtin::BIfmaf: 14888 case Builtin::BIfmal: 14889 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14890 break; 14891 default: 14892 break; 14893 } 14894 } 14895 14896 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14897 !FD->hasAttr<ReturnsTwiceAttr>()) 14898 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14899 FD->getLocation())); 14900 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14901 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14902 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14903 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14904 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14905 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14906 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14907 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14908 // Add the appropriate attribute, depending on the CUDA compilation mode 14909 // and which target the builtin belongs to. For example, during host 14910 // compilation, aux builtins are __device__, while the rest are __host__. 14911 if (getLangOpts().CUDAIsDevice != 14912 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14913 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14914 else 14915 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14916 } 14917 } 14918 14919 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14920 14921 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14922 // throw, add an implicit nothrow attribute to any extern "C" function we come 14923 // across. 14924 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14925 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14926 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14927 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14928 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14929 } 14930 14931 IdentifierInfo *Name = FD->getIdentifier(); 14932 if (!Name) 14933 return; 14934 if ((!getLangOpts().CPlusPlus && 14935 FD->getDeclContext()->isTranslationUnit()) || 14936 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14937 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14938 LinkageSpecDecl::lang_c)) { 14939 // Okay: this could be a libc/libm/Objective-C function we know 14940 // about. 14941 } else 14942 return; 14943 14944 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14945 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14946 // target-specific builtins, perhaps? 14947 if (!FD->hasAttr<FormatAttr>()) 14948 FD->addAttr(FormatAttr::CreateImplicit(Context, 14949 &Context.Idents.get("printf"), 2, 14950 Name->isStr("vasprintf") ? 0 : 3, 14951 FD->getLocation())); 14952 } 14953 14954 if (Name->isStr("__CFStringMakeConstantString")) { 14955 // We already have a __builtin___CFStringMakeConstantString, 14956 // but builds that use -fno-constant-cfstrings don't go through that. 14957 if (!FD->hasAttr<FormatArgAttr>()) 14958 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14959 FD->getLocation())); 14960 } 14961 } 14962 14963 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14964 TypeSourceInfo *TInfo) { 14965 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14966 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14967 14968 if (!TInfo) { 14969 assert(D.isInvalidType() && "no declarator info for valid type"); 14970 TInfo = Context.getTrivialTypeSourceInfo(T); 14971 } 14972 14973 // Scope manipulation handled by caller. 14974 TypedefDecl *NewTD = 14975 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14976 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14977 14978 // Bail out immediately if we have an invalid declaration. 14979 if (D.isInvalidType()) { 14980 NewTD->setInvalidDecl(); 14981 return NewTD; 14982 } 14983 14984 if (D.getDeclSpec().isModulePrivateSpecified()) { 14985 if (CurContext->isFunctionOrMethod()) 14986 Diag(NewTD->getLocation(), diag::err_module_private_local) 14987 << 2 << NewTD 14988 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14989 << FixItHint::CreateRemoval( 14990 D.getDeclSpec().getModulePrivateSpecLoc()); 14991 else 14992 NewTD->setModulePrivate(); 14993 } 14994 14995 // C++ [dcl.typedef]p8: 14996 // If the typedef declaration defines an unnamed class (or 14997 // enum), the first typedef-name declared by the declaration 14998 // to be that class type (or enum type) is used to denote the 14999 // class type (or enum type) for linkage purposes only. 15000 // We need to check whether the type was declared in the declaration. 15001 switch (D.getDeclSpec().getTypeSpecType()) { 15002 case TST_enum: 15003 case TST_struct: 15004 case TST_interface: 15005 case TST_union: 15006 case TST_class: { 15007 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15008 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15009 break; 15010 } 15011 15012 default: 15013 break; 15014 } 15015 15016 return NewTD; 15017 } 15018 15019 /// Check that this is a valid underlying type for an enum declaration. 15020 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15021 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15022 QualType T = TI->getType(); 15023 15024 if (T->isDependentType()) 15025 return false; 15026 15027 // This doesn't use 'isIntegralType' despite the error message mentioning 15028 // integral type because isIntegralType would also allow enum types in C. 15029 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15030 if (BT->isInteger()) 15031 return false; 15032 15033 if (T->isExtIntType()) 15034 return false; 15035 15036 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15037 } 15038 15039 /// Check whether this is a valid redeclaration of a previous enumeration. 15040 /// \return true if the redeclaration was invalid. 15041 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15042 QualType EnumUnderlyingTy, bool IsFixed, 15043 const EnumDecl *Prev) { 15044 if (IsScoped != Prev->isScoped()) { 15045 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15046 << Prev->isScoped(); 15047 Diag(Prev->getLocation(), diag::note_previous_declaration); 15048 return true; 15049 } 15050 15051 if (IsFixed && Prev->isFixed()) { 15052 if (!EnumUnderlyingTy->isDependentType() && 15053 !Prev->getIntegerType()->isDependentType() && 15054 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15055 Prev->getIntegerType())) { 15056 // TODO: Highlight the underlying type of the redeclaration. 15057 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15058 << EnumUnderlyingTy << Prev->getIntegerType(); 15059 Diag(Prev->getLocation(), diag::note_previous_declaration) 15060 << Prev->getIntegerTypeRange(); 15061 return true; 15062 } 15063 } else if (IsFixed != Prev->isFixed()) { 15064 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15065 << Prev->isFixed(); 15066 Diag(Prev->getLocation(), diag::note_previous_declaration); 15067 return true; 15068 } 15069 15070 return false; 15071 } 15072 15073 /// Get diagnostic %select index for tag kind for 15074 /// redeclaration diagnostic message. 15075 /// WARNING: Indexes apply to particular diagnostics only! 15076 /// 15077 /// \returns diagnostic %select index. 15078 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15079 switch (Tag) { 15080 case TTK_Struct: return 0; 15081 case TTK_Interface: return 1; 15082 case TTK_Class: return 2; 15083 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15084 } 15085 } 15086 15087 /// Determine if tag kind is a class-key compatible with 15088 /// class for redeclaration (class, struct, or __interface). 15089 /// 15090 /// \returns true iff the tag kind is compatible. 15091 static bool isClassCompatTagKind(TagTypeKind Tag) 15092 { 15093 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15094 } 15095 15096 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15097 TagTypeKind TTK) { 15098 if (isa<TypedefDecl>(PrevDecl)) 15099 return NTK_Typedef; 15100 else if (isa<TypeAliasDecl>(PrevDecl)) 15101 return NTK_TypeAlias; 15102 else if (isa<ClassTemplateDecl>(PrevDecl)) 15103 return NTK_Template; 15104 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15105 return NTK_TypeAliasTemplate; 15106 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15107 return NTK_TemplateTemplateArgument; 15108 switch (TTK) { 15109 case TTK_Struct: 15110 case TTK_Interface: 15111 case TTK_Class: 15112 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15113 case TTK_Union: 15114 return NTK_NonUnion; 15115 case TTK_Enum: 15116 return NTK_NonEnum; 15117 } 15118 llvm_unreachable("invalid TTK"); 15119 } 15120 15121 /// Determine whether a tag with a given kind is acceptable 15122 /// as a redeclaration of the given tag declaration. 15123 /// 15124 /// \returns true if the new tag kind is acceptable, false otherwise. 15125 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15126 TagTypeKind NewTag, bool isDefinition, 15127 SourceLocation NewTagLoc, 15128 const IdentifierInfo *Name) { 15129 // C++ [dcl.type.elab]p3: 15130 // The class-key or enum keyword present in the 15131 // elaborated-type-specifier shall agree in kind with the 15132 // declaration to which the name in the elaborated-type-specifier 15133 // refers. This rule also applies to the form of 15134 // elaborated-type-specifier that declares a class-name or 15135 // friend class since it can be construed as referring to the 15136 // definition of the class. Thus, in any 15137 // elaborated-type-specifier, the enum keyword shall be used to 15138 // refer to an enumeration (7.2), the union class-key shall be 15139 // used to refer to a union (clause 9), and either the class or 15140 // struct class-key shall be used to refer to a class (clause 9) 15141 // declared using the class or struct class-key. 15142 TagTypeKind OldTag = Previous->getTagKind(); 15143 if (OldTag != NewTag && 15144 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15145 return false; 15146 15147 // Tags are compatible, but we might still want to warn on mismatched tags. 15148 // Non-class tags can't be mismatched at this point. 15149 if (!isClassCompatTagKind(NewTag)) 15150 return true; 15151 15152 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15153 // by our warning analysis. We don't want to warn about mismatches with (eg) 15154 // declarations in system headers that are designed to be specialized, but if 15155 // a user asks us to warn, we should warn if their code contains mismatched 15156 // declarations. 15157 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15158 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15159 Loc); 15160 }; 15161 if (IsIgnoredLoc(NewTagLoc)) 15162 return true; 15163 15164 auto IsIgnored = [&](const TagDecl *Tag) { 15165 return IsIgnoredLoc(Tag->getLocation()); 15166 }; 15167 while (IsIgnored(Previous)) { 15168 Previous = Previous->getPreviousDecl(); 15169 if (!Previous) 15170 return true; 15171 OldTag = Previous->getTagKind(); 15172 } 15173 15174 bool isTemplate = false; 15175 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15176 isTemplate = Record->getDescribedClassTemplate(); 15177 15178 if (inTemplateInstantiation()) { 15179 if (OldTag != NewTag) { 15180 // In a template instantiation, do not offer fix-its for tag mismatches 15181 // since they usually mess up the template instead of fixing the problem. 15182 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15183 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15184 << getRedeclDiagFromTagKind(OldTag); 15185 // FIXME: Note previous location? 15186 } 15187 return true; 15188 } 15189 15190 if (isDefinition) { 15191 // On definitions, check all previous tags and issue a fix-it for each 15192 // one that doesn't match the current tag. 15193 if (Previous->getDefinition()) { 15194 // Don't suggest fix-its for redefinitions. 15195 return true; 15196 } 15197 15198 bool previousMismatch = false; 15199 for (const TagDecl *I : Previous->redecls()) { 15200 if (I->getTagKind() != NewTag) { 15201 // Ignore previous declarations for which the warning was disabled. 15202 if (IsIgnored(I)) 15203 continue; 15204 15205 if (!previousMismatch) { 15206 previousMismatch = true; 15207 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15208 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15209 << getRedeclDiagFromTagKind(I->getTagKind()); 15210 } 15211 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15212 << getRedeclDiagFromTagKind(NewTag) 15213 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15214 TypeWithKeyword::getTagTypeKindName(NewTag)); 15215 } 15216 } 15217 return true; 15218 } 15219 15220 // Identify the prevailing tag kind: this is the kind of the definition (if 15221 // there is a non-ignored definition), or otherwise the kind of the prior 15222 // (non-ignored) declaration. 15223 const TagDecl *PrevDef = Previous->getDefinition(); 15224 if (PrevDef && IsIgnored(PrevDef)) 15225 PrevDef = nullptr; 15226 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15227 if (Redecl->getTagKind() != NewTag) { 15228 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15229 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15230 << getRedeclDiagFromTagKind(OldTag); 15231 Diag(Redecl->getLocation(), diag::note_previous_use); 15232 15233 // If there is a previous definition, suggest a fix-it. 15234 if (PrevDef) { 15235 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15236 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15237 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15238 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15239 } 15240 } 15241 15242 return true; 15243 } 15244 15245 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15246 /// from an outer enclosing namespace or file scope inside a friend declaration. 15247 /// This should provide the commented out code in the following snippet: 15248 /// namespace N { 15249 /// struct X; 15250 /// namespace M { 15251 /// struct Y { friend struct /*N::*/ X; }; 15252 /// } 15253 /// } 15254 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15255 SourceLocation NameLoc) { 15256 // While the decl is in a namespace, do repeated lookup of that name and see 15257 // if we get the same namespace back. If we do not, continue until 15258 // translation unit scope, at which point we have a fully qualified NNS. 15259 SmallVector<IdentifierInfo *, 4> Namespaces; 15260 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15261 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15262 // This tag should be declared in a namespace, which can only be enclosed by 15263 // other namespaces. Bail if there's an anonymous namespace in the chain. 15264 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15265 if (!Namespace || Namespace->isAnonymousNamespace()) 15266 return FixItHint(); 15267 IdentifierInfo *II = Namespace->getIdentifier(); 15268 Namespaces.push_back(II); 15269 NamedDecl *Lookup = SemaRef.LookupSingleName( 15270 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15271 if (Lookup == Namespace) 15272 break; 15273 } 15274 15275 // Once we have all the namespaces, reverse them to go outermost first, and 15276 // build an NNS. 15277 SmallString<64> Insertion; 15278 llvm::raw_svector_ostream OS(Insertion); 15279 if (DC->isTranslationUnit()) 15280 OS << "::"; 15281 std::reverse(Namespaces.begin(), Namespaces.end()); 15282 for (auto *II : Namespaces) 15283 OS << II->getName() << "::"; 15284 return FixItHint::CreateInsertion(NameLoc, Insertion); 15285 } 15286 15287 /// Determine whether a tag originally declared in context \p OldDC can 15288 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15289 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15290 /// using-declaration). 15291 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15292 DeclContext *NewDC) { 15293 OldDC = OldDC->getRedeclContext(); 15294 NewDC = NewDC->getRedeclContext(); 15295 15296 if (OldDC->Equals(NewDC)) 15297 return true; 15298 15299 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15300 // encloses the other). 15301 if (S.getLangOpts().MSVCCompat && 15302 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15303 return true; 15304 15305 return false; 15306 } 15307 15308 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15309 /// former case, Name will be non-null. In the later case, Name will be null. 15310 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15311 /// reference/declaration/definition of a tag. 15312 /// 15313 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15314 /// trailing-type-specifier) other than one in an alias-declaration. 15315 /// 15316 /// \param SkipBody If non-null, will be set to indicate if the caller should 15317 /// skip the definition of this tag and treat it as if it were a declaration. 15318 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15319 SourceLocation KWLoc, CXXScopeSpec &SS, 15320 IdentifierInfo *Name, SourceLocation NameLoc, 15321 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15322 SourceLocation ModulePrivateLoc, 15323 MultiTemplateParamsArg TemplateParameterLists, 15324 bool &OwnedDecl, bool &IsDependent, 15325 SourceLocation ScopedEnumKWLoc, 15326 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15327 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15328 SkipBodyInfo *SkipBody) { 15329 // If this is not a definition, it must have a name. 15330 IdentifierInfo *OrigName = Name; 15331 assert((Name != nullptr || TUK == TUK_Definition) && 15332 "Nameless record must be a definition!"); 15333 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15334 15335 OwnedDecl = false; 15336 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15337 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15338 15339 // FIXME: Check member specializations more carefully. 15340 bool isMemberSpecialization = false; 15341 bool Invalid = false; 15342 15343 // We only need to do this matching if we have template parameters 15344 // or a scope specifier, which also conveniently avoids this work 15345 // for non-C++ cases. 15346 if (TemplateParameterLists.size() > 0 || 15347 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15348 if (TemplateParameterList *TemplateParams = 15349 MatchTemplateParametersToScopeSpecifier( 15350 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15351 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15352 if (Kind == TTK_Enum) { 15353 Diag(KWLoc, diag::err_enum_template); 15354 return nullptr; 15355 } 15356 15357 if (TemplateParams->size() > 0) { 15358 // This is a declaration or definition of a class template (which may 15359 // be a member of another template). 15360 15361 if (Invalid) 15362 return nullptr; 15363 15364 OwnedDecl = false; 15365 DeclResult Result = CheckClassTemplate( 15366 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15367 AS, ModulePrivateLoc, 15368 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15369 TemplateParameterLists.data(), SkipBody); 15370 return Result.get(); 15371 } else { 15372 // The "template<>" header is extraneous. 15373 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15374 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15375 isMemberSpecialization = true; 15376 } 15377 } 15378 15379 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15380 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15381 return nullptr; 15382 } 15383 15384 // Figure out the underlying type if this a enum declaration. We need to do 15385 // this early, because it's needed to detect if this is an incompatible 15386 // redeclaration. 15387 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15388 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15389 15390 if (Kind == TTK_Enum) { 15391 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15392 // No underlying type explicitly specified, or we failed to parse the 15393 // type, default to int. 15394 EnumUnderlying = Context.IntTy.getTypePtr(); 15395 } else if (UnderlyingType.get()) { 15396 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15397 // integral type; any cv-qualification is ignored. 15398 TypeSourceInfo *TI = nullptr; 15399 GetTypeFromParser(UnderlyingType.get(), &TI); 15400 EnumUnderlying = TI; 15401 15402 if (CheckEnumUnderlyingType(TI)) 15403 // Recover by falling back to int. 15404 EnumUnderlying = Context.IntTy.getTypePtr(); 15405 15406 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15407 UPPC_FixedUnderlyingType)) 15408 EnumUnderlying = Context.IntTy.getTypePtr(); 15409 15410 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15411 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15412 // of 'int'. However, if this is an unfixed forward declaration, don't set 15413 // the underlying type unless the user enables -fms-compatibility. This 15414 // makes unfixed forward declared enums incomplete and is more conforming. 15415 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15416 EnumUnderlying = Context.IntTy.getTypePtr(); 15417 } 15418 } 15419 15420 DeclContext *SearchDC = CurContext; 15421 DeclContext *DC = CurContext; 15422 bool isStdBadAlloc = false; 15423 bool isStdAlignValT = false; 15424 15425 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15426 if (TUK == TUK_Friend || TUK == TUK_Reference) 15427 Redecl = NotForRedeclaration; 15428 15429 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15430 /// implemented asks for structural equivalence checking, the returned decl 15431 /// here is passed back to the parser, allowing the tag body to be parsed. 15432 auto createTagFromNewDecl = [&]() -> TagDecl * { 15433 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15434 // If there is an identifier, use the location of the identifier as the 15435 // location of the decl, otherwise use the location of the struct/union 15436 // keyword. 15437 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15438 TagDecl *New = nullptr; 15439 15440 if (Kind == TTK_Enum) { 15441 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15442 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15443 // If this is an undefined enum, bail. 15444 if (TUK != TUK_Definition && !Invalid) 15445 return nullptr; 15446 if (EnumUnderlying) { 15447 EnumDecl *ED = cast<EnumDecl>(New); 15448 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15449 ED->setIntegerTypeSourceInfo(TI); 15450 else 15451 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15452 ED->setPromotionType(ED->getIntegerType()); 15453 } 15454 } else { // struct/union 15455 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15456 nullptr); 15457 } 15458 15459 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15460 // Add alignment attributes if necessary; these attributes are checked 15461 // when the ASTContext lays out the structure. 15462 // 15463 // It is important for implementing the correct semantics that this 15464 // happen here (in ActOnTag). The #pragma pack stack is 15465 // maintained as a result of parser callbacks which can occur at 15466 // many points during the parsing of a struct declaration (because 15467 // the #pragma tokens are effectively skipped over during the 15468 // parsing of the struct). 15469 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15470 AddAlignmentAttributesForRecord(RD); 15471 AddMsStructLayoutForRecord(RD); 15472 } 15473 } 15474 New->setLexicalDeclContext(CurContext); 15475 return New; 15476 }; 15477 15478 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15479 if (Name && SS.isNotEmpty()) { 15480 // We have a nested-name tag ('struct foo::bar'). 15481 15482 // Check for invalid 'foo::'. 15483 if (SS.isInvalid()) { 15484 Name = nullptr; 15485 goto CreateNewDecl; 15486 } 15487 15488 // If this is a friend or a reference to a class in a dependent 15489 // context, don't try to make a decl for it. 15490 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15491 DC = computeDeclContext(SS, false); 15492 if (!DC) { 15493 IsDependent = true; 15494 return nullptr; 15495 } 15496 } else { 15497 DC = computeDeclContext(SS, true); 15498 if (!DC) { 15499 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15500 << SS.getRange(); 15501 return nullptr; 15502 } 15503 } 15504 15505 if (RequireCompleteDeclContext(SS, DC)) 15506 return nullptr; 15507 15508 SearchDC = DC; 15509 // Look-up name inside 'foo::'. 15510 LookupQualifiedName(Previous, DC); 15511 15512 if (Previous.isAmbiguous()) 15513 return nullptr; 15514 15515 if (Previous.empty()) { 15516 // Name lookup did not find anything. However, if the 15517 // nested-name-specifier refers to the current instantiation, 15518 // and that current instantiation has any dependent base 15519 // classes, we might find something at instantiation time: treat 15520 // this as a dependent elaborated-type-specifier. 15521 // But this only makes any sense for reference-like lookups. 15522 if (Previous.wasNotFoundInCurrentInstantiation() && 15523 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15524 IsDependent = true; 15525 return nullptr; 15526 } 15527 15528 // A tag 'foo::bar' must already exist. 15529 Diag(NameLoc, diag::err_not_tag_in_scope) 15530 << Kind << Name << DC << SS.getRange(); 15531 Name = nullptr; 15532 Invalid = true; 15533 goto CreateNewDecl; 15534 } 15535 } else if (Name) { 15536 // C++14 [class.mem]p14: 15537 // If T is the name of a class, then each of the following shall have a 15538 // name different from T: 15539 // -- every member of class T that is itself a type 15540 if (TUK != TUK_Reference && TUK != TUK_Friend && 15541 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15542 return nullptr; 15543 15544 // If this is a named struct, check to see if there was a previous forward 15545 // declaration or definition. 15546 // FIXME: We're looking into outer scopes here, even when we 15547 // shouldn't be. Doing so can result in ambiguities that we 15548 // shouldn't be diagnosing. 15549 LookupName(Previous, S); 15550 15551 // When declaring or defining a tag, ignore ambiguities introduced 15552 // by types using'ed into this scope. 15553 if (Previous.isAmbiguous() && 15554 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15555 LookupResult::Filter F = Previous.makeFilter(); 15556 while (F.hasNext()) { 15557 NamedDecl *ND = F.next(); 15558 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15559 SearchDC->getRedeclContext())) 15560 F.erase(); 15561 } 15562 F.done(); 15563 } 15564 15565 // C++11 [namespace.memdef]p3: 15566 // If the name in a friend declaration is neither qualified nor 15567 // a template-id and the declaration is a function or an 15568 // elaborated-type-specifier, the lookup to determine whether 15569 // the entity has been previously declared shall not consider 15570 // any scopes outside the innermost enclosing namespace. 15571 // 15572 // MSVC doesn't implement the above rule for types, so a friend tag 15573 // declaration may be a redeclaration of a type declared in an enclosing 15574 // scope. They do implement this rule for friend functions. 15575 // 15576 // Does it matter that this should be by scope instead of by 15577 // semantic context? 15578 if (!Previous.empty() && TUK == TUK_Friend) { 15579 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15580 LookupResult::Filter F = Previous.makeFilter(); 15581 bool FriendSawTagOutsideEnclosingNamespace = false; 15582 while (F.hasNext()) { 15583 NamedDecl *ND = F.next(); 15584 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15585 if (DC->isFileContext() && 15586 !EnclosingNS->Encloses(ND->getDeclContext())) { 15587 if (getLangOpts().MSVCCompat) 15588 FriendSawTagOutsideEnclosingNamespace = true; 15589 else 15590 F.erase(); 15591 } 15592 } 15593 F.done(); 15594 15595 // Diagnose this MSVC extension in the easy case where lookup would have 15596 // unambiguously found something outside the enclosing namespace. 15597 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15598 NamedDecl *ND = Previous.getFoundDecl(); 15599 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15600 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15601 } 15602 } 15603 15604 // Note: there used to be some attempt at recovery here. 15605 if (Previous.isAmbiguous()) 15606 return nullptr; 15607 15608 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15609 // FIXME: This makes sure that we ignore the contexts associated 15610 // with C structs, unions, and enums when looking for a matching 15611 // tag declaration or definition. See the similar lookup tweak 15612 // in Sema::LookupName; is there a better way to deal with this? 15613 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15614 SearchDC = SearchDC->getParent(); 15615 } 15616 } 15617 15618 if (Previous.isSingleResult() && 15619 Previous.getFoundDecl()->isTemplateParameter()) { 15620 // Maybe we will complain about the shadowed template parameter. 15621 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15622 // Just pretend that we didn't see the previous declaration. 15623 Previous.clear(); 15624 } 15625 15626 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15627 DC->Equals(getStdNamespace())) { 15628 if (Name->isStr("bad_alloc")) { 15629 // This is a declaration of or a reference to "std::bad_alloc". 15630 isStdBadAlloc = true; 15631 15632 // If std::bad_alloc has been implicitly declared (but made invisible to 15633 // name lookup), fill in this implicit declaration as the previous 15634 // declaration, so that the declarations get chained appropriately. 15635 if (Previous.empty() && StdBadAlloc) 15636 Previous.addDecl(getStdBadAlloc()); 15637 } else if (Name->isStr("align_val_t")) { 15638 isStdAlignValT = true; 15639 if (Previous.empty() && StdAlignValT) 15640 Previous.addDecl(getStdAlignValT()); 15641 } 15642 } 15643 15644 // If we didn't find a previous declaration, and this is a reference 15645 // (or friend reference), move to the correct scope. In C++, we 15646 // also need to do a redeclaration lookup there, just in case 15647 // there's a shadow friend decl. 15648 if (Name && Previous.empty() && 15649 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15650 if (Invalid) goto CreateNewDecl; 15651 assert(SS.isEmpty()); 15652 15653 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15654 // C++ [basic.scope.pdecl]p5: 15655 // -- for an elaborated-type-specifier of the form 15656 // 15657 // class-key identifier 15658 // 15659 // if the elaborated-type-specifier is used in the 15660 // decl-specifier-seq or parameter-declaration-clause of a 15661 // function defined in namespace scope, the identifier is 15662 // declared as a class-name in the namespace that contains 15663 // the declaration; otherwise, except as a friend 15664 // declaration, the identifier is declared in the smallest 15665 // non-class, non-function-prototype scope that contains the 15666 // declaration. 15667 // 15668 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15669 // C structs and unions. 15670 // 15671 // It is an error in C++ to declare (rather than define) an enum 15672 // type, including via an elaborated type specifier. We'll 15673 // diagnose that later; for now, declare the enum in the same 15674 // scope as we would have picked for any other tag type. 15675 // 15676 // GNU C also supports this behavior as part of its incomplete 15677 // enum types extension, while GNU C++ does not. 15678 // 15679 // Find the context where we'll be declaring the tag. 15680 // FIXME: We would like to maintain the current DeclContext as the 15681 // lexical context, 15682 SearchDC = getTagInjectionContext(SearchDC); 15683 15684 // Find the scope where we'll be declaring the tag. 15685 S = getTagInjectionScope(S, getLangOpts()); 15686 } else { 15687 assert(TUK == TUK_Friend); 15688 // C++ [namespace.memdef]p3: 15689 // If a friend declaration in a non-local class first declares a 15690 // class or function, the friend class or function is a member of 15691 // the innermost enclosing namespace. 15692 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15693 } 15694 15695 // In C++, we need to do a redeclaration lookup to properly 15696 // diagnose some problems. 15697 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15698 // hidden declaration so that we don't get ambiguity errors when using a 15699 // type declared by an elaborated-type-specifier. In C that is not correct 15700 // and we should instead merge compatible types found by lookup. 15701 if (getLangOpts().CPlusPlus) { 15702 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15703 LookupQualifiedName(Previous, SearchDC); 15704 } else { 15705 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15706 LookupName(Previous, S); 15707 } 15708 } 15709 15710 // If we have a known previous declaration to use, then use it. 15711 if (Previous.empty() && SkipBody && SkipBody->Previous) 15712 Previous.addDecl(SkipBody->Previous); 15713 15714 if (!Previous.empty()) { 15715 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15716 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15717 15718 // It's okay to have a tag decl in the same scope as a typedef 15719 // which hides a tag decl in the same scope. Finding this 15720 // insanity with a redeclaration lookup can only actually happen 15721 // in C++. 15722 // 15723 // This is also okay for elaborated-type-specifiers, which is 15724 // technically forbidden by the current standard but which is 15725 // okay according to the likely resolution of an open issue; 15726 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15727 if (getLangOpts().CPlusPlus) { 15728 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15729 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15730 TagDecl *Tag = TT->getDecl(); 15731 if (Tag->getDeclName() == Name && 15732 Tag->getDeclContext()->getRedeclContext() 15733 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15734 PrevDecl = Tag; 15735 Previous.clear(); 15736 Previous.addDecl(Tag); 15737 Previous.resolveKind(); 15738 } 15739 } 15740 } 15741 } 15742 15743 // If this is a redeclaration of a using shadow declaration, it must 15744 // declare a tag in the same context. In MSVC mode, we allow a 15745 // redefinition if either context is within the other. 15746 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15747 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15748 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15749 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15750 !(OldTag && isAcceptableTagRedeclContext( 15751 *this, OldTag->getDeclContext(), SearchDC))) { 15752 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15753 Diag(Shadow->getTargetDecl()->getLocation(), 15754 diag::note_using_decl_target); 15755 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15756 << 0; 15757 // Recover by ignoring the old declaration. 15758 Previous.clear(); 15759 goto CreateNewDecl; 15760 } 15761 } 15762 15763 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15764 // If this is a use of a previous tag, or if the tag is already declared 15765 // in the same scope (so that the definition/declaration completes or 15766 // rementions the tag), reuse the decl. 15767 if (TUK == TUK_Reference || TUK == TUK_Friend || 15768 isDeclInScope(DirectPrevDecl, SearchDC, S, 15769 SS.isNotEmpty() || isMemberSpecialization)) { 15770 // Make sure that this wasn't declared as an enum and now used as a 15771 // struct or something similar. 15772 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15773 TUK == TUK_Definition, KWLoc, 15774 Name)) { 15775 bool SafeToContinue 15776 = (PrevTagDecl->getTagKind() != TTK_Enum && 15777 Kind != TTK_Enum); 15778 if (SafeToContinue) 15779 Diag(KWLoc, diag::err_use_with_wrong_tag) 15780 << Name 15781 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15782 PrevTagDecl->getKindName()); 15783 else 15784 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15785 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15786 15787 if (SafeToContinue) 15788 Kind = PrevTagDecl->getTagKind(); 15789 else { 15790 // Recover by making this an anonymous redefinition. 15791 Name = nullptr; 15792 Previous.clear(); 15793 Invalid = true; 15794 } 15795 } 15796 15797 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15798 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15799 if (TUK == TUK_Reference || TUK == TUK_Friend) 15800 return PrevTagDecl; 15801 15802 QualType EnumUnderlyingTy; 15803 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15804 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15805 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15806 EnumUnderlyingTy = QualType(T, 0); 15807 15808 // All conflicts with previous declarations are recovered by 15809 // returning the previous declaration, unless this is a definition, 15810 // in which case we want the caller to bail out. 15811 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15812 ScopedEnum, EnumUnderlyingTy, 15813 IsFixed, PrevEnum)) 15814 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15815 } 15816 15817 // C++11 [class.mem]p1: 15818 // A member shall not be declared twice in the member-specification, 15819 // except that a nested class or member class template can be declared 15820 // and then later defined. 15821 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15822 S->isDeclScope(PrevDecl)) { 15823 Diag(NameLoc, diag::ext_member_redeclared); 15824 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15825 } 15826 15827 if (!Invalid) { 15828 // If this is a use, just return the declaration we found, unless 15829 // we have attributes. 15830 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15831 if (!Attrs.empty()) { 15832 // FIXME: Diagnose these attributes. For now, we create a new 15833 // declaration to hold them. 15834 } else if (TUK == TUK_Reference && 15835 (PrevTagDecl->getFriendObjectKind() == 15836 Decl::FOK_Undeclared || 15837 PrevDecl->getOwningModule() != getCurrentModule()) && 15838 SS.isEmpty()) { 15839 // This declaration is a reference to an existing entity, but 15840 // has different visibility from that entity: it either makes 15841 // a friend visible or it makes a type visible in a new module. 15842 // In either case, create a new declaration. We only do this if 15843 // the declaration would have meant the same thing if no prior 15844 // declaration were found, that is, if it was found in the same 15845 // scope where we would have injected a declaration. 15846 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15847 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15848 return PrevTagDecl; 15849 // This is in the injected scope, create a new declaration in 15850 // that scope. 15851 S = getTagInjectionScope(S, getLangOpts()); 15852 } else { 15853 return PrevTagDecl; 15854 } 15855 } 15856 15857 // Diagnose attempts to redefine a tag. 15858 if (TUK == TUK_Definition) { 15859 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15860 // If we're defining a specialization and the previous definition 15861 // is from an implicit instantiation, don't emit an error 15862 // here; we'll catch this in the general case below. 15863 bool IsExplicitSpecializationAfterInstantiation = false; 15864 if (isMemberSpecialization) { 15865 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15866 IsExplicitSpecializationAfterInstantiation = 15867 RD->getTemplateSpecializationKind() != 15868 TSK_ExplicitSpecialization; 15869 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15870 IsExplicitSpecializationAfterInstantiation = 15871 ED->getTemplateSpecializationKind() != 15872 TSK_ExplicitSpecialization; 15873 } 15874 15875 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15876 // not keep more that one definition around (merge them). However, 15877 // ensure the decl passes the structural compatibility check in 15878 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15879 NamedDecl *Hidden = nullptr; 15880 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15881 // There is a definition of this tag, but it is not visible. We 15882 // explicitly make use of C++'s one definition rule here, and 15883 // assume that this definition is identical to the hidden one 15884 // we already have. Make the existing definition visible and 15885 // use it in place of this one. 15886 if (!getLangOpts().CPlusPlus) { 15887 // Postpone making the old definition visible until after we 15888 // complete parsing the new one and do the structural 15889 // comparison. 15890 SkipBody->CheckSameAsPrevious = true; 15891 SkipBody->New = createTagFromNewDecl(); 15892 SkipBody->Previous = Def; 15893 return Def; 15894 } else { 15895 SkipBody->ShouldSkip = true; 15896 SkipBody->Previous = Def; 15897 makeMergedDefinitionVisible(Hidden); 15898 // Carry on and handle it like a normal definition. We'll 15899 // skip starting the definitiion later. 15900 } 15901 } else if (!IsExplicitSpecializationAfterInstantiation) { 15902 // A redeclaration in function prototype scope in C isn't 15903 // visible elsewhere, so merely issue a warning. 15904 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15905 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15906 else 15907 Diag(NameLoc, diag::err_redefinition) << Name; 15908 notePreviousDefinition(Def, 15909 NameLoc.isValid() ? NameLoc : KWLoc); 15910 // If this is a redefinition, recover by making this 15911 // struct be anonymous, which will make any later 15912 // references get the previous definition. 15913 Name = nullptr; 15914 Previous.clear(); 15915 Invalid = true; 15916 } 15917 } else { 15918 // If the type is currently being defined, complain 15919 // about a nested redefinition. 15920 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15921 if (TD->isBeingDefined()) { 15922 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15923 Diag(PrevTagDecl->getLocation(), 15924 diag::note_previous_definition); 15925 Name = nullptr; 15926 Previous.clear(); 15927 Invalid = true; 15928 } 15929 } 15930 15931 // Okay, this is definition of a previously declared or referenced 15932 // tag. We're going to create a new Decl for it. 15933 } 15934 15935 // Okay, we're going to make a redeclaration. If this is some kind 15936 // of reference, make sure we build the redeclaration in the same DC 15937 // as the original, and ignore the current access specifier. 15938 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15939 SearchDC = PrevTagDecl->getDeclContext(); 15940 AS = AS_none; 15941 } 15942 } 15943 // If we get here we have (another) forward declaration or we 15944 // have a definition. Just create a new decl. 15945 15946 } else { 15947 // If we get here, this is a definition of a new tag type in a nested 15948 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15949 // new decl/type. We set PrevDecl to NULL so that the entities 15950 // have distinct types. 15951 Previous.clear(); 15952 } 15953 // If we get here, we're going to create a new Decl. If PrevDecl 15954 // is non-NULL, it's a definition of the tag declared by 15955 // PrevDecl. If it's NULL, we have a new definition. 15956 15957 // Otherwise, PrevDecl is not a tag, but was found with tag 15958 // lookup. This is only actually possible in C++, where a few 15959 // things like templates still live in the tag namespace. 15960 } else { 15961 // Use a better diagnostic if an elaborated-type-specifier 15962 // found the wrong kind of type on the first 15963 // (non-redeclaration) lookup. 15964 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15965 !Previous.isForRedeclaration()) { 15966 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15967 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15968 << Kind; 15969 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15970 Invalid = true; 15971 15972 // Otherwise, only diagnose if the declaration is in scope. 15973 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15974 SS.isNotEmpty() || isMemberSpecialization)) { 15975 // do nothing 15976 15977 // Diagnose implicit declarations introduced by elaborated types. 15978 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15979 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15980 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15981 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15982 Invalid = true; 15983 15984 // Otherwise it's a declaration. Call out a particularly common 15985 // case here. 15986 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15987 unsigned Kind = 0; 15988 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15989 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15990 << Name << Kind << TND->getUnderlyingType(); 15991 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15992 Invalid = true; 15993 15994 // Otherwise, diagnose. 15995 } else { 15996 // The tag name clashes with something else in the target scope, 15997 // issue an error and recover by making this tag be anonymous. 15998 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15999 notePreviousDefinition(PrevDecl, NameLoc); 16000 Name = nullptr; 16001 Invalid = true; 16002 } 16003 16004 // The existing declaration isn't relevant to us; we're in a 16005 // new scope, so clear out the previous declaration. 16006 Previous.clear(); 16007 } 16008 } 16009 16010 CreateNewDecl: 16011 16012 TagDecl *PrevDecl = nullptr; 16013 if (Previous.isSingleResult()) 16014 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16015 16016 // If there is an identifier, use the location of the identifier as the 16017 // location of the decl, otherwise use the location of the struct/union 16018 // keyword. 16019 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16020 16021 // Otherwise, create a new declaration. If there is a previous 16022 // declaration of the same entity, the two will be linked via 16023 // PrevDecl. 16024 TagDecl *New; 16025 16026 if (Kind == TTK_Enum) { 16027 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16028 // enum X { A, B, C } D; D should chain to X. 16029 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16030 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16031 ScopedEnumUsesClassTag, IsFixed); 16032 16033 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16034 StdAlignValT = cast<EnumDecl>(New); 16035 16036 // If this is an undefined enum, warn. 16037 if (TUK != TUK_Definition && !Invalid) { 16038 TagDecl *Def; 16039 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16040 // C++0x: 7.2p2: opaque-enum-declaration. 16041 // Conflicts are diagnosed above. Do nothing. 16042 } 16043 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16044 Diag(Loc, diag::ext_forward_ref_enum_def) 16045 << New; 16046 Diag(Def->getLocation(), diag::note_previous_definition); 16047 } else { 16048 unsigned DiagID = diag::ext_forward_ref_enum; 16049 if (getLangOpts().MSVCCompat) 16050 DiagID = diag::ext_ms_forward_ref_enum; 16051 else if (getLangOpts().CPlusPlus) 16052 DiagID = diag::err_forward_ref_enum; 16053 Diag(Loc, DiagID); 16054 } 16055 } 16056 16057 if (EnumUnderlying) { 16058 EnumDecl *ED = cast<EnumDecl>(New); 16059 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16060 ED->setIntegerTypeSourceInfo(TI); 16061 else 16062 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16063 ED->setPromotionType(ED->getIntegerType()); 16064 assert(ED->isComplete() && "enum with type should be complete"); 16065 } 16066 } else { 16067 // struct/union/class 16068 16069 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16070 // struct X { int A; } D; D should chain to X. 16071 if (getLangOpts().CPlusPlus) { 16072 // FIXME: Look for a way to use RecordDecl for simple structs. 16073 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16074 cast_or_null<CXXRecordDecl>(PrevDecl)); 16075 16076 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16077 StdBadAlloc = cast<CXXRecordDecl>(New); 16078 } else 16079 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16080 cast_or_null<RecordDecl>(PrevDecl)); 16081 } 16082 16083 // C++11 [dcl.type]p3: 16084 // A type-specifier-seq shall not define a class or enumeration [...]. 16085 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16086 TUK == TUK_Definition) { 16087 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16088 << Context.getTagDeclType(New); 16089 Invalid = true; 16090 } 16091 16092 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16093 DC->getDeclKind() == Decl::Enum) { 16094 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16095 << Context.getTagDeclType(New); 16096 Invalid = true; 16097 } 16098 16099 // Maybe add qualifier info. 16100 if (SS.isNotEmpty()) { 16101 if (SS.isSet()) { 16102 // If this is either a declaration or a definition, check the 16103 // nested-name-specifier against the current context. 16104 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16105 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16106 isMemberSpecialization)) 16107 Invalid = true; 16108 16109 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16110 if (TemplateParameterLists.size() > 0) { 16111 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16112 } 16113 } 16114 else 16115 Invalid = true; 16116 } 16117 16118 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16119 // Add alignment attributes if necessary; these attributes are checked when 16120 // the ASTContext lays out the structure. 16121 // 16122 // It is important for implementing the correct semantics that this 16123 // happen here (in ActOnTag). The #pragma pack stack is 16124 // maintained as a result of parser callbacks which can occur at 16125 // many points during the parsing of a struct declaration (because 16126 // the #pragma tokens are effectively skipped over during the 16127 // parsing of the struct). 16128 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16129 AddAlignmentAttributesForRecord(RD); 16130 AddMsStructLayoutForRecord(RD); 16131 } 16132 } 16133 16134 if (ModulePrivateLoc.isValid()) { 16135 if (isMemberSpecialization) 16136 Diag(New->getLocation(), diag::err_module_private_specialization) 16137 << 2 16138 << FixItHint::CreateRemoval(ModulePrivateLoc); 16139 // __module_private__ does not apply to local classes. However, we only 16140 // diagnose this as an error when the declaration specifiers are 16141 // freestanding. Here, we just ignore the __module_private__. 16142 else if (!SearchDC->isFunctionOrMethod()) 16143 New->setModulePrivate(); 16144 } 16145 16146 // If this is a specialization of a member class (of a class template), 16147 // check the specialization. 16148 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16149 Invalid = true; 16150 16151 // If we're declaring or defining a tag in function prototype scope in C, 16152 // note that this type can only be used within the function and add it to 16153 // the list of decls to inject into the function definition scope. 16154 if ((Name || Kind == TTK_Enum) && 16155 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16156 if (getLangOpts().CPlusPlus) { 16157 // C++ [dcl.fct]p6: 16158 // Types shall not be defined in return or parameter types. 16159 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16160 Diag(Loc, diag::err_type_defined_in_param_type) 16161 << Name; 16162 Invalid = true; 16163 } 16164 } else if (!PrevDecl) { 16165 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16166 } 16167 } 16168 16169 if (Invalid) 16170 New->setInvalidDecl(); 16171 16172 // Set the lexical context. If the tag has a C++ scope specifier, the 16173 // lexical context will be different from the semantic context. 16174 New->setLexicalDeclContext(CurContext); 16175 16176 // Mark this as a friend decl if applicable. 16177 // In Microsoft mode, a friend declaration also acts as a forward 16178 // declaration so we always pass true to setObjectOfFriendDecl to make 16179 // the tag name visible. 16180 if (TUK == TUK_Friend) 16181 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16182 16183 // Set the access specifier. 16184 if (!Invalid && SearchDC->isRecord()) 16185 SetMemberAccessSpecifier(New, PrevDecl, AS); 16186 16187 if (PrevDecl) 16188 CheckRedeclarationModuleOwnership(New, PrevDecl); 16189 16190 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16191 New->startDefinition(); 16192 16193 ProcessDeclAttributeList(S, New, Attrs); 16194 AddPragmaAttributes(S, New); 16195 16196 // If this has an identifier, add it to the scope stack. 16197 if (TUK == TUK_Friend) { 16198 // We might be replacing an existing declaration in the lookup tables; 16199 // if so, borrow its access specifier. 16200 if (PrevDecl) 16201 New->setAccess(PrevDecl->getAccess()); 16202 16203 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16204 DC->makeDeclVisibleInContext(New); 16205 if (Name) // can be null along some error paths 16206 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16207 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16208 } else if (Name) { 16209 S = getNonFieldDeclScope(S); 16210 PushOnScopeChains(New, S, true); 16211 } else { 16212 CurContext->addDecl(New); 16213 } 16214 16215 // If this is the C FILE type, notify the AST context. 16216 if (IdentifierInfo *II = New->getIdentifier()) 16217 if (!New->isInvalidDecl() && 16218 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16219 II->isStr("FILE")) 16220 Context.setFILEDecl(New); 16221 16222 if (PrevDecl) 16223 mergeDeclAttributes(New, PrevDecl); 16224 16225 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16226 inferGslOwnerPointerAttribute(CXXRD); 16227 16228 // If there's a #pragma GCC visibility in scope, set the visibility of this 16229 // record. 16230 AddPushedVisibilityAttribute(New); 16231 16232 if (isMemberSpecialization && !New->isInvalidDecl()) 16233 CompleteMemberSpecialization(New, Previous); 16234 16235 OwnedDecl = true; 16236 // In C++, don't return an invalid declaration. We can't recover well from 16237 // the cases where we make the type anonymous. 16238 if (Invalid && getLangOpts().CPlusPlus) { 16239 if (New->isBeingDefined()) 16240 if (auto RD = dyn_cast<RecordDecl>(New)) 16241 RD->completeDefinition(); 16242 return nullptr; 16243 } else if (SkipBody && SkipBody->ShouldSkip) { 16244 return SkipBody->Previous; 16245 } else { 16246 return New; 16247 } 16248 } 16249 16250 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16251 AdjustDeclIfTemplate(TagD); 16252 TagDecl *Tag = cast<TagDecl>(TagD); 16253 16254 // Enter the tag context. 16255 PushDeclContext(S, Tag); 16256 16257 ActOnDocumentableDecl(TagD); 16258 16259 // If there's a #pragma GCC visibility in scope, set the visibility of this 16260 // record. 16261 AddPushedVisibilityAttribute(Tag); 16262 } 16263 16264 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16265 SkipBodyInfo &SkipBody) { 16266 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16267 return false; 16268 16269 // Make the previous decl visible. 16270 makeMergedDefinitionVisible(SkipBody.Previous); 16271 return true; 16272 } 16273 16274 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16275 assert(isa<ObjCContainerDecl>(IDecl) && 16276 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16277 DeclContext *OCD = cast<DeclContext>(IDecl); 16278 assert(OCD->getLexicalParent() == CurContext && 16279 "The next DeclContext should be lexically contained in the current one."); 16280 CurContext = OCD; 16281 return IDecl; 16282 } 16283 16284 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16285 SourceLocation FinalLoc, 16286 bool IsFinalSpelledSealed, 16287 SourceLocation LBraceLoc) { 16288 AdjustDeclIfTemplate(TagD); 16289 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16290 16291 FieldCollector->StartClass(); 16292 16293 if (!Record->getIdentifier()) 16294 return; 16295 16296 if (FinalLoc.isValid()) 16297 Record->addAttr(FinalAttr::Create( 16298 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16299 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16300 16301 // C++ [class]p2: 16302 // [...] The class-name is also inserted into the scope of the 16303 // class itself; this is known as the injected-class-name. For 16304 // purposes of access checking, the injected-class-name is treated 16305 // as if it were a public member name. 16306 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16307 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16308 Record->getLocation(), Record->getIdentifier(), 16309 /*PrevDecl=*/nullptr, 16310 /*DelayTypeCreation=*/true); 16311 Context.getTypeDeclType(InjectedClassName, Record); 16312 InjectedClassName->setImplicit(); 16313 InjectedClassName->setAccess(AS_public); 16314 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16315 InjectedClassName->setDescribedClassTemplate(Template); 16316 PushOnScopeChains(InjectedClassName, S); 16317 assert(InjectedClassName->isInjectedClassName() && 16318 "Broken injected-class-name"); 16319 } 16320 16321 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16322 SourceRange BraceRange) { 16323 AdjustDeclIfTemplate(TagD); 16324 TagDecl *Tag = cast<TagDecl>(TagD); 16325 Tag->setBraceRange(BraceRange); 16326 16327 // Make sure we "complete" the definition even it is invalid. 16328 if (Tag->isBeingDefined()) { 16329 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16330 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16331 RD->completeDefinition(); 16332 } 16333 16334 if (isa<CXXRecordDecl>(Tag)) { 16335 FieldCollector->FinishClass(); 16336 } 16337 16338 // Exit this scope of this tag's definition. 16339 PopDeclContext(); 16340 16341 if (getCurLexicalContext()->isObjCContainer() && 16342 Tag->getDeclContext()->isFileContext()) 16343 Tag->setTopLevelDeclInObjCContainer(); 16344 16345 // Notify the consumer that we've defined a tag. 16346 if (!Tag->isInvalidDecl()) 16347 Consumer.HandleTagDeclDefinition(Tag); 16348 } 16349 16350 void Sema::ActOnObjCContainerFinishDefinition() { 16351 // Exit this scope of this interface definition. 16352 PopDeclContext(); 16353 } 16354 16355 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16356 assert(DC == CurContext && "Mismatch of container contexts"); 16357 OriginalLexicalContext = DC; 16358 ActOnObjCContainerFinishDefinition(); 16359 } 16360 16361 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16362 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16363 OriginalLexicalContext = nullptr; 16364 } 16365 16366 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16367 AdjustDeclIfTemplate(TagD); 16368 TagDecl *Tag = cast<TagDecl>(TagD); 16369 Tag->setInvalidDecl(); 16370 16371 // Make sure we "complete" the definition even it is invalid. 16372 if (Tag->isBeingDefined()) { 16373 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16374 RD->completeDefinition(); 16375 } 16376 16377 // We're undoing ActOnTagStartDefinition here, not 16378 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16379 // the FieldCollector. 16380 16381 PopDeclContext(); 16382 } 16383 16384 // Note that FieldName may be null for anonymous bitfields. 16385 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16386 IdentifierInfo *FieldName, 16387 QualType FieldTy, bool IsMsStruct, 16388 Expr *BitWidth, bool *ZeroWidth) { 16389 assert(BitWidth); 16390 if (BitWidth->containsErrors()) 16391 return ExprError(); 16392 16393 // Default to true; that shouldn't confuse checks for emptiness 16394 if (ZeroWidth) 16395 *ZeroWidth = true; 16396 16397 // C99 6.7.2.1p4 - verify the field type. 16398 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16399 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16400 // Handle incomplete and sizeless types with a specific error. 16401 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16402 diag::err_field_incomplete_or_sizeless)) 16403 return ExprError(); 16404 if (FieldName) 16405 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16406 << FieldName << FieldTy << BitWidth->getSourceRange(); 16407 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16408 << FieldTy << BitWidth->getSourceRange(); 16409 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16410 UPPC_BitFieldWidth)) 16411 return ExprError(); 16412 16413 // If the bit-width is type- or value-dependent, don't try to check 16414 // it now. 16415 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16416 return BitWidth; 16417 16418 llvm::APSInt Value; 16419 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16420 if (ICE.isInvalid()) 16421 return ICE; 16422 BitWidth = ICE.get(); 16423 16424 if (Value != 0 && ZeroWidth) 16425 *ZeroWidth = false; 16426 16427 // Zero-width bitfield is ok for anonymous field. 16428 if (Value == 0 && FieldName) 16429 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16430 16431 if (Value.isSigned() && Value.isNegative()) { 16432 if (FieldName) 16433 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16434 << FieldName << Value.toString(10); 16435 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16436 << Value.toString(10); 16437 } 16438 16439 if (!FieldTy->isDependentType()) { 16440 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16441 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16442 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16443 16444 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16445 // ABI. 16446 bool CStdConstraintViolation = 16447 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16448 bool MSBitfieldViolation = 16449 Value.ugt(TypeStorageSize) && 16450 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16451 if (CStdConstraintViolation || MSBitfieldViolation) { 16452 unsigned DiagWidth = 16453 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16454 if (FieldName) 16455 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16456 << FieldName << (unsigned)Value.getZExtValue() 16457 << !CStdConstraintViolation << DiagWidth; 16458 16459 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16460 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16461 << DiagWidth; 16462 } 16463 16464 // Warn on types where the user might conceivably expect to get all 16465 // specified bits as value bits: that's all integral types other than 16466 // 'bool'. 16467 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16468 if (FieldName) 16469 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16470 << FieldName << (unsigned)Value.getZExtValue() 16471 << (unsigned)TypeWidth; 16472 else 16473 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16474 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16475 } 16476 } 16477 16478 return BitWidth; 16479 } 16480 16481 /// ActOnField - Each field of a C struct/union is passed into this in order 16482 /// to create a FieldDecl object for it. 16483 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16484 Declarator &D, Expr *BitfieldWidth) { 16485 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16486 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16487 /*InitStyle=*/ICIS_NoInit, AS_public); 16488 return Res; 16489 } 16490 16491 /// HandleField - Analyze a field of a C struct or a C++ data member. 16492 /// 16493 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16494 SourceLocation DeclStart, 16495 Declarator &D, Expr *BitWidth, 16496 InClassInitStyle InitStyle, 16497 AccessSpecifier AS) { 16498 if (D.isDecompositionDeclarator()) { 16499 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16500 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16501 << Decomp.getSourceRange(); 16502 return nullptr; 16503 } 16504 16505 IdentifierInfo *II = D.getIdentifier(); 16506 SourceLocation Loc = DeclStart; 16507 if (II) Loc = D.getIdentifierLoc(); 16508 16509 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16510 QualType T = TInfo->getType(); 16511 if (getLangOpts().CPlusPlus) { 16512 CheckExtraCXXDefaultArguments(D); 16513 16514 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16515 UPPC_DataMemberType)) { 16516 D.setInvalidType(); 16517 T = Context.IntTy; 16518 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16519 } 16520 } 16521 16522 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16523 16524 if (D.getDeclSpec().isInlineSpecified()) 16525 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16526 << getLangOpts().CPlusPlus17; 16527 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16528 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16529 diag::err_invalid_thread) 16530 << DeclSpec::getSpecifierName(TSCS); 16531 16532 // Check to see if this name was declared as a member previously 16533 NamedDecl *PrevDecl = nullptr; 16534 LookupResult Previous(*this, II, Loc, LookupMemberName, 16535 ForVisibleRedeclaration); 16536 LookupName(Previous, S); 16537 switch (Previous.getResultKind()) { 16538 case LookupResult::Found: 16539 case LookupResult::FoundUnresolvedValue: 16540 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16541 break; 16542 16543 case LookupResult::FoundOverloaded: 16544 PrevDecl = Previous.getRepresentativeDecl(); 16545 break; 16546 16547 case LookupResult::NotFound: 16548 case LookupResult::NotFoundInCurrentInstantiation: 16549 case LookupResult::Ambiguous: 16550 break; 16551 } 16552 Previous.suppressDiagnostics(); 16553 16554 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16555 // Maybe we will complain about the shadowed template parameter. 16556 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16557 // Just pretend that we didn't see the previous declaration. 16558 PrevDecl = nullptr; 16559 } 16560 16561 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16562 PrevDecl = nullptr; 16563 16564 bool Mutable 16565 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16566 SourceLocation TSSL = D.getBeginLoc(); 16567 FieldDecl *NewFD 16568 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16569 TSSL, AS, PrevDecl, &D); 16570 16571 if (NewFD->isInvalidDecl()) 16572 Record->setInvalidDecl(); 16573 16574 if (D.getDeclSpec().isModulePrivateSpecified()) 16575 NewFD->setModulePrivate(); 16576 16577 if (NewFD->isInvalidDecl() && PrevDecl) { 16578 // Don't introduce NewFD into scope; there's already something 16579 // with the same name in the same scope. 16580 } else if (II) { 16581 PushOnScopeChains(NewFD, S); 16582 } else 16583 Record->addDecl(NewFD); 16584 16585 return NewFD; 16586 } 16587 16588 /// Build a new FieldDecl and check its well-formedness. 16589 /// 16590 /// This routine builds a new FieldDecl given the fields name, type, 16591 /// record, etc. \p PrevDecl should refer to any previous declaration 16592 /// with the same name and in the same scope as the field to be 16593 /// created. 16594 /// 16595 /// \returns a new FieldDecl. 16596 /// 16597 /// \todo The Declarator argument is a hack. It will be removed once 16598 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16599 TypeSourceInfo *TInfo, 16600 RecordDecl *Record, SourceLocation Loc, 16601 bool Mutable, Expr *BitWidth, 16602 InClassInitStyle InitStyle, 16603 SourceLocation TSSL, 16604 AccessSpecifier AS, NamedDecl *PrevDecl, 16605 Declarator *D) { 16606 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16607 bool InvalidDecl = false; 16608 if (D) InvalidDecl = D->isInvalidType(); 16609 16610 // If we receive a broken type, recover by assuming 'int' and 16611 // marking this declaration as invalid. 16612 if (T.isNull() || T->containsErrors()) { 16613 InvalidDecl = true; 16614 T = Context.IntTy; 16615 } 16616 16617 QualType EltTy = Context.getBaseElementType(T); 16618 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16619 if (RequireCompleteSizedType(Loc, EltTy, 16620 diag::err_field_incomplete_or_sizeless)) { 16621 // Fields of incomplete type force their record to be invalid. 16622 Record->setInvalidDecl(); 16623 InvalidDecl = true; 16624 } else { 16625 NamedDecl *Def; 16626 EltTy->isIncompleteType(&Def); 16627 if (Def && Def->isInvalidDecl()) { 16628 Record->setInvalidDecl(); 16629 InvalidDecl = true; 16630 } 16631 } 16632 } 16633 16634 // TR 18037 does not allow fields to be declared with address space 16635 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16636 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16637 Diag(Loc, diag::err_field_with_address_space); 16638 Record->setInvalidDecl(); 16639 InvalidDecl = true; 16640 } 16641 16642 if (LangOpts.OpenCL) { 16643 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16644 // used as structure or union field: image, sampler, event or block types. 16645 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16646 T->isBlockPointerType()) { 16647 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16648 Record->setInvalidDecl(); 16649 InvalidDecl = true; 16650 } 16651 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16652 if (BitWidth) { 16653 Diag(Loc, diag::err_opencl_bitfields); 16654 InvalidDecl = true; 16655 } 16656 } 16657 16658 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16659 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16660 T.hasQualifiers()) { 16661 InvalidDecl = true; 16662 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16663 } 16664 16665 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16666 // than a variably modified type. 16667 if (!InvalidDecl && T->isVariablyModifiedType()) { 16668 bool SizeIsNegative; 16669 llvm::APSInt Oversized; 16670 16671 TypeSourceInfo *FixedTInfo = 16672 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16673 SizeIsNegative, 16674 Oversized); 16675 if (FixedTInfo) { 16676 Diag(Loc, diag::warn_illegal_constant_array_size); 16677 TInfo = FixedTInfo; 16678 T = FixedTInfo->getType(); 16679 } else { 16680 if (SizeIsNegative) 16681 Diag(Loc, diag::err_typecheck_negative_array_size); 16682 else if (Oversized.getBoolValue()) 16683 Diag(Loc, diag::err_array_too_large) 16684 << Oversized.toString(10); 16685 else 16686 Diag(Loc, diag::err_typecheck_field_variable_size); 16687 InvalidDecl = true; 16688 } 16689 } 16690 16691 // Fields can not have abstract class types 16692 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16693 diag::err_abstract_type_in_decl, 16694 AbstractFieldType)) 16695 InvalidDecl = true; 16696 16697 bool ZeroWidth = false; 16698 if (InvalidDecl) 16699 BitWidth = nullptr; 16700 // If this is declared as a bit-field, check the bit-field. 16701 if (BitWidth) { 16702 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16703 &ZeroWidth).get(); 16704 if (!BitWidth) { 16705 InvalidDecl = true; 16706 BitWidth = nullptr; 16707 ZeroWidth = false; 16708 } 16709 } 16710 16711 // Check that 'mutable' is consistent with the type of the declaration. 16712 if (!InvalidDecl && Mutable) { 16713 unsigned DiagID = 0; 16714 if (T->isReferenceType()) 16715 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16716 : diag::err_mutable_reference; 16717 else if (T.isConstQualified()) 16718 DiagID = diag::err_mutable_const; 16719 16720 if (DiagID) { 16721 SourceLocation ErrLoc = Loc; 16722 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16723 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16724 Diag(ErrLoc, DiagID); 16725 if (DiagID != diag::ext_mutable_reference) { 16726 Mutable = false; 16727 InvalidDecl = true; 16728 } 16729 } 16730 } 16731 16732 // C++11 [class.union]p8 (DR1460): 16733 // At most one variant member of a union may have a 16734 // brace-or-equal-initializer. 16735 if (InitStyle != ICIS_NoInit) 16736 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16737 16738 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16739 BitWidth, Mutable, InitStyle); 16740 if (InvalidDecl) 16741 NewFD->setInvalidDecl(); 16742 16743 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16744 Diag(Loc, diag::err_duplicate_member) << II; 16745 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16746 NewFD->setInvalidDecl(); 16747 } 16748 16749 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16750 if (Record->isUnion()) { 16751 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16752 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16753 if (RDecl->getDefinition()) { 16754 // C++ [class.union]p1: An object of a class with a non-trivial 16755 // constructor, a non-trivial copy constructor, a non-trivial 16756 // destructor, or a non-trivial copy assignment operator 16757 // cannot be a member of a union, nor can an array of such 16758 // objects. 16759 if (CheckNontrivialField(NewFD)) 16760 NewFD->setInvalidDecl(); 16761 } 16762 } 16763 16764 // C++ [class.union]p1: If a union contains a member of reference type, 16765 // the program is ill-formed, except when compiling with MSVC extensions 16766 // enabled. 16767 if (EltTy->isReferenceType()) { 16768 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16769 diag::ext_union_member_of_reference_type : 16770 diag::err_union_member_of_reference_type) 16771 << NewFD->getDeclName() << EltTy; 16772 if (!getLangOpts().MicrosoftExt) 16773 NewFD->setInvalidDecl(); 16774 } 16775 } 16776 } 16777 16778 // FIXME: We need to pass in the attributes given an AST 16779 // representation, not a parser representation. 16780 if (D) { 16781 // FIXME: The current scope is almost... but not entirely... correct here. 16782 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16783 16784 if (NewFD->hasAttrs()) 16785 CheckAlignasUnderalignment(NewFD); 16786 } 16787 16788 // In auto-retain/release, infer strong retension for fields of 16789 // retainable type. 16790 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16791 NewFD->setInvalidDecl(); 16792 16793 if (T.isObjCGCWeak()) 16794 Diag(Loc, diag::warn_attribute_weak_on_field); 16795 16796 NewFD->setAccess(AS); 16797 return NewFD; 16798 } 16799 16800 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16801 assert(FD); 16802 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16803 16804 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16805 return false; 16806 16807 QualType EltTy = Context.getBaseElementType(FD->getType()); 16808 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16809 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16810 if (RDecl->getDefinition()) { 16811 // We check for copy constructors before constructors 16812 // because otherwise we'll never get complaints about 16813 // copy constructors. 16814 16815 CXXSpecialMember member = CXXInvalid; 16816 // We're required to check for any non-trivial constructors. Since the 16817 // implicit default constructor is suppressed if there are any 16818 // user-declared constructors, we just need to check that there is a 16819 // trivial default constructor and a trivial copy constructor. (We don't 16820 // worry about move constructors here, since this is a C++98 check.) 16821 if (RDecl->hasNonTrivialCopyConstructor()) 16822 member = CXXCopyConstructor; 16823 else if (!RDecl->hasTrivialDefaultConstructor()) 16824 member = CXXDefaultConstructor; 16825 else if (RDecl->hasNonTrivialCopyAssignment()) 16826 member = CXXCopyAssignment; 16827 else if (RDecl->hasNonTrivialDestructor()) 16828 member = CXXDestructor; 16829 16830 if (member != CXXInvalid) { 16831 if (!getLangOpts().CPlusPlus11 && 16832 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16833 // Objective-C++ ARC: it is an error to have a non-trivial field of 16834 // a union. However, system headers in Objective-C programs 16835 // occasionally have Objective-C lifetime objects within unions, 16836 // and rather than cause the program to fail, we make those 16837 // members unavailable. 16838 SourceLocation Loc = FD->getLocation(); 16839 if (getSourceManager().isInSystemHeader(Loc)) { 16840 if (!FD->hasAttr<UnavailableAttr>()) 16841 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16842 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16843 return false; 16844 } 16845 } 16846 16847 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16848 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16849 diag::err_illegal_union_or_anon_struct_member) 16850 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16851 DiagnoseNontrivial(RDecl, member); 16852 return !getLangOpts().CPlusPlus11; 16853 } 16854 } 16855 } 16856 16857 return false; 16858 } 16859 16860 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16861 /// AST enum value. 16862 static ObjCIvarDecl::AccessControl 16863 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16864 switch (ivarVisibility) { 16865 default: llvm_unreachable("Unknown visitibility kind"); 16866 case tok::objc_private: return ObjCIvarDecl::Private; 16867 case tok::objc_public: return ObjCIvarDecl::Public; 16868 case tok::objc_protected: return ObjCIvarDecl::Protected; 16869 case tok::objc_package: return ObjCIvarDecl::Package; 16870 } 16871 } 16872 16873 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16874 /// in order to create an IvarDecl object for it. 16875 Decl *Sema::ActOnIvar(Scope *S, 16876 SourceLocation DeclStart, 16877 Declarator &D, Expr *BitfieldWidth, 16878 tok::ObjCKeywordKind Visibility) { 16879 16880 IdentifierInfo *II = D.getIdentifier(); 16881 Expr *BitWidth = (Expr*)BitfieldWidth; 16882 SourceLocation Loc = DeclStart; 16883 if (II) Loc = D.getIdentifierLoc(); 16884 16885 // FIXME: Unnamed fields can be handled in various different ways, for 16886 // example, unnamed unions inject all members into the struct namespace! 16887 16888 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16889 QualType T = TInfo->getType(); 16890 16891 if (BitWidth) { 16892 // 6.7.2.1p3, 6.7.2.1p4 16893 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16894 if (!BitWidth) 16895 D.setInvalidType(); 16896 } else { 16897 // Not a bitfield. 16898 16899 // validate II. 16900 16901 } 16902 if (T->isReferenceType()) { 16903 Diag(Loc, diag::err_ivar_reference_type); 16904 D.setInvalidType(); 16905 } 16906 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16907 // than a variably modified type. 16908 else if (T->isVariablyModifiedType()) { 16909 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16910 D.setInvalidType(); 16911 } 16912 16913 // Get the visibility (access control) for this ivar. 16914 ObjCIvarDecl::AccessControl ac = 16915 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16916 : ObjCIvarDecl::None; 16917 // Must set ivar's DeclContext to its enclosing interface. 16918 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16919 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16920 return nullptr; 16921 ObjCContainerDecl *EnclosingContext; 16922 if (ObjCImplementationDecl *IMPDecl = 16923 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16924 if (LangOpts.ObjCRuntime.isFragile()) { 16925 // Case of ivar declared in an implementation. Context is that of its class. 16926 EnclosingContext = IMPDecl->getClassInterface(); 16927 assert(EnclosingContext && "Implementation has no class interface!"); 16928 } 16929 else 16930 EnclosingContext = EnclosingDecl; 16931 } else { 16932 if (ObjCCategoryDecl *CDecl = 16933 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16934 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16935 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16936 return nullptr; 16937 } 16938 } 16939 EnclosingContext = EnclosingDecl; 16940 } 16941 16942 // Construct the decl. 16943 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16944 DeclStart, Loc, II, T, 16945 TInfo, ac, (Expr *)BitfieldWidth); 16946 16947 if (II) { 16948 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16949 ForVisibleRedeclaration); 16950 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16951 && !isa<TagDecl>(PrevDecl)) { 16952 Diag(Loc, diag::err_duplicate_member) << II; 16953 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16954 NewID->setInvalidDecl(); 16955 } 16956 } 16957 16958 // Process attributes attached to the ivar. 16959 ProcessDeclAttributes(S, NewID, D); 16960 16961 if (D.isInvalidType()) 16962 NewID->setInvalidDecl(); 16963 16964 // In ARC, infer 'retaining' for ivars of retainable type. 16965 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16966 NewID->setInvalidDecl(); 16967 16968 if (D.getDeclSpec().isModulePrivateSpecified()) 16969 NewID->setModulePrivate(); 16970 16971 if (II) { 16972 // FIXME: When interfaces are DeclContexts, we'll need to add 16973 // these to the interface. 16974 S->AddDecl(NewID); 16975 IdResolver.AddDecl(NewID); 16976 } 16977 16978 if (LangOpts.ObjCRuntime.isNonFragile() && 16979 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16980 Diag(Loc, diag::warn_ivars_in_interface); 16981 16982 return NewID; 16983 } 16984 16985 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16986 /// class and class extensions. For every class \@interface and class 16987 /// extension \@interface, if the last ivar is a bitfield of any type, 16988 /// then add an implicit `char :0` ivar to the end of that interface. 16989 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16990 SmallVectorImpl<Decl *> &AllIvarDecls) { 16991 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16992 return; 16993 16994 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16995 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16996 16997 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16998 return; 16999 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17000 if (!ID) { 17001 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17002 if (!CD->IsClassExtension()) 17003 return; 17004 } 17005 // No need to add this to end of @implementation. 17006 else 17007 return; 17008 } 17009 // All conditions are met. Add a new bitfield to the tail end of ivars. 17010 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17011 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17012 17013 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17014 DeclLoc, DeclLoc, nullptr, 17015 Context.CharTy, 17016 Context.getTrivialTypeSourceInfo(Context.CharTy, 17017 DeclLoc), 17018 ObjCIvarDecl::Private, BW, 17019 true); 17020 AllIvarDecls.push_back(Ivar); 17021 } 17022 17023 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17024 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17025 SourceLocation RBrac, 17026 const ParsedAttributesView &Attrs) { 17027 assert(EnclosingDecl && "missing record or interface decl"); 17028 17029 // If this is an Objective-C @implementation or category and we have 17030 // new fields here we should reset the layout of the interface since 17031 // it will now change. 17032 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17033 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17034 switch (DC->getKind()) { 17035 default: break; 17036 case Decl::ObjCCategory: 17037 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17038 break; 17039 case Decl::ObjCImplementation: 17040 Context. 17041 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17042 break; 17043 } 17044 } 17045 17046 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17047 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17048 17049 // Start counting up the number of named members; make sure to include 17050 // members of anonymous structs and unions in the total. 17051 unsigned NumNamedMembers = 0; 17052 if (Record) { 17053 for (const auto *I : Record->decls()) { 17054 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17055 if (IFD->getDeclName()) 17056 ++NumNamedMembers; 17057 } 17058 } 17059 17060 // Verify that all the fields are okay. 17061 SmallVector<FieldDecl*, 32> RecFields; 17062 17063 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17064 i != end; ++i) { 17065 FieldDecl *FD = cast<FieldDecl>(*i); 17066 17067 // Get the type for the field. 17068 const Type *FDTy = FD->getType().getTypePtr(); 17069 17070 if (!FD->isAnonymousStructOrUnion()) { 17071 // Remember all fields written by the user. 17072 RecFields.push_back(FD); 17073 } 17074 17075 // If the field is already invalid for some reason, don't emit more 17076 // diagnostics about it. 17077 if (FD->isInvalidDecl()) { 17078 EnclosingDecl->setInvalidDecl(); 17079 continue; 17080 } 17081 17082 // C99 6.7.2.1p2: 17083 // A structure or union shall not contain a member with 17084 // incomplete or function type (hence, a structure shall not 17085 // contain an instance of itself, but may contain a pointer to 17086 // an instance of itself), except that the last member of a 17087 // structure with more than one named member may have incomplete 17088 // array type; such a structure (and any union containing, 17089 // possibly recursively, a member that is such a structure) 17090 // shall not be a member of a structure or an element of an 17091 // array. 17092 bool IsLastField = (i + 1 == Fields.end()); 17093 if (FDTy->isFunctionType()) { 17094 // Field declared as a function. 17095 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17096 << FD->getDeclName(); 17097 FD->setInvalidDecl(); 17098 EnclosingDecl->setInvalidDecl(); 17099 continue; 17100 } else if (FDTy->isIncompleteArrayType() && 17101 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17102 if (Record) { 17103 // Flexible array member. 17104 // Microsoft and g++ is more permissive regarding flexible array. 17105 // It will accept flexible array in union and also 17106 // as the sole element of a struct/class. 17107 unsigned DiagID = 0; 17108 if (!Record->isUnion() && !IsLastField) { 17109 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17110 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17111 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17112 FD->setInvalidDecl(); 17113 EnclosingDecl->setInvalidDecl(); 17114 continue; 17115 } else if (Record->isUnion()) 17116 DiagID = getLangOpts().MicrosoftExt 17117 ? diag::ext_flexible_array_union_ms 17118 : getLangOpts().CPlusPlus 17119 ? diag::ext_flexible_array_union_gnu 17120 : diag::err_flexible_array_union; 17121 else if (NumNamedMembers < 1) 17122 DiagID = getLangOpts().MicrosoftExt 17123 ? diag::ext_flexible_array_empty_aggregate_ms 17124 : getLangOpts().CPlusPlus 17125 ? diag::ext_flexible_array_empty_aggregate_gnu 17126 : diag::err_flexible_array_empty_aggregate; 17127 17128 if (DiagID) 17129 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17130 << Record->getTagKind(); 17131 // While the layout of types that contain virtual bases is not specified 17132 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17133 // virtual bases after the derived members. This would make a flexible 17134 // array member declared at the end of an object not adjacent to the end 17135 // of the type. 17136 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17137 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17138 << FD->getDeclName() << Record->getTagKind(); 17139 if (!getLangOpts().C99) 17140 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17141 << FD->getDeclName() << Record->getTagKind(); 17142 17143 // If the element type has a non-trivial destructor, we would not 17144 // implicitly destroy the elements, so disallow it for now. 17145 // 17146 // FIXME: GCC allows this. We should probably either implicitly delete 17147 // the destructor of the containing class, or just allow this. 17148 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17149 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17150 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17151 << FD->getDeclName() << FD->getType(); 17152 FD->setInvalidDecl(); 17153 EnclosingDecl->setInvalidDecl(); 17154 continue; 17155 } 17156 // Okay, we have a legal flexible array member at the end of the struct. 17157 Record->setHasFlexibleArrayMember(true); 17158 } else { 17159 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17160 // unless they are followed by another ivar. That check is done 17161 // elsewhere, after synthesized ivars are known. 17162 } 17163 } else if (!FDTy->isDependentType() && 17164 RequireCompleteSizedType( 17165 FD->getLocation(), FD->getType(), 17166 diag::err_field_incomplete_or_sizeless)) { 17167 // Incomplete type 17168 FD->setInvalidDecl(); 17169 EnclosingDecl->setInvalidDecl(); 17170 continue; 17171 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17172 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17173 // A type which contains a flexible array member is considered to be a 17174 // flexible array member. 17175 Record->setHasFlexibleArrayMember(true); 17176 if (!Record->isUnion()) { 17177 // If this is a struct/class and this is not the last element, reject 17178 // it. Note that GCC supports variable sized arrays in the middle of 17179 // structures. 17180 if (!IsLastField) 17181 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17182 << FD->getDeclName() << FD->getType(); 17183 else { 17184 // We support flexible arrays at the end of structs in 17185 // other structs as an extension. 17186 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17187 << FD->getDeclName(); 17188 } 17189 } 17190 } 17191 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17192 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17193 diag::err_abstract_type_in_decl, 17194 AbstractIvarType)) { 17195 // Ivars can not have abstract class types 17196 FD->setInvalidDecl(); 17197 } 17198 if (Record && FDTTy->getDecl()->hasObjectMember()) 17199 Record->setHasObjectMember(true); 17200 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17201 Record->setHasVolatileMember(true); 17202 } else if (FDTy->isObjCObjectType()) { 17203 /// A field cannot be an Objective-c object 17204 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17205 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17206 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17207 FD->setType(T); 17208 } else if (Record && Record->isUnion() && 17209 FD->getType().hasNonTrivialObjCLifetime() && 17210 getSourceManager().isInSystemHeader(FD->getLocation()) && 17211 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17212 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17213 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17214 // For backward compatibility, fields of C unions declared in system 17215 // headers that have non-trivial ObjC ownership qualifications are marked 17216 // as unavailable unless the qualifier is explicit and __strong. This can 17217 // break ABI compatibility between programs compiled with ARC and MRR, but 17218 // is a better option than rejecting programs using those unions under 17219 // ARC. 17220 FD->addAttr(UnavailableAttr::CreateImplicit( 17221 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17222 FD->getLocation())); 17223 } else if (getLangOpts().ObjC && 17224 getLangOpts().getGC() != LangOptions::NonGC && Record && 17225 !Record->hasObjectMember()) { 17226 if (FD->getType()->isObjCObjectPointerType() || 17227 FD->getType().isObjCGCStrong()) 17228 Record->setHasObjectMember(true); 17229 else if (Context.getAsArrayType(FD->getType())) { 17230 QualType BaseType = Context.getBaseElementType(FD->getType()); 17231 if (BaseType->isRecordType() && 17232 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17233 Record->setHasObjectMember(true); 17234 else if (BaseType->isObjCObjectPointerType() || 17235 BaseType.isObjCGCStrong()) 17236 Record->setHasObjectMember(true); 17237 } 17238 } 17239 17240 if (Record && !getLangOpts().CPlusPlus && 17241 !shouldIgnoreForRecordTriviality(FD)) { 17242 QualType FT = FD->getType(); 17243 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17244 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17245 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17246 Record->isUnion()) 17247 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17248 } 17249 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17250 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17251 Record->setNonTrivialToPrimitiveCopy(true); 17252 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17253 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17254 } 17255 if (FT.isDestructedType()) { 17256 Record->setNonTrivialToPrimitiveDestroy(true); 17257 Record->setParamDestroyedInCallee(true); 17258 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17259 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17260 } 17261 17262 if (const auto *RT = FT->getAs<RecordType>()) { 17263 if (RT->getDecl()->getArgPassingRestrictions() == 17264 RecordDecl::APK_CanNeverPassInRegs) 17265 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17266 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17267 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17268 } 17269 17270 if (Record && FD->getType().isVolatileQualified()) 17271 Record->setHasVolatileMember(true); 17272 // Keep track of the number of named members. 17273 if (FD->getIdentifier()) 17274 ++NumNamedMembers; 17275 } 17276 17277 // Okay, we successfully defined 'Record'. 17278 if (Record) { 17279 bool Completed = false; 17280 if (CXXRecord) { 17281 if (!CXXRecord->isInvalidDecl()) { 17282 // Set access bits correctly on the directly-declared conversions. 17283 for (CXXRecordDecl::conversion_iterator 17284 I = CXXRecord->conversion_begin(), 17285 E = CXXRecord->conversion_end(); I != E; ++I) 17286 I.setAccess((*I)->getAccess()); 17287 } 17288 17289 // Add any implicitly-declared members to this class. 17290 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17291 17292 if (!CXXRecord->isDependentType()) { 17293 if (!CXXRecord->isInvalidDecl()) { 17294 // If we have virtual base classes, we may end up finding multiple 17295 // final overriders for a given virtual function. Check for this 17296 // problem now. 17297 if (CXXRecord->getNumVBases()) { 17298 CXXFinalOverriderMap FinalOverriders; 17299 CXXRecord->getFinalOverriders(FinalOverriders); 17300 17301 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17302 MEnd = FinalOverriders.end(); 17303 M != MEnd; ++M) { 17304 for (OverridingMethods::iterator SO = M->second.begin(), 17305 SOEnd = M->second.end(); 17306 SO != SOEnd; ++SO) { 17307 assert(SO->second.size() > 0 && 17308 "Virtual function without overriding functions?"); 17309 if (SO->second.size() == 1) 17310 continue; 17311 17312 // C++ [class.virtual]p2: 17313 // In a derived class, if a virtual member function of a base 17314 // class subobject has more than one final overrider the 17315 // program is ill-formed. 17316 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17317 << (const NamedDecl *)M->first << Record; 17318 Diag(M->first->getLocation(), 17319 diag::note_overridden_virtual_function); 17320 for (OverridingMethods::overriding_iterator 17321 OM = SO->second.begin(), 17322 OMEnd = SO->second.end(); 17323 OM != OMEnd; ++OM) 17324 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17325 << (const NamedDecl *)M->first << OM->Method->getParent(); 17326 17327 Record->setInvalidDecl(); 17328 } 17329 } 17330 CXXRecord->completeDefinition(&FinalOverriders); 17331 Completed = true; 17332 } 17333 } 17334 } 17335 } 17336 17337 if (!Completed) 17338 Record->completeDefinition(); 17339 17340 // Handle attributes before checking the layout. 17341 ProcessDeclAttributeList(S, Record, Attrs); 17342 17343 // We may have deferred checking for a deleted destructor. Check now. 17344 if (CXXRecord) { 17345 auto *Dtor = CXXRecord->getDestructor(); 17346 if (Dtor && Dtor->isImplicit() && 17347 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17348 CXXRecord->setImplicitDestructorIsDeleted(); 17349 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17350 } 17351 } 17352 17353 if (Record->hasAttrs()) { 17354 CheckAlignasUnderalignment(Record); 17355 17356 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17357 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17358 IA->getRange(), IA->getBestCase(), 17359 IA->getInheritanceModel()); 17360 } 17361 17362 // Check if the structure/union declaration is a type that can have zero 17363 // size in C. For C this is a language extension, for C++ it may cause 17364 // compatibility problems. 17365 bool CheckForZeroSize; 17366 if (!getLangOpts().CPlusPlus) { 17367 CheckForZeroSize = true; 17368 } else { 17369 // For C++ filter out types that cannot be referenced in C code. 17370 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17371 CheckForZeroSize = 17372 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17373 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17374 CXXRecord->isCLike(); 17375 } 17376 if (CheckForZeroSize) { 17377 bool ZeroSize = true; 17378 bool IsEmpty = true; 17379 unsigned NonBitFields = 0; 17380 for (RecordDecl::field_iterator I = Record->field_begin(), 17381 E = Record->field_end(); 17382 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17383 IsEmpty = false; 17384 if (I->isUnnamedBitfield()) { 17385 if (!I->isZeroLengthBitField(Context)) 17386 ZeroSize = false; 17387 } else { 17388 ++NonBitFields; 17389 QualType FieldType = I->getType(); 17390 if (FieldType->isIncompleteType() || 17391 !Context.getTypeSizeInChars(FieldType).isZero()) 17392 ZeroSize = false; 17393 } 17394 } 17395 17396 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17397 // allowed in C++, but warn if its declaration is inside 17398 // extern "C" block. 17399 if (ZeroSize) { 17400 Diag(RecLoc, getLangOpts().CPlusPlus ? 17401 diag::warn_zero_size_struct_union_in_extern_c : 17402 diag::warn_zero_size_struct_union_compat) 17403 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17404 } 17405 17406 // Structs without named members are extension in C (C99 6.7.2.1p7), 17407 // but are accepted by GCC. 17408 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17409 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17410 diag::ext_no_named_members_in_struct_union) 17411 << Record->isUnion(); 17412 } 17413 } 17414 } else { 17415 ObjCIvarDecl **ClsFields = 17416 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17417 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17418 ID->setEndOfDefinitionLoc(RBrac); 17419 // Add ivar's to class's DeclContext. 17420 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17421 ClsFields[i]->setLexicalDeclContext(ID); 17422 ID->addDecl(ClsFields[i]); 17423 } 17424 // Must enforce the rule that ivars in the base classes may not be 17425 // duplicates. 17426 if (ID->getSuperClass()) 17427 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17428 } else if (ObjCImplementationDecl *IMPDecl = 17429 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17430 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17431 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17432 // Ivar declared in @implementation never belongs to the implementation. 17433 // Only it is in implementation's lexical context. 17434 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17435 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17436 IMPDecl->setIvarLBraceLoc(LBrac); 17437 IMPDecl->setIvarRBraceLoc(RBrac); 17438 } else if (ObjCCategoryDecl *CDecl = 17439 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17440 // case of ivars in class extension; all other cases have been 17441 // reported as errors elsewhere. 17442 // FIXME. Class extension does not have a LocEnd field. 17443 // CDecl->setLocEnd(RBrac); 17444 // Add ivar's to class extension's DeclContext. 17445 // Diagnose redeclaration of private ivars. 17446 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17447 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17448 if (IDecl) { 17449 if (const ObjCIvarDecl *ClsIvar = 17450 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17451 Diag(ClsFields[i]->getLocation(), 17452 diag::err_duplicate_ivar_declaration); 17453 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17454 continue; 17455 } 17456 for (const auto *Ext : IDecl->known_extensions()) { 17457 if (const ObjCIvarDecl *ClsExtIvar 17458 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17459 Diag(ClsFields[i]->getLocation(), 17460 diag::err_duplicate_ivar_declaration); 17461 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17462 continue; 17463 } 17464 } 17465 } 17466 ClsFields[i]->setLexicalDeclContext(CDecl); 17467 CDecl->addDecl(ClsFields[i]); 17468 } 17469 CDecl->setIvarLBraceLoc(LBrac); 17470 CDecl->setIvarRBraceLoc(RBrac); 17471 } 17472 } 17473 } 17474 17475 /// Determine whether the given integral value is representable within 17476 /// the given type T. 17477 static bool isRepresentableIntegerValue(ASTContext &Context, 17478 llvm::APSInt &Value, 17479 QualType T) { 17480 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17481 "Integral type required!"); 17482 unsigned BitWidth = Context.getIntWidth(T); 17483 17484 if (Value.isUnsigned() || Value.isNonNegative()) { 17485 if (T->isSignedIntegerOrEnumerationType()) 17486 --BitWidth; 17487 return Value.getActiveBits() <= BitWidth; 17488 } 17489 return Value.getMinSignedBits() <= BitWidth; 17490 } 17491 17492 // Given an integral type, return the next larger integral type 17493 // (or a NULL type of no such type exists). 17494 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17495 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17496 // enum checking below. 17497 assert((T->isIntegralType(Context) || 17498 T->isEnumeralType()) && "Integral type required!"); 17499 const unsigned NumTypes = 4; 17500 QualType SignedIntegralTypes[NumTypes] = { 17501 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17502 }; 17503 QualType UnsignedIntegralTypes[NumTypes] = { 17504 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17505 Context.UnsignedLongLongTy 17506 }; 17507 17508 unsigned BitWidth = Context.getTypeSize(T); 17509 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17510 : UnsignedIntegralTypes; 17511 for (unsigned I = 0; I != NumTypes; ++I) 17512 if (Context.getTypeSize(Types[I]) > BitWidth) 17513 return Types[I]; 17514 17515 return QualType(); 17516 } 17517 17518 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17519 EnumConstantDecl *LastEnumConst, 17520 SourceLocation IdLoc, 17521 IdentifierInfo *Id, 17522 Expr *Val) { 17523 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17524 llvm::APSInt EnumVal(IntWidth); 17525 QualType EltTy; 17526 17527 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17528 Val = nullptr; 17529 17530 if (Val) 17531 Val = DefaultLvalueConversion(Val).get(); 17532 17533 if (Val) { 17534 if (Enum->isDependentType() || Val->isTypeDependent()) 17535 EltTy = Context.DependentTy; 17536 else { 17537 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17538 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17539 // constant-expression in the enumerator-definition shall be a converted 17540 // constant expression of the underlying type. 17541 EltTy = Enum->getIntegerType(); 17542 ExprResult Converted = 17543 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17544 CCEK_Enumerator); 17545 if (Converted.isInvalid()) 17546 Val = nullptr; 17547 else 17548 Val = Converted.get(); 17549 } else if (!Val->isValueDependent() && 17550 !(Val = VerifyIntegerConstantExpression(Val, 17551 &EnumVal).get())) { 17552 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17553 } else { 17554 if (Enum->isComplete()) { 17555 EltTy = Enum->getIntegerType(); 17556 17557 // In Obj-C and Microsoft mode, require the enumeration value to be 17558 // representable in the underlying type of the enumeration. In C++11, 17559 // we perform a non-narrowing conversion as part of converted constant 17560 // expression checking. 17561 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17562 if (Context.getTargetInfo() 17563 .getTriple() 17564 .isWindowsMSVCEnvironment()) { 17565 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17566 } else { 17567 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17568 } 17569 } 17570 17571 // Cast to the underlying type. 17572 Val = ImpCastExprToType(Val, EltTy, 17573 EltTy->isBooleanType() ? CK_IntegralToBoolean 17574 : CK_IntegralCast) 17575 .get(); 17576 } else if (getLangOpts().CPlusPlus) { 17577 // C++11 [dcl.enum]p5: 17578 // If the underlying type is not fixed, the type of each enumerator 17579 // is the type of its initializing value: 17580 // - If an initializer is specified for an enumerator, the 17581 // initializing value has the same type as the expression. 17582 EltTy = Val->getType(); 17583 } else { 17584 // C99 6.7.2.2p2: 17585 // The expression that defines the value of an enumeration constant 17586 // shall be an integer constant expression that has a value 17587 // representable as an int. 17588 17589 // Complain if the value is not representable in an int. 17590 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17591 Diag(IdLoc, diag::ext_enum_value_not_int) 17592 << EnumVal.toString(10) << Val->getSourceRange() 17593 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17594 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17595 // Force the type of the expression to 'int'. 17596 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17597 } 17598 EltTy = Val->getType(); 17599 } 17600 } 17601 } 17602 } 17603 17604 if (!Val) { 17605 if (Enum->isDependentType()) 17606 EltTy = Context.DependentTy; 17607 else if (!LastEnumConst) { 17608 // C++0x [dcl.enum]p5: 17609 // If the underlying type is not fixed, the type of each enumerator 17610 // is the type of its initializing value: 17611 // - If no initializer is specified for the first enumerator, the 17612 // initializing value has an unspecified integral type. 17613 // 17614 // GCC uses 'int' for its unspecified integral type, as does 17615 // C99 6.7.2.2p3. 17616 if (Enum->isFixed()) { 17617 EltTy = Enum->getIntegerType(); 17618 } 17619 else { 17620 EltTy = Context.IntTy; 17621 } 17622 } else { 17623 // Assign the last value + 1. 17624 EnumVal = LastEnumConst->getInitVal(); 17625 ++EnumVal; 17626 EltTy = LastEnumConst->getType(); 17627 17628 // Check for overflow on increment. 17629 if (EnumVal < LastEnumConst->getInitVal()) { 17630 // C++0x [dcl.enum]p5: 17631 // If the underlying type is not fixed, the type of each enumerator 17632 // is the type of its initializing value: 17633 // 17634 // - Otherwise the type of the initializing value is the same as 17635 // the type of the initializing value of the preceding enumerator 17636 // unless the incremented value is not representable in that type, 17637 // in which case the type is an unspecified integral type 17638 // sufficient to contain the incremented value. If no such type 17639 // exists, the program is ill-formed. 17640 QualType T = getNextLargerIntegralType(Context, EltTy); 17641 if (T.isNull() || Enum->isFixed()) { 17642 // There is no integral type larger enough to represent this 17643 // value. Complain, then allow the value to wrap around. 17644 EnumVal = LastEnumConst->getInitVal(); 17645 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17646 ++EnumVal; 17647 if (Enum->isFixed()) 17648 // When the underlying type is fixed, this is ill-formed. 17649 Diag(IdLoc, diag::err_enumerator_wrapped) 17650 << EnumVal.toString(10) 17651 << EltTy; 17652 else 17653 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17654 << EnumVal.toString(10); 17655 } else { 17656 EltTy = T; 17657 } 17658 17659 // Retrieve the last enumerator's value, extent that type to the 17660 // type that is supposed to be large enough to represent the incremented 17661 // value, then increment. 17662 EnumVal = LastEnumConst->getInitVal(); 17663 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17664 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17665 ++EnumVal; 17666 17667 // If we're not in C++, diagnose the overflow of enumerator values, 17668 // which in C99 means that the enumerator value is not representable in 17669 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17670 // permits enumerator values that are representable in some larger 17671 // integral type. 17672 if (!getLangOpts().CPlusPlus && !T.isNull()) 17673 Diag(IdLoc, diag::warn_enum_value_overflow); 17674 } else if (!getLangOpts().CPlusPlus && 17675 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17676 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17677 Diag(IdLoc, diag::ext_enum_value_not_int) 17678 << EnumVal.toString(10) << 1; 17679 } 17680 } 17681 } 17682 17683 if (!EltTy->isDependentType()) { 17684 // Make the enumerator value match the signedness and size of the 17685 // enumerator's type. 17686 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17687 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17688 } 17689 17690 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17691 Val, EnumVal); 17692 } 17693 17694 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17695 SourceLocation IILoc) { 17696 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17697 !getLangOpts().CPlusPlus) 17698 return SkipBodyInfo(); 17699 17700 // We have an anonymous enum definition. Look up the first enumerator to 17701 // determine if we should merge the definition with an existing one and 17702 // skip the body. 17703 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17704 forRedeclarationInCurContext()); 17705 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17706 if (!PrevECD) 17707 return SkipBodyInfo(); 17708 17709 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17710 NamedDecl *Hidden; 17711 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17712 SkipBodyInfo Skip; 17713 Skip.Previous = Hidden; 17714 return Skip; 17715 } 17716 17717 return SkipBodyInfo(); 17718 } 17719 17720 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17721 SourceLocation IdLoc, IdentifierInfo *Id, 17722 const ParsedAttributesView &Attrs, 17723 SourceLocation EqualLoc, Expr *Val) { 17724 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17725 EnumConstantDecl *LastEnumConst = 17726 cast_or_null<EnumConstantDecl>(lastEnumConst); 17727 17728 // The scope passed in may not be a decl scope. Zip up the scope tree until 17729 // we find one that is. 17730 S = getNonFieldDeclScope(S); 17731 17732 // Verify that there isn't already something declared with this name in this 17733 // scope. 17734 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17735 LookupName(R, S); 17736 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17737 17738 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17739 // Maybe we will complain about the shadowed template parameter. 17740 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17741 // Just pretend that we didn't see the previous declaration. 17742 PrevDecl = nullptr; 17743 } 17744 17745 // C++ [class.mem]p15: 17746 // If T is the name of a class, then each of the following shall have a name 17747 // different from T: 17748 // - every enumerator of every member of class T that is an unscoped 17749 // enumerated type 17750 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17751 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17752 DeclarationNameInfo(Id, IdLoc)); 17753 17754 EnumConstantDecl *New = 17755 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17756 if (!New) 17757 return nullptr; 17758 17759 if (PrevDecl) { 17760 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17761 // Check for other kinds of shadowing not already handled. 17762 CheckShadow(New, PrevDecl, R); 17763 } 17764 17765 // When in C++, we may get a TagDecl with the same name; in this case the 17766 // enum constant will 'hide' the tag. 17767 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17768 "Received TagDecl when not in C++!"); 17769 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17770 if (isa<EnumConstantDecl>(PrevDecl)) 17771 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17772 else 17773 Diag(IdLoc, diag::err_redefinition) << Id; 17774 notePreviousDefinition(PrevDecl, IdLoc); 17775 return nullptr; 17776 } 17777 } 17778 17779 // Process attributes. 17780 ProcessDeclAttributeList(S, New, Attrs); 17781 AddPragmaAttributes(S, New); 17782 17783 // Register this decl in the current scope stack. 17784 New->setAccess(TheEnumDecl->getAccess()); 17785 PushOnScopeChains(New, S); 17786 17787 ActOnDocumentableDecl(New); 17788 17789 return New; 17790 } 17791 17792 // Returns true when the enum initial expression does not trigger the 17793 // duplicate enum warning. A few common cases are exempted as follows: 17794 // Element2 = Element1 17795 // Element2 = Element1 + 1 17796 // Element2 = Element1 - 1 17797 // Where Element2 and Element1 are from the same enum. 17798 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17799 Expr *InitExpr = ECD->getInitExpr(); 17800 if (!InitExpr) 17801 return true; 17802 InitExpr = InitExpr->IgnoreImpCasts(); 17803 17804 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17805 if (!BO->isAdditiveOp()) 17806 return true; 17807 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17808 if (!IL) 17809 return true; 17810 if (IL->getValue() != 1) 17811 return true; 17812 17813 InitExpr = BO->getLHS(); 17814 } 17815 17816 // This checks if the elements are from the same enum. 17817 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17818 if (!DRE) 17819 return true; 17820 17821 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17822 if (!EnumConstant) 17823 return true; 17824 17825 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17826 Enum) 17827 return true; 17828 17829 return false; 17830 } 17831 17832 // Emits a warning when an element is implicitly set a value that 17833 // a previous element has already been set to. 17834 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17835 EnumDecl *Enum, QualType EnumType) { 17836 // Avoid anonymous enums 17837 if (!Enum->getIdentifier()) 17838 return; 17839 17840 // Only check for small enums. 17841 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17842 return; 17843 17844 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17845 return; 17846 17847 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17848 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17849 17850 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17851 17852 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17853 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17854 17855 // Use int64_t as a key to avoid needing special handling for map keys. 17856 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17857 llvm::APSInt Val = D->getInitVal(); 17858 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17859 }; 17860 17861 DuplicatesVector DupVector; 17862 ValueToVectorMap EnumMap; 17863 17864 // Populate the EnumMap with all values represented by enum constants without 17865 // an initializer. 17866 for (auto *Element : Elements) { 17867 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17868 17869 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17870 // this constant. Skip this enum since it may be ill-formed. 17871 if (!ECD) { 17872 return; 17873 } 17874 17875 // Constants with initalizers are handled in the next loop. 17876 if (ECD->getInitExpr()) 17877 continue; 17878 17879 // Duplicate values are handled in the next loop. 17880 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17881 } 17882 17883 if (EnumMap.size() == 0) 17884 return; 17885 17886 // Create vectors for any values that has duplicates. 17887 for (auto *Element : Elements) { 17888 // The last loop returned if any constant was null. 17889 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17890 if (!ValidDuplicateEnum(ECD, Enum)) 17891 continue; 17892 17893 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17894 if (Iter == EnumMap.end()) 17895 continue; 17896 17897 DeclOrVector& Entry = Iter->second; 17898 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17899 // Ensure constants are different. 17900 if (D == ECD) 17901 continue; 17902 17903 // Create new vector and push values onto it. 17904 auto Vec = std::make_unique<ECDVector>(); 17905 Vec->push_back(D); 17906 Vec->push_back(ECD); 17907 17908 // Update entry to point to the duplicates vector. 17909 Entry = Vec.get(); 17910 17911 // Store the vector somewhere we can consult later for quick emission of 17912 // diagnostics. 17913 DupVector.emplace_back(std::move(Vec)); 17914 continue; 17915 } 17916 17917 ECDVector *Vec = Entry.get<ECDVector*>(); 17918 // Make sure constants are not added more than once. 17919 if (*Vec->begin() == ECD) 17920 continue; 17921 17922 Vec->push_back(ECD); 17923 } 17924 17925 // Emit diagnostics. 17926 for (const auto &Vec : DupVector) { 17927 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17928 17929 // Emit warning for one enum constant. 17930 auto *FirstECD = Vec->front(); 17931 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17932 << FirstECD << FirstECD->getInitVal().toString(10) 17933 << FirstECD->getSourceRange(); 17934 17935 // Emit one note for each of the remaining enum constants with 17936 // the same value. 17937 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17938 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17939 << ECD << ECD->getInitVal().toString(10) 17940 << ECD->getSourceRange(); 17941 } 17942 } 17943 17944 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17945 bool AllowMask) const { 17946 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17947 assert(ED->isCompleteDefinition() && "expected enum definition"); 17948 17949 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17950 llvm::APInt &FlagBits = R.first->second; 17951 17952 if (R.second) { 17953 for (auto *E : ED->enumerators()) { 17954 const auto &EVal = E->getInitVal(); 17955 // Only single-bit enumerators introduce new flag values. 17956 if (EVal.isPowerOf2()) 17957 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17958 } 17959 } 17960 17961 // A value is in a flag enum if either its bits are a subset of the enum's 17962 // flag bits (the first condition) or we are allowing masks and the same is 17963 // true of its complement (the second condition). When masks are allowed, we 17964 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17965 // 17966 // While it's true that any value could be used as a mask, the assumption is 17967 // that a mask will have all of the insignificant bits set. Anything else is 17968 // likely a logic error. 17969 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17970 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17971 } 17972 17973 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17974 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17975 const ParsedAttributesView &Attrs) { 17976 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17977 QualType EnumType = Context.getTypeDeclType(Enum); 17978 17979 ProcessDeclAttributeList(S, Enum, Attrs); 17980 17981 if (Enum->isDependentType()) { 17982 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17983 EnumConstantDecl *ECD = 17984 cast_or_null<EnumConstantDecl>(Elements[i]); 17985 if (!ECD) continue; 17986 17987 ECD->setType(EnumType); 17988 } 17989 17990 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17991 return; 17992 } 17993 17994 // TODO: If the result value doesn't fit in an int, it must be a long or long 17995 // long value. ISO C does not support this, but GCC does as an extension, 17996 // emit a warning. 17997 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17998 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17999 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18000 18001 // Verify that all the values are okay, compute the size of the values, and 18002 // reverse the list. 18003 unsigned NumNegativeBits = 0; 18004 unsigned NumPositiveBits = 0; 18005 18006 // Keep track of whether all elements have type int. 18007 bool AllElementsInt = true; 18008 18009 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18010 EnumConstantDecl *ECD = 18011 cast_or_null<EnumConstantDecl>(Elements[i]); 18012 if (!ECD) continue; // Already issued a diagnostic. 18013 18014 const llvm::APSInt &InitVal = ECD->getInitVal(); 18015 18016 // Keep track of the size of positive and negative values. 18017 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18018 NumPositiveBits = std::max(NumPositiveBits, 18019 (unsigned)InitVal.getActiveBits()); 18020 else 18021 NumNegativeBits = std::max(NumNegativeBits, 18022 (unsigned)InitVal.getMinSignedBits()); 18023 18024 // Keep track of whether every enum element has type int (very common). 18025 if (AllElementsInt) 18026 AllElementsInt = ECD->getType() == Context.IntTy; 18027 } 18028 18029 // Figure out the type that should be used for this enum. 18030 QualType BestType; 18031 unsigned BestWidth; 18032 18033 // C++0x N3000 [conv.prom]p3: 18034 // An rvalue of an unscoped enumeration type whose underlying 18035 // type is not fixed can be converted to an rvalue of the first 18036 // of the following types that can represent all the values of 18037 // the enumeration: int, unsigned int, long int, unsigned long 18038 // int, long long int, or unsigned long long int. 18039 // C99 6.4.4.3p2: 18040 // An identifier declared as an enumeration constant has type int. 18041 // The C99 rule is modified by a gcc extension 18042 QualType BestPromotionType; 18043 18044 bool Packed = Enum->hasAttr<PackedAttr>(); 18045 // -fshort-enums is the equivalent to specifying the packed attribute on all 18046 // enum definitions. 18047 if (LangOpts.ShortEnums) 18048 Packed = true; 18049 18050 // If the enum already has a type because it is fixed or dictated by the 18051 // target, promote that type instead of analyzing the enumerators. 18052 if (Enum->isComplete()) { 18053 BestType = Enum->getIntegerType(); 18054 if (BestType->isPromotableIntegerType()) 18055 BestPromotionType = Context.getPromotedIntegerType(BestType); 18056 else 18057 BestPromotionType = BestType; 18058 18059 BestWidth = Context.getIntWidth(BestType); 18060 } 18061 else if (NumNegativeBits) { 18062 // If there is a negative value, figure out the smallest integer type (of 18063 // int/long/longlong) that fits. 18064 // If it's packed, check also if it fits a char or a short. 18065 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18066 BestType = Context.SignedCharTy; 18067 BestWidth = CharWidth; 18068 } else if (Packed && NumNegativeBits <= ShortWidth && 18069 NumPositiveBits < ShortWidth) { 18070 BestType = Context.ShortTy; 18071 BestWidth = ShortWidth; 18072 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18073 BestType = Context.IntTy; 18074 BestWidth = IntWidth; 18075 } else { 18076 BestWidth = Context.getTargetInfo().getLongWidth(); 18077 18078 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18079 BestType = Context.LongTy; 18080 } else { 18081 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18082 18083 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18084 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18085 BestType = Context.LongLongTy; 18086 } 18087 } 18088 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18089 } else { 18090 // If there is no negative value, figure out the smallest type that fits 18091 // all of the enumerator values. 18092 // If it's packed, check also if it fits a char or a short. 18093 if (Packed && NumPositiveBits <= CharWidth) { 18094 BestType = Context.UnsignedCharTy; 18095 BestPromotionType = Context.IntTy; 18096 BestWidth = CharWidth; 18097 } else if (Packed && NumPositiveBits <= ShortWidth) { 18098 BestType = Context.UnsignedShortTy; 18099 BestPromotionType = Context.IntTy; 18100 BestWidth = ShortWidth; 18101 } else if (NumPositiveBits <= IntWidth) { 18102 BestType = Context.UnsignedIntTy; 18103 BestWidth = IntWidth; 18104 BestPromotionType 18105 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18106 ? Context.UnsignedIntTy : Context.IntTy; 18107 } else if (NumPositiveBits <= 18108 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18109 BestType = Context.UnsignedLongTy; 18110 BestPromotionType 18111 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18112 ? Context.UnsignedLongTy : Context.LongTy; 18113 } else { 18114 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18115 assert(NumPositiveBits <= BestWidth && 18116 "How could an initializer get larger than ULL?"); 18117 BestType = Context.UnsignedLongLongTy; 18118 BestPromotionType 18119 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18120 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18121 } 18122 } 18123 18124 // Loop over all of the enumerator constants, changing their types to match 18125 // the type of the enum if needed. 18126 for (auto *D : Elements) { 18127 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18128 if (!ECD) continue; // Already issued a diagnostic. 18129 18130 // Standard C says the enumerators have int type, but we allow, as an 18131 // extension, the enumerators to be larger than int size. If each 18132 // enumerator value fits in an int, type it as an int, otherwise type it the 18133 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18134 // that X has type 'int', not 'unsigned'. 18135 18136 // Determine whether the value fits into an int. 18137 llvm::APSInt InitVal = ECD->getInitVal(); 18138 18139 // If it fits into an integer type, force it. Otherwise force it to match 18140 // the enum decl type. 18141 QualType NewTy; 18142 unsigned NewWidth; 18143 bool NewSign; 18144 if (!getLangOpts().CPlusPlus && 18145 !Enum->isFixed() && 18146 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18147 NewTy = Context.IntTy; 18148 NewWidth = IntWidth; 18149 NewSign = true; 18150 } else if (ECD->getType() == BestType) { 18151 // Already the right type! 18152 if (getLangOpts().CPlusPlus) 18153 // C++ [dcl.enum]p4: Following the closing brace of an 18154 // enum-specifier, each enumerator has the type of its 18155 // enumeration. 18156 ECD->setType(EnumType); 18157 continue; 18158 } else { 18159 NewTy = BestType; 18160 NewWidth = BestWidth; 18161 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18162 } 18163 18164 // Adjust the APSInt value. 18165 InitVal = InitVal.extOrTrunc(NewWidth); 18166 InitVal.setIsSigned(NewSign); 18167 ECD->setInitVal(InitVal); 18168 18169 // Adjust the Expr initializer and type. 18170 if (ECD->getInitExpr() && 18171 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18172 ECD->setInitExpr(ImplicitCastExpr::Create( 18173 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18174 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18175 if (getLangOpts().CPlusPlus) 18176 // C++ [dcl.enum]p4: Following the closing brace of an 18177 // enum-specifier, each enumerator has the type of its 18178 // enumeration. 18179 ECD->setType(EnumType); 18180 else 18181 ECD->setType(NewTy); 18182 } 18183 18184 Enum->completeDefinition(BestType, BestPromotionType, 18185 NumPositiveBits, NumNegativeBits); 18186 18187 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18188 18189 if (Enum->isClosedFlag()) { 18190 for (Decl *D : Elements) { 18191 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18192 if (!ECD) continue; // Already issued a diagnostic. 18193 18194 llvm::APSInt InitVal = ECD->getInitVal(); 18195 if (InitVal != 0 && !InitVal.isPowerOf2() && 18196 !IsValueInFlagEnum(Enum, InitVal, true)) 18197 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18198 << ECD << Enum; 18199 } 18200 } 18201 18202 // Now that the enum type is defined, ensure it's not been underaligned. 18203 if (Enum->hasAttrs()) 18204 CheckAlignasUnderalignment(Enum); 18205 } 18206 18207 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18208 SourceLocation StartLoc, 18209 SourceLocation EndLoc) { 18210 StringLiteral *AsmString = cast<StringLiteral>(expr); 18211 18212 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18213 AsmString, StartLoc, 18214 EndLoc); 18215 CurContext->addDecl(New); 18216 return New; 18217 } 18218 18219 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18220 IdentifierInfo* AliasName, 18221 SourceLocation PragmaLoc, 18222 SourceLocation NameLoc, 18223 SourceLocation AliasNameLoc) { 18224 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18225 LookupOrdinaryName); 18226 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18227 AttributeCommonInfo::AS_Pragma); 18228 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18229 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18230 18231 // If a declaration that: 18232 // 1) declares a function or a variable 18233 // 2) has external linkage 18234 // already exists, add a label attribute to it. 18235 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18236 if (isDeclExternC(PrevDecl)) 18237 PrevDecl->addAttr(Attr); 18238 else 18239 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18240 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18241 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18242 } else 18243 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18244 } 18245 18246 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18247 SourceLocation PragmaLoc, 18248 SourceLocation NameLoc) { 18249 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18250 18251 if (PrevDecl) { 18252 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18253 } else { 18254 (void)WeakUndeclaredIdentifiers.insert( 18255 std::pair<IdentifierInfo*,WeakInfo> 18256 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18257 } 18258 } 18259 18260 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18261 IdentifierInfo* AliasName, 18262 SourceLocation PragmaLoc, 18263 SourceLocation NameLoc, 18264 SourceLocation AliasNameLoc) { 18265 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18266 LookupOrdinaryName); 18267 WeakInfo W = WeakInfo(Name, NameLoc); 18268 18269 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18270 if (!PrevDecl->hasAttr<AliasAttr>()) 18271 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18272 DeclApplyPragmaWeak(TUScope, ND, W); 18273 } else { 18274 (void)WeakUndeclaredIdentifiers.insert( 18275 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18276 } 18277 } 18278 18279 Decl *Sema::getObjCDeclContext() const { 18280 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18281 } 18282 18283 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18284 bool Final) { 18285 // SYCL functions can be template, so we check if they have appropriate 18286 // attribute prior to checking if it is a template. 18287 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18288 return FunctionEmissionStatus::Emitted; 18289 18290 // Templates are emitted when they're instantiated. 18291 if (FD->isDependentContext()) 18292 return FunctionEmissionStatus::TemplateDiscarded; 18293 18294 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18295 if (LangOpts.OpenMPIsDevice) { 18296 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18297 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18298 if (DevTy.hasValue()) { 18299 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18300 OMPES = FunctionEmissionStatus::OMPDiscarded; 18301 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18302 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18303 OMPES = FunctionEmissionStatus::Emitted; 18304 } 18305 } 18306 } else if (LangOpts.OpenMP) { 18307 // In OpenMP 4.5 all the functions are host functions. 18308 if (LangOpts.OpenMP <= 45) { 18309 OMPES = FunctionEmissionStatus::Emitted; 18310 } else { 18311 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18312 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18313 // In OpenMP 5.0 or above, DevTy may be changed later by 18314 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18315 // having no value does not imply host. The emission status will be 18316 // checked again at the end of compilation unit. 18317 if (DevTy.hasValue()) { 18318 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18319 OMPES = FunctionEmissionStatus::OMPDiscarded; 18320 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18321 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18322 OMPES = FunctionEmissionStatus::Emitted; 18323 } else if (Final) 18324 OMPES = FunctionEmissionStatus::Emitted; 18325 } 18326 } 18327 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18328 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18329 return OMPES; 18330 18331 if (LangOpts.CUDA) { 18332 // When compiling for device, host functions are never emitted. Similarly, 18333 // when compiling for host, device and global functions are never emitted. 18334 // (Technically, we do emit a host-side stub for global functions, but this 18335 // doesn't count for our purposes here.) 18336 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18337 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18338 return FunctionEmissionStatus::CUDADiscarded; 18339 if (!LangOpts.CUDAIsDevice && 18340 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18341 return FunctionEmissionStatus::CUDADiscarded; 18342 18343 // Check whether this function is externally visible -- if so, it's 18344 // known-emitted. 18345 // 18346 // We have to check the GVA linkage of the function's *definition* -- if we 18347 // only have a declaration, we don't know whether or not the function will 18348 // be emitted, because (say) the definition could include "inline". 18349 FunctionDecl *Def = FD->getDefinition(); 18350 18351 if (Def && 18352 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18353 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18354 return FunctionEmissionStatus::Emitted; 18355 } 18356 18357 // Otherwise, the function is known-emitted if it's in our set of 18358 // known-emitted functions. 18359 return FunctionEmissionStatus::Unknown; 18360 } 18361 18362 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18363 // Host-side references to a __global__ function refer to the stub, so the 18364 // function itself is never emitted and therefore should not be marked. 18365 // If we have host fn calls kernel fn calls host+device, the HD function 18366 // does not get instantiated on the host. We model this by omitting at the 18367 // call to the kernel from the callgraph. This ensures that, when compiling 18368 // for host, only HD functions actually called from the host get marked as 18369 // known-emitted. 18370 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18371 IdentifyCUDATarget(Callee) == CFT_Global; 18372 } 18373