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 return nullptr; 2110 2111 // If we could not find a type for setjmp it is because the jmp_buf type was 2112 // not defined prior to the setjmp declaration. 2113 if (Error == ASTContext::GE_Missing_setjmp) { 2114 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2115 << Context.BuiltinInfo.getName(ID); 2116 return nullptr; 2117 } 2118 2119 // Generally, we emit a warning that the declaration requires the 2120 // appropriate header. 2121 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2122 << getHeaderName(Context.BuiltinInfo, ID, Error) 2123 << Context.BuiltinInfo.getName(ID); 2124 return nullptr; 2125 } 2126 2127 if (!ForRedeclaration && 2128 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2129 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2130 Diag(Loc, diag::ext_implicit_lib_function_decl) 2131 << Context.BuiltinInfo.getName(ID) << R; 2132 if (Context.BuiltinInfo.getHeaderName(ID) && 2133 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2134 Diag(Loc, diag::note_include_header_or_declare) 2135 << Context.BuiltinInfo.getHeaderName(ID) 2136 << Context.BuiltinInfo.getName(ID); 2137 } 2138 2139 if (R.isNull()) 2140 return nullptr; 2141 2142 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2143 RegisterLocallyScopedExternCDecl(New, S); 2144 2145 // TUScope is the translation-unit scope to insert this function into. 2146 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2147 // relate Scopes to DeclContexts, and probably eliminate CurContext 2148 // entirely, but we're not there yet. 2149 DeclContext *SavedContext = CurContext; 2150 CurContext = New->getDeclContext(); 2151 PushOnScopeChains(New, TUScope); 2152 CurContext = SavedContext; 2153 return New; 2154 } 2155 2156 /// Typedef declarations don't have linkage, but they still denote the same 2157 /// entity if their types are the same. 2158 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2159 /// isSameEntity. 2160 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2161 TypedefNameDecl *Decl, 2162 LookupResult &Previous) { 2163 // This is only interesting when modules are enabled. 2164 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2165 return; 2166 2167 // Empty sets are uninteresting. 2168 if (Previous.empty()) 2169 return; 2170 2171 LookupResult::Filter Filter = Previous.makeFilter(); 2172 while (Filter.hasNext()) { 2173 NamedDecl *Old = Filter.next(); 2174 2175 // Non-hidden declarations are never ignored. 2176 if (S.isVisible(Old)) 2177 continue; 2178 2179 // Declarations of the same entity are not ignored, even if they have 2180 // different linkages. 2181 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2182 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2183 Decl->getUnderlyingType())) 2184 continue; 2185 2186 // If both declarations give a tag declaration a typedef name for linkage 2187 // purposes, then they declare the same entity. 2188 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2189 Decl->getAnonDeclWithTypedefName()) 2190 continue; 2191 } 2192 2193 Filter.erase(); 2194 } 2195 2196 Filter.done(); 2197 } 2198 2199 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2200 QualType OldType; 2201 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2202 OldType = OldTypedef->getUnderlyingType(); 2203 else 2204 OldType = Context.getTypeDeclType(Old); 2205 QualType NewType = New->getUnderlyingType(); 2206 2207 if (NewType->isVariablyModifiedType()) { 2208 // Must not redefine a typedef with a variably-modified type. 2209 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2210 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2211 << Kind << NewType; 2212 if (Old->getLocation().isValid()) 2213 notePreviousDefinition(Old, New->getLocation()); 2214 New->setInvalidDecl(); 2215 return true; 2216 } 2217 2218 if (OldType != NewType && 2219 !OldType->isDependentType() && 2220 !NewType->isDependentType() && 2221 !Context.hasSameType(OldType, NewType)) { 2222 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2223 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2224 << Kind << NewType << OldType; 2225 if (Old->getLocation().isValid()) 2226 notePreviousDefinition(Old, New->getLocation()); 2227 New->setInvalidDecl(); 2228 return true; 2229 } 2230 return false; 2231 } 2232 2233 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2234 /// same name and scope as a previous declaration 'Old'. Figure out 2235 /// how to resolve this situation, merging decls or emitting 2236 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2237 /// 2238 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2239 LookupResult &OldDecls) { 2240 // If the new decl is known invalid already, don't bother doing any 2241 // merging checks. 2242 if (New->isInvalidDecl()) return; 2243 2244 // Allow multiple definitions for ObjC built-in typedefs. 2245 // FIXME: Verify the underlying types are equivalent! 2246 if (getLangOpts().ObjC) { 2247 const IdentifierInfo *TypeID = New->getIdentifier(); 2248 switch (TypeID->getLength()) { 2249 default: break; 2250 case 2: 2251 { 2252 if (!TypeID->isStr("id")) 2253 break; 2254 QualType T = New->getUnderlyingType(); 2255 if (!T->isPointerType()) 2256 break; 2257 if (!T->isVoidPointerType()) { 2258 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2259 if (!PT->isStructureType()) 2260 break; 2261 } 2262 Context.setObjCIdRedefinitionType(T); 2263 // Install the built-in type for 'id', ignoring the current definition. 2264 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2265 return; 2266 } 2267 case 5: 2268 if (!TypeID->isStr("Class")) 2269 break; 2270 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2271 // Install the built-in type for 'Class', ignoring the current definition. 2272 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2273 return; 2274 case 3: 2275 if (!TypeID->isStr("SEL")) 2276 break; 2277 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2278 // Install the built-in type for 'SEL', ignoring the current definition. 2279 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2280 return; 2281 } 2282 // Fall through - the typedef name was not a builtin type. 2283 } 2284 2285 // Verify the old decl was also a type. 2286 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2287 if (!Old) { 2288 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2289 << New->getDeclName(); 2290 2291 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2292 if (OldD->getLocation().isValid()) 2293 notePreviousDefinition(OldD, New->getLocation()); 2294 2295 return New->setInvalidDecl(); 2296 } 2297 2298 // If the old declaration is invalid, just give up here. 2299 if (Old->isInvalidDecl()) 2300 return New->setInvalidDecl(); 2301 2302 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2303 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2304 auto *NewTag = New->getAnonDeclWithTypedefName(); 2305 NamedDecl *Hidden = nullptr; 2306 if (OldTag && NewTag && 2307 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2308 !hasVisibleDefinition(OldTag, &Hidden)) { 2309 // There is a definition of this tag, but it is not visible. Use it 2310 // instead of our tag. 2311 New->setTypeForDecl(OldTD->getTypeForDecl()); 2312 if (OldTD->isModed()) 2313 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2314 OldTD->getUnderlyingType()); 2315 else 2316 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2317 2318 // Make the old tag definition visible. 2319 makeMergedDefinitionVisible(Hidden); 2320 2321 // If this was an unscoped enumeration, yank all of its enumerators 2322 // out of the scope. 2323 if (isa<EnumDecl>(NewTag)) { 2324 Scope *EnumScope = getNonFieldDeclScope(S); 2325 for (auto *D : NewTag->decls()) { 2326 auto *ED = cast<EnumConstantDecl>(D); 2327 assert(EnumScope->isDeclScope(ED)); 2328 EnumScope->RemoveDecl(ED); 2329 IdResolver.RemoveDecl(ED); 2330 ED->getLexicalDeclContext()->removeDecl(ED); 2331 } 2332 } 2333 } 2334 } 2335 2336 // If the typedef types are not identical, reject them in all languages and 2337 // with any extensions enabled. 2338 if (isIncompatibleTypedef(Old, New)) 2339 return; 2340 2341 // The types match. Link up the redeclaration chain and merge attributes if 2342 // the old declaration was a typedef. 2343 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2344 New->setPreviousDecl(Typedef); 2345 mergeDeclAttributes(New, Old); 2346 } 2347 2348 if (getLangOpts().MicrosoftExt) 2349 return; 2350 2351 if (getLangOpts().CPlusPlus) { 2352 // C++ [dcl.typedef]p2: 2353 // In a given non-class scope, a typedef specifier can be used to 2354 // redefine the name of any type declared in that scope to refer 2355 // to the type to which it already refers. 2356 if (!isa<CXXRecordDecl>(CurContext)) 2357 return; 2358 2359 // C++0x [dcl.typedef]p4: 2360 // In a given class scope, a typedef specifier can be used to redefine 2361 // any class-name declared in that scope that is not also a typedef-name 2362 // to refer to the type to which it already refers. 2363 // 2364 // This wording came in via DR424, which was a correction to the 2365 // wording in DR56, which accidentally banned code like: 2366 // 2367 // struct S { 2368 // typedef struct A { } A; 2369 // }; 2370 // 2371 // in the C++03 standard. We implement the C++0x semantics, which 2372 // allow the above but disallow 2373 // 2374 // struct S { 2375 // typedef int I; 2376 // typedef int I; 2377 // }; 2378 // 2379 // since that was the intent of DR56. 2380 if (!isa<TypedefNameDecl>(Old)) 2381 return; 2382 2383 Diag(New->getLocation(), diag::err_redefinition) 2384 << New->getDeclName(); 2385 notePreviousDefinition(Old, New->getLocation()); 2386 return New->setInvalidDecl(); 2387 } 2388 2389 // Modules always permit redefinition of typedefs, as does C11. 2390 if (getLangOpts().Modules || getLangOpts().C11) 2391 return; 2392 2393 // If we have a redefinition of a typedef in C, emit a warning. This warning 2394 // is normally mapped to an error, but can be controlled with 2395 // -Wtypedef-redefinition. If either the original or the redefinition is 2396 // in a system header, don't emit this for compatibility with GCC. 2397 if (getDiagnostics().getSuppressSystemWarnings() && 2398 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2399 (Old->isImplicit() || 2400 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2401 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2402 return; 2403 2404 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2405 << New->getDeclName(); 2406 notePreviousDefinition(Old, New->getLocation()); 2407 } 2408 2409 /// DeclhasAttr - returns true if decl Declaration already has the target 2410 /// attribute. 2411 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2412 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2413 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2414 for (const auto *i : D->attrs()) 2415 if (i->getKind() == A->getKind()) { 2416 if (Ann) { 2417 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2418 return true; 2419 continue; 2420 } 2421 // FIXME: Don't hardcode this check 2422 if (OA && isa<OwnershipAttr>(i)) 2423 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2424 return true; 2425 } 2426 2427 return false; 2428 } 2429 2430 static bool isAttributeTargetADefinition(Decl *D) { 2431 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2432 return VD->isThisDeclarationADefinition(); 2433 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2434 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2435 return true; 2436 } 2437 2438 /// Merge alignment attributes from \p Old to \p New, taking into account the 2439 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2440 /// 2441 /// \return \c true if any attributes were added to \p New. 2442 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2443 // Look for alignas attributes on Old, and pick out whichever attribute 2444 // specifies the strictest alignment requirement. 2445 AlignedAttr *OldAlignasAttr = nullptr; 2446 AlignedAttr *OldStrictestAlignAttr = nullptr; 2447 unsigned OldAlign = 0; 2448 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2449 // FIXME: We have no way of representing inherited dependent alignments 2450 // in a case like: 2451 // template<int A, int B> struct alignas(A) X; 2452 // template<int A, int B> struct alignas(B) X {}; 2453 // For now, we just ignore any alignas attributes which are not on the 2454 // definition in such a case. 2455 if (I->isAlignmentDependent()) 2456 return false; 2457 2458 if (I->isAlignas()) 2459 OldAlignasAttr = I; 2460 2461 unsigned Align = I->getAlignment(S.Context); 2462 if (Align > OldAlign) { 2463 OldAlign = Align; 2464 OldStrictestAlignAttr = I; 2465 } 2466 } 2467 2468 // Look for alignas attributes on New. 2469 AlignedAttr *NewAlignasAttr = nullptr; 2470 unsigned NewAlign = 0; 2471 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2472 if (I->isAlignmentDependent()) 2473 return false; 2474 2475 if (I->isAlignas()) 2476 NewAlignasAttr = I; 2477 2478 unsigned Align = I->getAlignment(S.Context); 2479 if (Align > NewAlign) 2480 NewAlign = Align; 2481 } 2482 2483 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2484 // Both declarations have 'alignas' attributes. We require them to match. 2485 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2486 // fall short. (If two declarations both have alignas, they must both match 2487 // every definition, and so must match each other if there is a definition.) 2488 2489 // If either declaration only contains 'alignas(0)' specifiers, then it 2490 // specifies the natural alignment for the type. 2491 if (OldAlign == 0 || NewAlign == 0) { 2492 QualType Ty; 2493 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2494 Ty = VD->getType(); 2495 else 2496 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2497 2498 if (OldAlign == 0) 2499 OldAlign = S.Context.getTypeAlign(Ty); 2500 if (NewAlign == 0) 2501 NewAlign = S.Context.getTypeAlign(Ty); 2502 } 2503 2504 if (OldAlign != NewAlign) { 2505 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2506 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2507 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2508 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2509 } 2510 } 2511 2512 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2513 // C++11 [dcl.align]p6: 2514 // if any declaration of an entity has an alignment-specifier, 2515 // every defining declaration of that entity shall specify an 2516 // equivalent alignment. 2517 // C11 6.7.5/7: 2518 // If the definition of an object does not have an alignment 2519 // specifier, any other declaration of that object shall also 2520 // have no alignment specifier. 2521 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2522 << OldAlignasAttr; 2523 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2524 << OldAlignasAttr; 2525 } 2526 2527 bool AnyAdded = false; 2528 2529 // Ensure we have an attribute representing the strictest alignment. 2530 if (OldAlign > NewAlign) { 2531 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2532 Clone->setInherited(true); 2533 New->addAttr(Clone); 2534 AnyAdded = true; 2535 } 2536 2537 // Ensure we have an alignas attribute if the old declaration had one. 2538 if (OldAlignasAttr && !NewAlignasAttr && 2539 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2540 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2541 Clone->setInherited(true); 2542 New->addAttr(Clone); 2543 AnyAdded = true; 2544 } 2545 2546 return AnyAdded; 2547 } 2548 2549 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2550 const InheritableAttr *Attr, 2551 Sema::AvailabilityMergeKind AMK) { 2552 // This function copies an attribute Attr from a previous declaration to the 2553 // new declaration D if the new declaration doesn't itself have that attribute 2554 // yet or if that attribute allows duplicates. 2555 // If you're adding a new attribute that requires logic different from 2556 // "use explicit attribute on decl if present, else use attribute from 2557 // previous decl", for example if the attribute needs to be consistent 2558 // between redeclarations, you need to call a custom merge function here. 2559 InheritableAttr *NewAttr = nullptr; 2560 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2561 NewAttr = S.mergeAvailabilityAttr( 2562 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2563 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2564 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2565 AA->getPriority()); 2566 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2567 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2568 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2569 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2570 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2571 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2572 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2573 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2574 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2575 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2576 FA->getFirstArg()); 2577 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2578 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2579 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2580 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2581 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2582 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2583 IA->getInheritanceModel()); 2584 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2585 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2586 &S.Context.Idents.get(AA->getSpelling())); 2587 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2588 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2589 isa<CUDAGlobalAttr>(Attr))) { 2590 // CUDA target attributes are part of function signature for 2591 // overloading purposes and must not be merged. 2592 return false; 2593 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2594 NewAttr = S.mergeMinSizeAttr(D, *MA); 2595 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2596 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2597 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2598 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2599 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2600 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2601 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2602 NewAttr = S.mergeCommonAttr(D, *CommonA); 2603 else if (isa<AlignedAttr>(Attr)) 2604 // AlignedAttrs are handled separately, because we need to handle all 2605 // such attributes on a declaration at the same time. 2606 NewAttr = nullptr; 2607 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2608 (AMK == Sema::AMK_Override || 2609 AMK == Sema::AMK_ProtocolImplementation)) 2610 NewAttr = nullptr; 2611 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2612 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2613 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2614 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2615 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2616 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2617 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2618 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2619 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2620 NewAttr = S.mergeImportNameAttr(D, *INA); 2621 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2622 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2623 2624 if (NewAttr) { 2625 NewAttr->setInherited(true); 2626 D->addAttr(NewAttr); 2627 if (isa<MSInheritanceAttr>(NewAttr)) 2628 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2629 return true; 2630 } 2631 2632 return false; 2633 } 2634 2635 static const NamedDecl *getDefinition(const Decl *D) { 2636 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2637 return TD->getDefinition(); 2638 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2639 const VarDecl *Def = VD->getDefinition(); 2640 if (Def) 2641 return Def; 2642 return VD->getActingDefinition(); 2643 } 2644 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2645 return FD->getDefinition(); 2646 return nullptr; 2647 } 2648 2649 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2650 for (const auto *Attribute : D->attrs()) 2651 if (Attribute->getKind() == Kind) 2652 return true; 2653 return false; 2654 } 2655 2656 /// checkNewAttributesAfterDef - If we already have a definition, check that 2657 /// there are no new attributes in this declaration. 2658 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2659 if (!New->hasAttrs()) 2660 return; 2661 2662 const NamedDecl *Def = getDefinition(Old); 2663 if (!Def || Def == New) 2664 return; 2665 2666 AttrVec &NewAttributes = New->getAttrs(); 2667 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2668 const Attr *NewAttribute = NewAttributes[I]; 2669 2670 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2671 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2672 Sema::SkipBodyInfo SkipBody; 2673 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2674 2675 // If we're skipping this definition, drop the "alias" attribute. 2676 if (SkipBody.ShouldSkip) { 2677 NewAttributes.erase(NewAttributes.begin() + I); 2678 --E; 2679 continue; 2680 } 2681 } else { 2682 VarDecl *VD = cast<VarDecl>(New); 2683 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2684 VarDecl::TentativeDefinition 2685 ? diag::err_alias_after_tentative 2686 : diag::err_redefinition; 2687 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2688 if (Diag == diag::err_redefinition) 2689 S.notePreviousDefinition(Def, VD->getLocation()); 2690 else 2691 S.Diag(Def->getLocation(), diag::note_previous_definition); 2692 VD->setInvalidDecl(); 2693 } 2694 ++I; 2695 continue; 2696 } 2697 2698 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2699 // Tentative definitions are only interesting for the alias check above. 2700 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2701 ++I; 2702 continue; 2703 } 2704 } 2705 2706 if (hasAttribute(Def, NewAttribute->getKind())) { 2707 ++I; 2708 continue; // regular attr merging will take care of validating this. 2709 } 2710 2711 if (isa<C11NoReturnAttr>(NewAttribute)) { 2712 // C's _Noreturn is allowed to be added to a function after it is defined. 2713 ++I; 2714 continue; 2715 } else if (isa<UuidAttr>(NewAttribute)) { 2716 // msvc will allow a subsequent definition to add an uuid to a class 2717 ++I; 2718 continue; 2719 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2720 if (AA->isAlignas()) { 2721 // C++11 [dcl.align]p6: 2722 // if any declaration of an entity has an alignment-specifier, 2723 // every defining declaration of that entity shall specify an 2724 // equivalent alignment. 2725 // C11 6.7.5/7: 2726 // If the definition of an object does not have an alignment 2727 // specifier, any other declaration of that object shall also 2728 // have no alignment specifier. 2729 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2730 << AA; 2731 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2732 << AA; 2733 NewAttributes.erase(NewAttributes.begin() + I); 2734 --E; 2735 continue; 2736 } 2737 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2738 // If there is a C definition followed by a redeclaration with this 2739 // attribute then there are two different definitions. In C++, prefer the 2740 // standard diagnostics. 2741 if (!S.getLangOpts().CPlusPlus) { 2742 S.Diag(NewAttribute->getLocation(), 2743 diag::err_loader_uninitialized_redeclaration); 2744 S.Diag(Def->getLocation(), diag::note_previous_definition); 2745 NewAttributes.erase(NewAttributes.begin() + I); 2746 --E; 2747 continue; 2748 } 2749 } else if (isa<SelectAnyAttr>(NewAttribute) && 2750 cast<VarDecl>(New)->isInline() && 2751 !cast<VarDecl>(New)->isInlineSpecified()) { 2752 // Don't warn about applying selectany to implicitly inline variables. 2753 // Older compilers and language modes would require the use of selectany 2754 // to make such variables inline, and it would have no effect if we 2755 // honored it. 2756 ++I; 2757 continue; 2758 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2759 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2760 // declarations after defintions. 2761 ++I; 2762 continue; 2763 } 2764 2765 S.Diag(NewAttribute->getLocation(), 2766 diag::warn_attribute_precede_definition); 2767 S.Diag(Def->getLocation(), diag::note_previous_definition); 2768 NewAttributes.erase(NewAttributes.begin() + I); 2769 --E; 2770 } 2771 } 2772 2773 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2774 const ConstInitAttr *CIAttr, 2775 bool AttrBeforeInit) { 2776 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2777 2778 // Figure out a good way to write this specifier on the old declaration. 2779 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2780 // enough of the attribute list spelling information to extract that without 2781 // heroics. 2782 std::string SuitableSpelling; 2783 if (S.getLangOpts().CPlusPlus20) 2784 SuitableSpelling = std::string( 2785 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2786 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2787 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2788 InsertLoc, {tok::l_square, tok::l_square, 2789 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2790 S.PP.getIdentifierInfo("require_constant_initialization"), 2791 tok::r_square, tok::r_square})); 2792 if (SuitableSpelling.empty()) 2793 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2794 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2795 S.PP.getIdentifierInfo("require_constant_initialization"), 2796 tok::r_paren, tok::r_paren})); 2797 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2798 SuitableSpelling = "constinit"; 2799 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2800 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2801 if (SuitableSpelling.empty()) 2802 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2803 SuitableSpelling += " "; 2804 2805 if (AttrBeforeInit) { 2806 // extern constinit int a; 2807 // int a = 0; // error (missing 'constinit'), accepted as extension 2808 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2809 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2810 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2811 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2812 } else { 2813 // int a = 0; 2814 // constinit extern int a; // error (missing 'constinit') 2815 S.Diag(CIAttr->getLocation(), 2816 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2817 : diag::warn_require_const_init_added_too_late) 2818 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2819 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2820 << CIAttr->isConstinit() 2821 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2822 } 2823 } 2824 2825 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2826 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2827 AvailabilityMergeKind AMK) { 2828 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2829 UsedAttr *NewAttr = OldAttr->clone(Context); 2830 NewAttr->setInherited(true); 2831 New->addAttr(NewAttr); 2832 } 2833 2834 if (!Old->hasAttrs() && !New->hasAttrs()) 2835 return; 2836 2837 // [dcl.constinit]p1: 2838 // If the [constinit] specifier is applied to any declaration of a 2839 // variable, it shall be applied to the initializing declaration. 2840 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2841 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2842 if (bool(OldConstInit) != bool(NewConstInit)) { 2843 const auto *OldVD = cast<VarDecl>(Old); 2844 auto *NewVD = cast<VarDecl>(New); 2845 2846 // Find the initializing declaration. Note that we might not have linked 2847 // the new declaration into the redeclaration chain yet. 2848 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2849 if (!InitDecl && 2850 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2851 InitDecl = NewVD; 2852 2853 if (InitDecl == NewVD) { 2854 // This is the initializing declaration. If it would inherit 'constinit', 2855 // that's ill-formed. (Note that we do not apply this to the attribute 2856 // form). 2857 if (OldConstInit && OldConstInit->isConstinit()) 2858 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2859 /*AttrBeforeInit=*/true); 2860 } else if (NewConstInit) { 2861 // This is the first time we've been told that this declaration should 2862 // have a constant initializer. If we already saw the initializing 2863 // declaration, this is too late. 2864 if (InitDecl && InitDecl != NewVD) { 2865 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2866 /*AttrBeforeInit=*/false); 2867 NewVD->dropAttr<ConstInitAttr>(); 2868 } 2869 } 2870 } 2871 2872 // Attributes declared post-definition are currently ignored. 2873 checkNewAttributesAfterDef(*this, New, Old); 2874 2875 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2876 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2877 if (!OldA->isEquivalent(NewA)) { 2878 // This redeclaration changes __asm__ label. 2879 Diag(New->getLocation(), diag::err_different_asm_label); 2880 Diag(OldA->getLocation(), diag::note_previous_declaration); 2881 } 2882 } else if (Old->isUsed()) { 2883 // This redeclaration adds an __asm__ label to a declaration that has 2884 // already been ODR-used. 2885 Diag(New->getLocation(), diag::err_late_asm_label_name) 2886 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2887 } 2888 } 2889 2890 // Re-declaration cannot add abi_tag's. 2891 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2892 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2893 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2894 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2895 NewTag) == OldAbiTagAttr->tags_end()) { 2896 Diag(NewAbiTagAttr->getLocation(), 2897 diag::err_new_abi_tag_on_redeclaration) 2898 << NewTag; 2899 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2900 } 2901 } 2902 } else { 2903 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2904 Diag(Old->getLocation(), diag::note_previous_declaration); 2905 } 2906 } 2907 2908 // This redeclaration adds a section attribute. 2909 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2910 if (auto *VD = dyn_cast<VarDecl>(New)) { 2911 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2912 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2913 Diag(Old->getLocation(), diag::note_previous_declaration); 2914 } 2915 } 2916 } 2917 2918 // Redeclaration adds code-seg attribute. 2919 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2920 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2921 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2922 Diag(New->getLocation(), diag::warn_mismatched_section) 2923 << 0 /*codeseg*/; 2924 Diag(Old->getLocation(), diag::note_previous_declaration); 2925 } 2926 2927 if (!Old->hasAttrs()) 2928 return; 2929 2930 bool foundAny = New->hasAttrs(); 2931 2932 // Ensure that any moving of objects within the allocated map is done before 2933 // we process them. 2934 if (!foundAny) New->setAttrs(AttrVec()); 2935 2936 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2937 // Ignore deprecated/unavailable/availability attributes if requested. 2938 AvailabilityMergeKind LocalAMK = AMK_None; 2939 if (isa<DeprecatedAttr>(I) || 2940 isa<UnavailableAttr>(I) || 2941 isa<AvailabilityAttr>(I)) { 2942 switch (AMK) { 2943 case AMK_None: 2944 continue; 2945 2946 case AMK_Redeclaration: 2947 case AMK_Override: 2948 case AMK_ProtocolImplementation: 2949 LocalAMK = AMK; 2950 break; 2951 } 2952 } 2953 2954 // Already handled. 2955 if (isa<UsedAttr>(I)) 2956 continue; 2957 2958 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2959 foundAny = true; 2960 } 2961 2962 if (mergeAlignedAttrs(*this, New, Old)) 2963 foundAny = true; 2964 2965 if (!foundAny) New->dropAttrs(); 2966 } 2967 2968 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2969 /// to the new one. 2970 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2971 const ParmVarDecl *oldDecl, 2972 Sema &S) { 2973 // C++11 [dcl.attr.depend]p2: 2974 // The first declaration of a function shall specify the 2975 // carries_dependency attribute for its declarator-id if any declaration 2976 // of the function specifies the carries_dependency attribute. 2977 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2978 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2979 S.Diag(CDA->getLocation(), 2980 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2981 // Find the first declaration of the parameter. 2982 // FIXME: Should we build redeclaration chains for function parameters? 2983 const FunctionDecl *FirstFD = 2984 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2985 const ParmVarDecl *FirstVD = 2986 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2987 S.Diag(FirstVD->getLocation(), 2988 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2989 } 2990 2991 if (!oldDecl->hasAttrs()) 2992 return; 2993 2994 bool foundAny = newDecl->hasAttrs(); 2995 2996 // Ensure that any moving of objects within the allocated map is 2997 // done before we process them. 2998 if (!foundAny) newDecl->setAttrs(AttrVec()); 2999 3000 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3001 if (!DeclHasAttr(newDecl, I)) { 3002 InheritableAttr *newAttr = 3003 cast<InheritableParamAttr>(I->clone(S.Context)); 3004 newAttr->setInherited(true); 3005 newDecl->addAttr(newAttr); 3006 foundAny = true; 3007 } 3008 } 3009 3010 if (!foundAny) newDecl->dropAttrs(); 3011 } 3012 3013 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3014 const ParmVarDecl *OldParam, 3015 Sema &S) { 3016 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3017 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3018 if (*Oldnullability != *Newnullability) { 3019 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3020 << DiagNullabilityKind( 3021 *Newnullability, 3022 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3023 != 0)) 3024 << DiagNullabilityKind( 3025 *Oldnullability, 3026 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3027 != 0)); 3028 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3029 } 3030 } else { 3031 QualType NewT = NewParam->getType(); 3032 NewT = S.Context.getAttributedType( 3033 AttributedType::getNullabilityAttrKind(*Oldnullability), 3034 NewT, NewT); 3035 NewParam->setType(NewT); 3036 } 3037 } 3038 } 3039 3040 namespace { 3041 3042 /// Used in MergeFunctionDecl to keep track of function parameters in 3043 /// C. 3044 struct GNUCompatibleParamWarning { 3045 ParmVarDecl *OldParm; 3046 ParmVarDecl *NewParm; 3047 QualType PromotedType; 3048 }; 3049 3050 } // end anonymous namespace 3051 3052 // Determine whether the previous declaration was a definition, implicit 3053 // declaration, or a declaration. 3054 template <typename T> 3055 static std::pair<diag::kind, SourceLocation> 3056 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3057 diag::kind PrevDiag; 3058 SourceLocation OldLocation = Old->getLocation(); 3059 if (Old->isThisDeclarationADefinition()) 3060 PrevDiag = diag::note_previous_definition; 3061 else if (Old->isImplicit()) { 3062 PrevDiag = diag::note_previous_implicit_declaration; 3063 if (OldLocation.isInvalid()) 3064 OldLocation = New->getLocation(); 3065 } else 3066 PrevDiag = diag::note_previous_declaration; 3067 return std::make_pair(PrevDiag, OldLocation); 3068 } 3069 3070 /// canRedefineFunction - checks if a function can be redefined. Currently, 3071 /// only extern inline functions can be redefined, and even then only in 3072 /// GNU89 mode. 3073 static bool canRedefineFunction(const FunctionDecl *FD, 3074 const LangOptions& LangOpts) { 3075 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3076 !LangOpts.CPlusPlus && 3077 FD->isInlineSpecified() && 3078 FD->getStorageClass() == SC_Extern); 3079 } 3080 3081 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3082 const AttributedType *AT = T->getAs<AttributedType>(); 3083 while (AT && !AT->isCallingConv()) 3084 AT = AT->getModifiedType()->getAs<AttributedType>(); 3085 return AT; 3086 } 3087 3088 template <typename T> 3089 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3090 const DeclContext *DC = Old->getDeclContext(); 3091 if (DC->isRecord()) 3092 return false; 3093 3094 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3095 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3096 return true; 3097 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3098 return true; 3099 return false; 3100 } 3101 3102 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3103 static bool isExternC(VarTemplateDecl *) { return false; } 3104 3105 /// Check whether a redeclaration of an entity introduced by a 3106 /// using-declaration is valid, given that we know it's not an overload 3107 /// (nor a hidden tag declaration). 3108 template<typename ExpectedDecl> 3109 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3110 ExpectedDecl *New) { 3111 // C++11 [basic.scope.declarative]p4: 3112 // Given a set of declarations in a single declarative region, each of 3113 // which specifies the same unqualified name, 3114 // -- they shall all refer to the same entity, or all refer to functions 3115 // and function templates; or 3116 // -- exactly one declaration shall declare a class name or enumeration 3117 // name that is not a typedef name and the other declarations shall all 3118 // refer to the same variable or enumerator, or all refer to functions 3119 // and function templates; in this case the class name or enumeration 3120 // name is hidden (3.3.10). 3121 3122 // C++11 [namespace.udecl]p14: 3123 // If a function declaration in namespace scope or block scope has the 3124 // same name and the same parameter-type-list as a function introduced 3125 // by a using-declaration, and the declarations do not declare the same 3126 // function, the program is ill-formed. 3127 3128 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3129 if (Old && 3130 !Old->getDeclContext()->getRedeclContext()->Equals( 3131 New->getDeclContext()->getRedeclContext()) && 3132 !(isExternC(Old) && isExternC(New))) 3133 Old = nullptr; 3134 3135 if (!Old) { 3136 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3137 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3138 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3139 return true; 3140 } 3141 return false; 3142 } 3143 3144 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3145 const FunctionDecl *B) { 3146 assert(A->getNumParams() == B->getNumParams()); 3147 3148 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3149 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3150 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3151 if (AttrA == AttrB) 3152 return true; 3153 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3154 AttrA->isDynamic() == AttrB->isDynamic(); 3155 }; 3156 3157 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3158 } 3159 3160 /// If necessary, adjust the semantic declaration context for a qualified 3161 /// declaration to name the correct inline namespace within the qualifier. 3162 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3163 DeclaratorDecl *OldD) { 3164 // The only case where we need to update the DeclContext is when 3165 // redeclaration lookup for a qualified name finds a declaration 3166 // in an inline namespace within the context named by the qualifier: 3167 // 3168 // inline namespace N { int f(); } 3169 // int ::f(); // Sema DC needs adjusting from :: to N::. 3170 // 3171 // For unqualified declarations, the semantic context *can* change 3172 // along the redeclaration chain (for local extern declarations, 3173 // extern "C" declarations, and friend declarations in particular). 3174 if (!NewD->getQualifier()) 3175 return; 3176 3177 // NewD is probably already in the right context. 3178 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3179 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3180 if (NamedDC->Equals(SemaDC)) 3181 return; 3182 3183 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3184 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3185 "unexpected context for redeclaration"); 3186 3187 auto *LexDC = NewD->getLexicalDeclContext(); 3188 auto FixSemaDC = [=](NamedDecl *D) { 3189 if (!D) 3190 return; 3191 D->setDeclContext(SemaDC); 3192 D->setLexicalDeclContext(LexDC); 3193 }; 3194 3195 FixSemaDC(NewD); 3196 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3197 FixSemaDC(FD->getDescribedFunctionTemplate()); 3198 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3199 FixSemaDC(VD->getDescribedVarTemplate()); 3200 } 3201 3202 /// MergeFunctionDecl - We just parsed a function 'New' from 3203 /// declarator D which has the same name and scope as a previous 3204 /// declaration 'Old'. Figure out how to resolve this situation, 3205 /// merging decls or emitting diagnostics as appropriate. 3206 /// 3207 /// In C++, New and Old must be declarations that are not 3208 /// overloaded. Use IsOverload to determine whether New and Old are 3209 /// overloaded, and to select the Old declaration that New should be 3210 /// merged with. 3211 /// 3212 /// Returns true if there was an error, false otherwise. 3213 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3214 Scope *S, bool MergeTypeWithOld) { 3215 // Verify the old decl was also a function. 3216 FunctionDecl *Old = OldD->getAsFunction(); 3217 if (!Old) { 3218 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3219 if (New->getFriendObjectKind()) { 3220 Diag(New->getLocation(), diag::err_using_decl_friend); 3221 Diag(Shadow->getTargetDecl()->getLocation(), 3222 diag::note_using_decl_target); 3223 Diag(Shadow->getUsingDecl()->getLocation(), 3224 diag::note_using_decl) << 0; 3225 return true; 3226 } 3227 3228 // Check whether the two declarations might declare the same function. 3229 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3230 return true; 3231 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3232 } else { 3233 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3234 << New->getDeclName(); 3235 notePreviousDefinition(OldD, New->getLocation()); 3236 return true; 3237 } 3238 } 3239 3240 // If the old declaration is invalid, just give up here. 3241 if (Old->isInvalidDecl()) 3242 return true; 3243 3244 // Disallow redeclaration of some builtins. 3245 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3246 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3247 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3248 << Old << Old->getType(); 3249 return true; 3250 } 3251 3252 diag::kind PrevDiag; 3253 SourceLocation OldLocation; 3254 std::tie(PrevDiag, OldLocation) = 3255 getNoteDiagForInvalidRedeclaration(Old, New); 3256 3257 // Don't complain about this if we're in GNU89 mode and the old function 3258 // is an extern inline function. 3259 // Don't complain about specializations. They are not supposed to have 3260 // storage classes. 3261 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3262 New->getStorageClass() == SC_Static && 3263 Old->hasExternalFormalLinkage() && 3264 !New->getTemplateSpecializationInfo() && 3265 !canRedefineFunction(Old, getLangOpts())) { 3266 if (getLangOpts().MicrosoftExt) { 3267 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3268 Diag(OldLocation, PrevDiag); 3269 } else { 3270 Diag(New->getLocation(), diag::err_static_non_static) << New; 3271 Diag(OldLocation, PrevDiag); 3272 return true; 3273 } 3274 } 3275 3276 if (New->hasAttr<InternalLinkageAttr>() && 3277 !Old->hasAttr<InternalLinkageAttr>()) { 3278 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3279 << New->getDeclName(); 3280 notePreviousDefinition(Old, New->getLocation()); 3281 New->dropAttr<InternalLinkageAttr>(); 3282 } 3283 3284 if (CheckRedeclarationModuleOwnership(New, Old)) 3285 return true; 3286 3287 if (!getLangOpts().CPlusPlus) { 3288 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3289 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3290 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3291 << New << OldOvl; 3292 3293 // Try our best to find a decl that actually has the overloadable 3294 // attribute for the note. In most cases (e.g. programs with only one 3295 // broken declaration/definition), this won't matter. 3296 // 3297 // FIXME: We could do this if we juggled some extra state in 3298 // OverloadableAttr, rather than just removing it. 3299 const Decl *DiagOld = Old; 3300 if (OldOvl) { 3301 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3302 const auto *A = D->getAttr<OverloadableAttr>(); 3303 return A && !A->isImplicit(); 3304 }); 3305 // If we've implicitly added *all* of the overloadable attrs to this 3306 // chain, emitting a "previous redecl" note is pointless. 3307 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3308 } 3309 3310 if (DiagOld) 3311 Diag(DiagOld->getLocation(), 3312 diag::note_attribute_overloadable_prev_overload) 3313 << OldOvl; 3314 3315 if (OldOvl) 3316 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3317 else 3318 New->dropAttr<OverloadableAttr>(); 3319 } 3320 } 3321 3322 // If a function is first declared with a calling convention, but is later 3323 // declared or defined without one, all following decls assume the calling 3324 // convention of the first. 3325 // 3326 // It's OK if a function is first declared without a calling convention, 3327 // but is later declared or defined with the default calling convention. 3328 // 3329 // To test if either decl has an explicit calling convention, we look for 3330 // AttributedType sugar nodes on the type as written. If they are missing or 3331 // were canonicalized away, we assume the calling convention was implicit. 3332 // 3333 // Note also that we DO NOT return at this point, because we still have 3334 // other tests to run. 3335 QualType OldQType = Context.getCanonicalType(Old->getType()); 3336 QualType NewQType = Context.getCanonicalType(New->getType()); 3337 const FunctionType *OldType = cast<FunctionType>(OldQType); 3338 const FunctionType *NewType = cast<FunctionType>(NewQType); 3339 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3340 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3341 bool RequiresAdjustment = false; 3342 3343 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3344 FunctionDecl *First = Old->getFirstDecl(); 3345 const FunctionType *FT = 3346 First->getType().getCanonicalType()->castAs<FunctionType>(); 3347 FunctionType::ExtInfo FI = FT->getExtInfo(); 3348 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3349 if (!NewCCExplicit) { 3350 // Inherit the CC from the previous declaration if it was specified 3351 // there but not here. 3352 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3353 RequiresAdjustment = true; 3354 } else if (Old->getBuiltinID()) { 3355 // Builtin attribute isn't propagated to the new one yet at this point, 3356 // so we check if the old one is a builtin. 3357 3358 // Calling Conventions on a Builtin aren't really useful and setting a 3359 // default calling convention and cdecl'ing some builtin redeclarations is 3360 // common, so warn and ignore the calling convention on the redeclaration. 3361 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3362 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3363 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3364 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3365 RequiresAdjustment = true; 3366 } else { 3367 // Calling conventions aren't compatible, so complain. 3368 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3369 Diag(New->getLocation(), diag::err_cconv_change) 3370 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3371 << !FirstCCExplicit 3372 << (!FirstCCExplicit ? "" : 3373 FunctionType::getNameForCallConv(FI.getCC())); 3374 3375 // Put the note on the first decl, since it is the one that matters. 3376 Diag(First->getLocation(), diag::note_previous_declaration); 3377 return true; 3378 } 3379 } 3380 3381 // FIXME: diagnose the other way around? 3382 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3383 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3384 RequiresAdjustment = true; 3385 } 3386 3387 // Merge regparm attribute. 3388 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3389 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3390 if (NewTypeInfo.getHasRegParm()) { 3391 Diag(New->getLocation(), diag::err_regparm_mismatch) 3392 << NewType->getRegParmType() 3393 << OldType->getRegParmType(); 3394 Diag(OldLocation, diag::note_previous_declaration); 3395 return true; 3396 } 3397 3398 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3399 RequiresAdjustment = true; 3400 } 3401 3402 // Merge ns_returns_retained attribute. 3403 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3404 if (NewTypeInfo.getProducesResult()) { 3405 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3406 << "'ns_returns_retained'"; 3407 Diag(OldLocation, diag::note_previous_declaration); 3408 return true; 3409 } 3410 3411 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3412 RequiresAdjustment = true; 3413 } 3414 3415 if (OldTypeInfo.getNoCallerSavedRegs() != 3416 NewTypeInfo.getNoCallerSavedRegs()) { 3417 if (NewTypeInfo.getNoCallerSavedRegs()) { 3418 AnyX86NoCallerSavedRegistersAttr *Attr = 3419 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3420 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3421 Diag(OldLocation, diag::note_previous_declaration); 3422 return true; 3423 } 3424 3425 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3426 RequiresAdjustment = true; 3427 } 3428 3429 if (RequiresAdjustment) { 3430 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3431 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3432 New->setType(QualType(AdjustedType, 0)); 3433 NewQType = Context.getCanonicalType(New->getType()); 3434 } 3435 3436 // If this redeclaration makes the function inline, we may need to add it to 3437 // UndefinedButUsed. 3438 if (!Old->isInlined() && New->isInlined() && 3439 !New->hasAttr<GNUInlineAttr>() && 3440 !getLangOpts().GNUInline && 3441 Old->isUsed(false) && 3442 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3443 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3444 SourceLocation())); 3445 3446 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3447 // about it. 3448 if (New->hasAttr<GNUInlineAttr>() && 3449 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3450 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3451 } 3452 3453 // If pass_object_size params don't match up perfectly, this isn't a valid 3454 // redeclaration. 3455 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3456 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3457 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3458 << New->getDeclName(); 3459 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3460 return true; 3461 } 3462 3463 if (getLangOpts().CPlusPlus) { 3464 // C++1z [over.load]p2 3465 // Certain function declarations cannot be overloaded: 3466 // -- Function declarations that differ only in the return type, 3467 // the exception specification, or both cannot be overloaded. 3468 3469 // Check the exception specifications match. This may recompute the type of 3470 // both Old and New if it resolved exception specifications, so grab the 3471 // types again after this. Because this updates the type, we do this before 3472 // any of the other checks below, which may update the "de facto" NewQType 3473 // but do not necessarily update the type of New. 3474 if (CheckEquivalentExceptionSpec(Old, New)) 3475 return true; 3476 OldQType = Context.getCanonicalType(Old->getType()); 3477 NewQType = Context.getCanonicalType(New->getType()); 3478 3479 // Go back to the type source info to compare the declared return types, 3480 // per C++1y [dcl.type.auto]p13: 3481 // Redeclarations or specializations of a function or function template 3482 // with a declared return type that uses a placeholder type shall also 3483 // use that placeholder, not a deduced type. 3484 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3485 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3486 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3487 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3488 OldDeclaredReturnType)) { 3489 QualType ResQT; 3490 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3491 OldDeclaredReturnType->isObjCObjectPointerType()) 3492 // FIXME: This does the wrong thing for a deduced return type. 3493 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3494 if (ResQT.isNull()) { 3495 if (New->isCXXClassMember() && New->isOutOfLine()) 3496 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3497 << New << New->getReturnTypeSourceRange(); 3498 else 3499 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3500 << New->getReturnTypeSourceRange(); 3501 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3502 << Old->getReturnTypeSourceRange(); 3503 return true; 3504 } 3505 else 3506 NewQType = ResQT; 3507 } 3508 3509 QualType OldReturnType = OldType->getReturnType(); 3510 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3511 if (OldReturnType != NewReturnType) { 3512 // If this function has a deduced return type and has already been 3513 // defined, copy the deduced value from the old declaration. 3514 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3515 if (OldAT && OldAT->isDeduced()) { 3516 New->setType( 3517 SubstAutoType(New->getType(), 3518 OldAT->isDependentType() ? Context.DependentTy 3519 : OldAT->getDeducedType())); 3520 NewQType = Context.getCanonicalType( 3521 SubstAutoType(NewQType, 3522 OldAT->isDependentType() ? Context.DependentTy 3523 : OldAT->getDeducedType())); 3524 } 3525 } 3526 3527 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3528 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3529 if (OldMethod && NewMethod) { 3530 // Preserve triviality. 3531 NewMethod->setTrivial(OldMethod->isTrivial()); 3532 3533 // MSVC allows explicit template specialization at class scope: 3534 // 2 CXXMethodDecls referring to the same function will be injected. 3535 // We don't want a redeclaration error. 3536 bool IsClassScopeExplicitSpecialization = 3537 OldMethod->isFunctionTemplateSpecialization() && 3538 NewMethod->isFunctionTemplateSpecialization(); 3539 bool isFriend = NewMethod->getFriendObjectKind(); 3540 3541 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3542 !IsClassScopeExplicitSpecialization) { 3543 // -- Member function declarations with the same name and the 3544 // same parameter types cannot be overloaded if any of them 3545 // is a static member function declaration. 3546 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3547 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3548 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3549 return true; 3550 } 3551 3552 // C++ [class.mem]p1: 3553 // [...] A member shall not be declared twice in the 3554 // member-specification, except that a nested class or member 3555 // class template can be declared and then later defined. 3556 if (!inTemplateInstantiation()) { 3557 unsigned NewDiag; 3558 if (isa<CXXConstructorDecl>(OldMethod)) 3559 NewDiag = diag::err_constructor_redeclared; 3560 else if (isa<CXXDestructorDecl>(NewMethod)) 3561 NewDiag = diag::err_destructor_redeclared; 3562 else if (isa<CXXConversionDecl>(NewMethod)) 3563 NewDiag = diag::err_conv_function_redeclared; 3564 else 3565 NewDiag = diag::err_member_redeclared; 3566 3567 Diag(New->getLocation(), NewDiag); 3568 } else { 3569 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3570 << New << New->getType(); 3571 } 3572 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3573 return true; 3574 3575 // Complain if this is an explicit declaration of a special 3576 // member that was initially declared implicitly. 3577 // 3578 // As an exception, it's okay to befriend such methods in order 3579 // to permit the implicit constructor/destructor/operator calls. 3580 } else if (OldMethod->isImplicit()) { 3581 if (isFriend) { 3582 NewMethod->setImplicit(); 3583 } else { 3584 Diag(NewMethod->getLocation(), 3585 diag::err_definition_of_implicitly_declared_member) 3586 << New << getSpecialMember(OldMethod); 3587 return true; 3588 } 3589 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3590 Diag(NewMethod->getLocation(), 3591 diag::err_definition_of_explicitly_defaulted_member) 3592 << getSpecialMember(OldMethod); 3593 return true; 3594 } 3595 } 3596 3597 // C++11 [dcl.attr.noreturn]p1: 3598 // The first declaration of a function shall specify the noreturn 3599 // attribute if any declaration of that function specifies the noreturn 3600 // attribute. 3601 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3602 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3603 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3604 Diag(Old->getFirstDecl()->getLocation(), 3605 diag::note_noreturn_missing_first_decl); 3606 } 3607 3608 // C++11 [dcl.attr.depend]p2: 3609 // The first declaration of a function shall specify the 3610 // carries_dependency attribute for its declarator-id if any declaration 3611 // of the function specifies the carries_dependency attribute. 3612 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3613 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3614 Diag(CDA->getLocation(), 3615 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3616 Diag(Old->getFirstDecl()->getLocation(), 3617 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3618 } 3619 3620 // (C++98 8.3.5p3): 3621 // All declarations for a function shall agree exactly in both the 3622 // return type and the parameter-type-list. 3623 // We also want to respect all the extended bits except noreturn. 3624 3625 // noreturn should now match unless the old type info didn't have it. 3626 QualType OldQTypeForComparison = OldQType; 3627 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3628 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3629 const FunctionType *OldTypeForComparison 3630 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3631 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3632 assert(OldQTypeForComparison.isCanonical()); 3633 } 3634 3635 if (haveIncompatibleLanguageLinkages(Old, New)) { 3636 // As a special case, retain the language linkage from previous 3637 // declarations of a friend function as an extension. 3638 // 3639 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3640 // and is useful because there's otherwise no way to specify language 3641 // linkage within class scope. 3642 // 3643 // Check cautiously as the friend object kind isn't yet complete. 3644 if (New->getFriendObjectKind() != Decl::FOK_None) { 3645 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3646 Diag(OldLocation, PrevDiag); 3647 } else { 3648 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3649 Diag(OldLocation, PrevDiag); 3650 return true; 3651 } 3652 } 3653 3654 // If the function types are compatible, merge the declarations. Ignore the 3655 // exception specifier because it was already checked above in 3656 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3657 // about incompatible types under -fms-compatibility. 3658 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3659 NewQType)) 3660 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3661 3662 // If the types are imprecise (due to dependent constructs in friends or 3663 // local extern declarations), it's OK if they differ. We'll check again 3664 // during instantiation. 3665 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3666 return false; 3667 3668 // Fall through for conflicting redeclarations and redefinitions. 3669 } 3670 3671 // C: Function types need to be compatible, not identical. This handles 3672 // duplicate function decls like "void f(int); void f(enum X);" properly. 3673 if (!getLangOpts().CPlusPlus && 3674 Context.typesAreCompatible(OldQType, NewQType)) { 3675 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3676 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3677 const FunctionProtoType *OldProto = nullptr; 3678 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3679 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3680 // The old declaration provided a function prototype, but the 3681 // new declaration does not. Merge in the prototype. 3682 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3683 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3684 NewQType = 3685 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3686 OldProto->getExtProtoInfo()); 3687 New->setType(NewQType); 3688 New->setHasInheritedPrototype(); 3689 3690 // Synthesize parameters with the same types. 3691 SmallVector<ParmVarDecl*, 16> Params; 3692 for (const auto &ParamType : OldProto->param_types()) { 3693 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3694 SourceLocation(), nullptr, 3695 ParamType, /*TInfo=*/nullptr, 3696 SC_None, nullptr); 3697 Param->setScopeInfo(0, Params.size()); 3698 Param->setImplicit(); 3699 Params.push_back(Param); 3700 } 3701 3702 New->setParams(Params); 3703 } 3704 3705 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3706 } 3707 3708 // Check if the function types are compatible when pointer size address 3709 // spaces are ignored. 3710 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3711 return false; 3712 3713 // GNU C permits a K&R definition to follow a prototype declaration 3714 // if the declared types of the parameters in the K&R definition 3715 // match the types in the prototype declaration, even when the 3716 // promoted types of the parameters from the K&R definition differ 3717 // from the types in the prototype. GCC then keeps the types from 3718 // the prototype. 3719 // 3720 // If a variadic prototype is followed by a non-variadic K&R definition, 3721 // the K&R definition becomes variadic. This is sort of an edge case, but 3722 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3723 // C99 6.9.1p8. 3724 if (!getLangOpts().CPlusPlus && 3725 Old->hasPrototype() && !New->hasPrototype() && 3726 New->getType()->getAs<FunctionProtoType>() && 3727 Old->getNumParams() == New->getNumParams()) { 3728 SmallVector<QualType, 16> ArgTypes; 3729 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3730 const FunctionProtoType *OldProto 3731 = Old->getType()->getAs<FunctionProtoType>(); 3732 const FunctionProtoType *NewProto 3733 = New->getType()->getAs<FunctionProtoType>(); 3734 3735 // Determine whether this is the GNU C extension. 3736 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3737 NewProto->getReturnType()); 3738 bool LooseCompatible = !MergedReturn.isNull(); 3739 for (unsigned Idx = 0, End = Old->getNumParams(); 3740 LooseCompatible && Idx != End; ++Idx) { 3741 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3742 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3743 if (Context.typesAreCompatible(OldParm->getType(), 3744 NewProto->getParamType(Idx))) { 3745 ArgTypes.push_back(NewParm->getType()); 3746 } else if (Context.typesAreCompatible(OldParm->getType(), 3747 NewParm->getType(), 3748 /*CompareUnqualified=*/true)) { 3749 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3750 NewProto->getParamType(Idx) }; 3751 Warnings.push_back(Warn); 3752 ArgTypes.push_back(NewParm->getType()); 3753 } else 3754 LooseCompatible = false; 3755 } 3756 3757 if (LooseCompatible) { 3758 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3759 Diag(Warnings[Warn].NewParm->getLocation(), 3760 diag::ext_param_promoted_not_compatible_with_prototype) 3761 << Warnings[Warn].PromotedType 3762 << Warnings[Warn].OldParm->getType(); 3763 if (Warnings[Warn].OldParm->getLocation().isValid()) 3764 Diag(Warnings[Warn].OldParm->getLocation(), 3765 diag::note_previous_declaration); 3766 } 3767 3768 if (MergeTypeWithOld) 3769 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3770 OldProto->getExtProtoInfo())); 3771 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3772 } 3773 3774 // Fall through to diagnose conflicting types. 3775 } 3776 3777 // A function that has already been declared has been redeclared or 3778 // defined with a different type; show an appropriate diagnostic. 3779 3780 // If the previous declaration was an implicitly-generated builtin 3781 // declaration, then at the very least we should use a specialized note. 3782 unsigned BuiltinID; 3783 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3784 // If it's actually a library-defined builtin function like 'malloc' 3785 // or 'printf', just warn about the incompatible redeclaration. 3786 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3787 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3788 Diag(OldLocation, diag::note_previous_builtin_declaration) 3789 << Old << Old->getType(); 3790 return false; 3791 } 3792 3793 PrevDiag = diag::note_previous_builtin_declaration; 3794 } 3795 3796 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3797 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3798 return true; 3799 } 3800 3801 /// Completes the merge of two function declarations that are 3802 /// known to be compatible. 3803 /// 3804 /// This routine handles the merging of attributes and other 3805 /// properties of function declarations from the old declaration to 3806 /// the new declaration, once we know that New is in fact a 3807 /// redeclaration of Old. 3808 /// 3809 /// \returns false 3810 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3811 Scope *S, bool MergeTypeWithOld) { 3812 // Merge the attributes 3813 mergeDeclAttributes(New, Old); 3814 3815 // Merge "pure" flag. 3816 if (Old->isPure()) 3817 New->setPure(); 3818 3819 // Merge "used" flag. 3820 if (Old->getMostRecentDecl()->isUsed(false)) 3821 New->setIsUsed(); 3822 3823 // Merge attributes from the parameters. These can mismatch with K&R 3824 // declarations. 3825 if (New->getNumParams() == Old->getNumParams()) 3826 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3827 ParmVarDecl *NewParam = New->getParamDecl(i); 3828 ParmVarDecl *OldParam = Old->getParamDecl(i); 3829 mergeParamDeclAttributes(NewParam, OldParam, *this); 3830 mergeParamDeclTypes(NewParam, OldParam, *this); 3831 } 3832 3833 if (getLangOpts().CPlusPlus) 3834 return MergeCXXFunctionDecl(New, Old, S); 3835 3836 // Merge the function types so the we get the composite types for the return 3837 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3838 // was visible. 3839 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3840 if (!Merged.isNull() && MergeTypeWithOld) 3841 New->setType(Merged); 3842 3843 return false; 3844 } 3845 3846 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3847 ObjCMethodDecl *oldMethod) { 3848 // Merge the attributes, including deprecated/unavailable 3849 AvailabilityMergeKind MergeKind = 3850 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3851 ? AMK_ProtocolImplementation 3852 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3853 : AMK_Override; 3854 3855 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3856 3857 // Merge attributes from the parameters. 3858 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3859 oe = oldMethod->param_end(); 3860 for (ObjCMethodDecl::param_iterator 3861 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3862 ni != ne && oi != oe; ++ni, ++oi) 3863 mergeParamDeclAttributes(*ni, *oi, *this); 3864 3865 CheckObjCMethodOverride(newMethod, oldMethod); 3866 } 3867 3868 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3869 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3870 3871 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3872 ? diag::err_redefinition_different_type 3873 : diag::err_redeclaration_different_type) 3874 << New->getDeclName() << New->getType() << Old->getType(); 3875 3876 diag::kind PrevDiag; 3877 SourceLocation OldLocation; 3878 std::tie(PrevDiag, OldLocation) 3879 = getNoteDiagForInvalidRedeclaration(Old, New); 3880 S.Diag(OldLocation, PrevDiag); 3881 New->setInvalidDecl(); 3882 } 3883 3884 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3885 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3886 /// emitting diagnostics as appropriate. 3887 /// 3888 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3889 /// to here in AddInitializerToDecl. We can't check them before the initializer 3890 /// is attached. 3891 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3892 bool MergeTypeWithOld) { 3893 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3894 return; 3895 3896 QualType MergedT; 3897 if (getLangOpts().CPlusPlus) { 3898 if (New->getType()->isUndeducedType()) { 3899 // We don't know what the new type is until the initializer is attached. 3900 return; 3901 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3902 // These could still be something that needs exception specs checked. 3903 return MergeVarDeclExceptionSpecs(New, Old); 3904 } 3905 // C++ [basic.link]p10: 3906 // [...] the types specified by all declarations referring to a given 3907 // object or function shall be identical, except that declarations for an 3908 // array object can specify array types that differ by the presence or 3909 // absence of a major array bound (8.3.4). 3910 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3911 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3912 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3913 3914 // We are merging a variable declaration New into Old. If it has an array 3915 // bound, and that bound differs from Old's bound, we should diagnose the 3916 // mismatch. 3917 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3918 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3919 PrevVD = PrevVD->getPreviousDecl()) { 3920 QualType PrevVDTy = PrevVD->getType(); 3921 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3922 continue; 3923 3924 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3925 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3926 } 3927 } 3928 3929 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3930 if (Context.hasSameType(OldArray->getElementType(), 3931 NewArray->getElementType())) 3932 MergedT = New->getType(); 3933 } 3934 // FIXME: Check visibility. New is hidden but has a complete type. If New 3935 // has no array bound, it should not inherit one from Old, if Old is not 3936 // visible. 3937 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3938 if (Context.hasSameType(OldArray->getElementType(), 3939 NewArray->getElementType())) 3940 MergedT = Old->getType(); 3941 } 3942 } 3943 else if (New->getType()->isObjCObjectPointerType() && 3944 Old->getType()->isObjCObjectPointerType()) { 3945 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3946 Old->getType()); 3947 } 3948 } else { 3949 // C 6.2.7p2: 3950 // All declarations that refer to the same object or function shall have 3951 // compatible type. 3952 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3953 } 3954 if (MergedT.isNull()) { 3955 // It's OK if we couldn't merge types if either type is dependent, for a 3956 // block-scope variable. In other cases (static data members of class 3957 // templates, variable templates, ...), we require the types to be 3958 // equivalent. 3959 // FIXME: The C++ standard doesn't say anything about this. 3960 if ((New->getType()->isDependentType() || 3961 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3962 // If the old type was dependent, we can't merge with it, so the new type 3963 // becomes dependent for now. We'll reproduce the original type when we 3964 // instantiate the TypeSourceInfo for the variable. 3965 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3966 New->setType(Context.DependentTy); 3967 return; 3968 } 3969 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3970 } 3971 3972 // Don't actually update the type on the new declaration if the old 3973 // declaration was an extern declaration in a different scope. 3974 if (MergeTypeWithOld) 3975 New->setType(MergedT); 3976 } 3977 3978 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3979 LookupResult &Previous) { 3980 // C11 6.2.7p4: 3981 // For an identifier with internal or external linkage declared 3982 // in a scope in which a prior declaration of that identifier is 3983 // visible, if the prior declaration specifies internal or 3984 // external linkage, the type of the identifier at the later 3985 // declaration becomes the composite type. 3986 // 3987 // If the variable isn't visible, we do not merge with its type. 3988 if (Previous.isShadowed()) 3989 return false; 3990 3991 if (S.getLangOpts().CPlusPlus) { 3992 // C++11 [dcl.array]p3: 3993 // If there is a preceding declaration of the entity in the same 3994 // scope in which the bound was specified, an omitted array bound 3995 // is taken to be the same as in that earlier declaration. 3996 return NewVD->isPreviousDeclInSameBlockScope() || 3997 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3998 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3999 } else { 4000 // If the old declaration was function-local, don't merge with its 4001 // type unless we're in the same function. 4002 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4003 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4004 } 4005 } 4006 4007 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4008 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4009 /// situation, merging decls or emitting diagnostics as appropriate. 4010 /// 4011 /// Tentative definition rules (C99 6.9.2p2) are checked by 4012 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4013 /// definitions here, since the initializer hasn't been attached. 4014 /// 4015 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4016 // If the new decl is already invalid, don't do any other checking. 4017 if (New->isInvalidDecl()) 4018 return; 4019 4020 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4021 return; 4022 4023 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4024 4025 // Verify the old decl was also a variable or variable template. 4026 VarDecl *Old = nullptr; 4027 VarTemplateDecl *OldTemplate = nullptr; 4028 if (Previous.isSingleResult()) { 4029 if (NewTemplate) { 4030 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4031 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4032 4033 if (auto *Shadow = 4034 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4035 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4036 return New->setInvalidDecl(); 4037 } else { 4038 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4039 4040 if (auto *Shadow = 4041 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4042 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4043 return New->setInvalidDecl(); 4044 } 4045 } 4046 if (!Old) { 4047 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4048 << New->getDeclName(); 4049 notePreviousDefinition(Previous.getRepresentativeDecl(), 4050 New->getLocation()); 4051 return New->setInvalidDecl(); 4052 } 4053 4054 // Ensure the template parameters are compatible. 4055 if (NewTemplate && 4056 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4057 OldTemplate->getTemplateParameters(), 4058 /*Complain=*/true, TPL_TemplateMatch)) 4059 return New->setInvalidDecl(); 4060 4061 // C++ [class.mem]p1: 4062 // A member shall not be declared twice in the member-specification [...] 4063 // 4064 // Here, we need only consider static data members. 4065 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4066 Diag(New->getLocation(), diag::err_duplicate_member) 4067 << New->getIdentifier(); 4068 Diag(Old->getLocation(), diag::note_previous_declaration); 4069 New->setInvalidDecl(); 4070 } 4071 4072 mergeDeclAttributes(New, Old); 4073 // Warn if an already-declared variable is made a weak_import in a subsequent 4074 // declaration 4075 if (New->hasAttr<WeakImportAttr>() && 4076 Old->getStorageClass() == SC_None && 4077 !Old->hasAttr<WeakImportAttr>()) { 4078 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4079 notePreviousDefinition(Old, New->getLocation()); 4080 // Remove weak_import attribute on new declaration. 4081 New->dropAttr<WeakImportAttr>(); 4082 } 4083 4084 if (New->hasAttr<InternalLinkageAttr>() && 4085 !Old->hasAttr<InternalLinkageAttr>()) { 4086 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4087 << New->getDeclName(); 4088 notePreviousDefinition(Old, New->getLocation()); 4089 New->dropAttr<InternalLinkageAttr>(); 4090 } 4091 4092 // Merge the types. 4093 VarDecl *MostRecent = Old->getMostRecentDecl(); 4094 if (MostRecent != Old) { 4095 MergeVarDeclTypes(New, MostRecent, 4096 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4097 if (New->isInvalidDecl()) 4098 return; 4099 } 4100 4101 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4102 if (New->isInvalidDecl()) 4103 return; 4104 4105 diag::kind PrevDiag; 4106 SourceLocation OldLocation; 4107 std::tie(PrevDiag, OldLocation) = 4108 getNoteDiagForInvalidRedeclaration(Old, New); 4109 4110 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4111 if (New->getStorageClass() == SC_Static && 4112 !New->isStaticDataMember() && 4113 Old->hasExternalFormalLinkage()) { 4114 if (getLangOpts().MicrosoftExt) { 4115 Diag(New->getLocation(), diag::ext_static_non_static) 4116 << New->getDeclName(); 4117 Diag(OldLocation, PrevDiag); 4118 } else { 4119 Diag(New->getLocation(), diag::err_static_non_static) 4120 << New->getDeclName(); 4121 Diag(OldLocation, PrevDiag); 4122 return New->setInvalidDecl(); 4123 } 4124 } 4125 // C99 6.2.2p4: 4126 // For an identifier declared with the storage-class specifier 4127 // extern in a scope in which a prior declaration of that 4128 // identifier is visible,23) if the prior declaration specifies 4129 // internal or external linkage, the linkage of the identifier at 4130 // the later declaration is the same as the linkage specified at 4131 // the prior declaration. If no prior declaration is visible, or 4132 // if the prior declaration specifies no linkage, then the 4133 // identifier has external linkage. 4134 if (New->hasExternalStorage() && Old->hasLinkage()) 4135 /* Okay */; 4136 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4137 !New->isStaticDataMember() && 4138 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4139 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4140 Diag(OldLocation, PrevDiag); 4141 return New->setInvalidDecl(); 4142 } 4143 4144 // Check if extern is followed by non-extern and vice-versa. 4145 if (New->hasExternalStorage() && 4146 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4147 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4148 Diag(OldLocation, PrevDiag); 4149 return New->setInvalidDecl(); 4150 } 4151 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4152 !New->hasExternalStorage()) { 4153 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4154 Diag(OldLocation, PrevDiag); 4155 return New->setInvalidDecl(); 4156 } 4157 4158 if (CheckRedeclarationModuleOwnership(New, Old)) 4159 return; 4160 4161 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4162 4163 // FIXME: The test for external storage here seems wrong? We still 4164 // need to check for mismatches. 4165 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4166 // Don't complain about out-of-line definitions of static members. 4167 !(Old->getLexicalDeclContext()->isRecord() && 4168 !New->getLexicalDeclContext()->isRecord())) { 4169 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4170 Diag(OldLocation, PrevDiag); 4171 return New->setInvalidDecl(); 4172 } 4173 4174 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4175 if (VarDecl *Def = Old->getDefinition()) { 4176 // C++1z [dcl.fcn.spec]p4: 4177 // If the definition of a variable appears in a translation unit before 4178 // its first declaration as inline, the program is ill-formed. 4179 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4180 Diag(Def->getLocation(), diag::note_previous_definition); 4181 } 4182 } 4183 4184 // If this redeclaration makes the variable inline, we may need to add it to 4185 // UndefinedButUsed. 4186 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4187 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4188 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4189 SourceLocation())); 4190 4191 if (New->getTLSKind() != Old->getTLSKind()) { 4192 if (!Old->getTLSKind()) { 4193 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4194 Diag(OldLocation, PrevDiag); 4195 } else if (!New->getTLSKind()) { 4196 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4197 Diag(OldLocation, PrevDiag); 4198 } else { 4199 // Do not allow redeclaration to change the variable between requiring 4200 // static and dynamic initialization. 4201 // FIXME: GCC allows this, but uses the TLS keyword on the first 4202 // declaration to determine the kind. Do we need to be compatible here? 4203 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4204 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4205 Diag(OldLocation, PrevDiag); 4206 } 4207 } 4208 4209 // C++ doesn't have tentative definitions, so go right ahead and check here. 4210 if (getLangOpts().CPlusPlus && 4211 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4212 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4213 Old->getCanonicalDecl()->isConstexpr()) { 4214 // This definition won't be a definition any more once it's been merged. 4215 Diag(New->getLocation(), 4216 diag::warn_deprecated_redundant_constexpr_static_def); 4217 } else if (VarDecl *Def = Old->getDefinition()) { 4218 if (checkVarDeclRedefinition(Def, New)) 4219 return; 4220 } 4221 } 4222 4223 if (haveIncompatibleLanguageLinkages(Old, New)) { 4224 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4225 Diag(OldLocation, PrevDiag); 4226 New->setInvalidDecl(); 4227 return; 4228 } 4229 4230 // Merge "used" flag. 4231 if (Old->getMostRecentDecl()->isUsed(false)) 4232 New->setIsUsed(); 4233 4234 // Keep a chain of previous declarations. 4235 New->setPreviousDecl(Old); 4236 if (NewTemplate) 4237 NewTemplate->setPreviousDecl(OldTemplate); 4238 adjustDeclContextForDeclaratorDecl(New, Old); 4239 4240 // Inherit access appropriately. 4241 New->setAccess(Old->getAccess()); 4242 if (NewTemplate) 4243 NewTemplate->setAccess(New->getAccess()); 4244 4245 if (Old->isInline()) 4246 New->setImplicitlyInline(); 4247 } 4248 4249 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4250 SourceManager &SrcMgr = getSourceManager(); 4251 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4252 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4253 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4254 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4255 auto &HSI = PP.getHeaderSearchInfo(); 4256 StringRef HdrFilename = 4257 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4258 4259 auto noteFromModuleOrInclude = [&](Module *Mod, 4260 SourceLocation IncLoc) -> bool { 4261 // Redefinition errors with modules are common with non modular mapped 4262 // headers, example: a non-modular header H in module A that also gets 4263 // included directly in a TU. Pointing twice to the same header/definition 4264 // is confusing, try to get better diagnostics when modules is on. 4265 if (IncLoc.isValid()) { 4266 if (Mod) { 4267 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4268 << HdrFilename.str() << Mod->getFullModuleName(); 4269 if (!Mod->DefinitionLoc.isInvalid()) 4270 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4271 << Mod->getFullModuleName(); 4272 } else { 4273 Diag(IncLoc, diag::note_redefinition_include_same_file) 4274 << HdrFilename.str(); 4275 } 4276 return true; 4277 } 4278 4279 return false; 4280 }; 4281 4282 // Is it the same file and same offset? Provide more information on why 4283 // this leads to a redefinition error. 4284 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4285 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4286 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4287 bool EmittedDiag = 4288 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4289 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4290 4291 // If the header has no guards, emit a note suggesting one. 4292 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4293 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4294 4295 if (EmittedDiag) 4296 return; 4297 } 4298 4299 // Redefinition coming from different files or couldn't do better above. 4300 if (Old->getLocation().isValid()) 4301 Diag(Old->getLocation(), diag::note_previous_definition); 4302 } 4303 4304 /// We've just determined that \p Old and \p New both appear to be definitions 4305 /// of the same variable. Either diagnose or fix the problem. 4306 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4307 if (!hasVisibleDefinition(Old) && 4308 (New->getFormalLinkage() == InternalLinkage || 4309 New->isInline() || 4310 New->getDescribedVarTemplate() || 4311 New->getNumTemplateParameterLists() || 4312 New->getDeclContext()->isDependentContext())) { 4313 // The previous definition is hidden, and multiple definitions are 4314 // permitted (in separate TUs). Demote this to a declaration. 4315 New->demoteThisDefinitionToDeclaration(); 4316 4317 // Make the canonical definition visible. 4318 if (auto *OldTD = Old->getDescribedVarTemplate()) 4319 makeMergedDefinitionVisible(OldTD); 4320 makeMergedDefinitionVisible(Old); 4321 return false; 4322 } else { 4323 Diag(New->getLocation(), diag::err_redefinition) << New; 4324 notePreviousDefinition(Old, New->getLocation()); 4325 New->setInvalidDecl(); 4326 return true; 4327 } 4328 } 4329 4330 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4331 /// no declarator (e.g. "struct foo;") is parsed. 4332 Decl * 4333 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4334 RecordDecl *&AnonRecord) { 4335 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4336 AnonRecord); 4337 } 4338 4339 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4340 // disambiguate entities defined in different scopes. 4341 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4342 // compatibility. 4343 // We will pick our mangling number depending on which version of MSVC is being 4344 // targeted. 4345 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4346 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4347 ? S->getMSCurManglingNumber() 4348 : S->getMSLastManglingNumber(); 4349 } 4350 4351 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4352 if (!Context.getLangOpts().CPlusPlus) 4353 return; 4354 4355 if (isa<CXXRecordDecl>(Tag->getParent())) { 4356 // If this tag is the direct child of a class, number it if 4357 // it is anonymous. 4358 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4359 return; 4360 MangleNumberingContext &MCtx = 4361 Context.getManglingNumberContext(Tag->getParent()); 4362 Context.setManglingNumber( 4363 Tag, MCtx.getManglingNumber( 4364 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4365 return; 4366 } 4367 4368 // If this tag isn't a direct child of a class, number it if it is local. 4369 MangleNumberingContext *MCtx; 4370 Decl *ManglingContextDecl; 4371 std::tie(MCtx, ManglingContextDecl) = 4372 getCurrentMangleNumberContext(Tag->getDeclContext()); 4373 if (MCtx) { 4374 Context.setManglingNumber( 4375 Tag, MCtx->getManglingNumber( 4376 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4377 } 4378 } 4379 4380 namespace { 4381 struct NonCLikeKind { 4382 enum { 4383 None, 4384 BaseClass, 4385 DefaultMemberInit, 4386 Lambda, 4387 Friend, 4388 OtherMember, 4389 Invalid, 4390 } Kind = None; 4391 SourceRange Range; 4392 4393 explicit operator bool() { return Kind != None; } 4394 }; 4395 } 4396 4397 /// Determine whether a class is C-like, according to the rules of C++ 4398 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4399 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4400 if (RD->isInvalidDecl()) 4401 return {NonCLikeKind::Invalid, {}}; 4402 4403 // C++ [dcl.typedef]p9: [P1766R1] 4404 // An unnamed class with a typedef name for linkage purposes shall not 4405 // 4406 // -- have any base classes 4407 if (RD->getNumBases()) 4408 return {NonCLikeKind::BaseClass, 4409 SourceRange(RD->bases_begin()->getBeginLoc(), 4410 RD->bases_end()[-1].getEndLoc())}; 4411 bool Invalid = false; 4412 for (Decl *D : RD->decls()) { 4413 // Don't complain about things we already diagnosed. 4414 if (D->isInvalidDecl()) { 4415 Invalid = true; 4416 continue; 4417 } 4418 4419 // -- have any [...] default member initializers 4420 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4421 if (FD->hasInClassInitializer()) { 4422 auto *Init = FD->getInClassInitializer(); 4423 return {NonCLikeKind::DefaultMemberInit, 4424 Init ? Init->getSourceRange() : D->getSourceRange()}; 4425 } 4426 continue; 4427 } 4428 4429 // FIXME: We don't allow friend declarations. This violates the wording of 4430 // P1766, but not the intent. 4431 if (isa<FriendDecl>(D)) 4432 return {NonCLikeKind::Friend, D->getSourceRange()}; 4433 4434 // -- declare any members other than non-static data members, member 4435 // enumerations, or member classes, 4436 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4437 isa<EnumDecl>(D)) 4438 continue; 4439 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4440 if (!MemberRD) { 4441 if (D->isImplicit()) 4442 continue; 4443 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4444 } 4445 4446 // -- contain a lambda-expression, 4447 if (MemberRD->isLambda()) 4448 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4449 4450 // and all member classes shall also satisfy these requirements 4451 // (recursively). 4452 if (MemberRD->isThisDeclarationADefinition()) { 4453 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4454 return Kind; 4455 } 4456 } 4457 4458 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4459 } 4460 4461 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4462 TypedefNameDecl *NewTD) { 4463 if (TagFromDeclSpec->isInvalidDecl()) 4464 return; 4465 4466 // Do nothing if the tag already has a name for linkage purposes. 4467 if (TagFromDeclSpec->hasNameForLinkage()) 4468 return; 4469 4470 // A well-formed anonymous tag must always be a TUK_Definition. 4471 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4472 4473 // The type must match the tag exactly; no qualifiers allowed. 4474 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4475 Context.getTagDeclType(TagFromDeclSpec))) { 4476 if (getLangOpts().CPlusPlus) 4477 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4478 return; 4479 } 4480 4481 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4482 // An unnamed class with a typedef name for linkage purposes shall [be 4483 // C-like]. 4484 // 4485 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4486 // shouldn't happen, but there are constructs that the language rule doesn't 4487 // disallow for which we can't reasonably avoid computing linkage early. 4488 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4489 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4490 : NonCLikeKind(); 4491 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4492 if (NonCLike || ChangesLinkage) { 4493 if (NonCLike.Kind == NonCLikeKind::Invalid) 4494 return; 4495 4496 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4497 if (ChangesLinkage) { 4498 // If the linkage changes, we can't accept this as an extension. 4499 if (NonCLike.Kind == NonCLikeKind::None) 4500 DiagID = diag::err_typedef_changes_linkage; 4501 else 4502 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4503 } 4504 4505 SourceLocation FixitLoc = 4506 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4507 llvm::SmallString<40> TextToInsert; 4508 TextToInsert += ' '; 4509 TextToInsert += NewTD->getIdentifier()->getName(); 4510 4511 Diag(FixitLoc, DiagID) 4512 << isa<TypeAliasDecl>(NewTD) 4513 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4514 if (NonCLike.Kind != NonCLikeKind::None) { 4515 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4516 << NonCLike.Kind - 1 << NonCLike.Range; 4517 } 4518 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4519 << NewTD << isa<TypeAliasDecl>(NewTD); 4520 4521 if (ChangesLinkage) 4522 return; 4523 } 4524 4525 // Otherwise, set this as the anon-decl typedef for the tag. 4526 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4527 } 4528 4529 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4530 switch (T) { 4531 case DeclSpec::TST_class: 4532 return 0; 4533 case DeclSpec::TST_struct: 4534 return 1; 4535 case DeclSpec::TST_interface: 4536 return 2; 4537 case DeclSpec::TST_union: 4538 return 3; 4539 case DeclSpec::TST_enum: 4540 return 4; 4541 default: 4542 llvm_unreachable("unexpected type specifier"); 4543 } 4544 } 4545 4546 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4547 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4548 /// parameters to cope with template friend declarations. 4549 Decl * 4550 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4551 MultiTemplateParamsArg TemplateParams, 4552 bool IsExplicitInstantiation, 4553 RecordDecl *&AnonRecord) { 4554 Decl *TagD = nullptr; 4555 TagDecl *Tag = nullptr; 4556 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4557 DS.getTypeSpecType() == DeclSpec::TST_struct || 4558 DS.getTypeSpecType() == DeclSpec::TST_interface || 4559 DS.getTypeSpecType() == DeclSpec::TST_union || 4560 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4561 TagD = DS.getRepAsDecl(); 4562 4563 if (!TagD) // We probably had an error 4564 return nullptr; 4565 4566 // Note that the above type specs guarantee that the 4567 // type rep is a Decl, whereas in many of the others 4568 // it's a Type. 4569 if (isa<TagDecl>(TagD)) 4570 Tag = cast<TagDecl>(TagD); 4571 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4572 Tag = CTD->getTemplatedDecl(); 4573 } 4574 4575 if (Tag) { 4576 handleTagNumbering(Tag, S); 4577 Tag->setFreeStanding(); 4578 if (Tag->isInvalidDecl()) 4579 return Tag; 4580 } 4581 4582 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4583 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4584 // or incomplete types shall not be restrict-qualified." 4585 if (TypeQuals & DeclSpec::TQ_restrict) 4586 Diag(DS.getRestrictSpecLoc(), 4587 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4588 << DS.getSourceRange(); 4589 } 4590 4591 if (DS.isInlineSpecified()) 4592 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4593 << getLangOpts().CPlusPlus17; 4594 4595 if (DS.hasConstexprSpecifier()) { 4596 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4597 // and definitions of functions and variables. 4598 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4599 // the declaration of a function or function template 4600 if (Tag) 4601 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4602 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4603 << DS.getConstexprSpecifier(); 4604 else 4605 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4606 << DS.getConstexprSpecifier(); 4607 // Don't emit warnings after this error. 4608 return TagD; 4609 } 4610 4611 DiagnoseFunctionSpecifiers(DS); 4612 4613 if (DS.isFriendSpecified()) { 4614 // If we're dealing with a decl but not a TagDecl, assume that 4615 // whatever routines created it handled the friendship aspect. 4616 if (TagD && !Tag) 4617 return nullptr; 4618 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4619 } 4620 4621 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4622 bool IsExplicitSpecialization = 4623 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4624 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4625 !IsExplicitInstantiation && !IsExplicitSpecialization && 4626 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4627 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4628 // nested-name-specifier unless it is an explicit instantiation 4629 // or an explicit specialization. 4630 // 4631 // FIXME: We allow class template partial specializations here too, per the 4632 // obvious intent of DR1819. 4633 // 4634 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4635 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4636 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4637 return nullptr; 4638 } 4639 4640 // Track whether this decl-specifier declares anything. 4641 bool DeclaresAnything = true; 4642 4643 // Handle anonymous struct definitions. 4644 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4645 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4646 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4647 if (getLangOpts().CPlusPlus || 4648 Record->getDeclContext()->isRecord()) { 4649 // If CurContext is a DeclContext that can contain statements, 4650 // RecursiveASTVisitor won't visit the decls that 4651 // BuildAnonymousStructOrUnion() will put into CurContext. 4652 // Also store them here so that they can be part of the 4653 // DeclStmt that gets created in this case. 4654 // FIXME: Also return the IndirectFieldDecls created by 4655 // BuildAnonymousStructOr union, for the same reason? 4656 if (CurContext->isFunctionOrMethod()) 4657 AnonRecord = Record; 4658 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4659 Context.getPrintingPolicy()); 4660 } 4661 4662 DeclaresAnything = false; 4663 } 4664 } 4665 4666 // C11 6.7.2.1p2: 4667 // A struct-declaration that does not declare an anonymous structure or 4668 // anonymous union shall contain a struct-declarator-list. 4669 // 4670 // This rule also existed in C89 and C99; the grammar for struct-declaration 4671 // did not permit a struct-declaration without a struct-declarator-list. 4672 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4673 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4674 // Check for Microsoft C extension: anonymous struct/union member. 4675 // Handle 2 kinds of anonymous struct/union: 4676 // struct STRUCT; 4677 // union UNION; 4678 // and 4679 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4680 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4681 if ((Tag && Tag->getDeclName()) || 4682 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4683 RecordDecl *Record = nullptr; 4684 if (Tag) 4685 Record = dyn_cast<RecordDecl>(Tag); 4686 else if (const RecordType *RT = 4687 DS.getRepAsType().get()->getAsStructureType()) 4688 Record = RT->getDecl(); 4689 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4690 Record = UT->getDecl(); 4691 4692 if (Record && getLangOpts().MicrosoftExt) { 4693 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4694 << Record->isUnion() << DS.getSourceRange(); 4695 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4696 } 4697 4698 DeclaresAnything = false; 4699 } 4700 } 4701 4702 // Skip all the checks below if we have a type error. 4703 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4704 (TagD && TagD->isInvalidDecl())) 4705 return TagD; 4706 4707 if (getLangOpts().CPlusPlus && 4708 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4709 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4710 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4711 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4712 DeclaresAnything = false; 4713 4714 if (!DS.isMissingDeclaratorOk()) { 4715 // Customize diagnostic for a typedef missing a name. 4716 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4717 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4718 << DS.getSourceRange(); 4719 else 4720 DeclaresAnything = false; 4721 } 4722 4723 if (DS.isModulePrivateSpecified() && 4724 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4725 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4726 << Tag->getTagKind() 4727 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4728 4729 ActOnDocumentableDecl(TagD); 4730 4731 // C 6.7/2: 4732 // A declaration [...] shall declare at least a declarator [...], a tag, 4733 // or the members of an enumeration. 4734 // C++ [dcl.dcl]p3: 4735 // [If there are no declarators], and except for the declaration of an 4736 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4737 // names into the program, or shall redeclare a name introduced by a 4738 // previous declaration. 4739 if (!DeclaresAnything) { 4740 // In C, we allow this as a (popular) extension / bug. Don't bother 4741 // producing further diagnostics for redundant qualifiers after this. 4742 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4743 ? diag::err_no_declarators 4744 : diag::ext_no_declarators) 4745 << DS.getSourceRange(); 4746 return TagD; 4747 } 4748 4749 // C++ [dcl.stc]p1: 4750 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4751 // init-declarator-list of the declaration shall not be empty. 4752 // C++ [dcl.fct.spec]p1: 4753 // If a cv-qualifier appears in a decl-specifier-seq, the 4754 // init-declarator-list of the declaration shall not be empty. 4755 // 4756 // Spurious qualifiers here appear to be valid in C. 4757 unsigned DiagID = diag::warn_standalone_specifier; 4758 if (getLangOpts().CPlusPlus) 4759 DiagID = diag::ext_standalone_specifier; 4760 4761 // Note that a linkage-specification sets a storage class, but 4762 // 'extern "C" struct foo;' is actually valid and not theoretically 4763 // useless. 4764 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4765 if (SCS == DeclSpec::SCS_mutable) 4766 // Since mutable is not a viable storage class specifier in C, there is 4767 // no reason to treat it as an extension. Instead, diagnose as an error. 4768 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4769 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4770 Diag(DS.getStorageClassSpecLoc(), DiagID) 4771 << DeclSpec::getSpecifierName(SCS); 4772 } 4773 4774 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4775 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4776 << DeclSpec::getSpecifierName(TSCS); 4777 if (DS.getTypeQualifiers()) { 4778 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4779 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4780 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4781 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4782 // Restrict is covered above. 4783 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4784 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4785 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4786 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4787 } 4788 4789 // Warn about ignored type attributes, for example: 4790 // __attribute__((aligned)) struct A; 4791 // Attributes should be placed after tag to apply to type declaration. 4792 if (!DS.getAttributes().empty()) { 4793 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4794 if (TypeSpecType == DeclSpec::TST_class || 4795 TypeSpecType == DeclSpec::TST_struct || 4796 TypeSpecType == DeclSpec::TST_interface || 4797 TypeSpecType == DeclSpec::TST_union || 4798 TypeSpecType == DeclSpec::TST_enum) { 4799 for (const ParsedAttr &AL : DS.getAttributes()) 4800 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4801 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4802 } 4803 } 4804 4805 return TagD; 4806 } 4807 4808 /// We are trying to inject an anonymous member into the given scope; 4809 /// check if there's an existing declaration that can't be overloaded. 4810 /// 4811 /// \return true if this is a forbidden redeclaration 4812 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4813 Scope *S, 4814 DeclContext *Owner, 4815 DeclarationName Name, 4816 SourceLocation NameLoc, 4817 bool IsUnion) { 4818 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4819 Sema::ForVisibleRedeclaration); 4820 if (!SemaRef.LookupName(R, S)) return false; 4821 4822 // Pick a representative declaration. 4823 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4824 assert(PrevDecl && "Expected a non-null Decl"); 4825 4826 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4827 return false; 4828 4829 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4830 << IsUnion << Name; 4831 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4832 4833 return true; 4834 } 4835 4836 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4837 /// anonymous struct or union AnonRecord into the owning context Owner 4838 /// and scope S. This routine will be invoked just after we realize 4839 /// that an unnamed union or struct is actually an anonymous union or 4840 /// struct, e.g., 4841 /// 4842 /// @code 4843 /// union { 4844 /// int i; 4845 /// float f; 4846 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4847 /// // f into the surrounding scope.x 4848 /// @endcode 4849 /// 4850 /// This routine is recursive, injecting the names of nested anonymous 4851 /// structs/unions into the owning context and scope as well. 4852 static bool 4853 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4854 RecordDecl *AnonRecord, AccessSpecifier AS, 4855 SmallVectorImpl<NamedDecl *> &Chaining) { 4856 bool Invalid = false; 4857 4858 // Look every FieldDecl and IndirectFieldDecl with a name. 4859 for (auto *D : AnonRecord->decls()) { 4860 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4861 cast<NamedDecl>(D)->getDeclName()) { 4862 ValueDecl *VD = cast<ValueDecl>(D); 4863 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4864 VD->getLocation(), 4865 AnonRecord->isUnion())) { 4866 // C++ [class.union]p2: 4867 // The names of the members of an anonymous union shall be 4868 // distinct from the names of any other entity in the 4869 // scope in which the anonymous union is declared. 4870 Invalid = true; 4871 } else { 4872 // C++ [class.union]p2: 4873 // For the purpose of name lookup, after the anonymous union 4874 // definition, the members of the anonymous union are 4875 // considered to have been defined in the scope in which the 4876 // anonymous union is declared. 4877 unsigned OldChainingSize = Chaining.size(); 4878 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4879 Chaining.append(IF->chain_begin(), IF->chain_end()); 4880 else 4881 Chaining.push_back(VD); 4882 4883 assert(Chaining.size() >= 2); 4884 NamedDecl **NamedChain = 4885 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4886 for (unsigned i = 0; i < Chaining.size(); i++) 4887 NamedChain[i] = Chaining[i]; 4888 4889 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4890 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4891 VD->getType(), {NamedChain, Chaining.size()}); 4892 4893 for (const auto *Attr : VD->attrs()) 4894 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4895 4896 IndirectField->setAccess(AS); 4897 IndirectField->setImplicit(); 4898 SemaRef.PushOnScopeChains(IndirectField, S); 4899 4900 // That includes picking up the appropriate access specifier. 4901 if (AS != AS_none) IndirectField->setAccess(AS); 4902 4903 Chaining.resize(OldChainingSize); 4904 } 4905 } 4906 } 4907 4908 return Invalid; 4909 } 4910 4911 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4912 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4913 /// illegal input values are mapped to SC_None. 4914 static StorageClass 4915 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4916 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4917 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4918 "Parser allowed 'typedef' as storage class VarDecl."); 4919 switch (StorageClassSpec) { 4920 case DeclSpec::SCS_unspecified: return SC_None; 4921 case DeclSpec::SCS_extern: 4922 if (DS.isExternInLinkageSpec()) 4923 return SC_None; 4924 return SC_Extern; 4925 case DeclSpec::SCS_static: return SC_Static; 4926 case DeclSpec::SCS_auto: return SC_Auto; 4927 case DeclSpec::SCS_register: return SC_Register; 4928 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4929 // Illegal SCSs map to None: error reporting is up to the caller. 4930 case DeclSpec::SCS_mutable: // Fall through. 4931 case DeclSpec::SCS_typedef: return SC_None; 4932 } 4933 llvm_unreachable("unknown storage class specifier"); 4934 } 4935 4936 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4937 assert(Record->hasInClassInitializer()); 4938 4939 for (const auto *I : Record->decls()) { 4940 const auto *FD = dyn_cast<FieldDecl>(I); 4941 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4942 FD = IFD->getAnonField(); 4943 if (FD && FD->hasInClassInitializer()) 4944 return FD->getLocation(); 4945 } 4946 4947 llvm_unreachable("couldn't find in-class initializer"); 4948 } 4949 4950 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4951 SourceLocation DefaultInitLoc) { 4952 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4953 return; 4954 4955 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4956 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4957 } 4958 4959 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4960 CXXRecordDecl *AnonUnion) { 4961 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4962 return; 4963 4964 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4965 } 4966 4967 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4968 /// anonymous structure or union. Anonymous unions are a C++ feature 4969 /// (C++ [class.union]) and a C11 feature; anonymous structures 4970 /// are a C11 feature and GNU C++ extension. 4971 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4972 AccessSpecifier AS, 4973 RecordDecl *Record, 4974 const PrintingPolicy &Policy) { 4975 DeclContext *Owner = Record->getDeclContext(); 4976 4977 // Diagnose whether this anonymous struct/union is an extension. 4978 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4979 Diag(Record->getLocation(), diag::ext_anonymous_union); 4980 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4981 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4982 else if (!Record->isUnion() && !getLangOpts().C11) 4983 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4984 4985 // C and C++ require different kinds of checks for anonymous 4986 // structs/unions. 4987 bool Invalid = false; 4988 if (getLangOpts().CPlusPlus) { 4989 const char *PrevSpec = nullptr; 4990 if (Record->isUnion()) { 4991 // C++ [class.union]p6: 4992 // C++17 [class.union.anon]p2: 4993 // Anonymous unions declared in a named namespace or in the 4994 // global namespace shall be declared static. 4995 unsigned DiagID; 4996 DeclContext *OwnerScope = Owner->getRedeclContext(); 4997 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4998 (OwnerScope->isTranslationUnit() || 4999 (OwnerScope->isNamespace() && 5000 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5001 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5002 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5003 5004 // Recover by adding 'static'. 5005 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5006 PrevSpec, DiagID, Policy); 5007 } 5008 // C++ [class.union]p6: 5009 // A storage class is not allowed in a declaration of an 5010 // anonymous union in a class scope. 5011 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5012 isa<RecordDecl>(Owner)) { 5013 Diag(DS.getStorageClassSpecLoc(), 5014 diag::err_anonymous_union_with_storage_spec) 5015 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5016 5017 // Recover by removing the storage specifier. 5018 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5019 SourceLocation(), 5020 PrevSpec, DiagID, Context.getPrintingPolicy()); 5021 } 5022 } 5023 5024 // Ignore const/volatile/restrict qualifiers. 5025 if (DS.getTypeQualifiers()) { 5026 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5027 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5028 << Record->isUnion() << "const" 5029 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5030 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5031 Diag(DS.getVolatileSpecLoc(), 5032 diag::ext_anonymous_struct_union_qualified) 5033 << Record->isUnion() << "volatile" 5034 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5035 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5036 Diag(DS.getRestrictSpecLoc(), 5037 diag::ext_anonymous_struct_union_qualified) 5038 << Record->isUnion() << "restrict" 5039 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5040 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5041 Diag(DS.getAtomicSpecLoc(), 5042 diag::ext_anonymous_struct_union_qualified) 5043 << Record->isUnion() << "_Atomic" 5044 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5045 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5046 Diag(DS.getUnalignedSpecLoc(), 5047 diag::ext_anonymous_struct_union_qualified) 5048 << Record->isUnion() << "__unaligned" 5049 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5050 5051 DS.ClearTypeQualifiers(); 5052 } 5053 5054 // C++ [class.union]p2: 5055 // The member-specification of an anonymous union shall only 5056 // define non-static data members. [Note: nested types and 5057 // functions cannot be declared within an anonymous union. ] 5058 for (auto *Mem : Record->decls()) { 5059 // Ignore invalid declarations; we already diagnosed them. 5060 if (Mem->isInvalidDecl()) 5061 continue; 5062 5063 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5064 // C++ [class.union]p3: 5065 // An anonymous union shall not have private or protected 5066 // members (clause 11). 5067 assert(FD->getAccess() != AS_none); 5068 if (FD->getAccess() != AS_public) { 5069 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5070 << Record->isUnion() << (FD->getAccess() == AS_protected); 5071 Invalid = true; 5072 } 5073 5074 // C++ [class.union]p1 5075 // An object of a class with a non-trivial constructor, a non-trivial 5076 // copy constructor, a non-trivial destructor, or a non-trivial copy 5077 // assignment operator cannot be a member of a union, nor can an 5078 // array of such objects. 5079 if (CheckNontrivialField(FD)) 5080 Invalid = true; 5081 } else if (Mem->isImplicit()) { 5082 // Any implicit members are fine. 5083 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5084 // This is a type that showed up in an 5085 // elaborated-type-specifier inside the anonymous struct or 5086 // union, but which actually declares a type outside of the 5087 // anonymous struct or union. It's okay. 5088 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5089 if (!MemRecord->isAnonymousStructOrUnion() && 5090 MemRecord->getDeclName()) { 5091 // Visual C++ allows type definition in anonymous struct or union. 5092 if (getLangOpts().MicrosoftExt) 5093 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5094 << Record->isUnion(); 5095 else { 5096 // This is a nested type declaration. 5097 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5098 << Record->isUnion(); 5099 Invalid = true; 5100 } 5101 } else { 5102 // This is an anonymous type definition within another anonymous type. 5103 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5104 // not part of standard C++. 5105 Diag(MemRecord->getLocation(), 5106 diag::ext_anonymous_record_with_anonymous_type) 5107 << Record->isUnion(); 5108 } 5109 } else if (isa<AccessSpecDecl>(Mem)) { 5110 // Any access specifier is fine. 5111 } else if (isa<StaticAssertDecl>(Mem)) { 5112 // In C++1z, static_assert declarations are also fine. 5113 } else { 5114 // We have something that isn't a non-static data 5115 // member. Complain about it. 5116 unsigned DK = diag::err_anonymous_record_bad_member; 5117 if (isa<TypeDecl>(Mem)) 5118 DK = diag::err_anonymous_record_with_type; 5119 else if (isa<FunctionDecl>(Mem)) 5120 DK = diag::err_anonymous_record_with_function; 5121 else if (isa<VarDecl>(Mem)) 5122 DK = diag::err_anonymous_record_with_static; 5123 5124 // Visual C++ allows type definition in anonymous struct or union. 5125 if (getLangOpts().MicrosoftExt && 5126 DK == diag::err_anonymous_record_with_type) 5127 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5128 << Record->isUnion(); 5129 else { 5130 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5131 Invalid = true; 5132 } 5133 } 5134 } 5135 5136 // C++11 [class.union]p8 (DR1460): 5137 // At most one variant member of a union may have a 5138 // brace-or-equal-initializer. 5139 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5140 Owner->isRecord()) 5141 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5142 cast<CXXRecordDecl>(Record)); 5143 } 5144 5145 if (!Record->isUnion() && !Owner->isRecord()) { 5146 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5147 << getLangOpts().CPlusPlus; 5148 Invalid = true; 5149 } 5150 5151 // C++ [dcl.dcl]p3: 5152 // [If there are no declarators], and except for the declaration of an 5153 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5154 // names into the program 5155 // C++ [class.mem]p2: 5156 // each such member-declaration shall either declare at least one member 5157 // name of the class or declare at least one unnamed bit-field 5158 // 5159 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5160 if (getLangOpts().CPlusPlus && Record->field_empty()) 5161 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5162 5163 // Mock up a declarator. 5164 Declarator Dc(DS, DeclaratorContext::MemberContext); 5165 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5166 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5167 5168 // Create a declaration for this anonymous struct/union. 5169 NamedDecl *Anon = nullptr; 5170 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5171 Anon = FieldDecl::Create( 5172 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5173 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5174 /*BitWidth=*/nullptr, /*Mutable=*/false, 5175 /*InitStyle=*/ICIS_NoInit); 5176 Anon->setAccess(AS); 5177 ProcessDeclAttributes(S, Anon, Dc); 5178 5179 if (getLangOpts().CPlusPlus) 5180 FieldCollector->Add(cast<FieldDecl>(Anon)); 5181 } else { 5182 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5183 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5184 if (SCSpec == DeclSpec::SCS_mutable) { 5185 // mutable can only appear on non-static class members, so it's always 5186 // an error here 5187 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5188 Invalid = true; 5189 SC = SC_None; 5190 } 5191 5192 assert(DS.getAttributes().empty() && "No attribute expected"); 5193 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5194 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5195 Context.getTypeDeclType(Record), TInfo, SC); 5196 5197 // Default-initialize the implicit variable. This initialization will be 5198 // trivial in almost all cases, except if a union member has an in-class 5199 // initializer: 5200 // union { int n = 0; }; 5201 ActOnUninitializedDecl(Anon); 5202 } 5203 Anon->setImplicit(); 5204 5205 // Mark this as an anonymous struct/union type. 5206 Record->setAnonymousStructOrUnion(true); 5207 5208 // Add the anonymous struct/union object to the current 5209 // context. We'll be referencing this object when we refer to one of 5210 // its members. 5211 Owner->addDecl(Anon); 5212 5213 // Inject the members of the anonymous struct/union into the owning 5214 // context and into the identifier resolver chain for name lookup 5215 // purposes. 5216 SmallVector<NamedDecl*, 2> Chain; 5217 Chain.push_back(Anon); 5218 5219 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5220 Invalid = true; 5221 5222 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5223 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5224 MangleNumberingContext *MCtx; 5225 Decl *ManglingContextDecl; 5226 std::tie(MCtx, ManglingContextDecl) = 5227 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5228 if (MCtx) { 5229 Context.setManglingNumber( 5230 NewVD, MCtx->getManglingNumber( 5231 NewVD, getMSManglingNumber(getLangOpts(), S))); 5232 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5233 } 5234 } 5235 } 5236 5237 if (Invalid) 5238 Anon->setInvalidDecl(); 5239 5240 return Anon; 5241 } 5242 5243 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5244 /// Microsoft C anonymous structure. 5245 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5246 /// Example: 5247 /// 5248 /// struct A { int a; }; 5249 /// struct B { struct A; int b; }; 5250 /// 5251 /// void foo() { 5252 /// B var; 5253 /// var.a = 3; 5254 /// } 5255 /// 5256 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5257 RecordDecl *Record) { 5258 assert(Record && "expected a record!"); 5259 5260 // Mock up a declarator. 5261 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5262 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5263 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5264 5265 auto *ParentDecl = cast<RecordDecl>(CurContext); 5266 QualType RecTy = Context.getTypeDeclType(Record); 5267 5268 // Create a declaration for this anonymous struct. 5269 NamedDecl *Anon = 5270 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5271 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5272 /*BitWidth=*/nullptr, /*Mutable=*/false, 5273 /*InitStyle=*/ICIS_NoInit); 5274 Anon->setImplicit(); 5275 5276 // Add the anonymous struct object to the current context. 5277 CurContext->addDecl(Anon); 5278 5279 // Inject the members of the anonymous struct into the current 5280 // context and into the identifier resolver chain for name lookup 5281 // purposes. 5282 SmallVector<NamedDecl*, 2> Chain; 5283 Chain.push_back(Anon); 5284 5285 RecordDecl *RecordDef = Record->getDefinition(); 5286 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5287 diag::err_field_incomplete_or_sizeless) || 5288 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5289 AS_none, Chain)) { 5290 Anon->setInvalidDecl(); 5291 ParentDecl->setInvalidDecl(); 5292 } 5293 5294 return Anon; 5295 } 5296 5297 /// GetNameForDeclarator - Determine the full declaration name for the 5298 /// given Declarator. 5299 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5300 return GetNameFromUnqualifiedId(D.getName()); 5301 } 5302 5303 /// Retrieves the declaration name from a parsed unqualified-id. 5304 DeclarationNameInfo 5305 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5306 DeclarationNameInfo NameInfo; 5307 NameInfo.setLoc(Name.StartLocation); 5308 5309 switch (Name.getKind()) { 5310 5311 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5312 case UnqualifiedIdKind::IK_Identifier: 5313 NameInfo.setName(Name.Identifier); 5314 return NameInfo; 5315 5316 case UnqualifiedIdKind::IK_DeductionGuideName: { 5317 // C++ [temp.deduct.guide]p3: 5318 // The simple-template-id shall name a class template specialization. 5319 // The template-name shall be the same identifier as the template-name 5320 // of the simple-template-id. 5321 // These together intend to imply that the template-name shall name a 5322 // class template. 5323 // FIXME: template<typename T> struct X {}; 5324 // template<typename T> using Y = X<T>; 5325 // Y(int) -> Y<int>; 5326 // satisfies these rules but does not name a class template. 5327 TemplateName TN = Name.TemplateName.get().get(); 5328 auto *Template = TN.getAsTemplateDecl(); 5329 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5330 Diag(Name.StartLocation, 5331 diag::err_deduction_guide_name_not_class_template) 5332 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5333 if (Template) 5334 Diag(Template->getLocation(), diag::note_template_decl_here); 5335 return DeclarationNameInfo(); 5336 } 5337 5338 NameInfo.setName( 5339 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5340 return NameInfo; 5341 } 5342 5343 case UnqualifiedIdKind::IK_OperatorFunctionId: 5344 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5345 Name.OperatorFunctionId.Operator)); 5346 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5347 = Name.OperatorFunctionId.SymbolLocations[0]; 5348 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5349 = Name.EndLocation.getRawEncoding(); 5350 return NameInfo; 5351 5352 case UnqualifiedIdKind::IK_LiteralOperatorId: 5353 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5354 Name.Identifier)); 5355 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5356 return NameInfo; 5357 5358 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5359 TypeSourceInfo *TInfo; 5360 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5361 if (Ty.isNull()) 5362 return DeclarationNameInfo(); 5363 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5364 Context.getCanonicalType(Ty))); 5365 NameInfo.setNamedTypeInfo(TInfo); 5366 return NameInfo; 5367 } 5368 5369 case UnqualifiedIdKind::IK_ConstructorName: { 5370 TypeSourceInfo *TInfo; 5371 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5372 if (Ty.isNull()) 5373 return DeclarationNameInfo(); 5374 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5375 Context.getCanonicalType(Ty))); 5376 NameInfo.setNamedTypeInfo(TInfo); 5377 return NameInfo; 5378 } 5379 5380 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5381 // In well-formed code, we can only have a constructor 5382 // template-id that refers to the current context, so go there 5383 // to find the actual type being constructed. 5384 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5385 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5386 return DeclarationNameInfo(); 5387 5388 // Determine the type of the class being constructed. 5389 QualType CurClassType = Context.getTypeDeclType(CurClass); 5390 5391 // FIXME: Check two things: that the template-id names the same type as 5392 // CurClassType, and that the template-id does not occur when the name 5393 // was qualified. 5394 5395 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5396 Context.getCanonicalType(CurClassType))); 5397 // FIXME: should we retrieve TypeSourceInfo? 5398 NameInfo.setNamedTypeInfo(nullptr); 5399 return NameInfo; 5400 } 5401 5402 case UnqualifiedIdKind::IK_DestructorName: { 5403 TypeSourceInfo *TInfo; 5404 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5405 if (Ty.isNull()) 5406 return DeclarationNameInfo(); 5407 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5408 Context.getCanonicalType(Ty))); 5409 NameInfo.setNamedTypeInfo(TInfo); 5410 return NameInfo; 5411 } 5412 5413 case UnqualifiedIdKind::IK_TemplateId: { 5414 TemplateName TName = Name.TemplateId->Template.get(); 5415 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5416 return Context.getNameForTemplate(TName, TNameLoc); 5417 } 5418 5419 } // switch (Name.getKind()) 5420 5421 llvm_unreachable("Unknown name kind"); 5422 } 5423 5424 static QualType getCoreType(QualType Ty) { 5425 do { 5426 if (Ty->isPointerType() || Ty->isReferenceType()) 5427 Ty = Ty->getPointeeType(); 5428 else if (Ty->isArrayType()) 5429 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5430 else 5431 return Ty.withoutLocalFastQualifiers(); 5432 } while (true); 5433 } 5434 5435 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5436 /// and Definition have "nearly" matching parameters. This heuristic is 5437 /// used to improve diagnostics in the case where an out-of-line function 5438 /// definition doesn't match any declaration within the class or namespace. 5439 /// Also sets Params to the list of indices to the parameters that differ 5440 /// between the declaration and the definition. If hasSimilarParameters 5441 /// returns true and Params is empty, then all of the parameters match. 5442 static bool hasSimilarParameters(ASTContext &Context, 5443 FunctionDecl *Declaration, 5444 FunctionDecl *Definition, 5445 SmallVectorImpl<unsigned> &Params) { 5446 Params.clear(); 5447 if (Declaration->param_size() != Definition->param_size()) 5448 return false; 5449 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5450 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5451 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5452 5453 // The parameter types are identical 5454 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5455 continue; 5456 5457 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5458 QualType DefParamBaseTy = getCoreType(DefParamTy); 5459 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5460 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5461 5462 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5463 (DeclTyName && DeclTyName == DefTyName)) 5464 Params.push_back(Idx); 5465 else // The two parameters aren't even close 5466 return false; 5467 } 5468 5469 return true; 5470 } 5471 5472 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5473 /// declarator needs to be rebuilt in the current instantiation. 5474 /// Any bits of declarator which appear before the name are valid for 5475 /// consideration here. That's specifically the type in the decl spec 5476 /// and the base type in any member-pointer chunks. 5477 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5478 DeclarationName Name) { 5479 // The types we specifically need to rebuild are: 5480 // - typenames, typeofs, and decltypes 5481 // - types which will become injected class names 5482 // Of course, we also need to rebuild any type referencing such a 5483 // type. It's safest to just say "dependent", but we call out a 5484 // few cases here. 5485 5486 DeclSpec &DS = D.getMutableDeclSpec(); 5487 switch (DS.getTypeSpecType()) { 5488 case DeclSpec::TST_typename: 5489 case DeclSpec::TST_typeofType: 5490 case DeclSpec::TST_underlyingType: 5491 case DeclSpec::TST_atomic: { 5492 // Grab the type from the parser. 5493 TypeSourceInfo *TSI = nullptr; 5494 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5495 if (T.isNull() || !T->isDependentType()) break; 5496 5497 // Make sure there's a type source info. This isn't really much 5498 // of a waste; most dependent types should have type source info 5499 // attached already. 5500 if (!TSI) 5501 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5502 5503 // Rebuild the type in the current instantiation. 5504 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5505 if (!TSI) return true; 5506 5507 // Store the new type back in the decl spec. 5508 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5509 DS.UpdateTypeRep(LocType); 5510 break; 5511 } 5512 5513 case DeclSpec::TST_decltype: 5514 case DeclSpec::TST_typeofExpr: { 5515 Expr *E = DS.getRepAsExpr(); 5516 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5517 if (Result.isInvalid()) return true; 5518 DS.UpdateExprRep(Result.get()); 5519 break; 5520 } 5521 5522 default: 5523 // Nothing to do for these decl specs. 5524 break; 5525 } 5526 5527 // It doesn't matter what order we do this in. 5528 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5529 DeclaratorChunk &Chunk = D.getTypeObject(I); 5530 5531 // The only type information in the declarator which can come 5532 // before the declaration name is the base type of a member 5533 // pointer. 5534 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5535 continue; 5536 5537 // Rebuild the scope specifier in-place. 5538 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5539 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5540 return true; 5541 } 5542 5543 return false; 5544 } 5545 5546 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5547 D.setFunctionDefinitionKind(FDK_Declaration); 5548 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5549 5550 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5551 Dcl && Dcl->getDeclContext()->isFileContext()) 5552 Dcl->setTopLevelDeclInObjCContainer(); 5553 5554 if (getLangOpts().OpenCL) 5555 setCurrentOpenCLExtensionForDecl(Dcl); 5556 5557 return Dcl; 5558 } 5559 5560 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5561 /// If T is the name of a class, then each of the following shall have a 5562 /// name different from T: 5563 /// - every static data member of class T; 5564 /// - every member function of class T 5565 /// - every member of class T that is itself a type; 5566 /// \returns true if the declaration name violates these rules. 5567 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5568 DeclarationNameInfo NameInfo) { 5569 DeclarationName Name = NameInfo.getName(); 5570 5571 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5572 while (Record && Record->isAnonymousStructOrUnion()) 5573 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5574 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5575 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5576 return true; 5577 } 5578 5579 return false; 5580 } 5581 5582 /// Diagnose a declaration whose declarator-id has the given 5583 /// nested-name-specifier. 5584 /// 5585 /// \param SS The nested-name-specifier of the declarator-id. 5586 /// 5587 /// \param DC The declaration context to which the nested-name-specifier 5588 /// resolves. 5589 /// 5590 /// \param Name The name of the entity being declared. 5591 /// 5592 /// \param Loc The location of the name of the entity being declared. 5593 /// 5594 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5595 /// we're declaring an explicit / partial specialization / instantiation. 5596 /// 5597 /// \returns true if we cannot safely recover from this error, false otherwise. 5598 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5599 DeclarationName Name, 5600 SourceLocation Loc, bool IsTemplateId) { 5601 DeclContext *Cur = CurContext; 5602 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5603 Cur = Cur->getParent(); 5604 5605 // If the user provided a superfluous scope specifier that refers back to the 5606 // class in which the entity is already declared, diagnose and ignore it. 5607 // 5608 // class X { 5609 // void X::f(); 5610 // }; 5611 // 5612 // Note, it was once ill-formed to give redundant qualification in all 5613 // contexts, but that rule was removed by DR482. 5614 if (Cur->Equals(DC)) { 5615 if (Cur->isRecord()) { 5616 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5617 : diag::err_member_extra_qualification) 5618 << Name << FixItHint::CreateRemoval(SS.getRange()); 5619 SS.clear(); 5620 } else { 5621 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5622 } 5623 return false; 5624 } 5625 5626 // Check whether the qualifying scope encloses the scope of the original 5627 // declaration. For a template-id, we perform the checks in 5628 // CheckTemplateSpecializationScope. 5629 if (!Cur->Encloses(DC) && !IsTemplateId) { 5630 if (Cur->isRecord()) 5631 Diag(Loc, diag::err_member_qualification) 5632 << Name << SS.getRange(); 5633 else if (isa<TranslationUnitDecl>(DC)) 5634 Diag(Loc, diag::err_invalid_declarator_global_scope) 5635 << Name << SS.getRange(); 5636 else if (isa<FunctionDecl>(Cur)) 5637 Diag(Loc, diag::err_invalid_declarator_in_function) 5638 << Name << SS.getRange(); 5639 else if (isa<BlockDecl>(Cur)) 5640 Diag(Loc, diag::err_invalid_declarator_in_block) 5641 << Name << SS.getRange(); 5642 else 5643 Diag(Loc, diag::err_invalid_declarator_scope) 5644 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5645 5646 return true; 5647 } 5648 5649 if (Cur->isRecord()) { 5650 // Cannot qualify members within a class. 5651 Diag(Loc, diag::err_member_qualification) 5652 << Name << SS.getRange(); 5653 SS.clear(); 5654 5655 // C++ constructors and destructors with incorrect scopes can break 5656 // our AST invariants by having the wrong underlying types. If 5657 // that's the case, then drop this declaration entirely. 5658 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5659 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5660 !Context.hasSameType(Name.getCXXNameType(), 5661 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5662 return true; 5663 5664 return false; 5665 } 5666 5667 // C++11 [dcl.meaning]p1: 5668 // [...] "The nested-name-specifier of the qualified declarator-id shall 5669 // not begin with a decltype-specifer" 5670 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5671 while (SpecLoc.getPrefix()) 5672 SpecLoc = SpecLoc.getPrefix(); 5673 if (dyn_cast_or_null<DecltypeType>( 5674 SpecLoc.getNestedNameSpecifier()->getAsType())) 5675 Diag(Loc, diag::err_decltype_in_declarator) 5676 << SpecLoc.getTypeLoc().getSourceRange(); 5677 5678 return false; 5679 } 5680 5681 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5682 MultiTemplateParamsArg TemplateParamLists) { 5683 // TODO: consider using NameInfo for diagnostic. 5684 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5685 DeclarationName Name = NameInfo.getName(); 5686 5687 // All of these full declarators require an identifier. If it doesn't have 5688 // one, the ParsedFreeStandingDeclSpec action should be used. 5689 if (D.isDecompositionDeclarator()) { 5690 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5691 } else if (!Name) { 5692 if (!D.isInvalidType()) // Reject this if we think it is valid. 5693 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5694 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5695 return nullptr; 5696 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5697 return nullptr; 5698 5699 // The scope passed in may not be a decl scope. Zip up the scope tree until 5700 // we find one that is. 5701 while ((S->getFlags() & Scope::DeclScope) == 0 || 5702 (S->getFlags() & Scope::TemplateParamScope) != 0) 5703 S = S->getParent(); 5704 5705 DeclContext *DC = CurContext; 5706 if (D.getCXXScopeSpec().isInvalid()) 5707 D.setInvalidType(); 5708 else if (D.getCXXScopeSpec().isSet()) { 5709 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5710 UPPC_DeclarationQualifier)) 5711 return nullptr; 5712 5713 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5714 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5715 if (!DC || isa<EnumDecl>(DC)) { 5716 // If we could not compute the declaration context, it's because the 5717 // declaration context is dependent but does not refer to a class, 5718 // class template, or class template partial specialization. Complain 5719 // and return early, to avoid the coming semantic disaster. 5720 Diag(D.getIdentifierLoc(), 5721 diag::err_template_qualified_declarator_no_match) 5722 << D.getCXXScopeSpec().getScopeRep() 5723 << D.getCXXScopeSpec().getRange(); 5724 return nullptr; 5725 } 5726 bool IsDependentContext = DC->isDependentContext(); 5727 5728 if (!IsDependentContext && 5729 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5730 return nullptr; 5731 5732 // If a class is incomplete, do not parse entities inside it. 5733 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5734 Diag(D.getIdentifierLoc(), 5735 diag::err_member_def_undefined_record) 5736 << Name << DC << D.getCXXScopeSpec().getRange(); 5737 return nullptr; 5738 } 5739 if (!D.getDeclSpec().isFriendSpecified()) { 5740 if (diagnoseQualifiedDeclaration( 5741 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5742 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5743 if (DC->isRecord()) 5744 return nullptr; 5745 5746 D.setInvalidType(); 5747 } 5748 } 5749 5750 // Check whether we need to rebuild the type of the given 5751 // declaration in the current instantiation. 5752 if (EnteringContext && IsDependentContext && 5753 TemplateParamLists.size() != 0) { 5754 ContextRAII SavedContext(*this, DC); 5755 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5756 D.setInvalidType(); 5757 } 5758 } 5759 5760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5761 QualType R = TInfo->getType(); 5762 5763 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5764 UPPC_DeclarationType)) 5765 D.setInvalidType(); 5766 5767 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5768 forRedeclarationInCurContext()); 5769 5770 // See if this is a redefinition of a variable in the same scope. 5771 if (!D.getCXXScopeSpec().isSet()) { 5772 bool IsLinkageLookup = false; 5773 bool CreateBuiltins = false; 5774 5775 // If the declaration we're planning to build will be a function 5776 // or object with linkage, then look for another declaration with 5777 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5778 // 5779 // If the declaration we're planning to build will be declared with 5780 // external linkage in the translation unit, create any builtin with 5781 // the same name. 5782 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5783 /* Do nothing*/; 5784 else if (CurContext->isFunctionOrMethod() && 5785 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5786 R->isFunctionType())) { 5787 IsLinkageLookup = true; 5788 CreateBuiltins = 5789 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5790 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5791 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5792 CreateBuiltins = true; 5793 5794 if (IsLinkageLookup) { 5795 Previous.clear(LookupRedeclarationWithLinkage); 5796 Previous.setRedeclarationKind(ForExternalRedeclaration); 5797 } 5798 5799 LookupName(Previous, S, CreateBuiltins); 5800 } else { // Something like "int foo::x;" 5801 LookupQualifiedName(Previous, DC); 5802 5803 // C++ [dcl.meaning]p1: 5804 // When the declarator-id is qualified, the declaration shall refer to a 5805 // previously declared member of the class or namespace to which the 5806 // qualifier refers (or, in the case of a namespace, of an element of the 5807 // inline namespace set of that namespace (7.3.1)) or to a specialization 5808 // thereof; [...] 5809 // 5810 // Note that we already checked the context above, and that we do not have 5811 // enough information to make sure that Previous contains the declaration 5812 // we want to match. For example, given: 5813 // 5814 // class X { 5815 // void f(); 5816 // void f(float); 5817 // }; 5818 // 5819 // void X::f(int) { } // ill-formed 5820 // 5821 // In this case, Previous will point to the overload set 5822 // containing the two f's declared in X, but neither of them 5823 // matches. 5824 5825 // C++ [dcl.meaning]p1: 5826 // [...] the member shall not merely have been introduced by a 5827 // using-declaration in the scope of the class or namespace nominated by 5828 // the nested-name-specifier of the declarator-id. 5829 RemoveUsingDecls(Previous); 5830 } 5831 5832 if (Previous.isSingleResult() && 5833 Previous.getFoundDecl()->isTemplateParameter()) { 5834 // Maybe we will complain about the shadowed template parameter. 5835 if (!D.isInvalidType()) 5836 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5837 Previous.getFoundDecl()); 5838 5839 // Just pretend that we didn't see the previous declaration. 5840 Previous.clear(); 5841 } 5842 5843 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5844 // Forget that the previous declaration is the injected-class-name. 5845 Previous.clear(); 5846 5847 // In C++, the previous declaration we find might be a tag type 5848 // (class or enum). In this case, the new declaration will hide the 5849 // tag type. Note that this applies to functions, function templates, and 5850 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5851 if (Previous.isSingleTagDecl() && 5852 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5853 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5854 Previous.clear(); 5855 5856 // Check that there are no default arguments other than in the parameters 5857 // of a function declaration (C++ only). 5858 if (getLangOpts().CPlusPlus) 5859 CheckExtraCXXDefaultArguments(D); 5860 5861 NamedDecl *New; 5862 5863 bool AddToScope = true; 5864 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5865 if (TemplateParamLists.size()) { 5866 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5867 return nullptr; 5868 } 5869 5870 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5871 } else if (R->isFunctionType()) { 5872 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5873 TemplateParamLists, 5874 AddToScope); 5875 } else { 5876 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5877 AddToScope); 5878 } 5879 5880 if (!New) 5881 return nullptr; 5882 5883 // If this has an identifier and is not a function template specialization, 5884 // add it to the scope stack. 5885 if (New->getDeclName() && AddToScope) 5886 PushOnScopeChains(New, S); 5887 5888 if (isInOpenMPDeclareTargetContext()) 5889 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5890 5891 return New; 5892 } 5893 5894 /// Helper method to turn variable array types into constant array 5895 /// types in certain situations which would otherwise be errors (for 5896 /// GCC compatibility). 5897 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5898 ASTContext &Context, 5899 bool &SizeIsNegative, 5900 llvm::APSInt &Oversized) { 5901 // This method tries to turn a variable array into a constant 5902 // array even when the size isn't an ICE. This is necessary 5903 // for compatibility with code that depends on gcc's buggy 5904 // constant expression folding, like struct {char x[(int)(char*)2];} 5905 SizeIsNegative = false; 5906 Oversized = 0; 5907 5908 if (T->isDependentType()) 5909 return QualType(); 5910 5911 QualifierCollector Qs; 5912 const Type *Ty = Qs.strip(T); 5913 5914 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5915 QualType Pointee = PTy->getPointeeType(); 5916 QualType FixedType = 5917 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5918 Oversized); 5919 if (FixedType.isNull()) return FixedType; 5920 FixedType = Context.getPointerType(FixedType); 5921 return Qs.apply(Context, FixedType); 5922 } 5923 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5924 QualType Inner = PTy->getInnerType(); 5925 QualType FixedType = 5926 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5927 Oversized); 5928 if (FixedType.isNull()) return FixedType; 5929 FixedType = Context.getParenType(FixedType); 5930 return Qs.apply(Context, FixedType); 5931 } 5932 5933 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5934 if (!VLATy) 5935 return QualType(); 5936 // FIXME: We should probably handle this case 5937 if (VLATy->getElementType()->isVariablyModifiedType()) 5938 return QualType(); 5939 5940 Expr::EvalResult Result; 5941 if (!VLATy->getSizeExpr() || 5942 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5943 return QualType(); 5944 5945 llvm::APSInt Res = Result.Val.getInt(); 5946 5947 // Check whether the array size is negative. 5948 if (Res.isSigned() && Res.isNegative()) { 5949 SizeIsNegative = true; 5950 return QualType(); 5951 } 5952 5953 // Check whether the array is too large to be addressed. 5954 unsigned ActiveSizeBits 5955 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5956 Res); 5957 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5958 Oversized = Res; 5959 return QualType(); 5960 } 5961 5962 return Context.getConstantArrayType( 5963 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5964 } 5965 5966 static void 5967 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5968 SrcTL = SrcTL.getUnqualifiedLoc(); 5969 DstTL = DstTL.getUnqualifiedLoc(); 5970 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5971 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5972 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5973 DstPTL.getPointeeLoc()); 5974 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5975 return; 5976 } 5977 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5978 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5979 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5980 DstPTL.getInnerLoc()); 5981 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5982 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5983 return; 5984 } 5985 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5986 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5987 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5988 TypeLoc DstElemTL = DstATL.getElementLoc(); 5989 DstElemTL.initializeFullCopy(SrcElemTL); 5990 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5991 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5992 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5993 } 5994 5995 /// Helper method to turn variable array types into constant array 5996 /// types in certain situations which would otherwise be errors (for 5997 /// GCC compatibility). 5998 static TypeSourceInfo* 5999 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6000 ASTContext &Context, 6001 bool &SizeIsNegative, 6002 llvm::APSInt &Oversized) { 6003 QualType FixedTy 6004 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6005 SizeIsNegative, Oversized); 6006 if (FixedTy.isNull()) 6007 return nullptr; 6008 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6009 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6010 FixedTInfo->getTypeLoc()); 6011 return FixedTInfo; 6012 } 6013 6014 /// Register the given locally-scoped extern "C" declaration so 6015 /// that it can be found later for redeclarations. We include any extern "C" 6016 /// declaration that is not visible in the translation unit here, not just 6017 /// function-scope declarations. 6018 void 6019 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6020 if (!getLangOpts().CPlusPlus && 6021 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6022 // Don't need to track declarations in the TU in C. 6023 return; 6024 6025 // Note that we have a locally-scoped external with this name. 6026 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6027 } 6028 6029 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6030 // FIXME: We can have multiple results via __attribute__((overloadable)). 6031 auto Result = Context.getExternCContextDecl()->lookup(Name); 6032 return Result.empty() ? nullptr : *Result.begin(); 6033 } 6034 6035 /// Diagnose function specifiers on a declaration of an identifier that 6036 /// does not identify a function. 6037 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6038 // FIXME: We should probably indicate the identifier in question to avoid 6039 // confusion for constructs like "virtual int a(), b;" 6040 if (DS.isVirtualSpecified()) 6041 Diag(DS.getVirtualSpecLoc(), 6042 diag::err_virtual_non_function); 6043 6044 if (DS.hasExplicitSpecifier()) 6045 Diag(DS.getExplicitSpecLoc(), 6046 diag::err_explicit_non_function); 6047 6048 if (DS.isNoreturnSpecified()) 6049 Diag(DS.getNoreturnSpecLoc(), 6050 diag::err_noreturn_non_function); 6051 } 6052 6053 NamedDecl* 6054 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6055 TypeSourceInfo *TInfo, LookupResult &Previous) { 6056 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6057 if (D.getCXXScopeSpec().isSet()) { 6058 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6059 << D.getCXXScopeSpec().getRange(); 6060 D.setInvalidType(); 6061 // Pretend we didn't see the scope specifier. 6062 DC = CurContext; 6063 Previous.clear(); 6064 } 6065 6066 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6067 6068 if (D.getDeclSpec().isInlineSpecified()) 6069 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6070 << getLangOpts().CPlusPlus17; 6071 if (D.getDeclSpec().hasConstexprSpecifier()) 6072 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6073 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6074 6075 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6076 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6077 Diag(D.getName().StartLocation, 6078 diag::err_deduction_guide_invalid_specifier) 6079 << "typedef"; 6080 else 6081 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6082 << D.getName().getSourceRange(); 6083 return nullptr; 6084 } 6085 6086 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6087 if (!NewTD) return nullptr; 6088 6089 // Handle attributes prior to checking for duplicates in MergeVarDecl 6090 ProcessDeclAttributes(S, NewTD, D); 6091 6092 CheckTypedefForVariablyModifiedType(S, NewTD); 6093 6094 bool Redeclaration = D.isRedeclaration(); 6095 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6096 D.setRedeclaration(Redeclaration); 6097 return ND; 6098 } 6099 6100 void 6101 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6102 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6103 // then it shall have block scope. 6104 // Note that variably modified types must be fixed before merging the decl so 6105 // that redeclarations will match. 6106 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6107 QualType T = TInfo->getType(); 6108 if (T->isVariablyModifiedType()) { 6109 setFunctionHasBranchProtectedScope(); 6110 6111 if (S->getFnParent() == nullptr) { 6112 bool SizeIsNegative; 6113 llvm::APSInt Oversized; 6114 TypeSourceInfo *FixedTInfo = 6115 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6116 SizeIsNegative, 6117 Oversized); 6118 if (FixedTInfo) { 6119 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6120 NewTD->setTypeSourceInfo(FixedTInfo); 6121 } else { 6122 if (SizeIsNegative) 6123 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6124 else if (T->isVariableArrayType()) 6125 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6126 else if (Oversized.getBoolValue()) 6127 Diag(NewTD->getLocation(), diag::err_array_too_large) 6128 << Oversized.toString(10); 6129 else 6130 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6131 NewTD->setInvalidDecl(); 6132 } 6133 } 6134 } 6135 } 6136 6137 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6138 /// declares a typedef-name, either using the 'typedef' type specifier or via 6139 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6140 NamedDecl* 6141 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6142 LookupResult &Previous, bool &Redeclaration) { 6143 6144 // Find the shadowed declaration before filtering for scope. 6145 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6146 6147 // Merge the decl with the existing one if appropriate. If the decl is 6148 // in an outer scope, it isn't the same thing. 6149 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6150 /*AllowInlineNamespace*/false); 6151 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6152 if (!Previous.empty()) { 6153 Redeclaration = true; 6154 MergeTypedefNameDecl(S, NewTD, Previous); 6155 } else { 6156 inferGslPointerAttribute(NewTD); 6157 } 6158 6159 if (ShadowedDecl && !Redeclaration) 6160 CheckShadow(NewTD, ShadowedDecl, Previous); 6161 6162 // If this is the C FILE type, notify the AST context. 6163 if (IdentifierInfo *II = NewTD->getIdentifier()) 6164 if (!NewTD->isInvalidDecl() && 6165 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6166 if (II->isStr("FILE")) 6167 Context.setFILEDecl(NewTD); 6168 else if (II->isStr("jmp_buf")) 6169 Context.setjmp_bufDecl(NewTD); 6170 else if (II->isStr("sigjmp_buf")) 6171 Context.setsigjmp_bufDecl(NewTD); 6172 else if (II->isStr("ucontext_t")) 6173 Context.setucontext_tDecl(NewTD); 6174 } 6175 6176 return NewTD; 6177 } 6178 6179 /// Determines whether the given declaration is an out-of-scope 6180 /// previous declaration. 6181 /// 6182 /// This routine should be invoked when name lookup has found a 6183 /// previous declaration (PrevDecl) that is not in the scope where a 6184 /// new declaration by the same name is being introduced. If the new 6185 /// declaration occurs in a local scope, previous declarations with 6186 /// linkage may still be considered previous declarations (C99 6187 /// 6.2.2p4-5, C++ [basic.link]p6). 6188 /// 6189 /// \param PrevDecl the previous declaration found by name 6190 /// lookup 6191 /// 6192 /// \param DC the context in which the new declaration is being 6193 /// declared. 6194 /// 6195 /// \returns true if PrevDecl is an out-of-scope previous declaration 6196 /// for a new delcaration with the same name. 6197 static bool 6198 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6199 ASTContext &Context) { 6200 if (!PrevDecl) 6201 return false; 6202 6203 if (!PrevDecl->hasLinkage()) 6204 return false; 6205 6206 if (Context.getLangOpts().CPlusPlus) { 6207 // C++ [basic.link]p6: 6208 // If there is a visible declaration of an entity with linkage 6209 // having the same name and type, ignoring entities declared 6210 // outside the innermost enclosing namespace scope, the block 6211 // scope declaration declares that same entity and receives the 6212 // linkage of the previous declaration. 6213 DeclContext *OuterContext = DC->getRedeclContext(); 6214 if (!OuterContext->isFunctionOrMethod()) 6215 // This rule only applies to block-scope declarations. 6216 return false; 6217 6218 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6219 if (PrevOuterContext->isRecord()) 6220 // We found a member function: ignore it. 6221 return false; 6222 6223 // Find the innermost enclosing namespace for the new and 6224 // previous declarations. 6225 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6226 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6227 6228 // The previous declaration is in a different namespace, so it 6229 // isn't the same function. 6230 if (!OuterContext->Equals(PrevOuterContext)) 6231 return false; 6232 } 6233 6234 return true; 6235 } 6236 6237 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6238 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6239 if (!SS.isSet()) return; 6240 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6241 } 6242 6243 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6244 QualType type = decl->getType(); 6245 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6246 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6247 // Various kinds of declaration aren't allowed to be __autoreleasing. 6248 unsigned kind = -1U; 6249 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6250 if (var->hasAttr<BlocksAttr>()) 6251 kind = 0; // __block 6252 else if (!var->hasLocalStorage()) 6253 kind = 1; // global 6254 } else if (isa<ObjCIvarDecl>(decl)) { 6255 kind = 3; // ivar 6256 } else if (isa<FieldDecl>(decl)) { 6257 kind = 2; // field 6258 } 6259 6260 if (kind != -1U) { 6261 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6262 << kind; 6263 } 6264 } else if (lifetime == Qualifiers::OCL_None) { 6265 // Try to infer lifetime. 6266 if (!type->isObjCLifetimeType()) 6267 return false; 6268 6269 lifetime = type->getObjCARCImplicitLifetime(); 6270 type = Context.getLifetimeQualifiedType(type, lifetime); 6271 decl->setType(type); 6272 } 6273 6274 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6275 // Thread-local variables cannot have lifetime. 6276 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6277 var->getTLSKind()) { 6278 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6279 << var->getType(); 6280 return true; 6281 } 6282 } 6283 6284 return false; 6285 } 6286 6287 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6288 if (Decl->getType().hasAddressSpace()) 6289 return; 6290 if (Decl->getType()->isDependentType()) 6291 return; 6292 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6293 QualType Type = Var->getType(); 6294 if (Type->isSamplerT() || Type->isVoidType()) 6295 return; 6296 LangAS ImplAS = LangAS::opencl_private; 6297 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6298 Var->hasGlobalStorage()) 6299 ImplAS = LangAS::opencl_global; 6300 // If the original type from a decayed type is an array type and that array 6301 // type has no address space yet, deduce it now. 6302 if (auto DT = dyn_cast<DecayedType>(Type)) { 6303 auto OrigTy = DT->getOriginalType(); 6304 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6305 // Add the address space to the original array type and then propagate 6306 // that to the element type through `getAsArrayType`. 6307 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6308 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6309 // Re-generate the decayed type. 6310 Type = Context.getDecayedType(OrigTy); 6311 } 6312 } 6313 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6314 // Apply any qualifiers (including address space) from the array type to 6315 // the element type. This implements C99 6.7.3p8: "If the specification of 6316 // an array type includes any type qualifiers, the element type is so 6317 // qualified, not the array type." 6318 if (Type->isArrayType()) 6319 Type = QualType(Context.getAsArrayType(Type), 0); 6320 Decl->setType(Type); 6321 } 6322 } 6323 6324 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6325 // Ensure that an auto decl is deduced otherwise the checks below might cache 6326 // the wrong linkage. 6327 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6328 6329 // 'weak' only applies to declarations with external linkage. 6330 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6331 if (!ND.isExternallyVisible()) { 6332 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6333 ND.dropAttr<WeakAttr>(); 6334 } 6335 } 6336 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6337 if (ND.isExternallyVisible()) { 6338 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6339 ND.dropAttr<WeakRefAttr>(); 6340 ND.dropAttr<AliasAttr>(); 6341 } 6342 } 6343 6344 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6345 if (VD->hasInit()) { 6346 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6347 assert(VD->isThisDeclarationADefinition() && 6348 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6349 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6350 VD->dropAttr<AliasAttr>(); 6351 } 6352 } 6353 } 6354 6355 // 'selectany' only applies to externally visible variable declarations. 6356 // It does not apply to functions. 6357 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6358 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6359 S.Diag(Attr->getLocation(), 6360 diag::err_attribute_selectany_non_extern_data); 6361 ND.dropAttr<SelectAnyAttr>(); 6362 } 6363 } 6364 6365 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6366 auto *VD = dyn_cast<VarDecl>(&ND); 6367 bool IsAnonymousNS = false; 6368 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6369 if (VD) { 6370 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6371 while (NS && !IsAnonymousNS) { 6372 IsAnonymousNS = NS->isAnonymousNamespace(); 6373 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6374 } 6375 } 6376 // dll attributes require external linkage. Static locals may have external 6377 // linkage but still cannot be explicitly imported or exported. 6378 // In Microsoft mode, a variable defined in anonymous namespace must have 6379 // external linkage in order to be exported. 6380 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6381 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6382 (!AnonNSInMicrosoftMode && 6383 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6384 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6385 << &ND << Attr; 6386 ND.setInvalidDecl(); 6387 } 6388 } 6389 6390 // Virtual functions cannot be marked as 'notail'. 6391 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6392 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6393 if (MD->isVirtual()) { 6394 S.Diag(ND.getLocation(), 6395 diag::err_invalid_attribute_on_virtual_function) 6396 << Attr; 6397 ND.dropAttr<NotTailCalledAttr>(); 6398 } 6399 6400 // Check the attributes on the function type, if any. 6401 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6402 // Don't declare this variable in the second operand of the for-statement; 6403 // GCC miscompiles that by ending its lifetime before evaluating the 6404 // third operand. See gcc.gnu.org/PR86769. 6405 AttributedTypeLoc ATL; 6406 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6407 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6408 TL = ATL.getModifiedLoc()) { 6409 // The [[lifetimebound]] attribute can be applied to the implicit object 6410 // parameter of a non-static member function (other than a ctor or dtor) 6411 // by applying it to the function type. 6412 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6413 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6414 if (!MD || MD->isStatic()) { 6415 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6416 << !MD << A->getRange(); 6417 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6418 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6419 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6420 } 6421 } 6422 } 6423 } 6424 } 6425 6426 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6427 NamedDecl *NewDecl, 6428 bool IsSpecialization, 6429 bool IsDefinition) { 6430 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6431 return; 6432 6433 bool IsTemplate = false; 6434 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6435 OldDecl = OldTD->getTemplatedDecl(); 6436 IsTemplate = true; 6437 if (!IsSpecialization) 6438 IsDefinition = false; 6439 } 6440 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6441 NewDecl = NewTD->getTemplatedDecl(); 6442 IsTemplate = true; 6443 } 6444 6445 if (!OldDecl || !NewDecl) 6446 return; 6447 6448 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6449 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6450 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6451 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6452 6453 // dllimport and dllexport are inheritable attributes so we have to exclude 6454 // inherited attribute instances. 6455 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6456 (NewExportAttr && !NewExportAttr->isInherited()); 6457 6458 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6459 // the only exception being explicit specializations. 6460 // Implicitly generated declarations are also excluded for now because there 6461 // is no other way to switch these to use dllimport or dllexport. 6462 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6463 6464 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6465 // Allow with a warning for free functions and global variables. 6466 bool JustWarn = false; 6467 if (!OldDecl->isCXXClassMember()) { 6468 auto *VD = dyn_cast<VarDecl>(OldDecl); 6469 if (VD && !VD->getDescribedVarTemplate()) 6470 JustWarn = true; 6471 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6472 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6473 JustWarn = true; 6474 } 6475 6476 // We cannot change a declaration that's been used because IR has already 6477 // been emitted. Dllimported functions will still work though (modulo 6478 // address equality) as they can use the thunk. 6479 if (OldDecl->isUsed()) 6480 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6481 JustWarn = false; 6482 6483 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6484 : diag::err_attribute_dll_redeclaration; 6485 S.Diag(NewDecl->getLocation(), DiagID) 6486 << NewDecl 6487 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6488 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6489 if (!JustWarn) { 6490 NewDecl->setInvalidDecl(); 6491 return; 6492 } 6493 } 6494 6495 // A redeclaration is not allowed to drop a dllimport attribute, the only 6496 // exceptions being inline function definitions (except for function 6497 // templates), local extern declarations, qualified friend declarations or 6498 // special MSVC extension: in the last case, the declaration is treated as if 6499 // it were marked dllexport. 6500 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6501 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6502 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6503 // Ignore static data because out-of-line definitions are diagnosed 6504 // separately. 6505 IsStaticDataMember = VD->isStaticDataMember(); 6506 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6507 VarDecl::DeclarationOnly; 6508 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6509 IsInline = FD->isInlined(); 6510 IsQualifiedFriend = FD->getQualifier() && 6511 FD->getFriendObjectKind() == Decl::FOK_Declared; 6512 } 6513 6514 if (OldImportAttr && !HasNewAttr && 6515 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6516 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6517 if (IsMicrosoft && IsDefinition) { 6518 S.Diag(NewDecl->getLocation(), 6519 diag::warn_redeclaration_without_import_attribute) 6520 << NewDecl; 6521 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6522 NewDecl->dropAttr<DLLImportAttr>(); 6523 NewDecl->addAttr( 6524 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6525 } else { 6526 S.Diag(NewDecl->getLocation(), 6527 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6528 << NewDecl << OldImportAttr; 6529 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6530 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6531 OldDecl->dropAttr<DLLImportAttr>(); 6532 NewDecl->dropAttr<DLLImportAttr>(); 6533 } 6534 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6535 // In MinGW, seeing a function declared inline drops the dllimport 6536 // attribute. 6537 OldDecl->dropAttr<DLLImportAttr>(); 6538 NewDecl->dropAttr<DLLImportAttr>(); 6539 S.Diag(NewDecl->getLocation(), 6540 diag::warn_dllimport_dropped_from_inline_function) 6541 << NewDecl << OldImportAttr; 6542 } 6543 6544 // A specialization of a class template member function is processed here 6545 // since it's a redeclaration. If the parent class is dllexport, the 6546 // specialization inherits that attribute. This doesn't happen automatically 6547 // since the parent class isn't instantiated until later. 6548 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6549 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6550 !NewImportAttr && !NewExportAttr) { 6551 if (const DLLExportAttr *ParentExportAttr = 6552 MD->getParent()->getAttr<DLLExportAttr>()) { 6553 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6554 NewAttr->setInherited(true); 6555 NewDecl->addAttr(NewAttr); 6556 } 6557 } 6558 } 6559 } 6560 6561 /// Given that we are within the definition of the given function, 6562 /// will that definition behave like C99's 'inline', where the 6563 /// definition is discarded except for optimization purposes? 6564 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6565 // Try to avoid calling GetGVALinkageForFunction. 6566 6567 // All cases of this require the 'inline' keyword. 6568 if (!FD->isInlined()) return false; 6569 6570 // This is only possible in C++ with the gnu_inline attribute. 6571 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6572 return false; 6573 6574 // Okay, go ahead and call the relatively-more-expensive function. 6575 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6576 } 6577 6578 /// Determine whether a variable is extern "C" prior to attaching 6579 /// an initializer. We can't just call isExternC() here, because that 6580 /// will also compute and cache whether the declaration is externally 6581 /// visible, which might change when we attach the initializer. 6582 /// 6583 /// This can only be used if the declaration is known to not be a 6584 /// redeclaration of an internal linkage declaration. 6585 /// 6586 /// For instance: 6587 /// 6588 /// auto x = []{}; 6589 /// 6590 /// Attaching the initializer here makes this declaration not externally 6591 /// visible, because its type has internal linkage. 6592 /// 6593 /// FIXME: This is a hack. 6594 template<typename T> 6595 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6596 if (S.getLangOpts().CPlusPlus) { 6597 // In C++, the overloadable attribute negates the effects of extern "C". 6598 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6599 return false; 6600 6601 // So do CUDA's host/device attributes. 6602 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6603 D->template hasAttr<CUDAHostAttr>())) 6604 return false; 6605 } 6606 return D->isExternC(); 6607 } 6608 6609 static bool shouldConsiderLinkage(const VarDecl *VD) { 6610 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6611 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6612 isa<OMPDeclareMapperDecl>(DC)) 6613 return VD->hasExternalStorage(); 6614 if (DC->isFileContext()) 6615 return true; 6616 if (DC->isRecord()) 6617 return false; 6618 if (isa<RequiresExprBodyDecl>(DC)) 6619 return false; 6620 llvm_unreachable("Unexpected context"); 6621 } 6622 6623 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6624 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6625 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6626 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6627 return true; 6628 if (DC->isRecord()) 6629 return false; 6630 llvm_unreachable("Unexpected context"); 6631 } 6632 6633 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6634 ParsedAttr::Kind Kind) { 6635 // Check decl attributes on the DeclSpec. 6636 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6637 return true; 6638 6639 // Walk the declarator structure, checking decl attributes that were in a type 6640 // position to the decl itself. 6641 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6642 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6643 return true; 6644 } 6645 6646 // Finally, check attributes on the decl itself. 6647 return PD.getAttributes().hasAttribute(Kind); 6648 } 6649 6650 /// Adjust the \c DeclContext for a function or variable that might be a 6651 /// function-local external declaration. 6652 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6653 if (!DC->isFunctionOrMethod()) 6654 return false; 6655 6656 // If this is a local extern function or variable declared within a function 6657 // template, don't add it into the enclosing namespace scope until it is 6658 // instantiated; it might have a dependent type right now. 6659 if (DC->isDependentContext()) 6660 return true; 6661 6662 // C++11 [basic.link]p7: 6663 // When a block scope declaration of an entity with linkage is not found to 6664 // refer to some other declaration, then that entity is a member of the 6665 // innermost enclosing namespace. 6666 // 6667 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6668 // semantically-enclosing namespace, not a lexically-enclosing one. 6669 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6670 DC = DC->getParent(); 6671 return true; 6672 } 6673 6674 /// Returns true if given declaration has external C language linkage. 6675 static bool isDeclExternC(const Decl *D) { 6676 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6677 return FD->isExternC(); 6678 if (const auto *VD = dyn_cast<VarDecl>(D)) 6679 return VD->isExternC(); 6680 6681 llvm_unreachable("Unknown type of decl!"); 6682 } 6683 /// Returns true if there hasn't been any invalid type diagnosed. 6684 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6685 DeclContext *DC, QualType R) { 6686 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6687 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6688 // argument. 6689 if (R->isImageType() || R->isPipeType()) { 6690 Se.Diag(D.getIdentifierLoc(), 6691 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6692 << R; 6693 D.setInvalidType(); 6694 return false; 6695 } 6696 6697 // OpenCL v1.2 s6.9.r: 6698 // The event type cannot be used to declare a program scope variable. 6699 // OpenCL v2.0 s6.9.q: 6700 // The clk_event_t and reserve_id_t types cannot be declared in program 6701 // scope. 6702 if (NULL == S->getParent()) { 6703 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6704 Se.Diag(D.getIdentifierLoc(), 6705 diag::err_invalid_type_for_program_scope_var) 6706 << R; 6707 D.setInvalidType(); 6708 return false; 6709 } 6710 } 6711 6712 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6713 QualType NR = R; 6714 while (NR->isPointerType()) { 6715 if (NR->isFunctionPointerType()) { 6716 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6717 D.setInvalidType(); 6718 return false; 6719 } 6720 NR = NR->getPointeeType(); 6721 } 6722 6723 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6724 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6725 // half array type (unless the cl_khr_fp16 extension is enabled). 6726 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6727 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6728 D.setInvalidType(); 6729 return false; 6730 } 6731 } 6732 6733 // OpenCL v1.2 s6.9.r: 6734 // The event type cannot be used with the __local, __constant and __global 6735 // address space qualifiers. 6736 if (R->isEventT()) { 6737 if (R.getAddressSpace() != LangAS::opencl_private) { 6738 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6739 D.setInvalidType(); 6740 return false; 6741 } 6742 } 6743 6744 // C++ for OpenCL does not allow the thread_local storage qualifier. 6745 // OpenCL C does not support thread_local either, and 6746 // also reject all other thread storage class specifiers. 6747 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6748 if (TSC != TSCS_unspecified) { 6749 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6750 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6751 diag::err_opencl_unknown_type_specifier) 6752 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6753 << DeclSpec::getSpecifierName(TSC) << 1; 6754 D.setInvalidType(); 6755 return false; 6756 } 6757 6758 if (R->isSamplerT()) { 6759 // OpenCL v1.2 s6.9.b p4: 6760 // The sampler type cannot be used with the __local and __global address 6761 // space qualifiers. 6762 if (R.getAddressSpace() == LangAS::opencl_local || 6763 R.getAddressSpace() == LangAS::opencl_global) { 6764 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6765 D.setInvalidType(); 6766 } 6767 6768 // OpenCL v1.2 s6.12.14.1: 6769 // A global sampler must be declared with either the constant address 6770 // space qualifier or with the const qualifier. 6771 if (DC->isTranslationUnit() && 6772 !(R.getAddressSpace() == LangAS::opencl_constant || 6773 R.isConstQualified())) { 6774 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6775 D.setInvalidType(); 6776 } 6777 if (D.isInvalidType()) 6778 return false; 6779 } 6780 return true; 6781 } 6782 6783 NamedDecl *Sema::ActOnVariableDeclarator( 6784 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6785 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6786 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6787 QualType R = TInfo->getType(); 6788 DeclarationName Name = GetNameForDeclarator(D).getName(); 6789 6790 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6791 6792 if (D.isDecompositionDeclarator()) { 6793 // Take the name of the first declarator as our name for diagnostic 6794 // purposes. 6795 auto &Decomp = D.getDecompositionDeclarator(); 6796 if (!Decomp.bindings().empty()) { 6797 II = Decomp.bindings()[0].Name; 6798 Name = II; 6799 } 6800 } else if (!II) { 6801 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6802 return nullptr; 6803 } 6804 6805 6806 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6807 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6808 6809 // dllimport globals without explicit storage class are treated as extern. We 6810 // have to change the storage class this early to get the right DeclContext. 6811 if (SC == SC_None && !DC->isRecord() && 6812 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6813 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6814 SC = SC_Extern; 6815 6816 DeclContext *OriginalDC = DC; 6817 bool IsLocalExternDecl = SC == SC_Extern && 6818 adjustContextForLocalExternDecl(DC); 6819 6820 if (SCSpec == DeclSpec::SCS_mutable) { 6821 // mutable can only appear on non-static class members, so it's always 6822 // an error here 6823 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6824 D.setInvalidType(); 6825 SC = SC_None; 6826 } 6827 6828 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6829 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6830 D.getDeclSpec().getStorageClassSpecLoc())) { 6831 // In C++11, the 'register' storage class specifier is deprecated. 6832 // Suppress the warning in system macros, it's used in macros in some 6833 // popular C system headers, such as in glibc's htonl() macro. 6834 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6835 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6836 : diag::warn_deprecated_register) 6837 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6838 } 6839 6840 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6841 6842 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6843 // C99 6.9p2: The storage-class specifiers auto and register shall not 6844 // appear in the declaration specifiers in an external declaration. 6845 // Global Register+Asm is a GNU extension we support. 6846 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6847 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6848 D.setInvalidType(); 6849 } 6850 } 6851 6852 bool IsMemberSpecialization = false; 6853 bool IsVariableTemplateSpecialization = false; 6854 bool IsPartialSpecialization = false; 6855 bool IsVariableTemplate = false; 6856 VarDecl *NewVD = nullptr; 6857 VarTemplateDecl *NewTemplate = nullptr; 6858 TemplateParameterList *TemplateParams = nullptr; 6859 if (!getLangOpts().CPlusPlus) { 6860 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6861 II, R, TInfo, SC); 6862 6863 if (R->getContainedDeducedType()) 6864 ParsingInitForAutoVars.insert(NewVD); 6865 6866 if (D.isInvalidType()) 6867 NewVD->setInvalidDecl(); 6868 6869 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6870 NewVD->hasLocalStorage()) 6871 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6872 NTCUC_AutoVar, NTCUK_Destruct); 6873 } else { 6874 bool Invalid = false; 6875 6876 if (DC->isRecord() && !CurContext->isRecord()) { 6877 // This is an out-of-line definition of a static data member. 6878 switch (SC) { 6879 case SC_None: 6880 break; 6881 case SC_Static: 6882 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6883 diag::err_static_out_of_line) 6884 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6885 break; 6886 case SC_Auto: 6887 case SC_Register: 6888 case SC_Extern: 6889 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6890 // to names of variables declared in a block or to function parameters. 6891 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6892 // of class members 6893 6894 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6895 diag::err_storage_class_for_static_member) 6896 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6897 break; 6898 case SC_PrivateExtern: 6899 llvm_unreachable("C storage class in c++!"); 6900 } 6901 } 6902 6903 if (SC == SC_Static && CurContext->isRecord()) { 6904 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6905 // Walk up the enclosing DeclContexts to check for any that are 6906 // incompatible with static data members. 6907 const DeclContext *FunctionOrMethod = nullptr; 6908 const CXXRecordDecl *AnonStruct = nullptr; 6909 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6910 if (Ctxt->isFunctionOrMethod()) { 6911 FunctionOrMethod = Ctxt; 6912 break; 6913 } 6914 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6915 if (ParentDecl && !ParentDecl->getDeclName()) { 6916 AnonStruct = ParentDecl; 6917 break; 6918 } 6919 } 6920 if (FunctionOrMethod) { 6921 // C++ [class.static.data]p5: A local class shall not have static data 6922 // members. 6923 Diag(D.getIdentifierLoc(), 6924 diag::err_static_data_member_not_allowed_in_local_class) 6925 << Name << RD->getDeclName() << RD->getTagKind(); 6926 } else if (AnonStruct) { 6927 // C++ [class.static.data]p4: Unnamed classes and classes contained 6928 // directly or indirectly within unnamed classes shall not contain 6929 // static data members. 6930 Diag(D.getIdentifierLoc(), 6931 diag::err_static_data_member_not_allowed_in_anon_struct) 6932 << Name << AnonStruct->getTagKind(); 6933 Invalid = true; 6934 } else if (RD->isUnion()) { 6935 // C++98 [class.union]p1: If a union contains a static data member, 6936 // the program is ill-formed. C++11 drops this restriction. 6937 Diag(D.getIdentifierLoc(), 6938 getLangOpts().CPlusPlus11 6939 ? diag::warn_cxx98_compat_static_data_member_in_union 6940 : diag::ext_static_data_member_in_union) << Name; 6941 } 6942 } 6943 } 6944 6945 // Match up the template parameter lists with the scope specifier, then 6946 // determine whether we have a template or a template specialization. 6947 bool InvalidScope = false; 6948 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6949 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6950 D.getCXXScopeSpec(), 6951 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6952 ? D.getName().TemplateId 6953 : nullptr, 6954 TemplateParamLists, 6955 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6956 Invalid |= InvalidScope; 6957 6958 if (TemplateParams) { 6959 if (!TemplateParams->size() && 6960 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6961 // There is an extraneous 'template<>' for this variable. Complain 6962 // about it, but allow the declaration of the variable. 6963 Diag(TemplateParams->getTemplateLoc(), 6964 diag::err_template_variable_noparams) 6965 << II 6966 << SourceRange(TemplateParams->getTemplateLoc(), 6967 TemplateParams->getRAngleLoc()); 6968 TemplateParams = nullptr; 6969 } else { 6970 // Check that we can declare a template here. 6971 if (CheckTemplateDeclScope(S, TemplateParams)) 6972 return nullptr; 6973 6974 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6975 // This is an explicit specialization or a partial specialization. 6976 IsVariableTemplateSpecialization = true; 6977 IsPartialSpecialization = TemplateParams->size() > 0; 6978 } else { // if (TemplateParams->size() > 0) 6979 // This is a template declaration. 6980 IsVariableTemplate = true; 6981 6982 // Only C++1y supports variable templates (N3651). 6983 Diag(D.getIdentifierLoc(), 6984 getLangOpts().CPlusPlus14 6985 ? diag::warn_cxx11_compat_variable_template 6986 : diag::ext_variable_template); 6987 } 6988 } 6989 } else { 6990 // Check that we can declare a member specialization here. 6991 if (!TemplateParamLists.empty() && IsMemberSpecialization && 6992 CheckTemplateDeclScope(S, TemplateParamLists.back())) 6993 return nullptr; 6994 assert((Invalid || 6995 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6996 "should have a 'template<>' for this decl"); 6997 } 6998 6999 if (IsVariableTemplateSpecialization) { 7000 SourceLocation TemplateKWLoc = 7001 TemplateParamLists.size() > 0 7002 ? TemplateParamLists[0]->getTemplateLoc() 7003 : SourceLocation(); 7004 DeclResult Res = ActOnVarTemplateSpecialization( 7005 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7006 IsPartialSpecialization); 7007 if (Res.isInvalid()) 7008 return nullptr; 7009 NewVD = cast<VarDecl>(Res.get()); 7010 AddToScope = false; 7011 } else if (D.isDecompositionDeclarator()) { 7012 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7013 D.getIdentifierLoc(), R, TInfo, SC, 7014 Bindings); 7015 } else 7016 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7017 D.getIdentifierLoc(), II, R, TInfo, SC); 7018 7019 // If this is supposed to be a variable template, create it as such. 7020 if (IsVariableTemplate) { 7021 NewTemplate = 7022 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7023 TemplateParams, NewVD); 7024 NewVD->setDescribedVarTemplate(NewTemplate); 7025 } 7026 7027 // If this decl has an auto type in need of deduction, make a note of the 7028 // Decl so we can diagnose uses of it in its own initializer. 7029 if (R->getContainedDeducedType()) 7030 ParsingInitForAutoVars.insert(NewVD); 7031 7032 if (D.isInvalidType() || Invalid) { 7033 NewVD->setInvalidDecl(); 7034 if (NewTemplate) 7035 NewTemplate->setInvalidDecl(); 7036 } 7037 7038 SetNestedNameSpecifier(*this, NewVD, D); 7039 7040 // If we have any template parameter lists that don't directly belong to 7041 // the variable (matching the scope specifier), store them. 7042 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7043 if (TemplateParamLists.size() > VDTemplateParamLists) 7044 NewVD->setTemplateParameterListsInfo( 7045 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7046 } 7047 7048 if (D.getDeclSpec().isInlineSpecified()) { 7049 if (!getLangOpts().CPlusPlus) { 7050 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7051 << 0; 7052 } else if (CurContext->isFunctionOrMethod()) { 7053 // 'inline' is not allowed on block scope variable declaration. 7054 Diag(D.getDeclSpec().getInlineSpecLoc(), 7055 diag::err_inline_declaration_block_scope) << Name 7056 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7057 } else { 7058 Diag(D.getDeclSpec().getInlineSpecLoc(), 7059 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7060 : diag::ext_inline_variable); 7061 NewVD->setInlineSpecified(); 7062 } 7063 } 7064 7065 // Set the lexical context. If the declarator has a C++ scope specifier, the 7066 // lexical context will be different from the semantic context. 7067 NewVD->setLexicalDeclContext(CurContext); 7068 if (NewTemplate) 7069 NewTemplate->setLexicalDeclContext(CurContext); 7070 7071 if (IsLocalExternDecl) { 7072 if (D.isDecompositionDeclarator()) 7073 for (auto *B : Bindings) 7074 B->setLocalExternDecl(); 7075 else 7076 NewVD->setLocalExternDecl(); 7077 } 7078 7079 bool EmitTLSUnsupportedError = false; 7080 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7081 // C++11 [dcl.stc]p4: 7082 // When thread_local is applied to a variable of block scope the 7083 // storage-class-specifier static is implied if it does not appear 7084 // explicitly. 7085 // Core issue: 'static' is not implied if the variable is declared 7086 // 'extern'. 7087 if (NewVD->hasLocalStorage() && 7088 (SCSpec != DeclSpec::SCS_unspecified || 7089 TSCS != DeclSpec::TSCS_thread_local || 7090 !DC->isFunctionOrMethod())) 7091 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7092 diag::err_thread_non_global) 7093 << DeclSpec::getSpecifierName(TSCS); 7094 else if (!Context.getTargetInfo().isTLSSupported()) { 7095 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7096 getLangOpts().SYCLIsDevice) { 7097 // Postpone error emission until we've collected attributes required to 7098 // figure out whether it's a host or device variable and whether the 7099 // error should be ignored. 7100 EmitTLSUnsupportedError = true; 7101 // We still need to mark the variable as TLS so it shows up in AST with 7102 // proper storage class for other tools to use even if we're not going 7103 // to emit any code for it. 7104 NewVD->setTSCSpec(TSCS); 7105 } else 7106 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7107 diag::err_thread_unsupported); 7108 } else 7109 NewVD->setTSCSpec(TSCS); 7110 } 7111 7112 switch (D.getDeclSpec().getConstexprSpecifier()) { 7113 case CSK_unspecified: 7114 break; 7115 7116 case CSK_consteval: 7117 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7118 diag::err_constexpr_wrong_decl_kind) 7119 << D.getDeclSpec().getConstexprSpecifier(); 7120 LLVM_FALLTHROUGH; 7121 7122 case CSK_constexpr: 7123 NewVD->setConstexpr(true); 7124 MaybeAddCUDAConstantAttr(NewVD); 7125 // C++1z [dcl.spec.constexpr]p1: 7126 // A static data member declared with the constexpr specifier is 7127 // implicitly an inline variable. 7128 if (NewVD->isStaticDataMember() && 7129 (getLangOpts().CPlusPlus17 || 7130 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7131 NewVD->setImplicitlyInline(); 7132 break; 7133 7134 case CSK_constinit: 7135 if (!NewVD->hasGlobalStorage()) 7136 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7137 diag::err_constinit_local_variable); 7138 else 7139 NewVD->addAttr(ConstInitAttr::Create( 7140 Context, D.getDeclSpec().getConstexprSpecLoc(), 7141 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7142 break; 7143 } 7144 7145 // C99 6.7.4p3 7146 // An inline definition of a function with external linkage shall 7147 // not contain a definition of a modifiable object with static or 7148 // thread storage duration... 7149 // We only apply this when the function is required to be defined 7150 // elsewhere, i.e. when the function is not 'extern inline'. Note 7151 // that a local variable with thread storage duration still has to 7152 // be marked 'static'. Also note that it's possible to get these 7153 // semantics in C++ using __attribute__((gnu_inline)). 7154 if (SC == SC_Static && S->getFnParent() != nullptr && 7155 !NewVD->getType().isConstQualified()) { 7156 FunctionDecl *CurFD = getCurFunctionDecl(); 7157 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7158 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7159 diag::warn_static_local_in_extern_inline); 7160 MaybeSuggestAddingStaticToDecl(CurFD); 7161 } 7162 } 7163 7164 if (D.getDeclSpec().isModulePrivateSpecified()) { 7165 if (IsVariableTemplateSpecialization) 7166 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7167 << (IsPartialSpecialization ? 1 : 0) 7168 << FixItHint::CreateRemoval( 7169 D.getDeclSpec().getModulePrivateSpecLoc()); 7170 else if (IsMemberSpecialization) 7171 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7172 << 2 7173 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7174 else if (NewVD->hasLocalStorage()) 7175 Diag(NewVD->getLocation(), diag::err_module_private_local) 7176 << 0 << NewVD 7177 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7178 << FixItHint::CreateRemoval( 7179 D.getDeclSpec().getModulePrivateSpecLoc()); 7180 else { 7181 NewVD->setModulePrivate(); 7182 if (NewTemplate) 7183 NewTemplate->setModulePrivate(); 7184 for (auto *B : Bindings) 7185 B->setModulePrivate(); 7186 } 7187 } 7188 7189 if (getLangOpts().OpenCL) { 7190 7191 deduceOpenCLAddressSpace(NewVD); 7192 7193 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7194 } 7195 7196 // Handle attributes prior to checking for duplicates in MergeVarDecl 7197 ProcessDeclAttributes(S, NewVD, D); 7198 7199 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7200 getLangOpts().SYCLIsDevice) { 7201 if (EmitTLSUnsupportedError && 7202 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7203 (getLangOpts().OpenMPIsDevice && 7204 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7205 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7206 diag::err_thread_unsupported); 7207 7208 if (EmitTLSUnsupportedError && 7209 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7210 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7211 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7212 // storage [duration]." 7213 if (SC == SC_None && S->getFnParent() != nullptr && 7214 (NewVD->hasAttr<CUDASharedAttr>() || 7215 NewVD->hasAttr<CUDAConstantAttr>())) { 7216 NewVD->setStorageClass(SC_Static); 7217 } 7218 } 7219 7220 // Ensure that dllimport globals without explicit storage class are treated as 7221 // extern. The storage class is set above using parsed attributes. Now we can 7222 // check the VarDecl itself. 7223 assert(!NewVD->hasAttr<DLLImportAttr>() || 7224 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7225 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7226 7227 // In auto-retain/release, infer strong retension for variables of 7228 // retainable type. 7229 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7230 NewVD->setInvalidDecl(); 7231 7232 // Handle GNU asm-label extension (encoded as an attribute). 7233 if (Expr *E = (Expr*)D.getAsmLabel()) { 7234 // The parser guarantees this is a string. 7235 StringLiteral *SE = cast<StringLiteral>(E); 7236 StringRef Label = SE->getString(); 7237 if (S->getFnParent() != nullptr) { 7238 switch (SC) { 7239 case SC_None: 7240 case SC_Auto: 7241 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7242 break; 7243 case SC_Register: 7244 // Local Named register 7245 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7246 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7247 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7248 break; 7249 case SC_Static: 7250 case SC_Extern: 7251 case SC_PrivateExtern: 7252 break; 7253 } 7254 } else if (SC == SC_Register) { 7255 // Global Named register 7256 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7257 const auto &TI = Context.getTargetInfo(); 7258 bool HasSizeMismatch; 7259 7260 if (!TI.isValidGCCRegisterName(Label)) 7261 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7262 else if (!TI.validateGlobalRegisterVariable(Label, 7263 Context.getTypeSize(R), 7264 HasSizeMismatch)) 7265 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7266 else if (HasSizeMismatch) 7267 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7268 } 7269 7270 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7271 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7272 NewVD->setInvalidDecl(true); 7273 } 7274 } 7275 7276 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7277 /*IsLiteralLabel=*/true, 7278 SE->getStrTokenLoc(0))); 7279 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7280 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7281 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7282 if (I != ExtnameUndeclaredIdentifiers.end()) { 7283 if (isDeclExternC(NewVD)) { 7284 NewVD->addAttr(I->second); 7285 ExtnameUndeclaredIdentifiers.erase(I); 7286 } else 7287 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7288 << /*Variable*/1 << NewVD; 7289 } 7290 } 7291 7292 // Find the shadowed declaration before filtering for scope. 7293 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7294 ? getShadowedDeclaration(NewVD, Previous) 7295 : nullptr; 7296 7297 // Don't consider existing declarations that are in a different 7298 // scope and are out-of-semantic-context declarations (if the new 7299 // declaration has linkage). 7300 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7301 D.getCXXScopeSpec().isNotEmpty() || 7302 IsMemberSpecialization || 7303 IsVariableTemplateSpecialization); 7304 7305 // Check whether the previous declaration is in the same block scope. This 7306 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7307 if (getLangOpts().CPlusPlus && 7308 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7309 NewVD->setPreviousDeclInSameBlockScope( 7310 Previous.isSingleResult() && !Previous.isShadowed() && 7311 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7312 7313 if (!getLangOpts().CPlusPlus) { 7314 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7315 } else { 7316 // If this is an explicit specialization of a static data member, check it. 7317 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7318 CheckMemberSpecialization(NewVD, Previous)) 7319 NewVD->setInvalidDecl(); 7320 7321 // Merge the decl with the existing one if appropriate. 7322 if (!Previous.empty()) { 7323 if (Previous.isSingleResult() && 7324 isa<FieldDecl>(Previous.getFoundDecl()) && 7325 D.getCXXScopeSpec().isSet()) { 7326 // The user tried to define a non-static data member 7327 // out-of-line (C++ [dcl.meaning]p1). 7328 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7329 << D.getCXXScopeSpec().getRange(); 7330 Previous.clear(); 7331 NewVD->setInvalidDecl(); 7332 } 7333 } else if (D.getCXXScopeSpec().isSet()) { 7334 // No previous declaration in the qualifying scope. 7335 Diag(D.getIdentifierLoc(), diag::err_no_member) 7336 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7337 << D.getCXXScopeSpec().getRange(); 7338 NewVD->setInvalidDecl(); 7339 } 7340 7341 if (!IsVariableTemplateSpecialization) 7342 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7343 7344 if (NewTemplate) { 7345 VarTemplateDecl *PrevVarTemplate = 7346 NewVD->getPreviousDecl() 7347 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7348 : nullptr; 7349 7350 // Check the template parameter list of this declaration, possibly 7351 // merging in the template parameter list from the previous variable 7352 // template declaration. 7353 if (CheckTemplateParameterList( 7354 TemplateParams, 7355 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7356 : nullptr, 7357 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7358 DC->isDependentContext()) 7359 ? TPC_ClassTemplateMember 7360 : TPC_VarTemplate)) 7361 NewVD->setInvalidDecl(); 7362 7363 // If we are providing an explicit specialization of a static variable 7364 // template, make a note of that. 7365 if (PrevVarTemplate && 7366 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7367 PrevVarTemplate->setMemberSpecialization(); 7368 } 7369 } 7370 7371 // Diagnose shadowed variables iff this isn't a redeclaration. 7372 if (ShadowedDecl && !D.isRedeclaration()) 7373 CheckShadow(NewVD, ShadowedDecl, Previous); 7374 7375 ProcessPragmaWeak(S, NewVD); 7376 7377 // If this is the first declaration of an extern C variable, update 7378 // the map of such variables. 7379 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7380 isIncompleteDeclExternC(*this, NewVD)) 7381 RegisterLocallyScopedExternCDecl(NewVD, S); 7382 7383 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7384 MangleNumberingContext *MCtx; 7385 Decl *ManglingContextDecl; 7386 std::tie(MCtx, ManglingContextDecl) = 7387 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7388 if (MCtx) { 7389 Context.setManglingNumber( 7390 NewVD, MCtx->getManglingNumber( 7391 NewVD, getMSManglingNumber(getLangOpts(), S))); 7392 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7393 } 7394 } 7395 7396 // Special handling of variable named 'main'. 7397 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7398 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7399 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7400 7401 // C++ [basic.start.main]p3 7402 // A program that declares a variable main at global scope is ill-formed. 7403 if (getLangOpts().CPlusPlus) 7404 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7405 7406 // In C, and external-linkage variable named main results in undefined 7407 // behavior. 7408 else if (NewVD->hasExternalFormalLinkage()) 7409 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7410 } 7411 7412 if (D.isRedeclaration() && !Previous.empty()) { 7413 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7414 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7415 D.isFunctionDefinition()); 7416 } 7417 7418 if (NewTemplate) { 7419 if (NewVD->isInvalidDecl()) 7420 NewTemplate->setInvalidDecl(); 7421 ActOnDocumentableDecl(NewTemplate); 7422 return NewTemplate; 7423 } 7424 7425 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7426 CompleteMemberSpecialization(NewVD, Previous); 7427 7428 return NewVD; 7429 } 7430 7431 /// Enum describing the %select options in diag::warn_decl_shadow. 7432 enum ShadowedDeclKind { 7433 SDK_Local, 7434 SDK_Global, 7435 SDK_StaticMember, 7436 SDK_Field, 7437 SDK_Typedef, 7438 SDK_Using 7439 }; 7440 7441 /// Determine what kind of declaration we're shadowing. 7442 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7443 const DeclContext *OldDC) { 7444 if (isa<TypeAliasDecl>(ShadowedDecl)) 7445 return SDK_Using; 7446 else if (isa<TypedefDecl>(ShadowedDecl)) 7447 return SDK_Typedef; 7448 else if (isa<RecordDecl>(OldDC)) 7449 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7450 7451 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7452 } 7453 7454 /// Return the location of the capture if the given lambda captures the given 7455 /// variable \p VD, or an invalid source location otherwise. 7456 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7457 const VarDecl *VD) { 7458 for (const Capture &Capture : LSI->Captures) { 7459 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7460 return Capture.getLocation(); 7461 } 7462 return SourceLocation(); 7463 } 7464 7465 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7466 const LookupResult &R) { 7467 // Only diagnose if we're shadowing an unambiguous field or variable. 7468 if (R.getResultKind() != LookupResult::Found) 7469 return false; 7470 7471 // Return false if warning is ignored. 7472 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7473 } 7474 7475 /// Return the declaration shadowed by the given variable \p D, or null 7476 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7477 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7478 const LookupResult &R) { 7479 if (!shouldWarnIfShadowedDecl(Diags, R)) 7480 return nullptr; 7481 7482 // Don't diagnose declarations at file scope. 7483 if (D->hasGlobalStorage()) 7484 return nullptr; 7485 7486 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7487 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7488 ? ShadowedDecl 7489 : nullptr; 7490 } 7491 7492 /// Return the declaration shadowed by the given typedef \p D, or null 7493 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7494 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7495 const LookupResult &R) { 7496 // Don't warn if typedef declaration is part of a class 7497 if (D->getDeclContext()->isRecord()) 7498 return nullptr; 7499 7500 if (!shouldWarnIfShadowedDecl(Diags, R)) 7501 return nullptr; 7502 7503 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7504 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7505 } 7506 7507 /// Diagnose variable or built-in function shadowing. Implements 7508 /// -Wshadow. 7509 /// 7510 /// This method is called whenever a VarDecl is added to a "useful" 7511 /// scope. 7512 /// 7513 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7514 /// \param R the lookup of the name 7515 /// 7516 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7517 const LookupResult &R) { 7518 DeclContext *NewDC = D->getDeclContext(); 7519 7520 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7521 // Fields are not shadowed by variables in C++ static methods. 7522 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7523 if (MD->isStatic()) 7524 return; 7525 7526 // Fields shadowed by constructor parameters are a special case. Usually 7527 // the constructor initializes the field with the parameter. 7528 if (isa<CXXConstructorDecl>(NewDC)) 7529 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7530 // Remember that this was shadowed so we can either warn about its 7531 // modification or its existence depending on warning settings. 7532 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7533 return; 7534 } 7535 } 7536 7537 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7538 if (shadowedVar->isExternC()) { 7539 // For shadowing external vars, make sure that we point to the global 7540 // declaration, not a locally scoped extern declaration. 7541 for (auto I : shadowedVar->redecls()) 7542 if (I->isFileVarDecl()) { 7543 ShadowedDecl = I; 7544 break; 7545 } 7546 } 7547 7548 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7549 7550 unsigned WarningDiag = diag::warn_decl_shadow; 7551 SourceLocation CaptureLoc; 7552 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7553 isa<CXXMethodDecl>(NewDC)) { 7554 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7555 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7556 if (RD->getLambdaCaptureDefault() == LCD_None) { 7557 // Try to avoid warnings for lambdas with an explicit capture list. 7558 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7559 // Warn only when the lambda captures the shadowed decl explicitly. 7560 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7561 if (CaptureLoc.isInvalid()) 7562 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7563 } else { 7564 // Remember that this was shadowed so we can avoid the warning if the 7565 // shadowed decl isn't captured and the warning settings allow it. 7566 cast<LambdaScopeInfo>(getCurFunction()) 7567 ->ShadowingDecls.push_back( 7568 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7569 return; 7570 } 7571 } 7572 7573 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7574 // A variable can't shadow a local variable in an enclosing scope, if 7575 // they are separated by a non-capturing declaration context. 7576 for (DeclContext *ParentDC = NewDC; 7577 ParentDC && !ParentDC->Equals(OldDC); 7578 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7579 // Only block literals, captured statements, and lambda expressions 7580 // can capture; other scopes don't. 7581 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7582 !isLambdaCallOperator(ParentDC)) { 7583 return; 7584 } 7585 } 7586 } 7587 } 7588 } 7589 7590 // Only warn about certain kinds of shadowing for class members. 7591 if (NewDC && NewDC->isRecord()) { 7592 // In particular, don't warn about shadowing non-class members. 7593 if (!OldDC->isRecord()) 7594 return; 7595 7596 // TODO: should we warn about static data members shadowing 7597 // static data members from base classes? 7598 7599 // TODO: don't diagnose for inaccessible shadowed members. 7600 // This is hard to do perfectly because we might friend the 7601 // shadowing context, but that's just a false negative. 7602 } 7603 7604 7605 DeclarationName Name = R.getLookupName(); 7606 7607 // Emit warning and note. 7608 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7609 return; 7610 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7611 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7612 if (!CaptureLoc.isInvalid()) 7613 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7614 << Name << /*explicitly*/ 1; 7615 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7616 } 7617 7618 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7619 /// when these variables are captured by the lambda. 7620 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7621 for (const auto &Shadow : LSI->ShadowingDecls) { 7622 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7623 // Try to avoid the warning when the shadowed decl isn't captured. 7624 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7625 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7626 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7627 ? diag::warn_decl_shadow_uncaptured_local 7628 : diag::warn_decl_shadow) 7629 << Shadow.VD->getDeclName() 7630 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7631 if (!CaptureLoc.isInvalid()) 7632 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7633 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7634 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7635 } 7636 } 7637 7638 /// Check -Wshadow without the advantage of a previous lookup. 7639 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7640 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7641 return; 7642 7643 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7644 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7645 LookupName(R, S); 7646 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7647 CheckShadow(D, ShadowedDecl, R); 7648 } 7649 7650 /// Check if 'E', which is an expression that is about to be modified, refers 7651 /// to a constructor parameter that shadows a field. 7652 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7653 // Quickly ignore expressions that can't be shadowing ctor parameters. 7654 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7655 return; 7656 E = E->IgnoreParenImpCasts(); 7657 auto *DRE = dyn_cast<DeclRefExpr>(E); 7658 if (!DRE) 7659 return; 7660 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7661 auto I = ShadowingDecls.find(D); 7662 if (I == ShadowingDecls.end()) 7663 return; 7664 const NamedDecl *ShadowedDecl = I->second; 7665 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7666 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7667 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7668 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7669 7670 // Avoid issuing multiple warnings about the same decl. 7671 ShadowingDecls.erase(I); 7672 } 7673 7674 /// Check for conflict between this global or extern "C" declaration and 7675 /// previous global or extern "C" declarations. This is only used in C++. 7676 template<typename T> 7677 static bool checkGlobalOrExternCConflict( 7678 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7679 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7680 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7681 7682 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7683 // The common case: this global doesn't conflict with any extern "C" 7684 // declaration. 7685 return false; 7686 } 7687 7688 if (Prev) { 7689 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7690 // Both the old and new declarations have C language linkage. This is a 7691 // redeclaration. 7692 Previous.clear(); 7693 Previous.addDecl(Prev); 7694 return true; 7695 } 7696 7697 // This is a global, non-extern "C" declaration, and there is a previous 7698 // non-global extern "C" declaration. Diagnose if this is a variable 7699 // declaration. 7700 if (!isa<VarDecl>(ND)) 7701 return false; 7702 } else { 7703 // The declaration is extern "C". Check for any declaration in the 7704 // translation unit which might conflict. 7705 if (IsGlobal) { 7706 // We have already performed the lookup into the translation unit. 7707 IsGlobal = false; 7708 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7709 I != E; ++I) { 7710 if (isa<VarDecl>(*I)) { 7711 Prev = *I; 7712 break; 7713 } 7714 } 7715 } else { 7716 DeclContext::lookup_result R = 7717 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7718 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7719 I != E; ++I) { 7720 if (isa<VarDecl>(*I)) { 7721 Prev = *I; 7722 break; 7723 } 7724 // FIXME: If we have any other entity with this name in global scope, 7725 // the declaration is ill-formed, but that is a defect: it breaks the 7726 // 'stat' hack, for instance. Only variables can have mangled name 7727 // clashes with extern "C" declarations, so only they deserve a 7728 // diagnostic. 7729 } 7730 } 7731 7732 if (!Prev) 7733 return false; 7734 } 7735 7736 // Use the first declaration's location to ensure we point at something which 7737 // is lexically inside an extern "C" linkage-spec. 7738 assert(Prev && "should have found a previous declaration to diagnose"); 7739 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7740 Prev = FD->getFirstDecl(); 7741 else 7742 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7743 7744 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7745 << IsGlobal << ND; 7746 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7747 << IsGlobal; 7748 return false; 7749 } 7750 7751 /// Apply special rules for handling extern "C" declarations. Returns \c true 7752 /// if we have found that this is a redeclaration of some prior entity. 7753 /// 7754 /// Per C++ [dcl.link]p6: 7755 /// Two declarations [for a function or variable] with C language linkage 7756 /// with the same name that appear in different scopes refer to the same 7757 /// [entity]. An entity with C language linkage shall not be declared with 7758 /// the same name as an entity in global scope. 7759 template<typename T> 7760 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7761 LookupResult &Previous) { 7762 if (!S.getLangOpts().CPlusPlus) { 7763 // In C, when declaring a global variable, look for a corresponding 'extern' 7764 // variable declared in function scope. We don't need this in C++, because 7765 // we find local extern decls in the surrounding file-scope DeclContext. 7766 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7767 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7768 Previous.clear(); 7769 Previous.addDecl(Prev); 7770 return true; 7771 } 7772 } 7773 return false; 7774 } 7775 7776 // A declaration in the translation unit can conflict with an extern "C" 7777 // declaration. 7778 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7779 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7780 7781 // An extern "C" declaration can conflict with a declaration in the 7782 // translation unit or can be a redeclaration of an extern "C" declaration 7783 // in another scope. 7784 if (isIncompleteDeclExternC(S,ND)) 7785 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7786 7787 // Neither global nor extern "C": nothing to do. 7788 return false; 7789 } 7790 7791 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7792 // If the decl is already known invalid, don't check it. 7793 if (NewVD->isInvalidDecl()) 7794 return; 7795 7796 QualType T = NewVD->getType(); 7797 7798 // Defer checking an 'auto' type until its initializer is attached. 7799 if (T->isUndeducedType()) 7800 return; 7801 7802 if (NewVD->hasAttrs()) 7803 CheckAlignasUnderalignment(NewVD); 7804 7805 if (T->isObjCObjectType()) { 7806 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7807 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7808 T = Context.getObjCObjectPointerType(T); 7809 NewVD->setType(T); 7810 } 7811 7812 // Emit an error if an address space was applied to decl with local storage. 7813 // This includes arrays of objects with address space qualifiers, but not 7814 // automatic variables that point to other address spaces. 7815 // ISO/IEC TR 18037 S5.1.2 7816 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7817 T.getAddressSpace() != LangAS::Default) { 7818 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7819 NewVD->setInvalidDecl(); 7820 return; 7821 } 7822 7823 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7824 // scope. 7825 if (getLangOpts().OpenCLVersion == 120 && 7826 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7827 NewVD->isStaticLocal()) { 7828 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7829 NewVD->setInvalidDecl(); 7830 return; 7831 } 7832 7833 if (getLangOpts().OpenCL) { 7834 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7835 if (NewVD->hasAttr<BlocksAttr>()) { 7836 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7837 return; 7838 } 7839 7840 if (T->isBlockPointerType()) { 7841 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7842 // can't use 'extern' storage class. 7843 if (!T.isConstQualified()) { 7844 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7845 << 0 /*const*/; 7846 NewVD->setInvalidDecl(); 7847 return; 7848 } 7849 if (NewVD->hasExternalStorage()) { 7850 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7851 NewVD->setInvalidDecl(); 7852 return; 7853 } 7854 } 7855 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7856 // __constant address space. 7857 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7858 // variables inside a function can also be declared in the global 7859 // address space. 7860 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7861 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7862 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7863 NewVD->hasExternalStorage()) { 7864 if (!T->isSamplerT() && 7865 !T->isDependentType() && 7866 !(T.getAddressSpace() == LangAS::opencl_constant || 7867 (T.getAddressSpace() == LangAS::opencl_global && 7868 (getLangOpts().OpenCLVersion == 200 || 7869 getLangOpts().OpenCLCPlusPlus)))) { 7870 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7871 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7872 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7873 << Scope << "global or constant"; 7874 else 7875 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7876 << Scope << "constant"; 7877 NewVD->setInvalidDecl(); 7878 return; 7879 } 7880 } else { 7881 if (T.getAddressSpace() == LangAS::opencl_global) { 7882 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7883 << 1 /*is any function*/ << "global"; 7884 NewVD->setInvalidDecl(); 7885 return; 7886 } 7887 if (T.getAddressSpace() == LangAS::opencl_constant || 7888 T.getAddressSpace() == LangAS::opencl_local) { 7889 FunctionDecl *FD = getCurFunctionDecl(); 7890 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7891 // in functions. 7892 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7893 if (T.getAddressSpace() == LangAS::opencl_constant) 7894 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7895 << 0 /*non-kernel only*/ << "constant"; 7896 else 7897 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7898 << 0 /*non-kernel only*/ << "local"; 7899 NewVD->setInvalidDecl(); 7900 return; 7901 } 7902 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7903 // in the outermost scope of a kernel function. 7904 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7905 if (!getCurScope()->isFunctionScope()) { 7906 if (T.getAddressSpace() == LangAS::opencl_constant) 7907 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7908 << "constant"; 7909 else 7910 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7911 << "local"; 7912 NewVD->setInvalidDecl(); 7913 return; 7914 } 7915 } 7916 } else if (T.getAddressSpace() != LangAS::opencl_private && 7917 // If we are parsing a template we didn't deduce an addr 7918 // space yet. 7919 T.getAddressSpace() != LangAS::Default) { 7920 // Do not allow other address spaces on automatic variable. 7921 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7922 NewVD->setInvalidDecl(); 7923 return; 7924 } 7925 } 7926 } 7927 7928 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7929 && !NewVD->hasAttr<BlocksAttr>()) { 7930 if (getLangOpts().getGC() != LangOptions::NonGC) 7931 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7932 else { 7933 assert(!getLangOpts().ObjCAutoRefCount); 7934 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7935 } 7936 } 7937 7938 bool isVM = T->isVariablyModifiedType(); 7939 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7940 NewVD->hasAttr<BlocksAttr>()) 7941 setFunctionHasBranchProtectedScope(); 7942 7943 if ((isVM && NewVD->hasLinkage()) || 7944 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7945 bool SizeIsNegative; 7946 llvm::APSInt Oversized; 7947 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7948 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7949 QualType FixedT; 7950 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7951 FixedT = FixedTInfo->getType(); 7952 else if (FixedTInfo) { 7953 // Type and type-as-written are canonically different. We need to fix up 7954 // both types separately. 7955 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7956 Oversized); 7957 } 7958 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7959 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7960 // FIXME: This won't give the correct result for 7961 // int a[10][n]; 7962 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7963 7964 if (NewVD->isFileVarDecl()) 7965 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7966 << SizeRange; 7967 else if (NewVD->isStaticLocal()) 7968 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7969 << SizeRange; 7970 else 7971 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7972 << SizeRange; 7973 NewVD->setInvalidDecl(); 7974 return; 7975 } 7976 7977 if (!FixedTInfo) { 7978 if (NewVD->isFileVarDecl()) 7979 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7980 else 7981 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7982 NewVD->setInvalidDecl(); 7983 return; 7984 } 7985 7986 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7987 NewVD->setType(FixedT); 7988 NewVD->setTypeSourceInfo(FixedTInfo); 7989 } 7990 7991 if (T->isVoidType()) { 7992 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7993 // of objects and functions. 7994 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7995 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7996 << T; 7997 NewVD->setInvalidDecl(); 7998 return; 7999 } 8000 } 8001 8002 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8003 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8004 NewVD->setInvalidDecl(); 8005 return; 8006 } 8007 8008 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8009 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8010 NewVD->setInvalidDecl(); 8011 return; 8012 } 8013 8014 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8015 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8016 NewVD->setInvalidDecl(); 8017 return; 8018 } 8019 8020 if (NewVD->isConstexpr() && !T->isDependentType() && 8021 RequireLiteralType(NewVD->getLocation(), T, 8022 diag::err_constexpr_var_non_literal)) { 8023 NewVD->setInvalidDecl(); 8024 return; 8025 } 8026 } 8027 8028 /// Perform semantic checking on a newly-created variable 8029 /// declaration. 8030 /// 8031 /// This routine performs all of the type-checking required for a 8032 /// variable declaration once it has been built. It is used both to 8033 /// check variables after they have been parsed and their declarators 8034 /// have been translated into a declaration, and to check variables 8035 /// that have been instantiated from a template. 8036 /// 8037 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8038 /// 8039 /// Returns true if the variable declaration is a redeclaration. 8040 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8041 CheckVariableDeclarationType(NewVD); 8042 8043 // If the decl is already known invalid, don't check it. 8044 if (NewVD->isInvalidDecl()) 8045 return false; 8046 8047 // If we did not find anything by this name, look for a non-visible 8048 // extern "C" declaration with the same name. 8049 if (Previous.empty() && 8050 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8051 Previous.setShadowed(); 8052 8053 if (!Previous.empty()) { 8054 MergeVarDecl(NewVD, Previous); 8055 return true; 8056 } 8057 return false; 8058 } 8059 8060 namespace { 8061 struct FindOverriddenMethod { 8062 Sema *S; 8063 CXXMethodDecl *Method; 8064 8065 /// Member lookup function that determines whether a given C++ 8066 /// method overrides a method in a base class, to be used with 8067 /// CXXRecordDecl::lookupInBases(). 8068 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8069 RecordDecl *BaseRecord = 8070 Specifier->getType()->castAs<RecordType>()->getDecl(); 8071 8072 DeclarationName Name = Method->getDeclName(); 8073 8074 // FIXME: Do we care about other names here too? 8075 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8076 // We really want to find the base class destructor here. 8077 QualType T = S->Context.getTypeDeclType(BaseRecord); 8078 CanQualType CT = S->Context.getCanonicalType(T); 8079 8080 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8081 } 8082 8083 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8084 Path.Decls = Path.Decls.slice(1)) { 8085 NamedDecl *D = Path.Decls.front(); 8086 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8087 if (MD->isVirtual() && 8088 !S->IsOverload( 8089 Method, MD, /*UseMemberUsingDeclRules=*/false, 8090 /*ConsiderCudaAttrs=*/true, 8091 // C++2a [class.virtual]p2 does not consider requires clauses 8092 // when overriding. 8093 /*ConsiderRequiresClauses=*/false)) 8094 return true; 8095 } 8096 } 8097 8098 return false; 8099 } 8100 }; 8101 } // end anonymous namespace 8102 8103 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8104 /// and if so, check that it's a valid override and remember it. 8105 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8106 // Look for methods in base classes that this method might override. 8107 CXXBasePaths Paths; 8108 FindOverriddenMethod FOM; 8109 FOM.Method = MD; 8110 FOM.S = this; 8111 bool AddedAny = false; 8112 if (DC->lookupInBases(FOM, Paths)) { 8113 for (auto *I : Paths.found_decls()) { 8114 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8115 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8116 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8117 !CheckOverridingFunctionAttributes(MD, OldMD) && 8118 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8119 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8120 AddedAny = true; 8121 } 8122 } 8123 } 8124 } 8125 8126 return AddedAny; 8127 } 8128 8129 namespace { 8130 // Struct for holding all of the extra arguments needed by 8131 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8132 struct ActOnFDArgs { 8133 Scope *S; 8134 Declarator &D; 8135 MultiTemplateParamsArg TemplateParamLists; 8136 bool AddToScope; 8137 }; 8138 } // end anonymous namespace 8139 8140 namespace { 8141 8142 // Callback to only accept typo corrections that have a non-zero edit distance. 8143 // Also only accept corrections that have the same parent decl. 8144 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8145 public: 8146 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8147 CXXRecordDecl *Parent) 8148 : Context(Context), OriginalFD(TypoFD), 8149 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8150 8151 bool ValidateCandidate(const TypoCorrection &candidate) override { 8152 if (candidate.getEditDistance() == 0) 8153 return false; 8154 8155 SmallVector<unsigned, 1> MismatchedParams; 8156 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8157 CDeclEnd = candidate.end(); 8158 CDecl != CDeclEnd; ++CDecl) { 8159 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8160 8161 if (FD && !FD->hasBody() && 8162 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8164 CXXRecordDecl *Parent = MD->getParent(); 8165 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8166 return true; 8167 } else if (!ExpectedParent) { 8168 return true; 8169 } 8170 } 8171 } 8172 8173 return false; 8174 } 8175 8176 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8177 return std::make_unique<DifferentNameValidatorCCC>(*this); 8178 } 8179 8180 private: 8181 ASTContext &Context; 8182 FunctionDecl *OriginalFD; 8183 CXXRecordDecl *ExpectedParent; 8184 }; 8185 8186 } // end anonymous namespace 8187 8188 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8189 TypoCorrectedFunctionDefinitions.insert(F); 8190 } 8191 8192 /// Generate diagnostics for an invalid function redeclaration. 8193 /// 8194 /// This routine handles generating the diagnostic messages for an invalid 8195 /// function redeclaration, including finding possible similar declarations 8196 /// or performing typo correction if there are no previous declarations with 8197 /// the same name. 8198 /// 8199 /// Returns a NamedDecl iff typo correction was performed and substituting in 8200 /// the new declaration name does not cause new errors. 8201 static NamedDecl *DiagnoseInvalidRedeclaration( 8202 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8203 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8204 DeclarationName Name = NewFD->getDeclName(); 8205 DeclContext *NewDC = NewFD->getDeclContext(); 8206 SmallVector<unsigned, 1> MismatchedParams; 8207 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8208 TypoCorrection Correction; 8209 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8210 unsigned DiagMsg = 8211 IsLocalFriend ? diag::err_no_matching_local_friend : 8212 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8213 diag::err_member_decl_does_not_match; 8214 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8215 IsLocalFriend ? Sema::LookupLocalFriendName 8216 : Sema::LookupOrdinaryName, 8217 Sema::ForVisibleRedeclaration); 8218 8219 NewFD->setInvalidDecl(); 8220 if (IsLocalFriend) 8221 SemaRef.LookupName(Prev, S); 8222 else 8223 SemaRef.LookupQualifiedName(Prev, NewDC); 8224 assert(!Prev.isAmbiguous() && 8225 "Cannot have an ambiguity in previous-declaration lookup"); 8226 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8227 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8228 MD ? MD->getParent() : nullptr); 8229 if (!Prev.empty()) { 8230 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8231 Func != FuncEnd; ++Func) { 8232 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8233 if (FD && 8234 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8235 // Add 1 to the index so that 0 can mean the mismatch didn't 8236 // involve a parameter 8237 unsigned ParamNum = 8238 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8239 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8240 } 8241 } 8242 // If the qualified name lookup yielded nothing, try typo correction 8243 } else if ((Correction = SemaRef.CorrectTypo( 8244 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8245 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8246 IsLocalFriend ? nullptr : NewDC))) { 8247 // Set up everything for the call to ActOnFunctionDeclarator 8248 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8249 ExtraArgs.D.getIdentifierLoc()); 8250 Previous.clear(); 8251 Previous.setLookupName(Correction.getCorrection()); 8252 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8253 CDeclEnd = Correction.end(); 8254 CDecl != CDeclEnd; ++CDecl) { 8255 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8256 if (FD && !FD->hasBody() && 8257 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8258 Previous.addDecl(FD); 8259 } 8260 } 8261 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8262 8263 NamedDecl *Result; 8264 // Retry building the function declaration with the new previous 8265 // declarations, and with errors suppressed. 8266 { 8267 // Trap errors. 8268 Sema::SFINAETrap Trap(SemaRef); 8269 8270 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8271 // pieces need to verify the typo-corrected C++ declaration and hopefully 8272 // eliminate the need for the parameter pack ExtraArgs. 8273 Result = SemaRef.ActOnFunctionDeclarator( 8274 ExtraArgs.S, ExtraArgs.D, 8275 Correction.getCorrectionDecl()->getDeclContext(), 8276 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8277 ExtraArgs.AddToScope); 8278 8279 if (Trap.hasErrorOccurred()) 8280 Result = nullptr; 8281 } 8282 8283 if (Result) { 8284 // Determine which correction we picked. 8285 Decl *Canonical = Result->getCanonicalDecl(); 8286 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8287 I != E; ++I) 8288 if ((*I)->getCanonicalDecl() == Canonical) 8289 Correction.setCorrectionDecl(*I); 8290 8291 // Let Sema know about the correction. 8292 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8293 SemaRef.diagnoseTypo( 8294 Correction, 8295 SemaRef.PDiag(IsLocalFriend 8296 ? diag::err_no_matching_local_friend_suggest 8297 : diag::err_member_decl_does_not_match_suggest) 8298 << Name << NewDC << IsDefinition); 8299 return Result; 8300 } 8301 8302 // Pretend the typo correction never occurred 8303 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8304 ExtraArgs.D.getIdentifierLoc()); 8305 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8306 Previous.clear(); 8307 Previous.setLookupName(Name); 8308 } 8309 8310 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8311 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8312 8313 bool NewFDisConst = false; 8314 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8315 NewFDisConst = NewMD->isConst(); 8316 8317 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8318 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8319 NearMatch != NearMatchEnd; ++NearMatch) { 8320 FunctionDecl *FD = NearMatch->first; 8321 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8322 bool FDisConst = MD && MD->isConst(); 8323 bool IsMember = MD || !IsLocalFriend; 8324 8325 // FIXME: These notes are poorly worded for the local friend case. 8326 if (unsigned Idx = NearMatch->second) { 8327 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8328 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8329 if (Loc.isInvalid()) Loc = FD->getLocation(); 8330 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8331 : diag::note_local_decl_close_param_match) 8332 << Idx << FDParam->getType() 8333 << NewFD->getParamDecl(Idx - 1)->getType(); 8334 } else if (FDisConst != NewFDisConst) { 8335 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8336 << NewFDisConst << FD->getSourceRange().getEnd(); 8337 } else 8338 SemaRef.Diag(FD->getLocation(), 8339 IsMember ? diag::note_member_def_close_match 8340 : diag::note_local_decl_close_match); 8341 } 8342 return nullptr; 8343 } 8344 8345 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8346 switch (D.getDeclSpec().getStorageClassSpec()) { 8347 default: llvm_unreachable("Unknown storage class!"); 8348 case DeclSpec::SCS_auto: 8349 case DeclSpec::SCS_register: 8350 case DeclSpec::SCS_mutable: 8351 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8352 diag::err_typecheck_sclass_func); 8353 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8354 D.setInvalidType(); 8355 break; 8356 case DeclSpec::SCS_unspecified: break; 8357 case DeclSpec::SCS_extern: 8358 if (D.getDeclSpec().isExternInLinkageSpec()) 8359 return SC_None; 8360 return SC_Extern; 8361 case DeclSpec::SCS_static: { 8362 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8363 // C99 6.7.1p5: 8364 // The declaration of an identifier for a function that has 8365 // block scope shall have no explicit storage-class specifier 8366 // other than extern 8367 // See also (C++ [dcl.stc]p4). 8368 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8369 diag::err_static_block_func); 8370 break; 8371 } else 8372 return SC_Static; 8373 } 8374 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8375 } 8376 8377 // No explicit storage class has already been returned 8378 return SC_None; 8379 } 8380 8381 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8382 DeclContext *DC, QualType &R, 8383 TypeSourceInfo *TInfo, 8384 StorageClass SC, 8385 bool &IsVirtualOkay) { 8386 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8387 DeclarationName Name = NameInfo.getName(); 8388 8389 FunctionDecl *NewFD = nullptr; 8390 bool isInline = D.getDeclSpec().isInlineSpecified(); 8391 8392 if (!SemaRef.getLangOpts().CPlusPlus) { 8393 // Determine whether the function was written with a 8394 // prototype. This true when: 8395 // - there is a prototype in the declarator, or 8396 // - the type R of the function is some kind of typedef or other non- 8397 // attributed reference to a type name (which eventually refers to a 8398 // function type). 8399 bool HasPrototype = 8400 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8401 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8402 8403 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8404 R, TInfo, SC, isInline, HasPrototype, 8405 CSK_unspecified, 8406 /*TrailingRequiresClause=*/nullptr); 8407 if (D.isInvalidType()) 8408 NewFD->setInvalidDecl(); 8409 8410 return NewFD; 8411 } 8412 8413 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8414 8415 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8416 if (ConstexprKind == CSK_constinit) { 8417 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8418 diag::err_constexpr_wrong_decl_kind) 8419 << ConstexprKind; 8420 ConstexprKind = CSK_unspecified; 8421 D.getMutableDeclSpec().ClearConstexprSpec(); 8422 } 8423 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8424 8425 // Check that the return type is not an abstract class type. 8426 // For record types, this is done by the AbstractClassUsageDiagnoser once 8427 // the class has been completely parsed. 8428 if (!DC->isRecord() && 8429 SemaRef.RequireNonAbstractType( 8430 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8431 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8432 D.setInvalidType(); 8433 8434 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8435 // This is a C++ constructor declaration. 8436 assert(DC->isRecord() && 8437 "Constructors can only be declared in a member context"); 8438 8439 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8440 return CXXConstructorDecl::Create( 8441 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8442 TInfo, ExplicitSpecifier, isInline, 8443 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8444 TrailingRequiresClause); 8445 8446 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8447 // This is a C++ destructor declaration. 8448 if (DC->isRecord()) { 8449 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8450 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8451 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8452 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8453 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8454 TrailingRequiresClause); 8455 8456 // If the destructor needs an implicit exception specification, set it 8457 // now. FIXME: It'd be nice to be able to create the right type to start 8458 // with, but the type needs to reference the destructor declaration. 8459 if (SemaRef.getLangOpts().CPlusPlus11) 8460 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8461 8462 IsVirtualOkay = true; 8463 return NewDD; 8464 8465 } else { 8466 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8467 D.setInvalidType(); 8468 8469 // Create a FunctionDecl to satisfy the function definition parsing 8470 // code path. 8471 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8472 D.getIdentifierLoc(), Name, R, TInfo, SC, 8473 isInline, 8474 /*hasPrototype=*/true, ConstexprKind, 8475 TrailingRequiresClause); 8476 } 8477 8478 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8479 if (!DC->isRecord()) { 8480 SemaRef.Diag(D.getIdentifierLoc(), 8481 diag::err_conv_function_not_member); 8482 return nullptr; 8483 } 8484 8485 SemaRef.CheckConversionDeclarator(D, R, SC); 8486 if (D.isInvalidType()) 8487 return nullptr; 8488 8489 IsVirtualOkay = true; 8490 return CXXConversionDecl::Create( 8491 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8492 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8493 TrailingRequiresClause); 8494 8495 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8496 if (TrailingRequiresClause) 8497 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8498 diag::err_trailing_requires_clause_on_deduction_guide) 8499 << TrailingRequiresClause->getSourceRange(); 8500 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8501 8502 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8503 ExplicitSpecifier, NameInfo, R, TInfo, 8504 D.getEndLoc()); 8505 } else if (DC->isRecord()) { 8506 // If the name of the function is the same as the name of the record, 8507 // then this must be an invalid constructor that has a return type. 8508 // (The parser checks for a return type and makes the declarator a 8509 // constructor if it has no return type). 8510 if (Name.getAsIdentifierInfo() && 8511 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8512 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8513 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8514 << SourceRange(D.getIdentifierLoc()); 8515 return nullptr; 8516 } 8517 8518 // This is a C++ method declaration. 8519 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8520 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8521 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8522 TrailingRequiresClause); 8523 IsVirtualOkay = !Ret->isStatic(); 8524 return Ret; 8525 } else { 8526 bool isFriend = 8527 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8528 if (!isFriend && SemaRef.CurContext->isRecord()) 8529 return nullptr; 8530 8531 // Determine whether the function was written with a 8532 // prototype. This true when: 8533 // - we're in C++ (where every function has a prototype), 8534 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8535 R, TInfo, SC, isInline, true /*HasPrototype*/, 8536 ConstexprKind, TrailingRequiresClause); 8537 } 8538 } 8539 8540 enum OpenCLParamType { 8541 ValidKernelParam, 8542 PtrPtrKernelParam, 8543 PtrKernelParam, 8544 InvalidAddrSpacePtrKernelParam, 8545 InvalidKernelParam, 8546 RecordKernelParam 8547 }; 8548 8549 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8550 // Size dependent types are just typedefs to normal integer types 8551 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8552 // integers other than by their names. 8553 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8554 8555 // Remove typedefs one by one until we reach a typedef 8556 // for a size dependent type. 8557 QualType DesugaredTy = Ty; 8558 do { 8559 ArrayRef<StringRef> Names(SizeTypeNames); 8560 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8561 if (Names.end() != Match) 8562 return true; 8563 8564 Ty = DesugaredTy; 8565 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8566 } while (DesugaredTy != Ty); 8567 8568 return false; 8569 } 8570 8571 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8572 if (PT->isPointerType()) { 8573 QualType PointeeType = PT->getPointeeType(); 8574 if (PointeeType->isPointerType()) 8575 return PtrPtrKernelParam; 8576 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8577 PointeeType.getAddressSpace() == LangAS::opencl_private || 8578 PointeeType.getAddressSpace() == LangAS::Default) 8579 return InvalidAddrSpacePtrKernelParam; 8580 return PtrKernelParam; 8581 } 8582 8583 // OpenCL v1.2 s6.9.k: 8584 // Arguments to kernel functions in a program cannot be declared with the 8585 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8586 // uintptr_t or a struct and/or union that contain fields declared to be one 8587 // of these built-in scalar types. 8588 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8589 return InvalidKernelParam; 8590 8591 if (PT->isImageType()) 8592 return PtrKernelParam; 8593 8594 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8595 return InvalidKernelParam; 8596 8597 // OpenCL extension spec v1.2 s9.5: 8598 // This extension adds support for half scalar and vector types as built-in 8599 // types that can be used for arithmetic operations, conversions etc. 8600 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8601 return InvalidKernelParam; 8602 8603 if (PT->isRecordType()) 8604 return RecordKernelParam; 8605 8606 // Look into an array argument to check if it has a forbidden type. 8607 if (PT->isArrayType()) { 8608 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8609 // Call ourself to check an underlying type of an array. Since the 8610 // getPointeeOrArrayElementType returns an innermost type which is not an 8611 // array, this recursive call only happens once. 8612 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8613 } 8614 8615 return ValidKernelParam; 8616 } 8617 8618 static void checkIsValidOpenCLKernelParameter( 8619 Sema &S, 8620 Declarator &D, 8621 ParmVarDecl *Param, 8622 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8623 QualType PT = Param->getType(); 8624 8625 // Cache the valid types we encounter to avoid rechecking structs that are 8626 // used again 8627 if (ValidTypes.count(PT.getTypePtr())) 8628 return; 8629 8630 switch (getOpenCLKernelParameterType(S, PT)) { 8631 case PtrPtrKernelParam: 8632 // OpenCL v1.2 s6.9.a: 8633 // A kernel function argument cannot be declared as a 8634 // pointer to a pointer type. 8635 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8636 D.setInvalidType(); 8637 return; 8638 8639 case InvalidAddrSpacePtrKernelParam: 8640 // OpenCL v1.0 s6.5: 8641 // __kernel function arguments declared to be a pointer of a type can point 8642 // to one of the following address spaces only : __global, __local or 8643 // __constant. 8644 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8645 D.setInvalidType(); 8646 return; 8647 8648 // OpenCL v1.2 s6.9.k: 8649 // Arguments to kernel functions in a program cannot be declared with the 8650 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8651 // uintptr_t or a struct and/or union that contain fields declared to be 8652 // one of these built-in scalar types. 8653 8654 case InvalidKernelParam: 8655 // OpenCL v1.2 s6.8 n: 8656 // A kernel function argument cannot be declared 8657 // of event_t type. 8658 // Do not diagnose half type since it is diagnosed as invalid argument 8659 // type for any function elsewhere. 8660 if (!PT->isHalfType()) { 8661 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8662 8663 // Explain what typedefs are involved. 8664 const TypedefType *Typedef = nullptr; 8665 while ((Typedef = PT->getAs<TypedefType>())) { 8666 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8667 // SourceLocation may be invalid for a built-in type. 8668 if (Loc.isValid()) 8669 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8670 PT = Typedef->desugar(); 8671 } 8672 } 8673 8674 D.setInvalidType(); 8675 return; 8676 8677 case PtrKernelParam: 8678 case ValidKernelParam: 8679 ValidTypes.insert(PT.getTypePtr()); 8680 return; 8681 8682 case RecordKernelParam: 8683 break; 8684 } 8685 8686 // Track nested structs we will inspect 8687 SmallVector<const Decl *, 4> VisitStack; 8688 8689 // Track where we are in the nested structs. Items will migrate from 8690 // VisitStack to HistoryStack as we do the DFS for bad field. 8691 SmallVector<const FieldDecl *, 4> HistoryStack; 8692 HistoryStack.push_back(nullptr); 8693 8694 // At this point we already handled everything except of a RecordType or 8695 // an ArrayType of a RecordType. 8696 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8697 const RecordType *RecTy = 8698 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8699 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8700 8701 VisitStack.push_back(RecTy->getDecl()); 8702 assert(VisitStack.back() && "First decl null?"); 8703 8704 do { 8705 const Decl *Next = VisitStack.pop_back_val(); 8706 if (!Next) { 8707 assert(!HistoryStack.empty()); 8708 // Found a marker, we have gone up a level 8709 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8710 ValidTypes.insert(Hist->getType().getTypePtr()); 8711 8712 continue; 8713 } 8714 8715 // Adds everything except the original parameter declaration (which is not a 8716 // field itself) to the history stack. 8717 const RecordDecl *RD; 8718 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8719 HistoryStack.push_back(Field); 8720 8721 QualType FieldTy = Field->getType(); 8722 // Other field types (known to be valid or invalid) are handled while we 8723 // walk around RecordDecl::fields(). 8724 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8725 "Unexpected type."); 8726 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8727 8728 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8729 } else { 8730 RD = cast<RecordDecl>(Next); 8731 } 8732 8733 // Add a null marker so we know when we've gone back up a level 8734 VisitStack.push_back(nullptr); 8735 8736 for (const auto *FD : RD->fields()) { 8737 QualType QT = FD->getType(); 8738 8739 if (ValidTypes.count(QT.getTypePtr())) 8740 continue; 8741 8742 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8743 if (ParamType == ValidKernelParam) 8744 continue; 8745 8746 if (ParamType == RecordKernelParam) { 8747 VisitStack.push_back(FD); 8748 continue; 8749 } 8750 8751 // OpenCL v1.2 s6.9.p: 8752 // Arguments to kernel functions that are declared to be a struct or union 8753 // do not allow OpenCL objects to be passed as elements of the struct or 8754 // union. 8755 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8756 ParamType == InvalidAddrSpacePtrKernelParam) { 8757 S.Diag(Param->getLocation(), 8758 diag::err_record_with_pointers_kernel_param) 8759 << PT->isUnionType() 8760 << PT; 8761 } else { 8762 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8763 } 8764 8765 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8766 << OrigRecDecl->getDeclName(); 8767 8768 // We have an error, now let's go back up through history and show where 8769 // the offending field came from 8770 for (ArrayRef<const FieldDecl *>::const_iterator 8771 I = HistoryStack.begin() + 1, 8772 E = HistoryStack.end(); 8773 I != E; ++I) { 8774 const FieldDecl *OuterField = *I; 8775 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8776 << OuterField->getType(); 8777 } 8778 8779 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8780 << QT->isPointerType() 8781 << QT; 8782 D.setInvalidType(); 8783 return; 8784 } 8785 } while (!VisitStack.empty()); 8786 } 8787 8788 /// Find the DeclContext in which a tag is implicitly declared if we see an 8789 /// elaborated type specifier in the specified context, and lookup finds 8790 /// nothing. 8791 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8792 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8793 DC = DC->getParent(); 8794 return DC; 8795 } 8796 8797 /// Find the Scope in which a tag is implicitly declared if we see an 8798 /// elaborated type specifier in the specified context, and lookup finds 8799 /// nothing. 8800 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8801 while (S->isClassScope() || 8802 (LangOpts.CPlusPlus && 8803 S->isFunctionPrototypeScope()) || 8804 ((S->getFlags() & Scope::DeclScope) == 0) || 8805 (S->getEntity() && S->getEntity()->isTransparentContext())) 8806 S = S->getParent(); 8807 return S; 8808 } 8809 8810 NamedDecl* 8811 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8812 TypeSourceInfo *TInfo, LookupResult &Previous, 8813 MultiTemplateParamsArg TemplateParamListsRef, 8814 bool &AddToScope) { 8815 QualType R = TInfo->getType(); 8816 8817 assert(R->isFunctionType()); 8818 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8819 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8820 8821 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8822 for (TemplateParameterList *TPL : TemplateParamListsRef) 8823 TemplateParamLists.push_back(TPL); 8824 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8825 if (!TemplateParamLists.empty() && 8826 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8827 TemplateParamLists.back() = Invented; 8828 else 8829 TemplateParamLists.push_back(Invented); 8830 } 8831 8832 // TODO: consider using NameInfo for diagnostic. 8833 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8834 DeclarationName Name = NameInfo.getName(); 8835 StorageClass SC = getFunctionStorageClass(*this, D); 8836 8837 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8838 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8839 diag::err_invalid_thread) 8840 << DeclSpec::getSpecifierName(TSCS); 8841 8842 if (D.isFirstDeclarationOfMember()) 8843 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8844 D.getIdentifierLoc()); 8845 8846 bool isFriend = false; 8847 FunctionTemplateDecl *FunctionTemplate = nullptr; 8848 bool isMemberSpecialization = false; 8849 bool isFunctionTemplateSpecialization = false; 8850 8851 bool isDependentClassScopeExplicitSpecialization = false; 8852 bool HasExplicitTemplateArgs = false; 8853 TemplateArgumentListInfo TemplateArgs; 8854 8855 bool isVirtualOkay = false; 8856 8857 DeclContext *OriginalDC = DC; 8858 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8859 8860 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8861 isVirtualOkay); 8862 if (!NewFD) return nullptr; 8863 8864 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8865 NewFD->setTopLevelDeclInObjCContainer(); 8866 8867 // Set the lexical context. If this is a function-scope declaration, or has a 8868 // C++ scope specifier, or is the object of a friend declaration, the lexical 8869 // context will be different from the semantic context. 8870 NewFD->setLexicalDeclContext(CurContext); 8871 8872 if (IsLocalExternDecl) 8873 NewFD->setLocalExternDecl(); 8874 8875 if (getLangOpts().CPlusPlus) { 8876 bool isInline = D.getDeclSpec().isInlineSpecified(); 8877 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8878 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8879 isFriend = D.getDeclSpec().isFriendSpecified(); 8880 if (isFriend && !isInline && D.isFunctionDefinition()) { 8881 // C++ [class.friend]p5 8882 // A function can be defined in a friend declaration of a 8883 // class . . . . Such a function is implicitly inline. 8884 NewFD->setImplicitlyInline(); 8885 } 8886 8887 // If this is a method defined in an __interface, and is not a constructor 8888 // or an overloaded operator, then set the pure flag (isVirtual will already 8889 // return true). 8890 if (const CXXRecordDecl *Parent = 8891 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8892 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8893 NewFD->setPure(true); 8894 8895 // C++ [class.union]p2 8896 // A union can have member functions, but not virtual functions. 8897 if (isVirtual && Parent->isUnion()) 8898 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8899 } 8900 8901 SetNestedNameSpecifier(*this, NewFD, D); 8902 isMemberSpecialization = false; 8903 isFunctionTemplateSpecialization = false; 8904 if (D.isInvalidType()) 8905 NewFD->setInvalidDecl(); 8906 8907 // Match up the template parameter lists with the scope specifier, then 8908 // determine whether we have a template or a template specialization. 8909 bool Invalid = false; 8910 TemplateParameterList *TemplateParams = 8911 MatchTemplateParametersToScopeSpecifier( 8912 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8913 D.getCXXScopeSpec(), 8914 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8915 ? D.getName().TemplateId 8916 : nullptr, 8917 TemplateParamLists, isFriend, isMemberSpecialization, 8918 Invalid); 8919 if (TemplateParams) { 8920 // Check that we can declare a template here. 8921 if (CheckTemplateDeclScope(S, TemplateParams)) 8922 NewFD->setInvalidDecl(); 8923 8924 if (TemplateParams->size() > 0) { 8925 // This is a function template 8926 8927 // A destructor cannot be a template. 8928 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8929 Diag(NewFD->getLocation(), diag::err_destructor_template); 8930 NewFD->setInvalidDecl(); 8931 } 8932 8933 // If we're adding a template to a dependent context, we may need to 8934 // rebuilding some of the types used within the template parameter list, 8935 // now that we know what the current instantiation is. 8936 if (DC->isDependentContext()) { 8937 ContextRAII SavedContext(*this, DC); 8938 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8939 Invalid = true; 8940 } 8941 8942 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8943 NewFD->getLocation(), 8944 Name, TemplateParams, 8945 NewFD); 8946 FunctionTemplate->setLexicalDeclContext(CurContext); 8947 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8948 8949 // For source fidelity, store the other template param lists. 8950 if (TemplateParamLists.size() > 1) { 8951 NewFD->setTemplateParameterListsInfo(Context, 8952 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8953 .drop_back(1)); 8954 } 8955 } else { 8956 // This is a function template specialization. 8957 isFunctionTemplateSpecialization = true; 8958 // For source fidelity, store all the template param lists. 8959 if (TemplateParamLists.size() > 0) 8960 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8961 8962 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8963 if (isFriend) { 8964 // We want to remove the "template<>", found here. 8965 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8966 8967 // If we remove the template<> and the name is not a 8968 // template-id, we're actually silently creating a problem: 8969 // the friend declaration will refer to an untemplated decl, 8970 // and clearly the user wants a template specialization. So 8971 // we need to insert '<>' after the name. 8972 SourceLocation InsertLoc; 8973 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8974 InsertLoc = D.getName().getSourceRange().getEnd(); 8975 InsertLoc = getLocForEndOfToken(InsertLoc); 8976 } 8977 8978 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8979 << Name << RemoveRange 8980 << FixItHint::CreateRemoval(RemoveRange) 8981 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8982 } 8983 } 8984 } else { 8985 // Check that we can declare a template here. 8986 if (!TemplateParamLists.empty() && isMemberSpecialization && 8987 CheckTemplateDeclScope(S, TemplateParamLists.back())) 8988 NewFD->setInvalidDecl(); 8989 8990 // All template param lists were matched against the scope specifier: 8991 // this is NOT (an explicit specialization of) a template. 8992 if (TemplateParamLists.size() > 0) 8993 // For source fidelity, store all the template param lists. 8994 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8995 } 8996 8997 if (Invalid) { 8998 NewFD->setInvalidDecl(); 8999 if (FunctionTemplate) 9000 FunctionTemplate->setInvalidDecl(); 9001 } 9002 9003 // C++ [dcl.fct.spec]p5: 9004 // The virtual specifier shall only be used in declarations of 9005 // nonstatic class member functions that appear within a 9006 // member-specification of a class declaration; see 10.3. 9007 // 9008 if (isVirtual && !NewFD->isInvalidDecl()) { 9009 if (!isVirtualOkay) { 9010 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9011 diag::err_virtual_non_function); 9012 } else if (!CurContext->isRecord()) { 9013 // 'virtual' was specified outside of the class. 9014 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9015 diag::err_virtual_out_of_class) 9016 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9017 } else if (NewFD->getDescribedFunctionTemplate()) { 9018 // C++ [temp.mem]p3: 9019 // A member function template shall not be virtual. 9020 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9021 diag::err_virtual_member_function_template) 9022 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9023 } else { 9024 // Okay: Add virtual to the method. 9025 NewFD->setVirtualAsWritten(true); 9026 } 9027 9028 if (getLangOpts().CPlusPlus14 && 9029 NewFD->getReturnType()->isUndeducedType()) 9030 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9031 } 9032 9033 if (getLangOpts().CPlusPlus14 && 9034 (NewFD->isDependentContext() || 9035 (isFriend && CurContext->isDependentContext())) && 9036 NewFD->getReturnType()->isUndeducedType()) { 9037 // If the function template is referenced directly (for instance, as a 9038 // member of the current instantiation), pretend it has a dependent type. 9039 // This is not really justified by the standard, but is the only sane 9040 // thing to do. 9041 // FIXME: For a friend function, we have not marked the function as being 9042 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9043 const FunctionProtoType *FPT = 9044 NewFD->getType()->castAs<FunctionProtoType>(); 9045 QualType Result = 9046 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9047 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9048 FPT->getExtProtoInfo())); 9049 } 9050 9051 // C++ [dcl.fct.spec]p3: 9052 // The inline specifier shall not appear on a block scope function 9053 // declaration. 9054 if (isInline && !NewFD->isInvalidDecl()) { 9055 if (CurContext->isFunctionOrMethod()) { 9056 // 'inline' is not allowed on block scope function declaration. 9057 Diag(D.getDeclSpec().getInlineSpecLoc(), 9058 diag::err_inline_declaration_block_scope) << Name 9059 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9060 } 9061 } 9062 9063 // C++ [dcl.fct.spec]p6: 9064 // The explicit specifier shall be used only in the declaration of a 9065 // constructor or conversion function within its class definition; 9066 // see 12.3.1 and 12.3.2. 9067 if (hasExplicit && !NewFD->isInvalidDecl() && 9068 !isa<CXXDeductionGuideDecl>(NewFD)) { 9069 if (!CurContext->isRecord()) { 9070 // 'explicit' was specified outside of the class. 9071 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9072 diag::err_explicit_out_of_class) 9073 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9074 } else if (!isa<CXXConstructorDecl>(NewFD) && 9075 !isa<CXXConversionDecl>(NewFD)) { 9076 // 'explicit' was specified on a function that wasn't a constructor 9077 // or conversion function. 9078 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9079 diag::err_explicit_non_ctor_or_conv_function) 9080 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9081 } 9082 } 9083 9084 if (ConstexprSpecKind ConstexprKind = 9085 D.getDeclSpec().getConstexprSpecifier()) { 9086 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9087 // are implicitly inline. 9088 NewFD->setImplicitlyInline(); 9089 9090 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9091 // be either constructors or to return a literal type. Therefore, 9092 // destructors cannot be declared constexpr. 9093 if (isa<CXXDestructorDecl>(NewFD) && 9094 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9095 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9096 << ConstexprKind; 9097 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9098 } 9099 // C++20 [dcl.constexpr]p2: An allocation function, or a 9100 // deallocation function shall not be declared with the consteval 9101 // specifier. 9102 if (ConstexprKind == CSK_consteval && 9103 (NewFD->getOverloadedOperator() == OO_New || 9104 NewFD->getOverloadedOperator() == OO_Array_New || 9105 NewFD->getOverloadedOperator() == OO_Delete || 9106 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9107 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9108 diag::err_invalid_consteval_decl_kind) 9109 << NewFD; 9110 NewFD->setConstexprKind(CSK_constexpr); 9111 } 9112 } 9113 9114 // If __module_private__ was specified, mark the function accordingly. 9115 if (D.getDeclSpec().isModulePrivateSpecified()) { 9116 if (isFunctionTemplateSpecialization) { 9117 SourceLocation ModulePrivateLoc 9118 = D.getDeclSpec().getModulePrivateSpecLoc(); 9119 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9120 << 0 9121 << FixItHint::CreateRemoval(ModulePrivateLoc); 9122 } else { 9123 NewFD->setModulePrivate(); 9124 if (FunctionTemplate) 9125 FunctionTemplate->setModulePrivate(); 9126 } 9127 } 9128 9129 if (isFriend) { 9130 if (FunctionTemplate) { 9131 FunctionTemplate->setObjectOfFriendDecl(); 9132 FunctionTemplate->setAccess(AS_public); 9133 } 9134 NewFD->setObjectOfFriendDecl(); 9135 NewFD->setAccess(AS_public); 9136 } 9137 9138 // If a function is defined as defaulted or deleted, mark it as such now. 9139 // We'll do the relevant checks on defaulted / deleted functions later. 9140 switch (D.getFunctionDefinitionKind()) { 9141 case FDK_Declaration: 9142 case FDK_Definition: 9143 break; 9144 9145 case FDK_Defaulted: 9146 NewFD->setDefaulted(); 9147 break; 9148 9149 case FDK_Deleted: 9150 NewFD->setDeletedAsWritten(); 9151 break; 9152 } 9153 9154 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9155 D.isFunctionDefinition()) { 9156 // C++ [class.mfct]p2: 9157 // A member function may be defined (8.4) in its class definition, in 9158 // which case it is an inline member function (7.1.2) 9159 NewFD->setImplicitlyInline(); 9160 } 9161 9162 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9163 !CurContext->isRecord()) { 9164 // C++ [class.static]p1: 9165 // A data or function member of a class may be declared static 9166 // in a class definition, in which case it is a static member of 9167 // the class. 9168 9169 // Complain about the 'static' specifier if it's on an out-of-line 9170 // member function definition. 9171 9172 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9173 // member function template declaration and class member template 9174 // declaration (MSVC versions before 2015), warn about this. 9175 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9176 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9177 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9178 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9179 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9180 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9181 } 9182 9183 // C++11 [except.spec]p15: 9184 // A deallocation function with no exception-specification is treated 9185 // as if it were specified with noexcept(true). 9186 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9187 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9188 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9189 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9190 NewFD->setType(Context.getFunctionType( 9191 FPT->getReturnType(), FPT->getParamTypes(), 9192 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9193 } 9194 9195 // Filter out previous declarations that don't match the scope. 9196 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9197 D.getCXXScopeSpec().isNotEmpty() || 9198 isMemberSpecialization || 9199 isFunctionTemplateSpecialization); 9200 9201 // Handle GNU asm-label extension (encoded as an attribute). 9202 if (Expr *E = (Expr*) D.getAsmLabel()) { 9203 // The parser guarantees this is a string. 9204 StringLiteral *SE = cast<StringLiteral>(E); 9205 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9206 /*IsLiteralLabel=*/true, 9207 SE->getStrTokenLoc(0))); 9208 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9209 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9210 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9211 if (I != ExtnameUndeclaredIdentifiers.end()) { 9212 if (isDeclExternC(NewFD)) { 9213 NewFD->addAttr(I->second); 9214 ExtnameUndeclaredIdentifiers.erase(I); 9215 } else 9216 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9217 << /*Variable*/0 << NewFD; 9218 } 9219 } 9220 9221 // Copy the parameter declarations from the declarator D to the function 9222 // declaration NewFD, if they are available. First scavenge them into Params. 9223 SmallVector<ParmVarDecl*, 16> Params; 9224 unsigned FTIIdx; 9225 if (D.isFunctionDeclarator(FTIIdx)) { 9226 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9227 9228 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9229 // function that takes no arguments, not a function that takes a 9230 // single void argument. 9231 // We let through "const void" here because Sema::GetTypeForDeclarator 9232 // already checks for that case. 9233 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9234 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9235 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9236 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9237 Param->setDeclContext(NewFD); 9238 Params.push_back(Param); 9239 9240 if (Param->isInvalidDecl()) 9241 NewFD->setInvalidDecl(); 9242 } 9243 } 9244 9245 if (!getLangOpts().CPlusPlus) { 9246 // In C, find all the tag declarations from the prototype and move them 9247 // into the function DeclContext. Remove them from the surrounding tag 9248 // injection context of the function, which is typically but not always 9249 // the TU. 9250 DeclContext *PrototypeTagContext = 9251 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9252 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9253 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9254 9255 // We don't want to reparent enumerators. Look at their parent enum 9256 // instead. 9257 if (!TD) { 9258 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9259 TD = cast<EnumDecl>(ECD->getDeclContext()); 9260 } 9261 if (!TD) 9262 continue; 9263 DeclContext *TagDC = TD->getLexicalDeclContext(); 9264 if (!TagDC->containsDecl(TD)) 9265 continue; 9266 TagDC->removeDecl(TD); 9267 TD->setDeclContext(NewFD); 9268 NewFD->addDecl(TD); 9269 9270 // Preserve the lexical DeclContext if it is not the surrounding tag 9271 // injection context of the FD. In this example, the semantic context of 9272 // E will be f and the lexical context will be S, while both the 9273 // semantic and lexical contexts of S will be f: 9274 // void f(struct S { enum E { a } f; } s); 9275 if (TagDC != PrototypeTagContext) 9276 TD->setLexicalDeclContext(TagDC); 9277 } 9278 } 9279 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9280 // When we're declaring a function with a typedef, typeof, etc as in the 9281 // following example, we'll need to synthesize (unnamed) 9282 // parameters for use in the declaration. 9283 // 9284 // @code 9285 // typedef void fn(int); 9286 // fn f; 9287 // @endcode 9288 9289 // Synthesize a parameter for each argument type. 9290 for (const auto &AI : FT->param_types()) { 9291 ParmVarDecl *Param = 9292 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9293 Param->setScopeInfo(0, Params.size()); 9294 Params.push_back(Param); 9295 } 9296 } else { 9297 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9298 "Should not need args for typedef of non-prototype fn"); 9299 } 9300 9301 // Finally, we know we have the right number of parameters, install them. 9302 NewFD->setParams(Params); 9303 9304 if (D.getDeclSpec().isNoreturnSpecified()) 9305 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9306 D.getDeclSpec().getNoreturnSpecLoc(), 9307 AttributeCommonInfo::AS_Keyword)); 9308 9309 // Functions returning a variably modified type violate C99 6.7.5.2p2 9310 // because all functions have linkage. 9311 if (!NewFD->isInvalidDecl() && 9312 NewFD->getReturnType()->isVariablyModifiedType()) { 9313 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9314 NewFD->setInvalidDecl(); 9315 } 9316 9317 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9318 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9319 !NewFD->hasAttr<SectionAttr>()) 9320 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9321 Context, PragmaClangTextSection.SectionName, 9322 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9323 9324 // Apply an implicit SectionAttr if #pragma code_seg is active. 9325 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9326 !NewFD->hasAttr<SectionAttr>()) { 9327 NewFD->addAttr(SectionAttr::CreateImplicit( 9328 Context, CodeSegStack.CurrentValue->getString(), 9329 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9330 SectionAttr::Declspec_allocate)); 9331 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9332 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9333 ASTContext::PSF_Read, 9334 NewFD)) 9335 NewFD->dropAttr<SectionAttr>(); 9336 } 9337 9338 // Apply an implicit CodeSegAttr from class declspec or 9339 // apply an implicit SectionAttr from #pragma code_seg if active. 9340 if (!NewFD->hasAttr<CodeSegAttr>()) { 9341 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9342 D.isFunctionDefinition())) { 9343 NewFD->addAttr(SAttr); 9344 } 9345 } 9346 9347 // Handle attributes. 9348 ProcessDeclAttributes(S, NewFD, D); 9349 9350 if (getLangOpts().OpenCL) { 9351 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9352 // type declaration will generate a compilation error. 9353 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9354 if (AddressSpace != LangAS::Default) { 9355 Diag(NewFD->getLocation(), 9356 diag::err_opencl_return_value_with_address_space); 9357 NewFD->setInvalidDecl(); 9358 } 9359 } 9360 9361 if (!getLangOpts().CPlusPlus) { 9362 // Perform semantic checking on the function declaration. 9363 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9364 CheckMain(NewFD, D.getDeclSpec()); 9365 9366 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9367 CheckMSVCRTEntryPoint(NewFD); 9368 9369 if (!NewFD->isInvalidDecl()) 9370 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9371 isMemberSpecialization)); 9372 else if (!Previous.empty()) 9373 // Recover gracefully from an invalid redeclaration. 9374 D.setRedeclaration(true); 9375 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9376 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9377 "previous declaration set still overloaded"); 9378 9379 // Diagnose no-prototype function declarations with calling conventions that 9380 // don't support variadic calls. Only do this in C and do it after merging 9381 // possibly prototyped redeclarations. 9382 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9383 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9384 CallingConv CC = FT->getExtInfo().getCC(); 9385 if (!supportsVariadicCall(CC)) { 9386 // Windows system headers sometimes accidentally use stdcall without 9387 // (void) parameters, so we relax this to a warning. 9388 int DiagID = 9389 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9390 Diag(NewFD->getLocation(), DiagID) 9391 << FunctionType::getNameForCallConv(CC); 9392 } 9393 } 9394 9395 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9396 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9397 checkNonTrivialCUnion(NewFD->getReturnType(), 9398 NewFD->getReturnTypeSourceRange().getBegin(), 9399 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9400 } else { 9401 // C++11 [replacement.functions]p3: 9402 // The program's definitions shall not be specified as inline. 9403 // 9404 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9405 // 9406 // Suppress the diagnostic if the function is __attribute__((used)), since 9407 // that forces an external definition to be emitted. 9408 if (D.getDeclSpec().isInlineSpecified() && 9409 NewFD->isReplaceableGlobalAllocationFunction() && 9410 !NewFD->hasAttr<UsedAttr>()) 9411 Diag(D.getDeclSpec().getInlineSpecLoc(), 9412 diag::ext_operator_new_delete_declared_inline) 9413 << NewFD->getDeclName(); 9414 9415 // If the declarator is a template-id, translate the parser's template 9416 // argument list into our AST format. 9417 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9418 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9419 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9420 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9421 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9422 TemplateId->NumArgs); 9423 translateTemplateArguments(TemplateArgsPtr, 9424 TemplateArgs); 9425 9426 HasExplicitTemplateArgs = true; 9427 9428 if (NewFD->isInvalidDecl()) { 9429 HasExplicitTemplateArgs = false; 9430 } else if (FunctionTemplate) { 9431 // Function template with explicit template arguments. 9432 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9433 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9434 9435 HasExplicitTemplateArgs = false; 9436 } else { 9437 assert((isFunctionTemplateSpecialization || 9438 D.getDeclSpec().isFriendSpecified()) && 9439 "should have a 'template<>' for this decl"); 9440 // "friend void foo<>(int);" is an implicit specialization decl. 9441 isFunctionTemplateSpecialization = true; 9442 } 9443 } else if (isFriend && isFunctionTemplateSpecialization) { 9444 // This combination is only possible in a recovery case; the user 9445 // wrote something like: 9446 // template <> friend void foo(int); 9447 // which we're recovering from as if the user had written: 9448 // friend void foo<>(int); 9449 // Go ahead and fake up a template id. 9450 HasExplicitTemplateArgs = true; 9451 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9452 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9453 } 9454 9455 // We do not add HD attributes to specializations here because 9456 // they may have different constexpr-ness compared to their 9457 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9458 // may end up with different effective targets. Instead, a 9459 // specialization inherits its target attributes from its template 9460 // in the CheckFunctionTemplateSpecialization() call below. 9461 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9462 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9463 9464 // If it's a friend (and only if it's a friend), it's possible 9465 // that either the specialized function type or the specialized 9466 // template is dependent, and therefore matching will fail. In 9467 // this case, don't check the specialization yet. 9468 bool InstantiationDependent = false; 9469 if (isFunctionTemplateSpecialization && isFriend && 9470 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9471 TemplateSpecializationType::anyDependentTemplateArguments( 9472 TemplateArgs, 9473 InstantiationDependent))) { 9474 assert(HasExplicitTemplateArgs && 9475 "friend function specialization without template args"); 9476 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9477 Previous)) 9478 NewFD->setInvalidDecl(); 9479 } else if (isFunctionTemplateSpecialization) { 9480 if (CurContext->isDependentContext() && CurContext->isRecord() 9481 && !isFriend) { 9482 isDependentClassScopeExplicitSpecialization = true; 9483 } else if (!NewFD->isInvalidDecl() && 9484 CheckFunctionTemplateSpecialization( 9485 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9486 Previous)) 9487 NewFD->setInvalidDecl(); 9488 9489 // C++ [dcl.stc]p1: 9490 // A storage-class-specifier shall not be specified in an explicit 9491 // specialization (14.7.3) 9492 FunctionTemplateSpecializationInfo *Info = 9493 NewFD->getTemplateSpecializationInfo(); 9494 if (Info && SC != SC_None) { 9495 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9496 Diag(NewFD->getLocation(), 9497 diag::err_explicit_specialization_inconsistent_storage_class) 9498 << SC 9499 << FixItHint::CreateRemoval( 9500 D.getDeclSpec().getStorageClassSpecLoc()); 9501 9502 else 9503 Diag(NewFD->getLocation(), 9504 diag::ext_explicit_specialization_storage_class) 9505 << FixItHint::CreateRemoval( 9506 D.getDeclSpec().getStorageClassSpecLoc()); 9507 } 9508 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9509 if (CheckMemberSpecialization(NewFD, Previous)) 9510 NewFD->setInvalidDecl(); 9511 } 9512 9513 // Perform semantic checking on the function declaration. 9514 if (!isDependentClassScopeExplicitSpecialization) { 9515 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9516 CheckMain(NewFD, D.getDeclSpec()); 9517 9518 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9519 CheckMSVCRTEntryPoint(NewFD); 9520 9521 if (!NewFD->isInvalidDecl()) 9522 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9523 isMemberSpecialization)); 9524 else if (!Previous.empty()) 9525 // Recover gracefully from an invalid redeclaration. 9526 D.setRedeclaration(true); 9527 } 9528 9529 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9530 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9531 "previous declaration set still overloaded"); 9532 9533 NamedDecl *PrincipalDecl = (FunctionTemplate 9534 ? cast<NamedDecl>(FunctionTemplate) 9535 : NewFD); 9536 9537 if (isFriend && NewFD->getPreviousDecl()) { 9538 AccessSpecifier Access = AS_public; 9539 if (!NewFD->isInvalidDecl()) 9540 Access = NewFD->getPreviousDecl()->getAccess(); 9541 9542 NewFD->setAccess(Access); 9543 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9544 } 9545 9546 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9547 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9548 PrincipalDecl->setNonMemberOperator(); 9549 9550 // If we have a function template, check the template parameter 9551 // list. This will check and merge default template arguments. 9552 if (FunctionTemplate) { 9553 FunctionTemplateDecl *PrevTemplate = 9554 FunctionTemplate->getPreviousDecl(); 9555 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9556 PrevTemplate ? PrevTemplate->getTemplateParameters() 9557 : nullptr, 9558 D.getDeclSpec().isFriendSpecified() 9559 ? (D.isFunctionDefinition() 9560 ? TPC_FriendFunctionTemplateDefinition 9561 : TPC_FriendFunctionTemplate) 9562 : (D.getCXXScopeSpec().isSet() && 9563 DC && DC->isRecord() && 9564 DC->isDependentContext()) 9565 ? TPC_ClassTemplateMember 9566 : TPC_FunctionTemplate); 9567 } 9568 9569 if (NewFD->isInvalidDecl()) { 9570 // Ignore all the rest of this. 9571 } else if (!D.isRedeclaration()) { 9572 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9573 AddToScope }; 9574 // Fake up an access specifier if it's supposed to be a class member. 9575 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9576 NewFD->setAccess(AS_public); 9577 9578 // Qualified decls generally require a previous declaration. 9579 if (D.getCXXScopeSpec().isSet()) { 9580 // ...with the major exception of templated-scope or 9581 // dependent-scope friend declarations. 9582 9583 // TODO: we currently also suppress this check in dependent 9584 // contexts because (1) the parameter depth will be off when 9585 // matching friend templates and (2) we might actually be 9586 // selecting a friend based on a dependent factor. But there 9587 // are situations where these conditions don't apply and we 9588 // can actually do this check immediately. 9589 // 9590 // Unless the scope is dependent, it's always an error if qualified 9591 // redeclaration lookup found nothing at all. Diagnose that now; 9592 // nothing will diagnose that error later. 9593 if (isFriend && 9594 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9595 (!Previous.empty() && CurContext->isDependentContext()))) { 9596 // ignore these 9597 } else { 9598 // The user tried to provide an out-of-line definition for a 9599 // function that is a member of a class or namespace, but there 9600 // was no such member function declared (C++ [class.mfct]p2, 9601 // C++ [namespace.memdef]p2). For example: 9602 // 9603 // class X { 9604 // void f() const; 9605 // }; 9606 // 9607 // void X::f() { } // ill-formed 9608 // 9609 // Complain about this problem, and attempt to suggest close 9610 // matches (e.g., those that differ only in cv-qualifiers and 9611 // whether the parameter types are references). 9612 9613 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9614 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9615 AddToScope = ExtraArgs.AddToScope; 9616 return Result; 9617 } 9618 } 9619 9620 // Unqualified local friend declarations are required to resolve 9621 // to something. 9622 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9623 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9624 *this, Previous, NewFD, ExtraArgs, true, S)) { 9625 AddToScope = ExtraArgs.AddToScope; 9626 return Result; 9627 } 9628 } 9629 } else if (!D.isFunctionDefinition() && 9630 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9631 !isFriend && !isFunctionTemplateSpecialization && 9632 !isMemberSpecialization) { 9633 // An out-of-line member function declaration must also be a 9634 // definition (C++ [class.mfct]p2). 9635 // Note that this is not the case for explicit specializations of 9636 // function templates or member functions of class templates, per 9637 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9638 // extension for compatibility with old SWIG code which likes to 9639 // generate them. 9640 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9641 << D.getCXXScopeSpec().getRange(); 9642 } 9643 } 9644 9645 // In C builtins get merged with implicitly lazily created declarations. 9646 // In C++ we need to check if it's a builtin and add the BuiltinAttr here. 9647 if (getLangOpts().CPlusPlus) { 9648 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9649 if (unsigned BuiltinID = II->getBuiltinID()) { 9650 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9651 // Declarations for builtins with custom typechecking by definition 9652 // don't make sense. Don't attempt typechecking and simply add the 9653 // attribute. 9654 if (Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 9655 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9656 } else { 9657 ASTContext::GetBuiltinTypeError Error; 9658 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9659 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9660 9661 if (!Error && !BuiltinType.isNull() && 9662 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9663 NewFD->getType(), BuiltinType)) 9664 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9665 } 9666 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9667 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9668 // FIXME: We should consider this a builtin only in the std namespace. 9669 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9670 } 9671 } 9672 } 9673 } 9674 9675 ProcessPragmaWeak(S, NewFD); 9676 checkAttributesAfterMerging(*this, *NewFD); 9677 9678 AddKnownFunctionAttributes(NewFD); 9679 9680 if (NewFD->hasAttr<OverloadableAttr>() && 9681 !NewFD->getType()->getAs<FunctionProtoType>()) { 9682 Diag(NewFD->getLocation(), 9683 diag::err_attribute_overloadable_no_prototype) 9684 << NewFD; 9685 9686 // Turn this into a variadic function with no parameters. 9687 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9688 FunctionProtoType::ExtProtoInfo EPI( 9689 Context.getDefaultCallingConvention(true, false)); 9690 EPI.Variadic = true; 9691 EPI.ExtInfo = FT->getExtInfo(); 9692 9693 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9694 NewFD->setType(R); 9695 } 9696 9697 // If there's a #pragma GCC visibility in scope, and this isn't a class 9698 // member, set the visibility of this function. 9699 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9700 AddPushedVisibilityAttribute(NewFD); 9701 9702 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9703 // marking the function. 9704 AddCFAuditedAttribute(NewFD); 9705 9706 // If this is a function definition, check if we have to apply optnone due to 9707 // a pragma. 9708 if(D.isFunctionDefinition()) 9709 AddRangeBasedOptnone(NewFD); 9710 9711 // If this is the first declaration of an extern C variable, update 9712 // the map of such variables. 9713 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9714 isIncompleteDeclExternC(*this, NewFD)) 9715 RegisterLocallyScopedExternCDecl(NewFD, S); 9716 9717 // Set this FunctionDecl's range up to the right paren. 9718 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9719 9720 if (D.isRedeclaration() && !Previous.empty()) { 9721 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9722 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9723 isMemberSpecialization || 9724 isFunctionTemplateSpecialization, 9725 D.isFunctionDefinition()); 9726 } 9727 9728 if (getLangOpts().CUDA) { 9729 IdentifierInfo *II = NewFD->getIdentifier(); 9730 if (II && II->isStr(getCudaConfigureFuncName()) && 9731 !NewFD->isInvalidDecl() && 9732 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9733 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9734 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9735 << getCudaConfigureFuncName(); 9736 Context.setcudaConfigureCallDecl(NewFD); 9737 } 9738 9739 // Variadic functions, other than a *declaration* of printf, are not allowed 9740 // in device-side CUDA code, unless someone passed 9741 // -fcuda-allow-variadic-functions. 9742 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9743 (NewFD->hasAttr<CUDADeviceAttr>() || 9744 NewFD->hasAttr<CUDAGlobalAttr>()) && 9745 !(II && II->isStr("printf") && NewFD->isExternC() && 9746 !D.isFunctionDefinition())) { 9747 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9748 } 9749 } 9750 9751 MarkUnusedFileScopedDecl(NewFD); 9752 9753 9754 9755 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9756 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9757 if ((getLangOpts().OpenCLVersion >= 120) 9758 && (SC == SC_Static)) { 9759 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9760 D.setInvalidType(); 9761 } 9762 9763 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9764 if (!NewFD->getReturnType()->isVoidType()) { 9765 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9766 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9767 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9768 : FixItHint()); 9769 D.setInvalidType(); 9770 } 9771 9772 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9773 for (auto Param : NewFD->parameters()) 9774 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9775 9776 if (getLangOpts().OpenCLCPlusPlus) { 9777 if (DC->isRecord()) { 9778 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9779 D.setInvalidType(); 9780 } 9781 if (FunctionTemplate) { 9782 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9783 D.setInvalidType(); 9784 } 9785 } 9786 } 9787 9788 if (getLangOpts().CPlusPlus) { 9789 if (FunctionTemplate) { 9790 if (NewFD->isInvalidDecl()) 9791 FunctionTemplate->setInvalidDecl(); 9792 return FunctionTemplate; 9793 } 9794 9795 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9796 CompleteMemberSpecialization(NewFD, Previous); 9797 } 9798 9799 for (const ParmVarDecl *Param : NewFD->parameters()) { 9800 QualType PT = Param->getType(); 9801 9802 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9803 // types. 9804 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9805 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9806 QualType ElemTy = PipeTy->getElementType(); 9807 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9808 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9809 D.setInvalidType(); 9810 } 9811 } 9812 } 9813 } 9814 9815 // Here we have an function template explicit specialization at class scope. 9816 // The actual specialization will be postponed to template instatiation 9817 // time via the ClassScopeFunctionSpecializationDecl node. 9818 if (isDependentClassScopeExplicitSpecialization) { 9819 ClassScopeFunctionSpecializationDecl *NewSpec = 9820 ClassScopeFunctionSpecializationDecl::Create( 9821 Context, CurContext, NewFD->getLocation(), 9822 cast<CXXMethodDecl>(NewFD), 9823 HasExplicitTemplateArgs, TemplateArgs); 9824 CurContext->addDecl(NewSpec); 9825 AddToScope = false; 9826 } 9827 9828 // Diagnose availability attributes. Availability cannot be used on functions 9829 // that are run during load/unload. 9830 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9831 if (NewFD->hasAttr<ConstructorAttr>()) { 9832 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9833 << 1; 9834 NewFD->dropAttr<AvailabilityAttr>(); 9835 } 9836 if (NewFD->hasAttr<DestructorAttr>()) { 9837 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9838 << 2; 9839 NewFD->dropAttr<AvailabilityAttr>(); 9840 } 9841 } 9842 9843 // Diagnose no_builtin attribute on function declaration that are not a 9844 // definition. 9845 // FIXME: We should really be doing this in 9846 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9847 // the FunctionDecl and at this point of the code 9848 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9849 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9850 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9851 switch (D.getFunctionDefinitionKind()) { 9852 case FDK_Defaulted: 9853 case FDK_Deleted: 9854 Diag(NBA->getLocation(), 9855 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9856 << NBA->getSpelling(); 9857 break; 9858 case FDK_Declaration: 9859 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9860 << NBA->getSpelling(); 9861 break; 9862 case FDK_Definition: 9863 break; 9864 } 9865 9866 return NewFD; 9867 } 9868 9869 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9870 /// when __declspec(code_seg) "is applied to a class, all member functions of 9871 /// the class and nested classes -- this includes compiler-generated special 9872 /// member functions -- are put in the specified segment." 9873 /// The actual behavior is a little more complicated. The Microsoft compiler 9874 /// won't check outer classes if there is an active value from #pragma code_seg. 9875 /// The CodeSeg is always applied from the direct parent but only from outer 9876 /// classes when the #pragma code_seg stack is empty. See: 9877 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9878 /// available since MS has removed the page. 9879 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9880 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9881 if (!Method) 9882 return nullptr; 9883 const CXXRecordDecl *Parent = Method->getParent(); 9884 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9885 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9886 NewAttr->setImplicit(true); 9887 return NewAttr; 9888 } 9889 9890 // The Microsoft compiler won't check outer classes for the CodeSeg 9891 // when the #pragma code_seg stack is active. 9892 if (S.CodeSegStack.CurrentValue) 9893 return nullptr; 9894 9895 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9896 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9897 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9898 NewAttr->setImplicit(true); 9899 return NewAttr; 9900 } 9901 } 9902 return nullptr; 9903 } 9904 9905 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9906 /// containing class. Otherwise it will return implicit SectionAttr if the 9907 /// function is a definition and there is an active value on CodeSegStack 9908 /// (from the current #pragma code-seg value). 9909 /// 9910 /// \param FD Function being declared. 9911 /// \param IsDefinition Whether it is a definition or just a declarartion. 9912 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9913 /// nullptr if no attribute should be added. 9914 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9915 bool IsDefinition) { 9916 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9917 return A; 9918 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9919 CodeSegStack.CurrentValue) 9920 return SectionAttr::CreateImplicit( 9921 getASTContext(), CodeSegStack.CurrentValue->getString(), 9922 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9923 SectionAttr::Declspec_allocate); 9924 return nullptr; 9925 } 9926 9927 /// Determines if we can perform a correct type check for \p D as a 9928 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9929 /// best-effort check. 9930 /// 9931 /// \param NewD The new declaration. 9932 /// \param OldD The old declaration. 9933 /// \param NewT The portion of the type of the new declaration to check. 9934 /// \param OldT The portion of the type of the old declaration to check. 9935 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9936 QualType NewT, QualType OldT) { 9937 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9938 return true; 9939 9940 // For dependently-typed local extern declarations and friends, we can't 9941 // perform a correct type check in general until instantiation: 9942 // 9943 // int f(); 9944 // template<typename T> void g() { T f(); } 9945 // 9946 // (valid if g() is only instantiated with T = int). 9947 if (NewT->isDependentType() && 9948 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9949 return false; 9950 9951 // Similarly, if the previous declaration was a dependent local extern 9952 // declaration, we don't really know its type yet. 9953 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9954 return false; 9955 9956 return true; 9957 } 9958 9959 /// Checks if the new declaration declared in dependent context must be 9960 /// put in the same redeclaration chain as the specified declaration. 9961 /// 9962 /// \param D Declaration that is checked. 9963 /// \param PrevDecl Previous declaration found with proper lookup method for the 9964 /// same declaration name. 9965 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9966 /// belongs to. 9967 /// 9968 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9969 if (!D->getLexicalDeclContext()->isDependentContext()) 9970 return true; 9971 9972 // Don't chain dependent friend function definitions until instantiation, to 9973 // permit cases like 9974 // 9975 // void func(); 9976 // template<typename T> class C1 { friend void func() {} }; 9977 // template<typename T> class C2 { friend void func() {} }; 9978 // 9979 // ... which is valid if only one of C1 and C2 is ever instantiated. 9980 // 9981 // FIXME: This need only apply to function definitions. For now, we proxy 9982 // this by checking for a file-scope function. We do not want this to apply 9983 // to friend declarations nominating member functions, because that gets in 9984 // the way of access checks. 9985 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9986 return false; 9987 9988 auto *VD = dyn_cast<ValueDecl>(D); 9989 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9990 return !VD || !PrevVD || 9991 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9992 PrevVD->getType()); 9993 } 9994 9995 /// Check the target attribute of the function for MultiVersion 9996 /// validity. 9997 /// 9998 /// Returns true if there was an error, false otherwise. 9999 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10000 const auto *TA = FD->getAttr<TargetAttr>(); 10001 assert(TA && "MultiVersion Candidate requires a target attribute"); 10002 ParsedTargetAttr ParseInfo = TA->parse(); 10003 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10004 enum ErrType { Feature = 0, Architecture = 1 }; 10005 10006 if (!ParseInfo.Architecture.empty() && 10007 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10008 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10009 << Architecture << ParseInfo.Architecture; 10010 return true; 10011 } 10012 10013 for (const auto &Feat : ParseInfo.Features) { 10014 auto BareFeat = StringRef{Feat}.substr(1); 10015 if (Feat[0] == '-') { 10016 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10017 << Feature << ("no-" + BareFeat).str(); 10018 return true; 10019 } 10020 10021 if (!TargetInfo.validateCpuSupports(BareFeat) || 10022 !TargetInfo.isValidFeatureName(BareFeat)) { 10023 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10024 << Feature << BareFeat; 10025 return true; 10026 } 10027 } 10028 return false; 10029 } 10030 10031 // Provide a white-list of attributes that are allowed to be combined with 10032 // multiversion functions. 10033 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10034 MultiVersionKind MVType) { 10035 // Note: this list/diagnosis must match the list in 10036 // checkMultiversionAttributesAllSame. 10037 switch (Kind) { 10038 default: 10039 return false; 10040 case attr::Used: 10041 return MVType == MultiVersionKind::Target; 10042 case attr::NonNull: 10043 case attr::NoThrow: 10044 return true; 10045 } 10046 } 10047 10048 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10049 const FunctionDecl *FD, 10050 const FunctionDecl *CausedFD, 10051 MultiVersionKind MVType) { 10052 bool IsCPUSpecificCPUDispatchMVType = 10053 MVType == MultiVersionKind::CPUDispatch || 10054 MVType == MultiVersionKind::CPUSpecific; 10055 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10056 Sema &S, const Attr *A) { 10057 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10058 << IsCPUSpecificCPUDispatchMVType << A; 10059 if (CausedFD) 10060 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10061 return true; 10062 }; 10063 10064 for (const Attr *A : FD->attrs()) { 10065 switch (A->getKind()) { 10066 case attr::CPUDispatch: 10067 case attr::CPUSpecific: 10068 if (MVType != MultiVersionKind::CPUDispatch && 10069 MVType != MultiVersionKind::CPUSpecific) 10070 return Diagnose(S, A); 10071 break; 10072 case attr::Target: 10073 if (MVType != MultiVersionKind::Target) 10074 return Diagnose(S, A); 10075 break; 10076 default: 10077 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10078 return Diagnose(S, A); 10079 break; 10080 } 10081 } 10082 return false; 10083 } 10084 10085 bool Sema::areMultiversionVariantFunctionsCompatible( 10086 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10087 const PartialDiagnostic &NoProtoDiagID, 10088 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10089 const PartialDiagnosticAt &NoSupportDiagIDAt, 10090 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10091 bool ConstexprSupported, bool CLinkageMayDiffer) { 10092 enum DoesntSupport { 10093 FuncTemplates = 0, 10094 VirtFuncs = 1, 10095 DeducedReturn = 2, 10096 Constructors = 3, 10097 Destructors = 4, 10098 DeletedFuncs = 5, 10099 DefaultedFuncs = 6, 10100 ConstexprFuncs = 7, 10101 ConstevalFuncs = 8, 10102 }; 10103 enum Different { 10104 CallingConv = 0, 10105 ReturnType = 1, 10106 ConstexprSpec = 2, 10107 InlineSpec = 3, 10108 StorageClass = 4, 10109 Linkage = 5, 10110 }; 10111 10112 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10113 !OldFD->getType()->getAs<FunctionProtoType>()) { 10114 Diag(OldFD->getLocation(), NoProtoDiagID); 10115 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10116 return true; 10117 } 10118 10119 if (NoProtoDiagID.getDiagID() != 0 && 10120 !NewFD->getType()->getAs<FunctionProtoType>()) 10121 return Diag(NewFD->getLocation(), NoProtoDiagID); 10122 10123 if (!TemplatesSupported && 10124 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10125 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10126 << FuncTemplates; 10127 10128 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10129 if (NewCXXFD->isVirtual()) 10130 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10131 << VirtFuncs; 10132 10133 if (isa<CXXConstructorDecl>(NewCXXFD)) 10134 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10135 << Constructors; 10136 10137 if (isa<CXXDestructorDecl>(NewCXXFD)) 10138 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10139 << Destructors; 10140 } 10141 10142 if (NewFD->isDeleted()) 10143 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10144 << DeletedFuncs; 10145 10146 if (NewFD->isDefaulted()) 10147 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10148 << DefaultedFuncs; 10149 10150 if (!ConstexprSupported && NewFD->isConstexpr()) 10151 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10152 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10153 10154 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10155 const auto *NewType = cast<FunctionType>(NewQType); 10156 QualType NewReturnType = NewType->getReturnType(); 10157 10158 if (NewReturnType->isUndeducedType()) 10159 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10160 << DeducedReturn; 10161 10162 // Ensure the return type is identical. 10163 if (OldFD) { 10164 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10165 const auto *OldType = cast<FunctionType>(OldQType); 10166 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10167 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10168 10169 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10170 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10171 10172 QualType OldReturnType = OldType->getReturnType(); 10173 10174 if (OldReturnType != NewReturnType) 10175 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10176 10177 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10178 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10179 10180 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10181 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10182 10183 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10184 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10185 10186 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10187 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10188 10189 if (CheckEquivalentExceptionSpec( 10190 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10191 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10192 return true; 10193 } 10194 return false; 10195 } 10196 10197 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10198 const FunctionDecl *NewFD, 10199 bool CausesMV, 10200 MultiVersionKind MVType) { 10201 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10202 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10203 if (OldFD) 10204 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10205 return true; 10206 } 10207 10208 bool IsCPUSpecificCPUDispatchMVType = 10209 MVType == MultiVersionKind::CPUDispatch || 10210 MVType == MultiVersionKind::CPUSpecific; 10211 10212 if (CausesMV && OldFD && 10213 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10214 return true; 10215 10216 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10217 return true; 10218 10219 // Only allow transition to MultiVersion if it hasn't been used. 10220 if (OldFD && CausesMV && OldFD->isUsed(false)) 10221 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10222 10223 return S.areMultiversionVariantFunctionsCompatible( 10224 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10225 PartialDiagnosticAt(NewFD->getLocation(), 10226 S.PDiag(diag::note_multiversioning_caused_here)), 10227 PartialDiagnosticAt(NewFD->getLocation(), 10228 S.PDiag(diag::err_multiversion_doesnt_support) 10229 << IsCPUSpecificCPUDispatchMVType), 10230 PartialDiagnosticAt(NewFD->getLocation(), 10231 S.PDiag(diag::err_multiversion_diff)), 10232 /*TemplatesSupported=*/false, 10233 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10234 /*CLinkageMayDiffer=*/false); 10235 } 10236 10237 /// Check the validity of a multiversion function declaration that is the 10238 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10239 /// 10240 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10241 /// 10242 /// Returns true if there was an error, false otherwise. 10243 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10244 MultiVersionKind MVType, 10245 const TargetAttr *TA) { 10246 assert(MVType != MultiVersionKind::None && 10247 "Function lacks multiversion attribute"); 10248 10249 // Target only causes MV if it is default, otherwise this is a normal 10250 // function. 10251 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10252 return false; 10253 10254 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10255 FD->setInvalidDecl(); 10256 return true; 10257 } 10258 10259 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10260 FD->setInvalidDecl(); 10261 return true; 10262 } 10263 10264 FD->setIsMultiVersion(); 10265 return false; 10266 } 10267 10268 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10269 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10270 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10271 return true; 10272 } 10273 10274 return false; 10275 } 10276 10277 static bool CheckTargetCausesMultiVersioning( 10278 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10279 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10280 LookupResult &Previous) { 10281 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10282 ParsedTargetAttr NewParsed = NewTA->parse(); 10283 // Sort order doesn't matter, it just needs to be consistent. 10284 llvm::sort(NewParsed.Features); 10285 10286 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10287 // to change, this is a simple redeclaration. 10288 if (!NewTA->isDefaultVersion() && 10289 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10290 return false; 10291 10292 // Otherwise, this decl causes MultiVersioning. 10293 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10294 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10295 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10296 NewFD->setInvalidDecl(); 10297 return true; 10298 } 10299 10300 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10301 MultiVersionKind::Target)) { 10302 NewFD->setInvalidDecl(); 10303 return true; 10304 } 10305 10306 if (CheckMultiVersionValue(S, NewFD)) { 10307 NewFD->setInvalidDecl(); 10308 return true; 10309 } 10310 10311 // If this is 'default', permit the forward declaration. 10312 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10313 Redeclaration = true; 10314 OldDecl = OldFD; 10315 OldFD->setIsMultiVersion(); 10316 NewFD->setIsMultiVersion(); 10317 return false; 10318 } 10319 10320 if (CheckMultiVersionValue(S, OldFD)) { 10321 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10322 NewFD->setInvalidDecl(); 10323 return true; 10324 } 10325 10326 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10327 10328 if (OldParsed == NewParsed) { 10329 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10330 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10331 NewFD->setInvalidDecl(); 10332 return true; 10333 } 10334 10335 for (const auto *FD : OldFD->redecls()) { 10336 const auto *CurTA = FD->getAttr<TargetAttr>(); 10337 // We allow forward declarations before ANY multiversioning attributes, but 10338 // nothing after the fact. 10339 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10340 (!CurTA || CurTA->isInherited())) { 10341 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10342 << 0; 10343 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10344 NewFD->setInvalidDecl(); 10345 return true; 10346 } 10347 } 10348 10349 OldFD->setIsMultiVersion(); 10350 NewFD->setIsMultiVersion(); 10351 Redeclaration = false; 10352 MergeTypeWithPrevious = false; 10353 OldDecl = nullptr; 10354 Previous.clear(); 10355 return false; 10356 } 10357 10358 /// Check the validity of a new function declaration being added to an existing 10359 /// multiversioned declaration collection. 10360 static bool CheckMultiVersionAdditionalDecl( 10361 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10362 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10363 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10364 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10365 LookupResult &Previous) { 10366 10367 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10368 // Disallow mixing of multiversioning types. 10369 if ((OldMVType == MultiVersionKind::Target && 10370 NewMVType != MultiVersionKind::Target) || 10371 (NewMVType == MultiVersionKind::Target && 10372 OldMVType != MultiVersionKind::Target)) { 10373 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10374 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10375 NewFD->setInvalidDecl(); 10376 return true; 10377 } 10378 10379 ParsedTargetAttr NewParsed; 10380 if (NewTA) { 10381 NewParsed = NewTA->parse(); 10382 llvm::sort(NewParsed.Features); 10383 } 10384 10385 bool UseMemberUsingDeclRules = 10386 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10387 10388 // Next, check ALL non-overloads to see if this is a redeclaration of a 10389 // previous member of the MultiVersion set. 10390 for (NamedDecl *ND : Previous) { 10391 FunctionDecl *CurFD = ND->getAsFunction(); 10392 if (!CurFD) 10393 continue; 10394 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10395 continue; 10396 10397 if (NewMVType == MultiVersionKind::Target) { 10398 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10399 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10400 NewFD->setIsMultiVersion(); 10401 Redeclaration = true; 10402 OldDecl = ND; 10403 return false; 10404 } 10405 10406 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10407 if (CurParsed == NewParsed) { 10408 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10409 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10410 NewFD->setInvalidDecl(); 10411 return true; 10412 } 10413 } else { 10414 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10415 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10416 // Handle CPUDispatch/CPUSpecific versions. 10417 // Only 1 CPUDispatch function is allowed, this will make it go through 10418 // the redeclaration errors. 10419 if (NewMVType == MultiVersionKind::CPUDispatch && 10420 CurFD->hasAttr<CPUDispatchAttr>()) { 10421 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10422 std::equal( 10423 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10424 NewCPUDisp->cpus_begin(), 10425 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10426 return Cur->getName() == New->getName(); 10427 })) { 10428 NewFD->setIsMultiVersion(); 10429 Redeclaration = true; 10430 OldDecl = ND; 10431 return false; 10432 } 10433 10434 // If the declarations don't match, this is an error condition. 10435 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10436 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10437 NewFD->setInvalidDecl(); 10438 return true; 10439 } 10440 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10441 10442 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10443 std::equal( 10444 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10445 NewCPUSpec->cpus_begin(), 10446 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10447 return Cur->getName() == New->getName(); 10448 })) { 10449 NewFD->setIsMultiVersion(); 10450 Redeclaration = true; 10451 OldDecl = ND; 10452 return false; 10453 } 10454 10455 // Only 1 version of CPUSpecific is allowed for each CPU. 10456 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10457 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10458 if (CurII == NewII) { 10459 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10460 << NewII; 10461 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10462 NewFD->setInvalidDecl(); 10463 return true; 10464 } 10465 } 10466 } 10467 } 10468 // If the two decls aren't the same MVType, there is no possible error 10469 // condition. 10470 } 10471 } 10472 10473 // Else, this is simply a non-redecl case. Checking the 'value' is only 10474 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10475 // handled in the attribute adding step. 10476 if (NewMVType == MultiVersionKind::Target && 10477 CheckMultiVersionValue(S, NewFD)) { 10478 NewFD->setInvalidDecl(); 10479 return true; 10480 } 10481 10482 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10483 !OldFD->isMultiVersion(), NewMVType)) { 10484 NewFD->setInvalidDecl(); 10485 return true; 10486 } 10487 10488 // Permit forward declarations in the case where these two are compatible. 10489 if (!OldFD->isMultiVersion()) { 10490 OldFD->setIsMultiVersion(); 10491 NewFD->setIsMultiVersion(); 10492 Redeclaration = true; 10493 OldDecl = OldFD; 10494 return false; 10495 } 10496 10497 NewFD->setIsMultiVersion(); 10498 Redeclaration = false; 10499 MergeTypeWithPrevious = false; 10500 OldDecl = nullptr; 10501 Previous.clear(); 10502 return false; 10503 } 10504 10505 10506 /// Check the validity of a mulitversion function declaration. 10507 /// Also sets the multiversion'ness' of the function itself. 10508 /// 10509 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10510 /// 10511 /// Returns true if there was an error, false otherwise. 10512 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10513 bool &Redeclaration, NamedDecl *&OldDecl, 10514 bool &MergeTypeWithPrevious, 10515 LookupResult &Previous) { 10516 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10517 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10518 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10519 10520 // Mixing Multiversioning types is prohibited. 10521 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10522 (NewCPUDisp && NewCPUSpec)) { 10523 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10524 NewFD->setInvalidDecl(); 10525 return true; 10526 } 10527 10528 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10529 10530 // Main isn't allowed to become a multiversion function, however it IS 10531 // permitted to have 'main' be marked with the 'target' optimization hint. 10532 if (NewFD->isMain()) { 10533 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10534 MVType == MultiVersionKind::CPUDispatch || 10535 MVType == MultiVersionKind::CPUSpecific) { 10536 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10537 NewFD->setInvalidDecl(); 10538 return true; 10539 } 10540 return false; 10541 } 10542 10543 if (!OldDecl || !OldDecl->getAsFunction() || 10544 OldDecl->getDeclContext()->getRedeclContext() != 10545 NewFD->getDeclContext()->getRedeclContext()) { 10546 // If there's no previous declaration, AND this isn't attempting to cause 10547 // multiversioning, this isn't an error condition. 10548 if (MVType == MultiVersionKind::None) 10549 return false; 10550 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10551 } 10552 10553 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10554 10555 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10556 return false; 10557 10558 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10559 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10560 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10561 NewFD->setInvalidDecl(); 10562 return true; 10563 } 10564 10565 // Handle the target potentially causes multiversioning case. 10566 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10567 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10568 Redeclaration, OldDecl, 10569 MergeTypeWithPrevious, Previous); 10570 10571 // At this point, we have a multiversion function decl (in OldFD) AND an 10572 // appropriate attribute in the current function decl. Resolve that these are 10573 // still compatible with previous declarations. 10574 return CheckMultiVersionAdditionalDecl( 10575 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10576 OldDecl, MergeTypeWithPrevious, Previous); 10577 } 10578 10579 /// Perform semantic checking of a new function declaration. 10580 /// 10581 /// Performs semantic analysis of the new function declaration 10582 /// NewFD. This routine performs all semantic checking that does not 10583 /// require the actual declarator involved in the declaration, and is 10584 /// used both for the declaration of functions as they are parsed 10585 /// (called via ActOnDeclarator) and for the declaration of functions 10586 /// that have been instantiated via C++ template instantiation (called 10587 /// via InstantiateDecl). 10588 /// 10589 /// \param IsMemberSpecialization whether this new function declaration is 10590 /// a member specialization (that replaces any definition provided by the 10591 /// previous declaration). 10592 /// 10593 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10594 /// 10595 /// \returns true if the function declaration is a redeclaration. 10596 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10597 LookupResult &Previous, 10598 bool IsMemberSpecialization) { 10599 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10600 "Variably modified return types are not handled here"); 10601 10602 // Determine whether the type of this function should be merged with 10603 // a previous visible declaration. This never happens for functions in C++, 10604 // and always happens in C if the previous declaration was visible. 10605 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10606 !Previous.isShadowed(); 10607 10608 bool Redeclaration = false; 10609 NamedDecl *OldDecl = nullptr; 10610 bool MayNeedOverloadableChecks = false; 10611 10612 // Merge or overload the declaration with an existing declaration of 10613 // the same name, if appropriate. 10614 if (!Previous.empty()) { 10615 // Determine whether NewFD is an overload of PrevDecl or 10616 // a declaration that requires merging. If it's an overload, 10617 // there's no more work to do here; we'll just add the new 10618 // function to the scope. 10619 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10620 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10621 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10622 Redeclaration = true; 10623 OldDecl = Candidate; 10624 } 10625 } else { 10626 MayNeedOverloadableChecks = true; 10627 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10628 /*NewIsUsingDecl*/ false)) { 10629 case Ovl_Match: 10630 Redeclaration = true; 10631 break; 10632 10633 case Ovl_NonFunction: 10634 Redeclaration = true; 10635 break; 10636 10637 case Ovl_Overload: 10638 Redeclaration = false; 10639 break; 10640 } 10641 } 10642 } 10643 10644 // Check for a previous extern "C" declaration with this name. 10645 if (!Redeclaration && 10646 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10647 if (!Previous.empty()) { 10648 // This is an extern "C" declaration with the same name as a previous 10649 // declaration, and thus redeclares that entity... 10650 Redeclaration = true; 10651 OldDecl = Previous.getFoundDecl(); 10652 MergeTypeWithPrevious = false; 10653 10654 // ... except in the presence of __attribute__((overloadable)). 10655 if (OldDecl->hasAttr<OverloadableAttr>() || 10656 NewFD->hasAttr<OverloadableAttr>()) { 10657 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10658 MayNeedOverloadableChecks = true; 10659 Redeclaration = false; 10660 OldDecl = nullptr; 10661 } 10662 } 10663 } 10664 } 10665 10666 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10667 MergeTypeWithPrevious, Previous)) 10668 return Redeclaration; 10669 10670 // C++11 [dcl.constexpr]p8: 10671 // A constexpr specifier for a non-static member function that is not 10672 // a constructor declares that member function to be const. 10673 // 10674 // This needs to be delayed until we know whether this is an out-of-line 10675 // definition of a static member function. 10676 // 10677 // This rule is not present in C++1y, so we produce a backwards 10678 // compatibility warning whenever it happens in C++11. 10679 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10680 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10681 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10682 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10683 CXXMethodDecl *OldMD = nullptr; 10684 if (OldDecl) 10685 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10686 if (!OldMD || !OldMD->isStatic()) { 10687 const FunctionProtoType *FPT = 10688 MD->getType()->castAs<FunctionProtoType>(); 10689 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10690 EPI.TypeQuals.addConst(); 10691 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10692 FPT->getParamTypes(), EPI)); 10693 10694 // Warn that we did this, if we're not performing template instantiation. 10695 // In that case, we'll have warned already when the template was defined. 10696 if (!inTemplateInstantiation()) { 10697 SourceLocation AddConstLoc; 10698 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10699 .IgnoreParens().getAs<FunctionTypeLoc>()) 10700 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10701 10702 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10703 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10704 } 10705 } 10706 } 10707 10708 if (Redeclaration) { 10709 // NewFD and OldDecl represent declarations that need to be 10710 // merged. 10711 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10712 NewFD->setInvalidDecl(); 10713 return Redeclaration; 10714 } 10715 10716 Previous.clear(); 10717 Previous.addDecl(OldDecl); 10718 10719 if (FunctionTemplateDecl *OldTemplateDecl = 10720 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10721 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10722 FunctionTemplateDecl *NewTemplateDecl 10723 = NewFD->getDescribedFunctionTemplate(); 10724 assert(NewTemplateDecl && "Template/non-template mismatch"); 10725 10726 // The call to MergeFunctionDecl above may have created some state in 10727 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10728 // can add it as a redeclaration. 10729 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10730 10731 NewFD->setPreviousDeclaration(OldFD); 10732 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10733 if (NewFD->isCXXClassMember()) { 10734 NewFD->setAccess(OldTemplateDecl->getAccess()); 10735 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10736 } 10737 10738 // If this is an explicit specialization of a member that is a function 10739 // template, mark it as a member specialization. 10740 if (IsMemberSpecialization && 10741 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10742 NewTemplateDecl->setMemberSpecialization(); 10743 assert(OldTemplateDecl->isMemberSpecialization()); 10744 // Explicit specializations of a member template do not inherit deleted 10745 // status from the parent member template that they are specializing. 10746 if (OldFD->isDeleted()) { 10747 // FIXME: This assert will not hold in the presence of modules. 10748 assert(OldFD->getCanonicalDecl() == OldFD); 10749 // FIXME: We need an update record for this AST mutation. 10750 OldFD->setDeletedAsWritten(false); 10751 } 10752 } 10753 10754 } else { 10755 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10756 auto *OldFD = cast<FunctionDecl>(OldDecl); 10757 // This needs to happen first so that 'inline' propagates. 10758 NewFD->setPreviousDeclaration(OldFD); 10759 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10760 if (NewFD->isCXXClassMember()) 10761 NewFD->setAccess(OldFD->getAccess()); 10762 } 10763 } 10764 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10765 !NewFD->getAttr<OverloadableAttr>()) { 10766 assert((Previous.empty() || 10767 llvm::any_of(Previous, 10768 [](const NamedDecl *ND) { 10769 return ND->hasAttr<OverloadableAttr>(); 10770 })) && 10771 "Non-redecls shouldn't happen without overloadable present"); 10772 10773 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10774 const auto *FD = dyn_cast<FunctionDecl>(ND); 10775 return FD && !FD->hasAttr<OverloadableAttr>(); 10776 }); 10777 10778 if (OtherUnmarkedIter != Previous.end()) { 10779 Diag(NewFD->getLocation(), 10780 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10781 Diag((*OtherUnmarkedIter)->getLocation(), 10782 diag::note_attribute_overloadable_prev_overload) 10783 << false; 10784 10785 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10786 } 10787 } 10788 10789 // Semantic checking for this function declaration (in isolation). 10790 10791 if (getLangOpts().CPlusPlus) { 10792 // C++-specific checks. 10793 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10794 CheckConstructor(Constructor); 10795 } else if (CXXDestructorDecl *Destructor = 10796 dyn_cast<CXXDestructorDecl>(NewFD)) { 10797 CXXRecordDecl *Record = Destructor->getParent(); 10798 QualType ClassType = Context.getTypeDeclType(Record); 10799 10800 // FIXME: Shouldn't we be able to perform this check even when the class 10801 // type is dependent? Both gcc and edg can handle that. 10802 if (!ClassType->isDependentType()) { 10803 DeclarationName Name 10804 = Context.DeclarationNames.getCXXDestructorName( 10805 Context.getCanonicalType(ClassType)); 10806 if (NewFD->getDeclName() != Name) { 10807 Diag(NewFD->getLocation(), diag::err_destructor_name); 10808 NewFD->setInvalidDecl(); 10809 return Redeclaration; 10810 } 10811 } 10812 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10813 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10814 CheckDeductionGuideTemplate(TD); 10815 10816 // A deduction guide is not on the list of entities that can be 10817 // explicitly specialized. 10818 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10819 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10820 << /*explicit specialization*/ 1; 10821 } 10822 10823 // Find any virtual functions that this function overrides. 10824 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10825 if (!Method->isFunctionTemplateSpecialization() && 10826 !Method->getDescribedFunctionTemplate() && 10827 Method->isCanonicalDecl()) { 10828 AddOverriddenMethods(Method->getParent(), Method); 10829 } 10830 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10831 // C++2a [class.virtual]p6 10832 // A virtual method shall not have a requires-clause. 10833 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10834 diag::err_constrained_virtual_method); 10835 10836 if (Method->isStatic()) 10837 checkThisInStaticMemberFunctionType(Method); 10838 } 10839 10840 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10841 ActOnConversionDeclarator(Conversion); 10842 10843 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10844 if (NewFD->isOverloadedOperator() && 10845 CheckOverloadedOperatorDeclaration(NewFD)) { 10846 NewFD->setInvalidDecl(); 10847 return Redeclaration; 10848 } 10849 10850 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10851 if (NewFD->getLiteralIdentifier() && 10852 CheckLiteralOperatorDeclaration(NewFD)) { 10853 NewFD->setInvalidDecl(); 10854 return Redeclaration; 10855 } 10856 10857 // In C++, check default arguments now that we have merged decls. Unless 10858 // the lexical context is the class, because in this case this is done 10859 // during delayed parsing anyway. 10860 if (!CurContext->isRecord()) 10861 CheckCXXDefaultArguments(NewFD); 10862 10863 // If this function declares a builtin function, check the type of this 10864 // declaration against the expected type for the builtin. 10865 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10866 ASTContext::GetBuiltinTypeError Error; 10867 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10868 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10869 // If the type of the builtin differs only in its exception 10870 // specification, that's OK. 10871 // FIXME: If the types do differ in this way, it would be better to 10872 // retain the 'noexcept' form of the type. 10873 if (!T.isNull() && 10874 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10875 NewFD->getType())) 10876 // The type of this function differs from the type of the builtin, 10877 // so forget about the builtin entirely. 10878 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10879 } 10880 10881 // If this function is declared as being extern "C", then check to see if 10882 // the function returns a UDT (class, struct, or union type) that is not C 10883 // compatible, and if it does, warn the user. 10884 // But, issue any diagnostic on the first declaration only. 10885 if (Previous.empty() && NewFD->isExternC()) { 10886 QualType R = NewFD->getReturnType(); 10887 if (R->isIncompleteType() && !R->isVoidType()) 10888 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10889 << NewFD << R; 10890 else if (!R.isPODType(Context) && !R->isVoidType() && 10891 !R->isObjCObjectPointerType()) 10892 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10893 } 10894 10895 // C++1z [dcl.fct]p6: 10896 // [...] whether the function has a non-throwing exception-specification 10897 // [is] part of the function type 10898 // 10899 // This results in an ABI break between C++14 and C++17 for functions whose 10900 // declared type includes an exception-specification in a parameter or 10901 // return type. (Exception specifications on the function itself are OK in 10902 // most cases, and exception specifications are not permitted in most other 10903 // contexts where they could make it into a mangling.) 10904 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10905 auto HasNoexcept = [&](QualType T) -> bool { 10906 // Strip off declarator chunks that could be between us and a function 10907 // type. We don't need to look far, exception specifications are very 10908 // restricted prior to C++17. 10909 if (auto *RT = T->getAs<ReferenceType>()) 10910 T = RT->getPointeeType(); 10911 else if (T->isAnyPointerType()) 10912 T = T->getPointeeType(); 10913 else if (auto *MPT = T->getAs<MemberPointerType>()) 10914 T = MPT->getPointeeType(); 10915 if (auto *FPT = T->getAs<FunctionProtoType>()) 10916 if (FPT->isNothrow()) 10917 return true; 10918 return false; 10919 }; 10920 10921 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10922 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10923 for (QualType T : FPT->param_types()) 10924 AnyNoexcept |= HasNoexcept(T); 10925 if (AnyNoexcept) 10926 Diag(NewFD->getLocation(), 10927 diag::warn_cxx17_compat_exception_spec_in_signature) 10928 << NewFD; 10929 } 10930 10931 if (!Redeclaration && LangOpts.CUDA) 10932 checkCUDATargetOverload(NewFD, Previous); 10933 } 10934 return Redeclaration; 10935 } 10936 10937 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10938 // C++11 [basic.start.main]p3: 10939 // A program that [...] declares main to be inline, static or 10940 // constexpr is ill-formed. 10941 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10942 // appear in a declaration of main. 10943 // static main is not an error under C99, but we should warn about it. 10944 // We accept _Noreturn main as an extension. 10945 if (FD->getStorageClass() == SC_Static) 10946 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10947 ? diag::err_static_main : diag::warn_static_main) 10948 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10949 if (FD->isInlineSpecified()) 10950 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10951 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10952 if (DS.isNoreturnSpecified()) { 10953 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10954 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10955 Diag(NoreturnLoc, diag::ext_noreturn_main); 10956 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10957 << FixItHint::CreateRemoval(NoreturnRange); 10958 } 10959 if (FD->isConstexpr()) { 10960 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10961 << FD->isConsteval() 10962 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10963 FD->setConstexprKind(CSK_unspecified); 10964 } 10965 10966 if (getLangOpts().OpenCL) { 10967 Diag(FD->getLocation(), diag::err_opencl_no_main) 10968 << FD->hasAttr<OpenCLKernelAttr>(); 10969 FD->setInvalidDecl(); 10970 return; 10971 } 10972 10973 QualType T = FD->getType(); 10974 assert(T->isFunctionType() && "function decl is not of function type"); 10975 const FunctionType* FT = T->castAs<FunctionType>(); 10976 10977 // Set default calling convention for main() 10978 if (FT->getCallConv() != CC_C) { 10979 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10980 FD->setType(QualType(FT, 0)); 10981 T = Context.getCanonicalType(FD->getType()); 10982 } 10983 10984 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10985 // In C with GNU extensions we allow main() to have non-integer return 10986 // type, but we should warn about the extension, and we disable the 10987 // implicit-return-zero rule. 10988 10989 // GCC in C mode accepts qualified 'int'. 10990 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10991 FD->setHasImplicitReturnZero(true); 10992 else { 10993 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10994 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10995 if (RTRange.isValid()) 10996 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10997 << FixItHint::CreateReplacement(RTRange, "int"); 10998 } 10999 } else { 11000 // In C and C++, main magically returns 0 if you fall off the end; 11001 // set the flag which tells us that. 11002 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11003 11004 // All the standards say that main() should return 'int'. 11005 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11006 FD->setHasImplicitReturnZero(true); 11007 else { 11008 // Otherwise, this is just a flat-out error. 11009 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11010 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11011 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11012 : FixItHint()); 11013 FD->setInvalidDecl(true); 11014 } 11015 } 11016 11017 // Treat protoless main() as nullary. 11018 if (isa<FunctionNoProtoType>(FT)) return; 11019 11020 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11021 unsigned nparams = FTP->getNumParams(); 11022 assert(FD->getNumParams() == nparams); 11023 11024 bool HasExtraParameters = (nparams > 3); 11025 11026 if (FTP->isVariadic()) { 11027 Diag(FD->getLocation(), diag::ext_variadic_main); 11028 // FIXME: if we had information about the location of the ellipsis, we 11029 // could add a FixIt hint to remove it as a parameter. 11030 } 11031 11032 // Darwin passes an undocumented fourth argument of type char**. If 11033 // other platforms start sprouting these, the logic below will start 11034 // getting shifty. 11035 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11036 HasExtraParameters = false; 11037 11038 if (HasExtraParameters) { 11039 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11040 FD->setInvalidDecl(true); 11041 nparams = 3; 11042 } 11043 11044 // FIXME: a lot of the following diagnostics would be improved 11045 // if we had some location information about types. 11046 11047 QualType CharPP = 11048 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11049 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11050 11051 for (unsigned i = 0; i < nparams; ++i) { 11052 QualType AT = FTP->getParamType(i); 11053 11054 bool mismatch = true; 11055 11056 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11057 mismatch = false; 11058 else if (Expected[i] == CharPP) { 11059 // As an extension, the following forms are okay: 11060 // char const ** 11061 // char const * const * 11062 // char * const * 11063 11064 QualifierCollector qs; 11065 const PointerType* PT; 11066 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11067 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11068 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11069 Context.CharTy)) { 11070 qs.removeConst(); 11071 mismatch = !qs.empty(); 11072 } 11073 } 11074 11075 if (mismatch) { 11076 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11077 // TODO: suggest replacing given type with expected type 11078 FD->setInvalidDecl(true); 11079 } 11080 } 11081 11082 if (nparams == 1 && !FD->isInvalidDecl()) { 11083 Diag(FD->getLocation(), diag::warn_main_one_arg); 11084 } 11085 11086 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11087 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11088 FD->setInvalidDecl(); 11089 } 11090 } 11091 11092 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11093 QualType T = FD->getType(); 11094 assert(T->isFunctionType() && "function decl is not of function type"); 11095 const FunctionType *FT = T->castAs<FunctionType>(); 11096 11097 // Set an implicit return of 'zero' if the function can return some integral, 11098 // enumeration, pointer or nullptr type. 11099 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11100 FT->getReturnType()->isAnyPointerType() || 11101 FT->getReturnType()->isNullPtrType()) 11102 // DllMain is exempt because a return value of zero means it failed. 11103 if (FD->getName() != "DllMain") 11104 FD->setHasImplicitReturnZero(true); 11105 11106 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11107 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11108 FD->setInvalidDecl(); 11109 } 11110 } 11111 11112 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11113 // FIXME: Need strict checking. In C89, we need to check for 11114 // any assignment, increment, decrement, function-calls, or 11115 // commas outside of a sizeof. In C99, it's the same list, 11116 // except that the aforementioned are allowed in unevaluated 11117 // expressions. Everything else falls under the 11118 // "may accept other forms of constant expressions" exception. 11119 // 11120 // Regular C++ code will not end up here (exceptions: language extensions, 11121 // OpenCL C++ etc), so the constant expression rules there don't matter. 11122 if (Init->isValueDependent()) { 11123 assert(Init->containsErrors() && 11124 "Dependent code should only occur in error-recovery path."); 11125 return true; 11126 } 11127 const Expr *Culprit; 11128 if (Init->isConstantInitializer(Context, false, &Culprit)) 11129 return false; 11130 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11131 << Culprit->getSourceRange(); 11132 return true; 11133 } 11134 11135 namespace { 11136 // Visits an initialization expression to see if OrigDecl is evaluated in 11137 // its own initialization and throws a warning if it does. 11138 class SelfReferenceChecker 11139 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11140 Sema &S; 11141 Decl *OrigDecl; 11142 bool isRecordType; 11143 bool isPODType; 11144 bool isReferenceType; 11145 11146 bool isInitList; 11147 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11148 11149 public: 11150 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11151 11152 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11153 S(S), OrigDecl(OrigDecl) { 11154 isPODType = false; 11155 isRecordType = false; 11156 isReferenceType = false; 11157 isInitList = false; 11158 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11159 isPODType = VD->getType().isPODType(S.Context); 11160 isRecordType = VD->getType()->isRecordType(); 11161 isReferenceType = VD->getType()->isReferenceType(); 11162 } 11163 } 11164 11165 // For most expressions, just call the visitor. For initializer lists, 11166 // track the index of the field being initialized since fields are 11167 // initialized in order allowing use of previously initialized fields. 11168 void CheckExpr(Expr *E) { 11169 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11170 if (!InitList) { 11171 Visit(E); 11172 return; 11173 } 11174 11175 // Track and increment the index here. 11176 isInitList = true; 11177 InitFieldIndex.push_back(0); 11178 for (auto Child : InitList->children()) { 11179 CheckExpr(cast<Expr>(Child)); 11180 ++InitFieldIndex.back(); 11181 } 11182 InitFieldIndex.pop_back(); 11183 } 11184 11185 // Returns true if MemberExpr is checked and no further checking is needed. 11186 // Returns false if additional checking is required. 11187 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11188 llvm::SmallVector<FieldDecl*, 4> Fields; 11189 Expr *Base = E; 11190 bool ReferenceField = false; 11191 11192 // Get the field members used. 11193 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11194 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11195 if (!FD) 11196 return false; 11197 Fields.push_back(FD); 11198 if (FD->getType()->isReferenceType()) 11199 ReferenceField = true; 11200 Base = ME->getBase()->IgnoreParenImpCasts(); 11201 } 11202 11203 // Keep checking only if the base Decl is the same. 11204 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11205 if (!DRE || DRE->getDecl() != OrigDecl) 11206 return false; 11207 11208 // A reference field can be bound to an unininitialized field. 11209 if (CheckReference && !ReferenceField) 11210 return true; 11211 11212 // Convert FieldDecls to their index number. 11213 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11214 for (const FieldDecl *I : llvm::reverse(Fields)) 11215 UsedFieldIndex.push_back(I->getFieldIndex()); 11216 11217 // See if a warning is needed by checking the first difference in index 11218 // numbers. If field being used has index less than the field being 11219 // initialized, then the use is safe. 11220 for (auto UsedIter = UsedFieldIndex.begin(), 11221 UsedEnd = UsedFieldIndex.end(), 11222 OrigIter = InitFieldIndex.begin(), 11223 OrigEnd = InitFieldIndex.end(); 11224 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11225 if (*UsedIter < *OrigIter) 11226 return true; 11227 if (*UsedIter > *OrigIter) 11228 break; 11229 } 11230 11231 // TODO: Add a different warning which will print the field names. 11232 HandleDeclRefExpr(DRE); 11233 return true; 11234 } 11235 11236 // For most expressions, the cast is directly above the DeclRefExpr. 11237 // For conditional operators, the cast can be outside the conditional 11238 // operator if both expressions are DeclRefExpr's. 11239 void HandleValue(Expr *E) { 11240 E = E->IgnoreParens(); 11241 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11242 HandleDeclRefExpr(DRE); 11243 return; 11244 } 11245 11246 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11247 Visit(CO->getCond()); 11248 HandleValue(CO->getTrueExpr()); 11249 HandleValue(CO->getFalseExpr()); 11250 return; 11251 } 11252 11253 if (BinaryConditionalOperator *BCO = 11254 dyn_cast<BinaryConditionalOperator>(E)) { 11255 Visit(BCO->getCond()); 11256 HandleValue(BCO->getFalseExpr()); 11257 return; 11258 } 11259 11260 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11261 HandleValue(OVE->getSourceExpr()); 11262 return; 11263 } 11264 11265 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11266 if (BO->getOpcode() == BO_Comma) { 11267 Visit(BO->getLHS()); 11268 HandleValue(BO->getRHS()); 11269 return; 11270 } 11271 } 11272 11273 if (isa<MemberExpr>(E)) { 11274 if (isInitList) { 11275 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11276 false /*CheckReference*/)) 11277 return; 11278 } 11279 11280 Expr *Base = E->IgnoreParenImpCasts(); 11281 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11282 // Check for static member variables and don't warn on them. 11283 if (!isa<FieldDecl>(ME->getMemberDecl())) 11284 return; 11285 Base = ME->getBase()->IgnoreParenImpCasts(); 11286 } 11287 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11288 HandleDeclRefExpr(DRE); 11289 return; 11290 } 11291 11292 Visit(E); 11293 } 11294 11295 // Reference types not handled in HandleValue are handled here since all 11296 // uses of references are bad, not just r-value uses. 11297 void VisitDeclRefExpr(DeclRefExpr *E) { 11298 if (isReferenceType) 11299 HandleDeclRefExpr(E); 11300 } 11301 11302 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11303 if (E->getCastKind() == CK_LValueToRValue) { 11304 HandleValue(E->getSubExpr()); 11305 return; 11306 } 11307 11308 Inherited::VisitImplicitCastExpr(E); 11309 } 11310 11311 void VisitMemberExpr(MemberExpr *E) { 11312 if (isInitList) { 11313 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11314 return; 11315 } 11316 11317 // Don't warn on arrays since they can be treated as pointers. 11318 if (E->getType()->canDecayToPointerType()) return; 11319 11320 // Warn when a non-static method call is followed by non-static member 11321 // field accesses, which is followed by a DeclRefExpr. 11322 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11323 bool Warn = (MD && !MD->isStatic()); 11324 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11325 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11326 if (!isa<FieldDecl>(ME->getMemberDecl())) 11327 Warn = false; 11328 Base = ME->getBase()->IgnoreParenImpCasts(); 11329 } 11330 11331 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11332 if (Warn) 11333 HandleDeclRefExpr(DRE); 11334 return; 11335 } 11336 11337 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11338 // Visit that expression. 11339 Visit(Base); 11340 } 11341 11342 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11343 Expr *Callee = E->getCallee(); 11344 11345 if (isa<UnresolvedLookupExpr>(Callee)) 11346 return Inherited::VisitCXXOperatorCallExpr(E); 11347 11348 Visit(Callee); 11349 for (auto Arg: E->arguments()) 11350 HandleValue(Arg->IgnoreParenImpCasts()); 11351 } 11352 11353 void VisitUnaryOperator(UnaryOperator *E) { 11354 // For POD record types, addresses of its own members are well-defined. 11355 if (E->getOpcode() == UO_AddrOf && isRecordType && 11356 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11357 if (!isPODType) 11358 HandleValue(E->getSubExpr()); 11359 return; 11360 } 11361 11362 if (E->isIncrementDecrementOp()) { 11363 HandleValue(E->getSubExpr()); 11364 return; 11365 } 11366 11367 Inherited::VisitUnaryOperator(E); 11368 } 11369 11370 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11371 11372 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11373 if (E->getConstructor()->isCopyConstructor()) { 11374 Expr *ArgExpr = E->getArg(0); 11375 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11376 if (ILE->getNumInits() == 1) 11377 ArgExpr = ILE->getInit(0); 11378 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11379 if (ICE->getCastKind() == CK_NoOp) 11380 ArgExpr = ICE->getSubExpr(); 11381 HandleValue(ArgExpr); 11382 return; 11383 } 11384 Inherited::VisitCXXConstructExpr(E); 11385 } 11386 11387 void VisitCallExpr(CallExpr *E) { 11388 // Treat std::move as a use. 11389 if (E->isCallToStdMove()) { 11390 HandleValue(E->getArg(0)); 11391 return; 11392 } 11393 11394 Inherited::VisitCallExpr(E); 11395 } 11396 11397 void VisitBinaryOperator(BinaryOperator *E) { 11398 if (E->isCompoundAssignmentOp()) { 11399 HandleValue(E->getLHS()); 11400 Visit(E->getRHS()); 11401 return; 11402 } 11403 11404 Inherited::VisitBinaryOperator(E); 11405 } 11406 11407 // A custom visitor for BinaryConditionalOperator is needed because the 11408 // regular visitor would check the condition and true expression separately 11409 // but both point to the same place giving duplicate diagnostics. 11410 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11411 Visit(E->getCond()); 11412 Visit(E->getFalseExpr()); 11413 } 11414 11415 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11416 Decl* ReferenceDecl = DRE->getDecl(); 11417 if (OrigDecl != ReferenceDecl) return; 11418 unsigned diag; 11419 if (isReferenceType) { 11420 diag = diag::warn_uninit_self_reference_in_reference_init; 11421 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11422 diag = diag::warn_static_self_reference_in_init; 11423 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11424 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11425 DRE->getDecl()->getType()->isRecordType()) { 11426 diag = diag::warn_uninit_self_reference_in_init; 11427 } else { 11428 // Local variables will be handled by the CFG analysis. 11429 return; 11430 } 11431 11432 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11433 S.PDiag(diag) 11434 << DRE->getDecl() << OrigDecl->getLocation() 11435 << DRE->getSourceRange()); 11436 } 11437 }; 11438 11439 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11440 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11441 bool DirectInit) { 11442 // Parameters arguments are occassionially constructed with itself, 11443 // for instance, in recursive functions. Skip them. 11444 if (isa<ParmVarDecl>(OrigDecl)) 11445 return; 11446 11447 E = E->IgnoreParens(); 11448 11449 // Skip checking T a = a where T is not a record or reference type. 11450 // Doing so is a way to silence uninitialized warnings. 11451 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11452 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11453 if (ICE->getCastKind() == CK_LValueToRValue) 11454 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11455 if (DRE->getDecl() == OrigDecl) 11456 return; 11457 11458 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11459 } 11460 } // end anonymous namespace 11461 11462 namespace { 11463 // Simple wrapper to add the name of a variable or (if no variable is 11464 // available) a DeclarationName into a diagnostic. 11465 struct VarDeclOrName { 11466 VarDecl *VDecl; 11467 DeclarationName Name; 11468 11469 friend const Sema::SemaDiagnosticBuilder & 11470 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11471 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11472 } 11473 }; 11474 } // end anonymous namespace 11475 11476 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11477 DeclarationName Name, QualType Type, 11478 TypeSourceInfo *TSI, 11479 SourceRange Range, bool DirectInit, 11480 Expr *Init) { 11481 bool IsInitCapture = !VDecl; 11482 assert((!VDecl || !VDecl->isInitCapture()) && 11483 "init captures are expected to be deduced prior to initialization"); 11484 11485 VarDeclOrName VN{VDecl, Name}; 11486 11487 DeducedType *Deduced = Type->getContainedDeducedType(); 11488 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11489 11490 // C++11 [dcl.spec.auto]p3 11491 if (!Init) { 11492 assert(VDecl && "no init for init capture deduction?"); 11493 11494 // Except for class argument deduction, and then for an initializing 11495 // declaration only, i.e. no static at class scope or extern. 11496 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11497 VDecl->hasExternalStorage() || 11498 VDecl->isStaticDataMember()) { 11499 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11500 << VDecl->getDeclName() << Type; 11501 return QualType(); 11502 } 11503 } 11504 11505 ArrayRef<Expr*> DeduceInits; 11506 if (Init) 11507 DeduceInits = Init; 11508 11509 if (DirectInit) { 11510 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11511 DeduceInits = PL->exprs(); 11512 } 11513 11514 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11515 assert(VDecl && "non-auto type for init capture deduction?"); 11516 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11517 InitializationKind Kind = InitializationKind::CreateForInit( 11518 VDecl->getLocation(), DirectInit, Init); 11519 // FIXME: Initialization should not be taking a mutable list of inits. 11520 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11521 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11522 InitsCopy); 11523 } 11524 11525 if (DirectInit) { 11526 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11527 DeduceInits = IL->inits(); 11528 } 11529 11530 // Deduction only works if we have exactly one source expression. 11531 if (DeduceInits.empty()) { 11532 // It isn't possible to write this directly, but it is possible to 11533 // end up in this situation with "auto x(some_pack...);" 11534 Diag(Init->getBeginLoc(), IsInitCapture 11535 ? diag::err_init_capture_no_expression 11536 : diag::err_auto_var_init_no_expression) 11537 << VN << Type << Range; 11538 return QualType(); 11539 } 11540 11541 if (DeduceInits.size() > 1) { 11542 Diag(DeduceInits[1]->getBeginLoc(), 11543 IsInitCapture ? diag::err_init_capture_multiple_expressions 11544 : diag::err_auto_var_init_multiple_expressions) 11545 << VN << Type << Range; 11546 return QualType(); 11547 } 11548 11549 Expr *DeduceInit = DeduceInits[0]; 11550 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11551 Diag(Init->getBeginLoc(), IsInitCapture 11552 ? diag::err_init_capture_paren_braces 11553 : diag::err_auto_var_init_paren_braces) 11554 << isa<InitListExpr>(Init) << VN << Type << Range; 11555 return QualType(); 11556 } 11557 11558 // Expressions default to 'id' when we're in a debugger. 11559 bool DefaultedAnyToId = false; 11560 if (getLangOpts().DebuggerCastResultToId && 11561 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11562 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11563 if (Result.isInvalid()) { 11564 return QualType(); 11565 } 11566 Init = Result.get(); 11567 DefaultedAnyToId = true; 11568 } 11569 11570 // C++ [dcl.decomp]p1: 11571 // If the assignment-expression [...] has array type A and no ref-qualifier 11572 // is present, e has type cv A 11573 if (VDecl && isa<DecompositionDecl>(VDecl) && 11574 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11575 DeduceInit->getType()->isConstantArrayType()) 11576 return Context.getQualifiedType(DeduceInit->getType(), 11577 Type.getQualifiers()); 11578 11579 QualType DeducedType; 11580 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11581 if (!IsInitCapture) 11582 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11583 else if (isa<InitListExpr>(Init)) 11584 Diag(Range.getBegin(), 11585 diag::err_init_capture_deduction_failure_from_init_list) 11586 << VN 11587 << (DeduceInit->getType().isNull() ? TSI->getType() 11588 : DeduceInit->getType()) 11589 << DeduceInit->getSourceRange(); 11590 else 11591 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11592 << VN << TSI->getType() 11593 << (DeduceInit->getType().isNull() ? TSI->getType() 11594 : DeduceInit->getType()) 11595 << DeduceInit->getSourceRange(); 11596 } 11597 11598 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11599 // 'id' instead of a specific object type prevents most of our usual 11600 // checks. 11601 // We only want to warn outside of template instantiations, though: 11602 // inside a template, the 'id' could have come from a parameter. 11603 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11604 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11605 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11606 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11607 } 11608 11609 return DeducedType; 11610 } 11611 11612 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11613 Expr *Init) { 11614 assert(!Init || !Init->containsErrors()); 11615 QualType DeducedType = deduceVarTypeFromInitializer( 11616 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11617 VDecl->getSourceRange(), DirectInit, Init); 11618 if (DeducedType.isNull()) { 11619 VDecl->setInvalidDecl(); 11620 return true; 11621 } 11622 11623 VDecl->setType(DeducedType); 11624 assert(VDecl->isLinkageValid()); 11625 11626 // In ARC, infer lifetime. 11627 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11628 VDecl->setInvalidDecl(); 11629 11630 if (getLangOpts().OpenCL) 11631 deduceOpenCLAddressSpace(VDecl); 11632 11633 // If this is a redeclaration, check that the type we just deduced matches 11634 // the previously declared type. 11635 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11636 // We never need to merge the type, because we cannot form an incomplete 11637 // array of auto, nor deduce such a type. 11638 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11639 } 11640 11641 // Check the deduced type is valid for a variable declaration. 11642 CheckVariableDeclarationType(VDecl); 11643 return VDecl->isInvalidDecl(); 11644 } 11645 11646 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11647 SourceLocation Loc) { 11648 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11649 Init = EWC->getSubExpr(); 11650 11651 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11652 Init = CE->getSubExpr(); 11653 11654 QualType InitType = Init->getType(); 11655 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11656 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11657 "shouldn't be called if type doesn't have a non-trivial C struct"); 11658 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11659 for (auto I : ILE->inits()) { 11660 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11661 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11662 continue; 11663 SourceLocation SL = I->getExprLoc(); 11664 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11665 } 11666 return; 11667 } 11668 11669 if (isa<ImplicitValueInitExpr>(Init)) { 11670 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11671 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11672 NTCUK_Init); 11673 } else { 11674 // Assume all other explicit initializers involving copying some existing 11675 // object. 11676 // TODO: ignore any explicit initializers where we can guarantee 11677 // copy-elision. 11678 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11679 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11680 } 11681 } 11682 11683 namespace { 11684 11685 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11686 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11687 // in the source code or implicitly by the compiler if it is in a union 11688 // defined in a system header and has non-trivial ObjC ownership 11689 // qualifications. We don't want those fields to participate in determining 11690 // whether the containing union is non-trivial. 11691 return FD->hasAttr<UnavailableAttr>(); 11692 } 11693 11694 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11695 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11696 void> { 11697 using Super = 11698 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11699 void>; 11700 11701 DiagNonTrivalCUnionDefaultInitializeVisitor( 11702 QualType OrigTy, SourceLocation OrigLoc, 11703 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11704 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11705 11706 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11707 const FieldDecl *FD, bool InNonTrivialUnion) { 11708 if (const auto *AT = S.Context.getAsArrayType(QT)) 11709 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11710 InNonTrivialUnion); 11711 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11712 } 11713 11714 void visitARCStrong(QualType QT, const FieldDecl *FD, 11715 bool InNonTrivialUnion) { 11716 if (InNonTrivialUnion) 11717 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11718 << 1 << 0 << QT << FD->getName(); 11719 } 11720 11721 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11722 if (InNonTrivialUnion) 11723 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11724 << 1 << 0 << QT << FD->getName(); 11725 } 11726 11727 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11728 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11729 if (RD->isUnion()) { 11730 if (OrigLoc.isValid()) { 11731 bool IsUnion = false; 11732 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11733 IsUnion = OrigRD->isUnion(); 11734 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11735 << 0 << OrigTy << IsUnion << UseContext; 11736 // Reset OrigLoc so that this diagnostic is emitted only once. 11737 OrigLoc = SourceLocation(); 11738 } 11739 InNonTrivialUnion = true; 11740 } 11741 11742 if (InNonTrivialUnion) 11743 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11744 << 0 << 0 << QT.getUnqualifiedType() << ""; 11745 11746 for (const FieldDecl *FD : RD->fields()) 11747 if (!shouldIgnoreForRecordTriviality(FD)) 11748 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11749 } 11750 11751 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11752 11753 // The non-trivial C union type or the struct/union type that contains a 11754 // non-trivial C union. 11755 QualType OrigTy; 11756 SourceLocation OrigLoc; 11757 Sema::NonTrivialCUnionContext UseContext; 11758 Sema &S; 11759 }; 11760 11761 struct DiagNonTrivalCUnionDestructedTypeVisitor 11762 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11763 using Super = 11764 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11765 11766 DiagNonTrivalCUnionDestructedTypeVisitor( 11767 QualType OrigTy, SourceLocation OrigLoc, 11768 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11769 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11770 11771 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11772 const FieldDecl *FD, bool InNonTrivialUnion) { 11773 if (const auto *AT = S.Context.getAsArrayType(QT)) 11774 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11775 InNonTrivialUnion); 11776 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11777 } 11778 11779 void visitARCStrong(QualType QT, const FieldDecl *FD, 11780 bool InNonTrivialUnion) { 11781 if (InNonTrivialUnion) 11782 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11783 << 1 << 1 << QT << FD->getName(); 11784 } 11785 11786 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11787 if (InNonTrivialUnion) 11788 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11789 << 1 << 1 << QT << FD->getName(); 11790 } 11791 11792 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11793 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11794 if (RD->isUnion()) { 11795 if (OrigLoc.isValid()) { 11796 bool IsUnion = false; 11797 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11798 IsUnion = OrigRD->isUnion(); 11799 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11800 << 1 << OrigTy << IsUnion << UseContext; 11801 // Reset OrigLoc so that this diagnostic is emitted only once. 11802 OrigLoc = SourceLocation(); 11803 } 11804 InNonTrivialUnion = true; 11805 } 11806 11807 if (InNonTrivialUnion) 11808 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11809 << 0 << 1 << QT.getUnqualifiedType() << ""; 11810 11811 for (const FieldDecl *FD : RD->fields()) 11812 if (!shouldIgnoreForRecordTriviality(FD)) 11813 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11814 } 11815 11816 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11817 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11818 bool InNonTrivialUnion) {} 11819 11820 // The non-trivial C union type or the struct/union type that contains a 11821 // non-trivial C union. 11822 QualType OrigTy; 11823 SourceLocation OrigLoc; 11824 Sema::NonTrivialCUnionContext UseContext; 11825 Sema &S; 11826 }; 11827 11828 struct DiagNonTrivalCUnionCopyVisitor 11829 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11830 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11831 11832 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11833 Sema::NonTrivialCUnionContext UseContext, 11834 Sema &S) 11835 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11836 11837 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11838 const FieldDecl *FD, bool InNonTrivialUnion) { 11839 if (const auto *AT = S.Context.getAsArrayType(QT)) 11840 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11841 InNonTrivialUnion); 11842 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11843 } 11844 11845 void visitARCStrong(QualType QT, const FieldDecl *FD, 11846 bool InNonTrivialUnion) { 11847 if (InNonTrivialUnion) 11848 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11849 << 1 << 2 << QT << FD->getName(); 11850 } 11851 11852 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11853 if (InNonTrivialUnion) 11854 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11855 << 1 << 2 << QT << FD->getName(); 11856 } 11857 11858 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11859 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11860 if (RD->isUnion()) { 11861 if (OrigLoc.isValid()) { 11862 bool IsUnion = false; 11863 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11864 IsUnion = OrigRD->isUnion(); 11865 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11866 << 2 << OrigTy << IsUnion << UseContext; 11867 // Reset OrigLoc so that this diagnostic is emitted only once. 11868 OrigLoc = SourceLocation(); 11869 } 11870 InNonTrivialUnion = true; 11871 } 11872 11873 if (InNonTrivialUnion) 11874 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11875 << 0 << 2 << QT.getUnqualifiedType() << ""; 11876 11877 for (const FieldDecl *FD : RD->fields()) 11878 if (!shouldIgnoreForRecordTriviality(FD)) 11879 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11880 } 11881 11882 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11883 const FieldDecl *FD, bool InNonTrivialUnion) {} 11884 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11885 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11886 bool InNonTrivialUnion) {} 11887 11888 // The non-trivial C union type or the struct/union type that contains a 11889 // non-trivial C union. 11890 QualType OrigTy; 11891 SourceLocation OrigLoc; 11892 Sema::NonTrivialCUnionContext UseContext; 11893 Sema &S; 11894 }; 11895 11896 } // namespace 11897 11898 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11899 NonTrivialCUnionContext UseContext, 11900 unsigned NonTrivialKind) { 11901 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11902 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11903 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11904 "shouldn't be called if type doesn't have a non-trivial C union"); 11905 11906 if ((NonTrivialKind & NTCUK_Init) && 11907 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11908 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11909 .visit(QT, nullptr, false); 11910 if ((NonTrivialKind & NTCUK_Destruct) && 11911 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11912 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11913 .visit(QT, nullptr, false); 11914 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11915 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11916 .visit(QT, nullptr, false); 11917 } 11918 11919 /// AddInitializerToDecl - Adds the initializer Init to the 11920 /// declaration dcl. If DirectInit is true, this is C++ direct 11921 /// initialization rather than copy initialization. 11922 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11923 // If there is no declaration, there was an error parsing it. Just ignore 11924 // the initializer. 11925 if (!RealDecl || RealDecl->isInvalidDecl()) { 11926 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11927 return; 11928 } 11929 11930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11931 // Pure-specifiers are handled in ActOnPureSpecifier. 11932 Diag(Method->getLocation(), diag::err_member_function_initialization) 11933 << Method->getDeclName() << Init->getSourceRange(); 11934 Method->setInvalidDecl(); 11935 return; 11936 } 11937 11938 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11939 if (!VDecl) { 11940 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11941 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11942 RealDecl->setInvalidDecl(); 11943 return; 11944 } 11945 11946 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11947 if (VDecl->getType()->isUndeducedType()) { 11948 // Attempt typo correction early so that the type of the init expression can 11949 // be deduced based on the chosen correction if the original init contains a 11950 // TypoExpr. 11951 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11952 if (!Res.isUsable()) { 11953 // There are unresolved typos in Init, just drop them. 11954 // FIXME: improve the recovery strategy to preserve the Init. 11955 RealDecl->setInvalidDecl(); 11956 return; 11957 } 11958 if (Res.get()->containsErrors()) { 11959 // Invalidate the decl as we don't know the type for recovery-expr yet. 11960 RealDecl->setInvalidDecl(); 11961 VDecl->setInit(Res.get()); 11962 return; 11963 } 11964 Init = Res.get(); 11965 11966 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11967 return; 11968 } 11969 11970 // dllimport cannot be used on variable definitions. 11971 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11972 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11973 VDecl->setInvalidDecl(); 11974 return; 11975 } 11976 11977 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11978 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11979 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11980 VDecl->setInvalidDecl(); 11981 return; 11982 } 11983 11984 if (!VDecl->getType()->isDependentType()) { 11985 // A definition must end up with a complete type, which means it must be 11986 // complete with the restriction that an array type might be completed by 11987 // the initializer; note that later code assumes this restriction. 11988 QualType BaseDeclType = VDecl->getType(); 11989 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11990 BaseDeclType = Array->getElementType(); 11991 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11992 diag::err_typecheck_decl_incomplete_type)) { 11993 RealDecl->setInvalidDecl(); 11994 return; 11995 } 11996 11997 // The variable can not have an abstract class type. 11998 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11999 diag::err_abstract_type_in_decl, 12000 AbstractVariableType)) 12001 VDecl->setInvalidDecl(); 12002 } 12003 12004 // If adding the initializer will turn this declaration into a definition, 12005 // and we already have a definition for this variable, diagnose or otherwise 12006 // handle the situation. 12007 VarDecl *Def; 12008 if ((Def = VDecl->getDefinition()) && Def != VDecl && 12009 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12010 !VDecl->isThisDeclarationADemotedDefinition() && 12011 checkVarDeclRedefinition(Def, VDecl)) 12012 return; 12013 12014 if (getLangOpts().CPlusPlus) { 12015 // C++ [class.static.data]p4 12016 // If a static data member is of const integral or const 12017 // enumeration type, its declaration in the class definition can 12018 // specify a constant-initializer which shall be an integral 12019 // constant expression (5.19). In that case, the member can appear 12020 // in integral constant expressions. The member shall still be 12021 // defined in a namespace scope if it is used in the program and the 12022 // namespace scope definition shall not contain an initializer. 12023 // 12024 // We already performed a redefinition check above, but for static 12025 // data members we also need to check whether there was an in-class 12026 // declaration with an initializer. 12027 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12028 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12029 << VDecl->getDeclName(); 12030 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12031 diag::note_previous_initializer) 12032 << 0; 12033 return; 12034 } 12035 12036 if (VDecl->hasLocalStorage()) 12037 setFunctionHasBranchProtectedScope(); 12038 12039 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12040 VDecl->setInvalidDecl(); 12041 return; 12042 } 12043 } 12044 12045 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12046 // a kernel function cannot be initialized." 12047 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12048 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12049 VDecl->setInvalidDecl(); 12050 return; 12051 } 12052 12053 // The LoaderUninitialized attribute acts as a definition (of undef). 12054 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12055 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12056 VDecl->setInvalidDecl(); 12057 return; 12058 } 12059 12060 // Get the decls type and save a reference for later, since 12061 // CheckInitializerTypes may change it. 12062 QualType DclT = VDecl->getType(), SavT = DclT; 12063 12064 // Expressions default to 'id' when we're in a debugger 12065 // and we are assigning it to a variable of Objective-C pointer type. 12066 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12067 Init->getType() == Context.UnknownAnyTy) { 12068 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12069 if (Result.isInvalid()) { 12070 VDecl->setInvalidDecl(); 12071 return; 12072 } 12073 Init = Result.get(); 12074 } 12075 12076 // Perform the initialization. 12077 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12078 if (!VDecl->isInvalidDecl()) { 12079 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12080 InitializationKind Kind = InitializationKind::CreateForInit( 12081 VDecl->getLocation(), DirectInit, Init); 12082 12083 MultiExprArg Args = Init; 12084 if (CXXDirectInit) 12085 Args = MultiExprArg(CXXDirectInit->getExprs(), 12086 CXXDirectInit->getNumExprs()); 12087 12088 // Try to correct any TypoExprs in the initialization arguments. 12089 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12090 ExprResult Res = CorrectDelayedTyposInExpr( 12091 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12092 [this, Entity, Kind](Expr *E) { 12093 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12094 return Init.Failed() ? ExprError() : E; 12095 }); 12096 if (Res.isInvalid()) { 12097 VDecl->setInvalidDecl(); 12098 } else if (Res.get() != Args[Idx]) { 12099 Args[Idx] = Res.get(); 12100 } 12101 } 12102 if (VDecl->isInvalidDecl()) 12103 return; 12104 12105 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12106 /*TopLevelOfInitList=*/false, 12107 /*TreatUnavailableAsInvalid=*/false); 12108 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12109 if (Result.isInvalid()) { 12110 // If the provied initializer fails to initialize the var decl, 12111 // we attach a recovery expr for better recovery. 12112 auto RecoveryExpr = 12113 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12114 if (RecoveryExpr.get()) 12115 VDecl->setInit(RecoveryExpr.get()); 12116 return; 12117 } 12118 12119 Init = Result.getAs<Expr>(); 12120 } 12121 12122 // Check for self-references within variable initializers. 12123 // Variables declared within a function/method body (except for references) 12124 // are handled by a dataflow analysis. 12125 // This is undefined behavior in C++, but valid in C. 12126 if (getLangOpts().CPlusPlus) { 12127 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12128 VDecl->getType()->isReferenceType()) { 12129 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12130 } 12131 } 12132 12133 // If the type changed, it means we had an incomplete type that was 12134 // completed by the initializer. For example: 12135 // int ary[] = { 1, 3, 5 }; 12136 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12137 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12138 VDecl->setType(DclT); 12139 12140 if (!VDecl->isInvalidDecl()) { 12141 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12142 12143 if (VDecl->hasAttr<BlocksAttr>()) 12144 checkRetainCycles(VDecl, Init); 12145 12146 // It is safe to assign a weak reference into a strong variable. 12147 // Although this code can still have problems: 12148 // id x = self.weakProp; 12149 // id y = self.weakProp; 12150 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12151 // paths through the function. This should be revisited if 12152 // -Wrepeated-use-of-weak is made flow-sensitive. 12153 if (FunctionScopeInfo *FSI = getCurFunction()) 12154 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12155 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12156 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12157 Init->getBeginLoc())) 12158 FSI->markSafeWeakUse(Init); 12159 } 12160 12161 // The initialization is usually a full-expression. 12162 // 12163 // FIXME: If this is a braced initialization of an aggregate, it is not 12164 // an expression, and each individual field initializer is a separate 12165 // full-expression. For instance, in: 12166 // 12167 // struct Temp { ~Temp(); }; 12168 // struct S { S(Temp); }; 12169 // struct T { S a, b; } t = { Temp(), Temp() } 12170 // 12171 // we should destroy the first Temp before constructing the second. 12172 ExprResult Result = 12173 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12174 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12175 if (Result.isInvalid()) { 12176 VDecl->setInvalidDecl(); 12177 return; 12178 } 12179 Init = Result.get(); 12180 12181 // Attach the initializer to the decl. 12182 VDecl->setInit(Init); 12183 12184 if (VDecl->isLocalVarDecl()) { 12185 // Don't check the initializer if the declaration is malformed. 12186 if (VDecl->isInvalidDecl()) { 12187 // do nothing 12188 12189 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12190 // This is true even in C++ for OpenCL. 12191 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12192 CheckForConstantInitializer(Init, DclT); 12193 12194 // Otherwise, C++ does not restrict the initializer. 12195 } else if (getLangOpts().CPlusPlus) { 12196 // do nothing 12197 12198 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12199 // static storage duration shall be constant expressions or string literals. 12200 } else if (VDecl->getStorageClass() == SC_Static) { 12201 CheckForConstantInitializer(Init, DclT); 12202 12203 // C89 is stricter than C99 for aggregate initializers. 12204 // C89 6.5.7p3: All the expressions [...] in an initializer list 12205 // for an object that has aggregate or union type shall be 12206 // constant expressions. 12207 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12208 isa<InitListExpr>(Init)) { 12209 const Expr *Culprit; 12210 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12211 Diag(Culprit->getExprLoc(), 12212 diag::ext_aggregate_init_not_constant) 12213 << Culprit->getSourceRange(); 12214 } 12215 } 12216 12217 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12218 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12219 if (VDecl->hasLocalStorage()) 12220 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12221 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12222 VDecl->getLexicalDeclContext()->isRecord()) { 12223 // This is an in-class initialization for a static data member, e.g., 12224 // 12225 // struct S { 12226 // static const int value = 17; 12227 // }; 12228 12229 // C++ [class.mem]p4: 12230 // A member-declarator can contain a constant-initializer only 12231 // if it declares a static member (9.4) of const integral or 12232 // const enumeration type, see 9.4.2. 12233 // 12234 // C++11 [class.static.data]p3: 12235 // If a non-volatile non-inline const static data member is of integral 12236 // or enumeration type, its declaration in the class definition can 12237 // specify a brace-or-equal-initializer in which every initializer-clause 12238 // that is an assignment-expression is a constant expression. A static 12239 // data member of literal type can be declared in the class definition 12240 // with the constexpr specifier; if so, its declaration shall specify a 12241 // brace-or-equal-initializer in which every initializer-clause that is 12242 // an assignment-expression is a constant expression. 12243 12244 // Do nothing on dependent types. 12245 if (DclT->isDependentType()) { 12246 12247 // Allow any 'static constexpr' members, whether or not they are of literal 12248 // type. We separately check that every constexpr variable is of literal 12249 // type. 12250 } else if (VDecl->isConstexpr()) { 12251 12252 // Require constness. 12253 } else if (!DclT.isConstQualified()) { 12254 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12255 << Init->getSourceRange(); 12256 VDecl->setInvalidDecl(); 12257 12258 // We allow integer constant expressions in all cases. 12259 } else if (DclT->isIntegralOrEnumerationType()) { 12260 // Check whether the expression is a constant expression. 12261 SourceLocation Loc; 12262 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12263 // In C++11, a non-constexpr const static data member with an 12264 // in-class initializer cannot be volatile. 12265 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12266 else if (Init->isValueDependent()) 12267 ; // Nothing to check. 12268 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12269 ; // Ok, it's an ICE! 12270 else if (Init->getType()->isScopedEnumeralType() && 12271 Init->isCXX11ConstantExpr(Context)) 12272 ; // Ok, it is a scoped-enum constant expression. 12273 else if (Init->isEvaluatable(Context)) { 12274 // If we can constant fold the initializer through heroics, accept it, 12275 // but report this as a use of an extension for -pedantic. 12276 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12277 << Init->getSourceRange(); 12278 } else { 12279 // Otherwise, this is some crazy unknown case. Report the issue at the 12280 // location provided by the isIntegerConstantExpr failed check. 12281 Diag(Loc, diag::err_in_class_initializer_non_constant) 12282 << Init->getSourceRange(); 12283 VDecl->setInvalidDecl(); 12284 } 12285 12286 // We allow foldable floating-point constants as an extension. 12287 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12288 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12289 // it anyway and provide a fixit to add the 'constexpr'. 12290 if (getLangOpts().CPlusPlus11) { 12291 Diag(VDecl->getLocation(), 12292 diag::ext_in_class_initializer_float_type_cxx11) 12293 << DclT << Init->getSourceRange(); 12294 Diag(VDecl->getBeginLoc(), 12295 diag::note_in_class_initializer_float_type_cxx11) 12296 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12297 } else { 12298 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12299 << DclT << Init->getSourceRange(); 12300 12301 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12302 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12303 << Init->getSourceRange(); 12304 VDecl->setInvalidDecl(); 12305 } 12306 } 12307 12308 // Suggest adding 'constexpr' in C++11 for literal types. 12309 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12310 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12311 << DclT << Init->getSourceRange() 12312 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12313 VDecl->setConstexpr(true); 12314 12315 } else { 12316 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12317 << DclT << Init->getSourceRange(); 12318 VDecl->setInvalidDecl(); 12319 } 12320 } else if (VDecl->isFileVarDecl()) { 12321 // In C, extern is typically used to avoid tentative definitions when 12322 // declaring variables in headers, but adding an intializer makes it a 12323 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12324 // In C++, extern is often used to give implictly static const variables 12325 // external linkage, so don't warn in that case. If selectany is present, 12326 // this might be header code intended for C and C++ inclusion, so apply the 12327 // C++ rules. 12328 if (VDecl->getStorageClass() == SC_Extern && 12329 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12330 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12331 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12332 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12333 Diag(VDecl->getLocation(), diag::warn_extern_init); 12334 12335 // In Microsoft C++ mode, a const variable defined in namespace scope has 12336 // external linkage by default if the variable is declared with 12337 // __declspec(dllexport). 12338 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12339 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12340 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12341 VDecl->setStorageClass(SC_Extern); 12342 12343 // C99 6.7.8p4. All file scoped initializers need to be constant. 12344 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12345 CheckForConstantInitializer(Init, DclT); 12346 } 12347 12348 QualType InitType = Init->getType(); 12349 if (!InitType.isNull() && 12350 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12351 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12352 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12353 12354 // We will represent direct-initialization similarly to copy-initialization: 12355 // int x(1); -as-> int x = 1; 12356 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12357 // 12358 // Clients that want to distinguish between the two forms, can check for 12359 // direct initializer using VarDecl::getInitStyle(). 12360 // A major benefit is that clients that don't particularly care about which 12361 // exactly form was it (like the CodeGen) can handle both cases without 12362 // special case code. 12363 12364 // C++ 8.5p11: 12365 // The form of initialization (using parentheses or '=') is generally 12366 // insignificant, but does matter when the entity being initialized has a 12367 // class type. 12368 if (CXXDirectInit) { 12369 assert(DirectInit && "Call-style initializer must be direct init."); 12370 VDecl->setInitStyle(VarDecl::CallInit); 12371 } else if (DirectInit) { 12372 // This must be list-initialization. No other way is direct-initialization. 12373 VDecl->setInitStyle(VarDecl::ListInit); 12374 } 12375 12376 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12377 DeclsToCheckForDeferredDiags.push_back(VDecl); 12378 CheckCompleteVariableDeclaration(VDecl); 12379 } 12380 12381 /// ActOnInitializerError - Given that there was an error parsing an 12382 /// initializer for the given declaration, try to return to some form 12383 /// of sanity. 12384 void Sema::ActOnInitializerError(Decl *D) { 12385 // Our main concern here is re-establishing invariants like "a 12386 // variable's type is either dependent or complete". 12387 if (!D || D->isInvalidDecl()) return; 12388 12389 VarDecl *VD = dyn_cast<VarDecl>(D); 12390 if (!VD) return; 12391 12392 // Bindings are not usable if we can't make sense of the initializer. 12393 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12394 for (auto *BD : DD->bindings()) 12395 BD->setInvalidDecl(); 12396 12397 // Auto types are meaningless if we can't make sense of the initializer. 12398 if (VD->getType()->isUndeducedType()) { 12399 D->setInvalidDecl(); 12400 return; 12401 } 12402 12403 QualType Ty = VD->getType(); 12404 if (Ty->isDependentType()) return; 12405 12406 // Require a complete type. 12407 if (RequireCompleteType(VD->getLocation(), 12408 Context.getBaseElementType(Ty), 12409 diag::err_typecheck_decl_incomplete_type)) { 12410 VD->setInvalidDecl(); 12411 return; 12412 } 12413 12414 // Require a non-abstract type. 12415 if (RequireNonAbstractType(VD->getLocation(), Ty, 12416 diag::err_abstract_type_in_decl, 12417 AbstractVariableType)) { 12418 VD->setInvalidDecl(); 12419 return; 12420 } 12421 12422 // Don't bother complaining about constructors or destructors, 12423 // though. 12424 } 12425 12426 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12427 // If there is no declaration, there was an error parsing it. Just ignore it. 12428 if (!RealDecl) 12429 return; 12430 12431 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12432 QualType Type = Var->getType(); 12433 12434 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12435 if (isa<DecompositionDecl>(RealDecl)) { 12436 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12437 Var->setInvalidDecl(); 12438 return; 12439 } 12440 12441 if (Type->isUndeducedType() && 12442 DeduceVariableDeclarationType(Var, false, nullptr)) 12443 return; 12444 12445 // C++11 [class.static.data]p3: A static data member can be declared with 12446 // the constexpr specifier; if so, its declaration shall specify 12447 // a brace-or-equal-initializer. 12448 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12449 // the definition of a variable [...] or the declaration of a static data 12450 // member. 12451 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12452 !Var->isThisDeclarationADemotedDefinition()) { 12453 if (Var->isStaticDataMember()) { 12454 // C++1z removes the relevant rule; the in-class declaration is always 12455 // a definition there. 12456 if (!getLangOpts().CPlusPlus17 && 12457 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12458 Diag(Var->getLocation(), 12459 diag::err_constexpr_static_mem_var_requires_init) 12460 << Var; 12461 Var->setInvalidDecl(); 12462 return; 12463 } 12464 } else { 12465 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12466 Var->setInvalidDecl(); 12467 return; 12468 } 12469 } 12470 12471 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12472 // be initialized. 12473 if (!Var->isInvalidDecl() && 12474 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12475 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12476 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12477 Var->setInvalidDecl(); 12478 return; 12479 } 12480 12481 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12482 if (Var->getStorageClass() == SC_Extern) { 12483 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12484 << Var; 12485 Var->setInvalidDecl(); 12486 return; 12487 } 12488 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12489 diag::err_typecheck_decl_incomplete_type)) { 12490 Var->setInvalidDecl(); 12491 return; 12492 } 12493 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12494 if (!RD->hasTrivialDefaultConstructor()) { 12495 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12496 Var->setInvalidDecl(); 12497 return; 12498 } 12499 } 12500 } 12501 12502 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12503 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12504 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12505 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12506 NTCUC_DefaultInitializedObject, NTCUK_Init); 12507 12508 12509 switch (DefKind) { 12510 case VarDecl::Definition: 12511 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12512 break; 12513 12514 // We have an out-of-line definition of a static data member 12515 // that has an in-class initializer, so we type-check this like 12516 // a declaration. 12517 // 12518 LLVM_FALLTHROUGH; 12519 12520 case VarDecl::DeclarationOnly: 12521 // It's only a declaration. 12522 12523 // Block scope. C99 6.7p7: If an identifier for an object is 12524 // declared with no linkage (C99 6.2.2p6), the type for the 12525 // object shall be complete. 12526 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12527 !Var->hasLinkage() && !Var->isInvalidDecl() && 12528 RequireCompleteType(Var->getLocation(), Type, 12529 diag::err_typecheck_decl_incomplete_type)) 12530 Var->setInvalidDecl(); 12531 12532 // Make sure that the type is not abstract. 12533 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12534 RequireNonAbstractType(Var->getLocation(), Type, 12535 diag::err_abstract_type_in_decl, 12536 AbstractVariableType)) 12537 Var->setInvalidDecl(); 12538 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12539 Var->getStorageClass() == SC_PrivateExtern) { 12540 Diag(Var->getLocation(), diag::warn_private_extern); 12541 Diag(Var->getLocation(), diag::note_private_extern); 12542 } 12543 12544 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12545 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12546 ExternalDeclarations.push_back(Var); 12547 12548 return; 12549 12550 case VarDecl::TentativeDefinition: 12551 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12552 // object that has file scope without an initializer, and without a 12553 // storage-class specifier or with the storage-class specifier "static", 12554 // constitutes a tentative definition. Note: A tentative definition with 12555 // external linkage is valid (C99 6.2.2p5). 12556 if (!Var->isInvalidDecl()) { 12557 if (const IncompleteArrayType *ArrayT 12558 = Context.getAsIncompleteArrayType(Type)) { 12559 if (RequireCompleteSizedType( 12560 Var->getLocation(), ArrayT->getElementType(), 12561 diag::err_array_incomplete_or_sizeless_type)) 12562 Var->setInvalidDecl(); 12563 } else if (Var->getStorageClass() == SC_Static) { 12564 // C99 6.9.2p3: If the declaration of an identifier for an object is 12565 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12566 // declared type shall not be an incomplete type. 12567 // NOTE: code such as the following 12568 // static struct s; 12569 // struct s { int a; }; 12570 // is accepted by gcc. Hence here we issue a warning instead of 12571 // an error and we do not invalidate the static declaration. 12572 // NOTE: to avoid multiple warnings, only check the first declaration. 12573 if (Var->isFirstDecl()) 12574 RequireCompleteType(Var->getLocation(), Type, 12575 diag::ext_typecheck_decl_incomplete_type); 12576 } 12577 } 12578 12579 // Record the tentative definition; we're done. 12580 if (!Var->isInvalidDecl()) 12581 TentativeDefinitions.push_back(Var); 12582 return; 12583 } 12584 12585 // Provide a specific diagnostic for uninitialized variable 12586 // definitions with incomplete array type. 12587 if (Type->isIncompleteArrayType()) { 12588 Diag(Var->getLocation(), 12589 diag::err_typecheck_incomplete_array_needs_initializer); 12590 Var->setInvalidDecl(); 12591 return; 12592 } 12593 12594 // Provide a specific diagnostic for uninitialized variable 12595 // definitions with reference type. 12596 if (Type->isReferenceType()) { 12597 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12598 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12599 Var->setInvalidDecl(); 12600 return; 12601 } 12602 12603 // Do not attempt to type-check the default initializer for a 12604 // variable with dependent type. 12605 if (Type->isDependentType()) 12606 return; 12607 12608 if (Var->isInvalidDecl()) 12609 return; 12610 12611 if (!Var->hasAttr<AliasAttr>()) { 12612 if (RequireCompleteType(Var->getLocation(), 12613 Context.getBaseElementType(Type), 12614 diag::err_typecheck_decl_incomplete_type)) { 12615 Var->setInvalidDecl(); 12616 return; 12617 } 12618 } else { 12619 return; 12620 } 12621 12622 // The variable can not have an abstract class type. 12623 if (RequireNonAbstractType(Var->getLocation(), Type, 12624 diag::err_abstract_type_in_decl, 12625 AbstractVariableType)) { 12626 Var->setInvalidDecl(); 12627 return; 12628 } 12629 12630 // Check for jumps past the implicit initializer. C++0x 12631 // clarifies that this applies to a "variable with automatic 12632 // storage duration", not a "local variable". 12633 // C++11 [stmt.dcl]p3 12634 // A program that jumps from a point where a variable with automatic 12635 // storage duration is not in scope to a point where it is in scope is 12636 // ill-formed unless the variable has scalar type, class type with a 12637 // trivial default constructor and a trivial destructor, a cv-qualified 12638 // version of one of these types, or an array of one of the preceding 12639 // types and is declared without an initializer. 12640 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12641 if (const RecordType *Record 12642 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12643 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12644 // Mark the function (if we're in one) for further checking even if the 12645 // looser rules of C++11 do not require such checks, so that we can 12646 // diagnose incompatibilities with C++98. 12647 if (!CXXRecord->isPOD()) 12648 setFunctionHasBranchProtectedScope(); 12649 } 12650 } 12651 // In OpenCL, we can't initialize objects in the __local address space, 12652 // even implicitly, so don't synthesize an implicit initializer. 12653 if (getLangOpts().OpenCL && 12654 Var->getType().getAddressSpace() == LangAS::opencl_local) 12655 return; 12656 // C++03 [dcl.init]p9: 12657 // If no initializer is specified for an object, and the 12658 // object is of (possibly cv-qualified) non-POD class type (or 12659 // array thereof), the object shall be default-initialized; if 12660 // the object is of const-qualified type, the underlying class 12661 // type shall have a user-declared default 12662 // constructor. Otherwise, if no initializer is specified for 12663 // a non- static object, the object and its subobjects, if 12664 // any, have an indeterminate initial value); if the object 12665 // or any of its subobjects are of const-qualified type, the 12666 // program is ill-formed. 12667 // C++0x [dcl.init]p11: 12668 // If no initializer is specified for an object, the object is 12669 // default-initialized; [...]. 12670 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12671 InitializationKind Kind 12672 = InitializationKind::CreateDefault(Var->getLocation()); 12673 12674 InitializationSequence InitSeq(*this, Entity, Kind, None); 12675 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12676 12677 if (Init.get()) { 12678 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12679 // This is important for template substitution. 12680 Var->setInitStyle(VarDecl::CallInit); 12681 } else if (Init.isInvalid()) { 12682 // If default-init fails, attach a recovery-expr initializer to track 12683 // that initialization was attempted and failed. 12684 auto RecoveryExpr = 12685 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12686 if (RecoveryExpr.get()) 12687 Var->setInit(RecoveryExpr.get()); 12688 } 12689 12690 CheckCompleteVariableDeclaration(Var); 12691 } 12692 } 12693 12694 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12695 // If there is no declaration, there was an error parsing it. Ignore it. 12696 if (!D) 12697 return; 12698 12699 VarDecl *VD = dyn_cast<VarDecl>(D); 12700 if (!VD) { 12701 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12702 D->setInvalidDecl(); 12703 return; 12704 } 12705 12706 VD->setCXXForRangeDecl(true); 12707 12708 // for-range-declaration cannot be given a storage class specifier. 12709 int Error = -1; 12710 switch (VD->getStorageClass()) { 12711 case SC_None: 12712 break; 12713 case SC_Extern: 12714 Error = 0; 12715 break; 12716 case SC_Static: 12717 Error = 1; 12718 break; 12719 case SC_PrivateExtern: 12720 Error = 2; 12721 break; 12722 case SC_Auto: 12723 Error = 3; 12724 break; 12725 case SC_Register: 12726 Error = 4; 12727 break; 12728 } 12729 if (Error != -1) { 12730 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12731 << VD << Error; 12732 D->setInvalidDecl(); 12733 } 12734 } 12735 12736 StmtResult 12737 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12738 IdentifierInfo *Ident, 12739 ParsedAttributes &Attrs, 12740 SourceLocation AttrEnd) { 12741 // C++1y [stmt.iter]p1: 12742 // A range-based for statement of the form 12743 // for ( for-range-identifier : for-range-initializer ) statement 12744 // is equivalent to 12745 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12746 DeclSpec DS(Attrs.getPool().getFactory()); 12747 12748 const char *PrevSpec; 12749 unsigned DiagID; 12750 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12751 getPrintingPolicy()); 12752 12753 Declarator D(DS, DeclaratorContext::ForContext); 12754 D.SetIdentifier(Ident, IdentLoc); 12755 D.takeAttributes(Attrs, AttrEnd); 12756 12757 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12758 IdentLoc); 12759 Decl *Var = ActOnDeclarator(S, D); 12760 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12761 FinalizeDeclaration(Var); 12762 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12763 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12764 } 12765 12766 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12767 if (var->isInvalidDecl()) return; 12768 12769 if (getLangOpts().OpenCL) { 12770 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12771 // initialiser 12772 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12773 !var->hasInit()) { 12774 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12775 << 1 /*Init*/; 12776 var->setInvalidDecl(); 12777 return; 12778 } 12779 } 12780 12781 // In Objective-C, don't allow jumps past the implicit initialization of a 12782 // local retaining variable. 12783 if (getLangOpts().ObjC && 12784 var->hasLocalStorage()) { 12785 switch (var->getType().getObjCLifetime()) { 12786 case Qualifiers::OCL_None: 12787 case Qualifiers::OCL_ExplicitNone: 12788 case Qualifiers::OCL_Autoreleasing: 12789 break; 12790 12791 case Qualifiers::OCL_Weak: 12792 case Qualifiers::OCL_Strong: 12793 setFunctionHasBranchProtectedScope(); 12794 break; 12795 } 12796 } 12797 12798 if (var->hasLocalStorage() && 12799 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12800 setFunctionHasBranchProtectedScope(); 12801 12802 // Warn about externally-visible variables being defined without a 12803 // prior declaration. We only want to do this for global 12804 // declarations, but we also specifically need to avoid doing it for 12805 // class members because the linkage of an anonymous class can 12806 // change if it's later given a typedef name. 12807 if (var->isThisDeclarationADefinition() && 12808 var->getDeclContext()->getRedeclContext()->isFileContext() && 12809 var->isExternallyVisible() && var->hasLinkage() && 12810 !var->isInline() && !var->getDescribedVarTemplate() && 12811 !isa<VarTemplatePartialSpecializationDecl>(var) && 12812 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12813 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12814 var->getLocation())) { 12815 // Find a previous declaration that's not a definition. 12816 VarDecl *prev = var->getPreviousDecl(); 12817 while (prev && prev->isThisDeclarationADefinition()) 12818 prev = prev->getPreviousDecl(); 12819 12820 if (!prev) { 12821 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12822 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12823 << /* variable */ 0; 12824 } 12825 } 12826 12827 // Cache the result of checking for constant initialization. 12828 Optional<bool> CacheHasConstInit; 12829 const Expr *CacheCulprit = nullptr; 12830 auto checkConstInit = [&]() mutable { 12831 if (!CacheHasConstInit) 12832 CacheHasConstInit = var->getInit()->isConstantInitializer( 12833 Context, var->getType()->isReferenceType(), &CacheCulprit); 12834 return *CacheHasConstInit; 12835 }; 12836 12837 if (var->getTLSKind() == VarDecl::TLS_Static) { 12838 if (var->getType().isDestructedType()) { 12839 // GNU C++98 edits for __thread, [basic.start.term]p3: 12840 // The type of an object with thread storage duration shall not 12841 // have a non-trivial destructor. 12842 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12843 if (getLangOpts().CPlusPlus11) 12844 Diag(var->getLocation(), diag::note_use_thread_local); 12845 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12846 if (!checkConstInit()) { 12847 // GNU C++98 edits for __thread, [basic.start.init]p4: 12848 // An object of thread storage duration shall not require dynamic 12849 // initialization. 12850 // FIXME: Need strict checking here. 12851 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12852 << CacheCulprit->getSourceRange(); 12853 if (getLangOpts().CPlusPlus11) 12854 Diag(var->getLocation(), diag::note_use_thread_local); 12855 } 12856 } 12857 } 12858 12859 // Apply section attributes and pragmas to global variables. 12860 bool GlobalStorage = var->hasGlobalStorage(); 12861 if (GlobalStorage && var->isThisDeclarationADefinition() && 12862 !inTemplateInstantiation()) { 12863 PragmaStack<StringLiteral *> *Stack = nullptr; 12864 int SectionFlags = ASTContext::PSF_Read; 12865 if (var->getType().isConstQualified()) 12866 Stack = &ConstSegStack; 12867 else if (!var->getInit()) { 12868 Stack = &BSSSegStack; 12869 SectionFlags |= ASTContext::PSF_Write; 12870 } else { 12871 Stack = &DataSegStack; 12872 SectionFlags |= ASTContext::PSF_Write; 12873 } 12874 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12875 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12876 SectionFlags |= ASTContext::PSF_Implicit; 12877 UnifySection(SA->getName(), SectionFlags, var); 12878 } else if (Stack->CurrentValue) { 12879 SectionFlags |= ASTContext::PSF_Implicit; 12880 auto SectionName = Stack->CurrentValue->getString(); 12881 var->addAttr(SectionAttr::CreateImplicit( 12882 Context, SectionName, Stack->CurrentPragmaLocation, 12883 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12884 if (UnifySection(SectionName, SectionFlags, var)) 12885 var->dropAttr<SectionAttr>(); 12886 } 12887 12888 // Apply the init_seg attribute if this has an initializer. If the 12889 // initializer turns out to not be dynamic, we'll end up ignoring this 12890 // attribute. 12891 if (CurInitSeg && var->getInit()) 12892 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12893 CurInitSegLoc, 12894 AttributeCommonInfo::AS_Pragma)); 12895 } 12896 12897 if (!var->getType()->isStructureType() && var->hasInit() && 12898 isa<InitListExpr>(var->getInit())) { 12899 const auto *ILE = cast<InitListExpr>(var->getInit()); 12900 unsigned NumInits = ILE->getNumInits(); 12901 if (NumInits > 2) 12902 for (unsigned I = 0; I < NumInits; ++I) { 12903 const auto *Init = ILE->getInit(I); 12904 if (!Init) 12905 break; 12906 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12907 if (!SL) 12908 break; 12909 12910 unsigned NumConcat = SL->getNumConcatenated(); 12911 // Diagnose missing comma in string array initialization. 12912 // Do not warn when all the elements in the initializer are concatenated 12913 // together. Do not warn for macros too. 12914 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 12915 bool OnlyOneMissingComma = true; 12916 for (unsigned J = I + 1; J < NumInits; ++J) { 12917 const auto *Init = ILE->getInit(J); 12918 if (!Init) 12919 break; 12920 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 12921 if (!SLJ || SLJ->getNumConcatenated() > 1) { 12922 OnlyOneMissingComma = false; 12923 break; 12924 } 12925 } 12926 12927 if (OnlyOneMissingComma) { 12928 SmallVector<FixItHint, 1> Hints; 12929 for (unsigned i = 0; i < NumConcat - 1; ++i) 12930 Hints.push_back(FixItHint::CreateInsertion( 12931 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 12932 12933 Diag(SL->getStrTokenLoc(1), 12934 diag::warn_concatenated_literal_array_init) 12935 << Hints; 12936 Diag(SL->getBeginLoc(), 12937 diag::note_concatenated_string_literal_silence); 12938 } 12939 // In any case, stop now. 12940 break; 12941 } 12942 } 12943 } 12944 12945 // All the following checks are C++ only. 12946 if (!getLangOpts().CPlusPlus) { 12947 // If this variable must be emitted, add it as an initializer for the 12948 // current module. 12949 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12950 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12951 return; 12952 } 12953 12954 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12955 CheckCompleteDecompositionDeclaration(DD); 12956 12957 QualType type = var->getType(); 12958 if (type->isDependentType()) return; 12959 12960 if (var->hasAttr<BlocksAttr>()) 12961 getCurFunction()->addByrefBlockVar(var); 12962 12963 Expr *Init = var->getInit(); 12964 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12965 QualType baseType = Context.getBaseElementType(type); 12966 12967 if (Init && !Init->isValueDependent()) { 12968 if (var->isConstexpr()) { 12969 SmallVector<PartialDiagnosticAt, 8> Notes; 12970 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12971 SourceLocation DiagLoc = var->getLocation(); 12972 // If the note doesn't add any useful information other than a source 12973 // location, fold it into the primary diagnostic. 12974 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12975 diag::note_invalid_subexpr_in_const_expr) { 12976 DiagLoc = Notes[0].first; 12977 Notes.clear(); 12978 } 12979 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12980 << var << Init->getSourceRange(); 12981 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12982 Diag(Notes[I].first, Notes[I].second); 12983 } 12984 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12985 // Check whether the initializer of a const variable of integral or 12986 // enumeration type is an ICE now, since we can't tell whether it was 12987 // initialized by a constant expression if we check later. 12988 var->checkInitIsICE(); 12989 } 12990 12991 // Don't emit further diagnostics about constexpr globals since they 12992 // were just diagnosed. 12993 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12994 // FIXME: Need strict checking in C++03 here. 12995 bool DiagErr = getLangOpts().CPlusPlus11 12996 ? !var->checkInitIsICE() : !checkConstInit(); 12997 if (DiagErr) { 12998 auto *Attr = var->getAttr<ConstInitAttr>(); 12999 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13000 << Init->getSourceRange(); 13001 Diag(Attr->getLocation(), 13002 diag::note_declared_required_constant_init_here) 13003 << Attr->getRange() << Attr->isConstinit(); 13004 if (getLangOpts().CPlusPlus11) { 13005 APValue Value; 13006 SmallVector<PartialDiagnosticAt, 8> Notes; 13007 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 13008 for (auto &it : Notes) 13009 Diag(it.first, it.second); 13010 } else { 13011 Diag(CacheCulprit->getExprLoc(), 13012 diag::note_invalid_subexpr_in_const_expr) 13013 << CacheCulprit->getSourceRange(); 13014 } 13015 } 13016 } 13017 else if (!var->isConstexpr() && IsGlobal && 13018 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13019 var->getLocation())) { 13020 // Warn about globals which don't have a constant initializer. Don't 13021 // warn about globals with a non-trivial destructor because we already 13022 // warned about them. 13023 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13024 if (!(RD && !RD->hasTrivialDestructor())) { 13025 if (!checkConstInit()) 13026 Diag(var->getLocation(), diag::warn_global_constructor) 13027 << Init->getSourceRange(); 13028 } 13029 } 13030 } 13031 13032 // Require the destructor. 13033 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13034 FinalizeVarWithDestructor(var, recordType); 13035 13036 // If this variable must be emitted, add it as an initializer for the current 13037 // module. 13038 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13039 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13040 } 13041 13042 /// Determines if a variable's alignment is dependent. 13043 static bool hasDependentAlignment(VarDecl *VD) { 13044 if (VD->getType()->isDependentType()) 13045 return true; 13046 for (auto *I : VD->specific_attrs<AlignedAttr>()) 13047 if (I->isAlignmentDependent()) 13048 return true; 13049 return false; 13050 } 13051 13052 /// Check if VD needs to be dllexport/dllimport due to being in a 13053 /// dllexport/import function. 13054 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13055 assert(VD->isStaticLocal()); 13056 13057 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13058 13059 // Find outermost function when VD is in lambda function. 13060 while (FD && !getDLLAttr(FD) && 13061 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13062 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13063 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13064 } 13065 13066 if (!FD) 13067 return; 13068 13069 // Static locals inherit dll attributes from their function. 13070 if (Attr *A = getDLLAttr(FD)) { 13071 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13072 NewAttr->setInherited(true); 13073 VD->addAttr(NewAttr); 13074 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13075 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13076 NewAttr->setInherited(true); 13077 VD->addAttr(NewAttr); 13078 13079 // Export this function to enforce exporting this static variable even 13080 // if it is not used in this compilation unit. 13081 if (!FD->hasAttr<DLLExportAttr>()) 13082 FD->addAttr(NewAttr); 13083 13084 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13085 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13086 NewAttr->setInherited(true); 13087 VD->addAttr(NewAttr); 13088 } 13089 } 13090 13091 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13092 /// any semantic actions necessary after any initializer has been attached. 13093 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13094 // Note that we are no longer parsing the initializer for this declaration. 13095 ParsingInitForAutoVars.erase(ThisDecl); 13096 13097 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13098 if (!VD) 13099 return; 13100 13101 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13102 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13103 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13104 if (PragmaClangBSSSection.Valid) 13105 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13106 Context, PragmaClangBSSSection.SectionName, 13107 PragmaClangBSSSection.PragmaLocation, 13108 AttributeCommonInfo::AS_Pragma)); 13109 if (PragmaClangDataSection.Valid) 13110 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13111 Context, PragmaClangDataSection.SectionName, 13112 PragmaClangDataSection.PragmaLocation, 13113 AttributeCommonInfo::AS_Pragma)); 13114 if (PragmaClangRodataSection.Valid) 13115 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13116 Context, PragmaClangRodataSection.SectionName, 13117 PragmaClangRodataSection.PragmaLocation, 13118 AttributeCommonInfo::AS_Pragma)); 13119 if (PragmaClangRelroSection.Valid) 13120 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13121 Context, PragmaClangRelroSection.SectionName, 13122 PragmaClangRelroSection.PragmaLocation, 13123 AttributeCommonInfo::AS_Pragma)); 13124 } 13125 13126 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13127 for (auto *BD : DD->bindings()) { 13128 FinalizeDeclaration(BD); 13129 } 13130 } 13131 13132 checkAttributesAfterMerging(*this, *VD); 13133 13134 // Perform TLS alignment check here after attributes attached to the variable 13135 // which may affect the alignment have been processed. Only perform the check 13136 // if the target has a maximum TLS alignment (zero means no constraints). 13137 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13138 // Protect the check so that it's not performed on dependent types and 13139 // dependent alignments (we can't determine the alignment in that case). 13140 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13141 !VD->isInvalidDecl()) { 13142 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13143 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13144 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13145 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13146 << (unsigned)MaxAlignChars.getQuantity(); 13147 } 13148 } 13149 } 13150 13151 if (VD->isStaticLocal()) { 13152 CheckStaticLocalForDllExport(VD); 13153 13154 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 13155 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 13156 // function, only __shared__ variables or variables without any device 13157 // memory qualifiers may be declared with static storage class. 13158 // Note: It is unclear how a function-scope non-const static variable 13159 // without device memory qualifier is implemented, therefore only static 13160 // const variable without device memory qualifier is allowed. 13161 [&]() { 13162 if (!getLangOpts().CUDA) 13163 return; 13164 if (VD->hasAttr<CUDASharedAttr>()) 13165 return; 13166 if (VD->getType().isConstQualified() && 13167 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13168 return; 13169 if (CUDADiagIfDeviceCode(VD->getLocation(), 13170 diag::err_device_static_local_var) 13171 << CurrentCUDATarget()) 13172 VD->setInvalidDecl(); 13173 }(); 13174 } 13175 } 13176 13177 // Perform check for initializers of device-side global variables. 13178 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13179 // 7.5). We must also apply the same checks to all __shared__ 13180 // variables whether they are local or not. CUDA also allows 13181 // constant initializers for __constant__ and __device__ variables. 13182 if (getLangOpts().CUDA) 13183 checkAllowedCUDAInitializer(VD); 13184 13185 // Grab the dllimport or dllexport attribute off of the VarDecl. 13186 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13187 13188 // Imported static data members cannot be defined out-of-line. 13189 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13190 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13191 VD->isThisDeclarationADefinition()) { 13192 // We allow definitions of dllimport class template static data members 13193 // with a warning. 13194 CXXRecordDecl *Context = 13195 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13196 bool IsClassTemplateMember = 13197 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13198 Context->getDescribedClassTemplate(); 13199 13200 Diag(VD->getLocation(), 13201 IsClassTemplateMember 13202 ? diag::warn_attribute_dllimport_static_field_definition 13203 : diag::err_attribute_dllimport_static_field_definition); 13204 Diag(IA->getLocation(), diag::note_attribute); 13205 if (!IsClassTemplateMember) 13206 VD->setInvalidDecl(); 13207 } 13208 } 13209 13210 // dllimport/dllexport variables cannot be thread local, their TLS index 13211 // isn't exported with the variable. 13212 if (DLLAttr && VD->getTLSKind()) { 13213 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13214 if (F && getDLLAttr(F)) { 13215 assert(VD->isStaticLocal()); 13216 // But if this is a static local in a dlimport/dllexport function, the 13217 // function will never be inlined, which means the var would never be 13218 // imported, so having it marked import/export is safe. 13219 } else { 13220 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13221 << DLLAttr; 13222 VD->setInvalidDecl(); 13223 } 13224 } 13225 13226 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13227 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13228 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13229 VD->dropAttr<UsedAttr>(); 13230 } 13231 } 13232 13233 const DeclContext *DC = VD->getDeclContext(); 13234 // If there's a #pragma GCC visibility in scope, and this isn't a class 13235 // member, set the visibility of this variable. 13236 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13237 AddPushedVisibilityAttribute(VD); 13238 13239 // FIXME: Warn on unused var template partial specializations. 13240 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13241 MarkUnusedFileScopedDecl(VD); 13242 13243 // Now we have parsed the initializer and can update the table of magic 13244 // tag values. 13245 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13246 !VD->getType()->isIntegralOrEnumerationType()) 13247 return; 13248 13249 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13250 const Expr *MagicValueExpr = VD->getInit(); 13251 if (!MagicValueExpr) { 13252 continue; 13253 } 13254 Optional<llvm::APSInt> MagicValueInt; 13255 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13256 Diag(I->getRange().getBegin(), 13257 diag::err_type_tag_for_datatype_not_ice) 13258 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13259 continue; 13260 } 13261 if (MagicValueInt->getActiveBits() > 64) { 13262 Diag(I->getRange().getBegin(), 13263 diag::err_type_tag_for_datatype_too_large) 13264 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13265 continue; 13266 } 13267 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13268 RegisterTypeTagForDatatype(I->getArgumentKind(), 13269 MagicValue, 13270 I->getMatchingCType(), 13271 I->getLayoutCompatible(), 13272 I->getMustBeNull()); 13273 } 13274 } 13275 13276 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13277 auto *VD = dyn_cast<VarDecl>(DD); 13278 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13279 } 13280 13281 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13282 ArrayRef<Decl *> Group) { 13283 SmallVector<Decl*, 8> Decls; 13284 13285 if (DS.isTypeSpecOwned()) 13286 Decls.push_back(DS.getRepAsDecl()); 13287 13288 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13289 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13290 bool DiagnosedMultipleDecomps = false; 13291 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13292 bool DiagnosedNonDeducedAuto = false; 13293 13294 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13295 if (Decl *D = Group[i]) { 13296 // For declarators, there are some additional syntactic-ish checks we need 13297 // to perform. 13298 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13299 if (!FirstDeclaratorInGroup) 13300 FirstDeclaratorInGroup = DD; 13301 if (!FirstDecompDeclaratorInGroup) 13302 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13303 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13304 !hasDeducedAuto(DD)) 13305 FirstNonDeducedAutoInGroup = DD; 13306 13307 if (FirstDeclaratorInGroup != DD) { 13308 // A decomposition declaration cannot be combined with any other 13309 // declaration in the same group. 13310 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13311 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13312 diag::err_decomp_decl_not_alone) 13313 << FirstDeclaratorInGroup->getSourceRange() 13314 << DD->getSourceRange(); 13315 DiagnosedMultipleDecomps = true; 13316 } 13317 13318 // A declarator that uses 'auto' in any way other than to declare a 13319 // variable with a deduced type cannot be combined with any other 13320 // declarator in the same group. 13321 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13322 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13323 diag::err_auto_non_deduced_not_alone) 13324 << FirstNonDeducedAutoInGroup->getType() 13325 ->hasAutoForTrailingReturnType() 13326 << FirstDeclaratorInGroup->getSourceRange() 13327 << DD->getSourceRange(); 13328 DiagnosedNonDeducedAuto = true; 13329 } 13330 } 13331 } 13332 13333 Decls.push_back(D); 13334 } 13335 } 13336 13337 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13338 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13339 handleTagNumbering(Tag, S); 13340 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13341 getLangOpts().CPlusPlus) 13342 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13343 } 13344 } 13345 13346 return BuildDeclaratorGroup(Decls); 13347 } 13348 13349 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13350 /// group, performing any necessary semantic checking. 13351 Sema::DeclGroupPtrTy 13352 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13353 // C++14 [dcl.spec.auto]p7: (DR1347) 13354 // If the type that replaces the placeholder type is not the same in each 13355 // deduction, the program is ill-formed. 13356 if (Group.size() > 1) { 13357 QualType Deduced; 13358 VarDecl *DeducedDecl = nullptr; 13359 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13360 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13361 if (!D || D->isInvalidDecl()) 13362 break; 13363 DeducedType *DT = D->getType()->getContainedDeducedType(); 13364 if (!DT || DT->getDeducedType().isNull()) 13365 continue; 13366 if (Deduced.isNull()) { 13367 Deduced = DT->getDeducedType(); 13368 DeducedDecl = D; 13369 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13370 auto *AT = dyn_cast<AutoType>(DT); 13371 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13372 diag::err_auto_different_deductions) 13373 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13374 << DeducedDecl->getDeclName() << DT->getDeducedType() 13375 << D->getDeclName(); 13376 if (DeducedDecl->hasInit()) 13377 Dia << DeducedDecl->getInit()->getSourceRange(); 13378 if (D->getInit()) 13379 Dia << D->getInit()->getSourceRange(); 13380 D->setInvalidDecl(); 13381 break; 13382 } 13383 } 13384 } 13385 13386 ActOnDocumentableDecls(Group); 13387 13388 return DeclGroupPtrTy::make( 13389 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13390 } 13391 13392 void Sema::ActOnDocumentableDecl(Decl *D) { 13393 ActOnDocumentableDecls(D); 13394 } 13395 13396 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13397 // Don't parse the comment if Doxygen diagnostics are ignored. 13398 if (Group.empty() || !Group[0]) 13399 return; 13400 13401 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13402 Group[0]->getLocation()) && 13403 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13404 Group[0]->getLocation())) 13405 return; 13406 13407 if (Group.size() >= 2) { 13408 // This is a decl group. Normally it will contain only declarations 13409 // produced from declarator list. But in case we have any definitions or 13410 // additional declaration references: 13411 // 'typedef struct S {} S;' 13412 // 'typedef struct S *S;' 13413 // 'struct S *pS;' 13414 // FinalizeDeclaratorGroup adds these as separate declarations. 13415 Decl *MaybeTagDecl = Group[0]; 13416 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13417 Group = Group.slice(1); 13418 } 13419 } 13420 13421 // FIMXE: We assume every Decl in the group is in the same file. 13422 // This is false when preprocessor constructs the group from decls in 13423 // different files (e. g. macros or #include). 13424 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13425 } 13426 13427 /// Common checks for a parameter-declaration that should apply to both function 13428 /// parameters and non-type template parameters. 13429 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13430 // Check that there are no default arguments inside the type of this 13431 // parameter. 13432 if (getLangOpts().CPlusPlus) 13433 CheckExtraCXXDefaultArguments(D); 13434 13435 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13436 if (D.getCXXScopeSpec().isSet()) { 13437 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13438 << D.getCXXScopeSpec().getRange(); 13439 } 13440 13441 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13442 // simple identifier except [...irrelevant cases...]. 13443 switch (D.getName().getKind()) { 13444 case UnqualifiedIdKind::IK_Identifier: 13445 break; 13446 13447 case UnqualifiedIdKind::IK_OperatorFunctionId: 13448 case UnqualifiedIdKind::IK_ConversionFunctionId: 13449 case UnqualifiedIdKind::IK_LiteralOperatorId: 13450 case UnqualifiedIdKind::IK_ConstructorName: 13451 case UnqualifiedIdKind::IK_DestructorName: 13452 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13453 case UnqualifiedIdKind::IK_DeductionGuideName: 13454 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13455 << GetNameForDeclarator(D).getName(); 13456 break; 13457 13458 case UnqualifiedIdKind::IK_TemplateId: 13459 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13460 // GetNameForDeclarator would not produce a useful name in this case. 13461 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13462 break; 13463 } 13464 } 13465 13466 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13467 /// to introduce parameters into function prototype scope. 13468 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13469 const DeclSpec &DS = D.getDeclSpec(); 13470 13471 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13472 13473 // C++03 [dcl.stc]p2 also permits 'auto'. 13474 StorageClass SC = SC_None; 13475 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13476 SC = SC_Register; 13477 // In C++11, the 'register' storage class specifier is deprecated. 13478 // In C++17, it is not allowed, but we tolerate it as an extension. 13479 if (getLangOpts().CPlusPlus11) { 13480 Diag(DS.getStorageClassSpecLoc(), 13481 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13482 : diag::warn_deprecated_register) 13483 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13484 } 13485 } else if (getLangOpts().CPlusPlus && 13486 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13487 SC = SC_Auto; 13488 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13489 Diag(DS.getStorageClassSpecLoc(), 13490 diag::err_invalid_storage_class_in_func_decl); 13491 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13492 } 13493 13494 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13495 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13496 << DeclSpec::getSpecifierName(TSCS); 13497 if (DS.isInlineSpecified()) 13498 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13499 << getLangOpts().CPlusPlus17; 13500 if (DS.hasConstexprSpecifier()) 13501 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13502 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13503 13504 DiagnoseFunctionSpecifiers(DS); 13505 13506 CheckFunctionOrTemplateParamDeclarator(S, D); 13507 13508 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13509 QualType parmDeclType = TInfo->getType(); 13510 13511 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13512 IdentifierInfo *II = D.getIdentifier(); 13513 if (II) { 13514 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13515 ForVisibleRedeclaration); 13516 LookupName(R, S); 13517 if (R.isSingleResult()) { 13518 NamedDecl *PrevDecl = R.getFoundDecl(); 13519 if (PrevDecl->isTemplateParameter()) { 13520 // Maybe we will complain about the shadowed template parameter. 13521 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13522 // Just pretend that we didn't see the previous declaration. 13523 PrevDecl = nullptr; 13524 } else if (S->isDeclScope(PrevDecl)) { 13525 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13526 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13527 13528 // Recover by removing the name 13529 II = nullptr; 13530 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13531 D.setInvalidType(true); 13532 } 13533 } 13534 } 13535 13536 // Temporarily put parameter variables in the translation unit, not 13537 // the enclosing context. This prevents them from accidentally 13538 // looking like class members in C++. 13539 ParmVarDecl *New = 13540 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13541 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13542 13543 if (D.isInvalidType()) 13544 New->setInvalidDecl(); 13545 13546 assert(S->isFunctionPrototypeScope()); 13547 assert(S->getFunctionPrototypeDepth() >= 1); 13548 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13549 S->getNextFunctionPrototypeIndex()); 13550 13551 // Add the parameter declaration into this scope. 13552 S->AddDecl(New); 13553 if (II) 13554 IdResolver.AddDecl(New); 13555 13556 ProcessDeclAttributes(S, New, D); 13557 13558 if (D.getDeclSpec().isModulePrivateSpecified()) 13559 Diag(New->getLocation(), diag::err_module_private_local) 13560 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13561 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13562 13563 if (New->hasAttr<BlocksAttr>()) { 13564 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13565 } 13566 13567 if (getLangOpts().OpenCL) 13568 deduceOpenCLAddressSpace(New); 13569 13570 return New; 13571 } 13572 13573 /// Synthesizes a variable for a parameter arising from a 13574 /// typedef. 13575 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13576 SourceLocation Loc, 13577 QualType T) { 13578 /* FIXME: setting StartLoc == Loc. 13579 Would it be worth to modify callers so as to provide proper source 13580 location for the unnamed parameters, embedding the parameter's type? */ 13581 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13582 T, Context.getTrivialTypeSourceInfo(T, Loc), 13583 SC_None, nullptr); 13584 Param->setImplicit(); 13585 return Param; 13586 } 13587 13588 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13589 // Don't diagnose unused-parameter errors in template instantiations; we 13590 // will already have done so in the template itself. 13591 if (inTemplateInstantiation()) 13592 return; 13593 13594 for (const ParmVarDecl *Parameter : Parameters) { 13595 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13596 !Parameter->hasAttr<UnusedAttr>()) { 13597 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13598 << Parameter->getDeclName(); 13599 } 13600 } 13601 } 13602 13603 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13604 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13605 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13606 return; 13607 13608 // Warn if the return value is pass-by-value and larger than the specified 13609 // threshold. 13610 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13611 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13612 if (Size > LangOpts.NumLargeByValueCopy) 13613 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13614 } 13615 13616 // Warn if any parameter is pass-by-value and larger than the specified 13617 // threshold. 13618 for (const ParmVarDecl *Parameter : Parameters) { 13619 QualType T = Parameter->getType(); 13620 if (T->isDependentType() || !T.isPODType(Context)) 13621 continue; 13622 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13623 if (Size > LangOpts.NumLargeByValueCopy) 13624 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13625 << Parameter << Size; 13626 } 13627 } 13628 13629 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13630 SourceLocation NameLoc, IdentifierInfo *Name, 13631 QualType T, TypeSourceInfo *TSInfo, 13632 StorageClass SC) { 13633 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13634 if (getLangOpts().ObjCAutoRefCount && 13635 T.getObjCLifetime() == Qualifiers::OCL_None && 13636 T->isObjCLifetimeType()) { 13637 13638 Qualifiers::ObjCLifetime lifetime; 13639 13640 // Special cases for arrays: 13641 // - if it's const, use __unsafe_unretained 13642 // - otherwise, it's an error 13643 if (T->isArrayType()) { 13644 if (!T.isConstQualified()) { 13645 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13646 DelayedDiagnostics.add( 13647 sema::DelayedDiagnostic::makeForbiddenType( 13648 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13649 else 13650 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13651 << TSInfo->getTypeLoc().getSourceRange(); 13652 } 13653 lifetime = Qualifiers::OCL_ExplicitNone; 13654 } else { 13655 lifetime = T->getObjCARCImplicitLifetime(); 13656 } 13657 T = Context.getLifetimeQualifiedType(T, lifetime); 13658 } 13659 13660 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13661 Context.getAdjustedParameterType(T), 13662 TSInfo, SC, nullptr); 13663 13664 // Make a note if we created a new pack in the scope of a lambda, so that 13665 // we know that references to that pack must also be expanded within the 13666 // lambda scope. 13667 if (New->isParameterPack()) 13668 if (auto *LSI = getEnclosingLambda()) 13669 LSI->LocalPacks.push_back(New); 13670 13671 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13672 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13673 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13674 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13675 13676 // Parameters can not be abstract class types. 13677 // For record types, this is done by the AbstractClassUsageDiagnoser once 13678 // the class has been completely parsed. 13679 if (!CurContext->isRecord() && 13680 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13681 AbstractParamType)) 13682 New->setInvalidDecl(); 13683 13684 // Parameter declarators cannot be interface types. All ObjC objects are 13685 // passed by reference. 13686 if (T->isObjCObjectType()) { 13687 SourceLocation TypeEndLoc = 13688 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13689 Diag(NameLoc, 13690 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13691 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13692 T = Context.getObjCObjectPointerType(T); 13693 New->setType(T); 13694 } 13695 13696 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13697 // duration shall not be qualified by an address-space qualifier." 13698 // Since all parameters have automatic store duration, they can not have 13699 // an address space. 13700 if (T.getAddressSpace() != LangAS::Default && 13701 // OpenCL allows function arguments declared to be an array of a type 13702 // to be qualified with an address space. 13703 !(getLangOpts().OpenCL && 13704 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13705 Diag(NameLoc, diag::err_arg_with_address_space); 13706 New->setInvalidDecl(); 13707 } 13708 13709 return New; 13710 } 13711 13712 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13713 SourceLocation LocAfterDecls) { 13714 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13715 13716 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13717 // for a K&R function. 13718 if (!FTI.hasPrototype) { 13719 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13720 --i; 13721 if (FTI.Params[i].Param == nullptr) { 13722 SmallString<256> Code; 13723 llvm::raw_svector_ostream(Code) 13724 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13725 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13726 << FTI.Params[i].Ident 13727 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13728 13729 // Implicitly declare the argument as type 'int' for lack of a better 13730 // type. 13731 AttributeFactory attrs; 13732 DeclSpec DS(attrs); 13733 const char* PrevSpec; // unused 13734 unsigned DiagID; // unused 13735 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13736 DiagID, Context.getPrintingPolicy()); 13737 // Use the identifier location for the type source range. 13738 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13739 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13740 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13741 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13742 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13743 } 13744 } 13745 } 13746 } 13747 13748 Decl * 13749 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13750 MultiTemplateParamsArg TemplateParameterLists, 13751 SkipBodyInfo *SkipBody) { 13752 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13753 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13754 Scope *ParentScope = FnBodyScope->getParent(); 13755 13756 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13757 // we define a non-templated function definition, we will create a declaration 13758 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13759 // The base function declaration will have the equivalent of an `omp declare 13760 // variant` annotation which specifies the mangled definition as a 13761 // specialization function under the OpenMP context defined as part of the 13762 // `omp begin declare variant`. 13763 SmallVector<FunctionDecl *, 4> Bases; 13764 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 13765 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13766 ParentScope, D, TemplateParameterLists, Bases); 13767 13768 D.setFunctionDefinitionKind(FDK_Definition); 13769 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13770 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13771 13772 if (!Bases.empty()) 13773 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 13774 13775 return Dcl; 13776 } 13777 13778 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13779 Consumer.HandleInlineFunctionDefinition(D); 13780 } 13781 13782 static bool 13783 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13784 const FunctionDecl *&PossiblePrototype) { 13785 // Don't warn about invalid declarations. 13786 if (FD->isInvalidDecl()) 13787 return false; 13788 13789 // Or declarations that aren't global. 13790 if (!FD->isGlobal()) 13791 return false; 13792 13793 // Don't warn about C++ member functions. 13794 if (isa<CXXMethodDecl>(FD)) 13795 return false; 13796 13797 // Don't warn about 'main'. 13798 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13799 if (IdentifierInfo *II = FD->getIdentifier()) 13800 if (II->isStr("main")) 13801 return false; 13802 13803 // Don't warn about inline functions. 13804 if (FD->isInlined()) 13805 return false; 13806 13807 // Don't warn about function templates. 13808 if (FD->getDescribedFunctionTemplate()) 13809 return false; 13810 13811 // Don't warn about function template specializations. 13812 if (FD->isFunctionTemplateSpecialization()) 13813 return false; 13814 13815 // Don't warn for OpenCL kernels. 13816 if (FD->hasAttr<OpenCLKernelAttr>()) 13817 return false; 13818 13819 // Don't warn on explicitly deleted functions. 13820 if (FD->isDeleted()) 13821 return false; 13822 13823 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13824 Prev; Prev = Prev->getPreviousDecl()) { 13825 // Ignore any declarations that occur in function or method 13826 // scope, because they aren't visible from the header. 13827 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13828 continue; 13829 13830 PossiblePrototype = Prev; 13831 return Prev->getType()->isFunctionNoProtoType(); 13832 } 13833 13834 return true; 13835 } 13836 13837 void 13838 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13839 const FunctionDecl *EffectiveDefinition, 13840 SkipBodyInfo *SkipBody) { 13841 const FunctionDecl *Definition = EffectiveDefinition; 13842 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13843 // If this is a friend function defined in a class template, it does not 13844 // have a body until it is used, nevertheless it is a definition, see 13845 // [temp.inst]p2: 13846 // 13847 // ... for the purpose of determining whether an instantiated redeclaration 13848 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13849 // corresponds to a definition in the template is considered to be a 13850 // definition. 13851 // 13852 // The following code must produce redefinition error: 13853 // 13854 // template<typename T> struct C20 { friend void func_20() {} }; 13855 // C20<int> c20i; 13856 // void func_20() {} 13857 // 13858 for (auto I : FD->redecls()) { 13859 if (I != FD && !I->isInvalidDecl() && 13860 I->getFriendObjectKind() != Decl::FOK_None) { 13861 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13862 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13863 // A merged copy of the same function, instantiated as a member of 13864 // the same class, is OK. 13865 if (declaresSameEntity(OrigFD, Original) && 13866 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13867 cast<Decl>(FD->getLexicalDeclContext()))) 13868 continue; 13869 } 13870 13871 if (Original->isThisDeclarationADefinition()) { 13872 Definition = I; 13873 break; 13874 } 13875 } 13876 } 13877 } 13878 } 13879 13880 if (!Definition) 13881 // Similar to friend functions a friend function template may be a 13882 // definition and do not have a body if it is instantiated in a class 13883 // template. 13884 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13885 for (auto I : FTD->redecls()) { 13886 auto D = cast<FunctionTemplateDecl>(I); 13887 if (D != FTD) { 13888 assert(!D->isThisDeclarationADefinition() && 13889 "More than one definition in redeclaration chain"); 13890 if (D->getFriendObjectKind() != Decl::FOK_None) 13891 if (FunctionTemplateDecl *FT = 13892 D->getInstantiatedFromMemberTemplate()) { 13893 if (FT->isThisDeclarationADefinition()) { 13894 Definition = D->getTemplatedDecl(); 13895 break; 13896 } 13897 } 13898 } 13899 } 13900 } 13901 13902 if (!Definition) 13903 return; 13904 13905 if (canRedefineFunction(Definition, getLangOpts())) 13906 return; 13907 13908 // Don't emit an error when this is redefinition of a typo-corrected 13909 // definition. 13910 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13911 return; 13912 13913 // If we don't have a visible definition of the function, and it's inline or 13914 // a template, skip the new definition. 13915 if (SkipBody && !hasVisibleDefinition(Definition) && 13916 (Definition->getFormalLinkage() == InternalLinkage || 13917 Definition->isInlined() || 13918 Definition->getDescribedFunctionTemplate() || 13919 Definition->getNumTemplateParameterLists())) { 13920 SkipBody->ShouldSkip = true; 13921 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13922 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13923 makeMergedDefinitionVisible(TD); 13924 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13925 return; 13926 } 13927 13928 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13929 Definition->getStorageClass() == SC_Extern) 13930 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13931 << FD << getLangOpts().CPlusPlus; 13932 else 13933 Diag(FD->getLocation(), diag::err_redefinition) << FD; 13934 13935 Diag(Definition->getLocation(), diag::note_previous_definition); 13936 FD->setInvalidDecl(); 13937 } 13938 13939 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13940 Sema &S) { 13941 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13942 13943 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13944 LSI->CallOperator = CallOperator; 13945 LSI->Lambda = LambdaClass; 13946 LSI->ReturnType = CallOperator->getReturnType(); 13947 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13948 13949 if (LCD == LCD_None) 13950 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13951 else if (LCD == LCD_ByCopy) 13952 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13953 else if (LCD == LCD_ByRef) 13954 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13955 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13956 13957 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13958 LSI->Mutable = !CallOperator->isConst(); 13959 13960 // Add the captures to the LSI so they can be noted as already 13961 // captured within tryCaptureVar. 13962 auto I = LambdaClass->field_begin(); 13963 for (const auto &C : LambdaClass->captures()) { 13964 if (C.capturesVariable()) { 13965 VarDecl *VD = C.getCapturedVar(); 13966 if (VD->isInitCapture()) 13967 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13968 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13969 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13970 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13971 /*EllipsisLoc*/C.isPackExpansion() 13972 ? C.getEllipsisLoc() : SourceLocation(), 13973 I->getType(), /*Invalid*/false); 13974 13975 } else if (C.capturesThis()) { 13976 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13977 C.getCaptureKind() == LCK_StarThis); 13978 } else { 13979 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13980 I->getType()); 13981 } 13982 ++I; 13983 } 13984 } 13985 13986 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13987 SkipBodyInfo *SkipBody) { 13988 if (!D) { 13989 // Parsing the function declaration failed in some way. Push on a fake scope 13990 // anyway so we can try to parse the function body. 13991 PushFunctionScope(); 13992 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13993 return D; 13994 } 13995 13996 FunctionDecl *FD = nullptr; 13997 13998 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13999 FD = FunTmpl->getTemplatedDecl(); 14000 else 14001 FD = cast<FunctionDecl>(D); 14002 14003 // Do not push if it is a lambda because one is already pushed when building 14004 // the lambda in ActOnStartOfLambdaDefinition(). 14005 if (!isLambdaCallOperator(FD)) 14006 PushExpressionEvaluationContext( 14007 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14008 : ExprEvalContexts.back().Context); 14009 14010 // Check for defining attributes before the check for redefinition. 14011 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14012 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14013 FD->dropAttr<AliasAttr>(); 14014 FD->setInvalidDecl(); 14015 } 14016 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14017 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14018 FD->dropAttr<IFuncAttr>(); 14019 FD->setInvalidDecl(); 14020 } 14021 14022 // See if this is a redefinition. If 'will have body' is already set, then 14023 // these checks were already performed when it was set. 14024 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 14025 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14026 14027 // If we're skipping the body, we're done. Don't enter the scope. 14028 if (SkipBody && SkipBody->ShouldSkip) 14029 return D; 14030 } 14031 14032 // Mark this function as "will have a body eventually". This lets users to 14033 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14034 // this function. 14035 FD->setWillHaveBody(); 14036 14037 // If we are instantiating a generic lambda call operator, push 14038 // a LambdaScopeInfo onto the function stack. But use the information 14039 // that's already been calculated (ActOnLambdaExpr) to prime the current 14040 // LambdaScopeInfo. 14041 // When the template operator is being specialized, the LambdaScopeInfo, 14042 // has to be properly restored so that tryCaptureVariable doesn't try 14043 // and capture any new variables. In addition when calculating potential 14044 // captures during transformation of nested lambdas, it is necessary to 14045 // have the LSI properly restored. 14046 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14047 assert(inTemplateInstantiation() && 14048 "There should be an active template instantiation on the stack " 14049 "when instantiating a generic lambda!"); 14050 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14051 } else { 14052 // Enter a new function scope 14053 PushFunctionScope(); 14054 } 14055 14056 // Builtin functions cannot be defined. 14057 if (unsigned BuiltinID = FD->getBuiltinID()) { 14058 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14059 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14060 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14061 FD->setInvalidDecl(); 14062 } 14063 } 14064 14065 // The return type of a function definition must be complete 14066 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14067 QualType ResultType = FD->getReturnType(); 14068 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14069 !FD->isInvalidDecl() && 14070 RequireCompleteType(FD->getLocation(), ResultType, 14071 diag::err_func_def_incomplete_result)) 14072 FD->setInvalidDecl(); 14073 14074 if (FnBodyScope) 14075 PushDeclContext(FnBodyScope, FD); 14076 14077 // Check the validity of our function parameters 14078 CheckParmsForFunctionDef(FD->parameters(), 14079 /*CheckParameterNames=*/true); 14080 14081 // Add non-parameter declarations already in the function to the current 14082 // scope. 14083 if (FnBodyScope) { 14084 for (Decl *NPD : FD->decls()) { 14085 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14086 if (!NonParmDecl) 14087 continue; 14088 assert(!isa<ParmVarDecl>(NonParmDecl) && 14089 "parameters should not be in newly created FD yet"); 14090 14091 // If the decl has a name, make it accessible in the current scope. 14092 if (NonParmDecl->getDeclName()) 14093 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14094 14095 // Similarly, dive into enums and fish their constants out, making them 14096 // accessible in this scope. 14097 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14098 for (auto *EI : ED->enumerators()) 14099 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14100 } 14101 } 14102 } 14103 14104 // Introduce our parameters into the function scope 14105 for (auto Param : FD->parameters()) { 14106 Param->setOwningFunction(FD); 14107 14108 // If this has an identifier, add it to the scope stack. 14109 if (Param->getIdentifier() && FnBodyScope) { 14110 CheckShadow(FnBodyScope, Param); 14111 14112 PushOnScopeChains(Param, FnBodyScope); 14113 } 14114 } 14115 14116 // Ensure that the function's exception specification is instantiated. 14117 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14118 ResolveExceptionSpec(D->getLocation(), FPT); 14119 14120 // dllimport cannot be applied to non-inline function definitions. 14121 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14122 !FD->isTemplateInstantiation()) { 14123 assert(!FD->hasAttr<DLLExportAttr>()); 14124 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14125 FD->setInvalidDecl(); 14126 return D; 14127 } 14128 // We want to attach documentation to original Decl (which might be 14129 // a function template). 14130 ActOnDocumentableDecl(D); 14131 if (getCurLexicalContext()->isObjCContainer() && 14132 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14133 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14134 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14135 14136 return D; 14137 } 14138 14139 /// Given the set of return statements within a function body, 14140 /// compute the variables that are subject to the named return value 14141 /// optimization. 14142 /// 14143 /// Each of the variables that is subject to the named return value 14144 /// optimization will be marked as NRVO variables in the AST, and any 14145 /// return statement that has a marked NRVO variable as its NRVO candidate can 14146 /// use the named return value optimization. 14147 /// 14148 /// This function applies a very simplistic algorithm for NRVO: if every return 14149 /// statement in the scope of a variable has the same NRVO candidate, that 14150 /// candidate is an NRVO variable. 14151 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14152 ReturnStmt **Returns = Scope->Returns.data(); 14153 14154 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14155 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14156 if (!NRVOCandidate->isNRVOVariable()) 14157 Returns[I]->setNRVOCandidate(nullptr); 14158 } 14159 } 14160 } 14161 14162 bool Sema::canDelayFunctionBody(const Declarator &D) { 14163 // We can't delay parsing the body of a constexpr function template (yet). 14164 if (D.getDeclSpec().hasConstexprSpecifier()) 14165 return false; 14166 14167 // We can't delay parsing the body of a function template with a deduced 14168 // return type (yet). 14169 if (D.getDeclSpec().hasAutoTypeSpec()) { 14170 // If the placeholder introduces a non-deduced trailing return type, 14171 // we can still delay parsing it. 14172 if (D.getNumTypeObjects()) { 14173 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14174 if (Outer.Kind == DeclaratorChunk::Function && 14175 Outer.Fun.hasTrailingReturnType()) { 14176 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14177 return Ty.isNull() || !Ty->isUndeducedType(); 14178 } 14179 } 14180 return false; 14181 } 14182 14183 return true; 14184 } 14185 14186 bool Sema::canSkipFunctionBody(Decl *D) { 14187 // We cannot skip the body of a function (or function template) which is 14188 // constexpr, since we may need to evaluate its body in order to parse the 14189 // rest of the file. 14190 // We cannot skip the body of a function with an undeduced return type, 14191 // because any callers of that function need to know the type. 14192 if (const FunctionDecl *FD = D->getAsFunction()) { 14193 if (FD->isConstexpr()) 14194 return false; 14195 // We can't simply call Type::isUndeducedType here, because inside template 14196 // auto can be deduced to a dependent type, which is not considered 14197 // "undeduced". 14198 if (FD->getReturnType()->getContainedDeducedType()) 14199 return false; 14200 } 14201 return Consumer.shouldSkipFunctionBody(D); 14202 } 14203 14204 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14205 if (!Decl) 14206 return nullptr; 14207 if (FunctionDecl *FD = Decl->getAsFunction()) 14208 FD->setHasSkippedBody(); 14209 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14210 MD->setHasSkippedBody(); 14211 return Decl; 14212 } 14213 14214 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14215 return ActOnFinishFunctionBody(D, BodyArg, false); 14216 } 14217 14218 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14219 /// body. 14220 class ExitFunctionBodyRAII { 14221 public: 14222 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14223 ~ExitFunctionBodyRAII() { 14224 if (!IsLambda) 14225 S.PopExpressionEvaluationContext(); 14226 } 14227 14228 private: 14229 Sema &S; 14230 bool IsLambda = false; 14231 }; 14232 14233 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14234 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14235 14236 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14237 if (EscapeInfo.count(BD)) 14238 return EscapeInfo[BD]; 14239 14240 bool R = false; 14241 const BlockDecl *CurBD = BD; 14242 14243 do { 14244 R = !CurBD->doesNotEscape(); 14245 if (R) 14246 break; 14247 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14248 } while (CurBD); 14249 14250 return EscapeInfo[BD] = R; 14251 }; 14252 14253 // If the location where 'self' is implicitly retained is inside a escaping 14254 // block, emit a diagnostic. 14255 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14256 S.ImplicitlyRetainedSelfLocs) 14257 if (IsOrNestedInEscapingBlock(P.second)) 14258 S.Diag(P.first, diag::warn_implicitly_retains_self) 14259 << FixItHint::CreateInsertion(P.first, "self->"); 14260 } 14261 14262 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14263 bool IsInstantiation) { 14264 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14265 14266 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14267 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14268 14269 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14270 CheckCompletedCoroutineBody(FD, Body); 14271 14272 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14273 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14274 // meant to pop the context added in ActOnStartOfFunctionDef(). 14275 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14276 14277 if (FD) { 14278 FD->setBody(Body); 14279 FD->setWillHaveBody(false); 14280 14281 if (getLangOpts().CPlusPlus14) { 14282 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14283 FD->getReturnType()->isUndeducedType()) { 14284 // If the function has a deduced result type but contains no 'return' 14285 // statements, the result type as written must be exactly 'auto', and 14286 // the deduced result type is 'void'. 14287 if (!FD->getReturnType()->getAs<AutoType>()) { 14288 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14289 << FD->getReturnType(); 14290 FD->setInvalidDecl(); 14291 } else { 14292 // Substitute 'void' for the 'auto' in the type. 14293 TypeLoc ResultType = getReturnTypeLoc(FD); 14294 Context.adjustDeducedFunctionResultType( 14295 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14296 } 14297 } 14298 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14299 // In C++11, we don't use 'auto' deduction rules for lambda call 14300 // operators because we don't support return type deduction. 14301 auto *LSI = getCurLambda(); 14302 if (LSI->HasImplicitReturnType) { 14303 deduceClosureReturnType(*LSI); 14304 14305 // C++11 [expr.prim.lambda]p4: 14306 // [...] if there are no return statements in the compound-statement 14307 // [the deduced type is] the type void 14308 QualType RetType = 14309 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14310 14311 // Update the return type to the deduced type. 14312 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14313 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14314 Proto->getExtProtoInfo())); 14315 } 14316 } 14317 14318 // If the function implicitly returns zero (like 'main') or is naked, 14319 // don't complain about missing return statements. 14320 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14321 WP.disableCheckFallThrough(); 14322 14323 // MSVC permits the use of pure specifier (=0) on function definition, 14324 // defined at class scope, warn about this non-standard construct. 14325 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14326 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14327 14328 if (!FD->isInvalidDecl()) { 14329 // Don't diagnose unused parameters of defaulted or deleted functions. 14330 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14331 DiagnoseUnusedParameters(FD->parameters()); 14332 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14333 FD->getReturnType(), FD); 14334 14335 // If this is a structor, we need a vtable. 14336 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14337 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14338 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14339 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14340 14341 // Try to apply the named return value optimization. We have to check 14342 // if we can do this here because lambdas keep return statements around 14343 // to deduce an implicit return type. 14344 if (FD->getReturnType()->isRecordType() && 14345 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14346 computeNRVO(Body, getCurFunction()); 14347 } 14348 14349 // GNU warning -Wmissing-prototypes: 14350 // Warn if a global function is defined without a previous 14351 // prototype declaration. This warning is issued even if the 14352 // definition itself provides a prototype. The aim is to detect 14353 // global functions that fail to be declared in header files. 14354 const FunctionDecl *PossiblePrototype = nullptr; 14355 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14356 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14357 14358 if (PossiblePrototype) { 14359 // We found a declaration that is not a prototype, 14360 // but that could be a zero-parameter prototype 14361 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14362 TypeLoc TL = TI->getTypeLoc(); 14363 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14364 Diag(PossiblePrototype->getLocation(), 14365 diag::note_declaration_not_a_prototype) 14366 << (FD->getNumParams() != 0) 14367 << (FD->getNumParams() == 0 14368 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14369 : FixItHint{}); 14370 } 14371 } else { 14372 // Returns true if the token beginning at this Loc is `const`. 14373 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14374 const LangOptions &LangOpts) { 14375 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14376 if (LocInfo.first.isInvalid()) 14377 return false; 14378 14379 bool Invalid = false; 14380 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14381 if (Invalid) 14382 return false; 14383 14384 if (LocInfo.second > Buffer.size()) 14385 return false; 14386 14387 const char *LexStart = Buffer.data() + LocInfo.second; 14388 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14389 14390 return StartTok.consume_front("const") && 14391 (StartTok.empty() || isWhitespace(StartTok[0]) || 14392 StartTok.startswith("/*") || StartTok.startswith("//")); 14393 }; 14394 14395 auto findBeginLoc = [&]() { 14396 // If the return type has `const` qualifier, we want to insert 14397 // `static` before `const` (and not before the typename). 14398 if ((FD->getReturnType()->isAnyPointerType() && 14399 FD->getReturnType()->getPointeeType().isConstQualified()) || 14400 FD->getReturnType().isConstQualified()) { 14401 // But only do this if we can determine where the `const` is. 14402 14403 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14404 getLangOpts())) 14405 14406 return FD->getBeginLoc(); 14407 } 14408 return FD->getTypeSpecStartLoc(); 14409 }; 14410 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14411 << /* function */ 1 14412 << (FD->getStorageClass() == SC_None 14413 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14414 : FixItHint{}); 14415 } 14416 14417 // GNU warning -Wstrict-prototypes 14418 // Warn if K&R function is defined without a previous declaration. 14419 // This warning is issued only if the definition itself does not provide 14420 // a prototype. Only K&R definitions do not provide a prototype. 14421 if (!FD->hasWrittenPrototype()) { 14422 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14423 TypeLoc TL = TI->getTypeLoc(); 14424 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14425 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14426 } 14427 } 14428 14429 // Warn on CPUDispatch with an actual body. 14430 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14431 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14432 if (!CmpndBody->body_empty()) 14433 Diag(CmpndBody->body_front()->getBeginLoc(), 14434 diag::warn_dispatch_body_ignored); 14435 14436 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14437 const CXXMethodDecl *KeyFunction; 14438 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14439 MD->isVirtual() && 14440 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14441 MD == KeyFunction->getCanonicalDecl()) { 14442 // Update the key-function state if necessary for this ABI. 14443 if (FD->isInlined() && 14444 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14445 Context.setNonKeyFunction(MD); 14446 14447 // If the newly-chosen key function is already defined, then we 14448 // need to mark the vtable as used retroactively. 14449 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14450 const FunctionDecl *Definition; 14451 if (KeyFunction && KeyFunction->isDefined(Definition)) 14452 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14453 } else { 14454 // We just defined they key function; mark the vtable as used. 14455 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14456 } 14457 } 14458 } 14459 14460 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14461 "Function parsing confused"); 14462 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14463 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14464 MD->setBody(Body); 14465 if (!MD->isInvalidDecl()) { 14466 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14467 MD->getReturnType(), MD); 14468 14469 if (Body) 14470 computeNRVO(Body, getCurFunction()); 14471 } 14472 if (getCurFunction()->ObjCShouldCallSuper) { 14473 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14474 << MD->getSelector().getAsString(); 14475 getCurFunction()->ObjCShouldCallSuper = false; 14476 } 14477 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14478 const ObjCMethodDecl *InitMethod = nullptr; 14479 bool isDesignated = 14480 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14481 assert(isDesignated && InitMethod); 14482 (void)isDesignated; 14483 14484 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14485 auto IFace = MD->getClassInterface(); 14486 if (!IFace) 14487 return false; 14488 auto SuperD = IFace->getSuperClass(); 14489 if (!SuperD) 14490 return false; 14491 return SuperD->getIdentifier() == 14492 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14493 }; 14494 // Don't issue this warning for unavailable inits or direct subclasses 14495 // of NSObject. 14496 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14497 Diag(MD->getLocation(), 14498 diag::warn_objc_designated_init_missing_super_call); 14499 Diag(InitMethod->getLocation(), 14500 diag::note_objc_designated_init_marked_here); 14501 } 14502 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14503 } 14504 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14505 // Don't issue this warning for unavaialable inits. 14506 if (!MD->isUnavailable()) 14507 Diag(MD->getLocation(), 14508 diag::warn_objc_secondary_init_missing_init_call); 14509 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14510 } 14511 14512 diagnoseImplicitlyRetainedSelf(*this); 14513 } else { 14514 // Parsing the function declaration failed in some way. Pop the fake scope 14515 // we pushed on. 14516 PopFunctionScopeInfo(ActivePolicy, dcl); 14517 return nullptr; 14518 } 14519 14520 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14521 DiagnoseUnguardedAvailabilityViolations(dcl); 14522 14523 assert(!getCurFunction()->ObjCShouldCallSuper && 14524 "This should only be set for ObjC methods, which should have been " 14525 "handled in the block above."); 14526 14527 // Verify and clean out per-function state. 14528 if (Body && (!FD || !FD->isDefaulted())) { 14529 // C++ constructors that have function-try-blocks can't have return 14530 // statements in the handlers of that block. (C++ [except.handle]p14) 14531 // Verify this. 14532 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14533 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14534 14535 // Verify that gotos and switch cases don't jump into scopes illegally. 14536 if (getCurFunction()->NeedsScopeChecking() && 14537 !PP.isCodeCompletionEnabled()) 14538 DiagnoseInvalidJumps(Body); 14539 14540 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14541 if (!Destructor->getParent()->isDependentType()) 14542 CheckDestructor(Destructor); 14543 14544 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14545 Destructor->getParent()); 14546 } 14547 14548 // If any errors have occurred, clear out any temporaries that may have 14549 // been leftover. This ensures that these temporaries won't be picked up for 14550 // deletion in some later function. 14551 if (getDiagnostics().hasUncompilableErrorOccurred() || 14552 getDiagnostics().getSuppressAllDiagnostics()) { 14553 DiscardCleanupsInEvaluationContext(); 14554 } 14555 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14556 !isa<FunctionTemplateDecl>(dcl)) { 14557 // Since the body is valid, issue any analysis-based warnings that are 14558 // enabled. 14559 ActivePolicy = &WP; 14560 } 14561 14562 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14563 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14564 FD->setInvalidDecl(); 14565 14566 if (FD && FD->hasAttr<NakedAttr>()) { 14567 for (const Stmt *S : Body->children()) { 14568 // Allow local register variables without initializer as they don't 14569 // require prologue. 14570 bool RegisterVariables = false; 14571 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14572 for (const auto *Decl : DS->decls()) { 14573 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14574 RegisterVariables = 14575 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14576 if (!RegisterVariables) 14577 break; 14578 } 14579 } 14580 } 14581 if (RegisterVariables) 14582 continue; 14583 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14584 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14585 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14586 FD->setInvalidDecl(); 14587 break; 14588 } 14589 } 14590 } 14591 14592 assert(ExprCleanupObjects.size() == 14593 ExprEvalContexts.back().NumCleanupObjects && 14594 "Leftover temporaries in function"); 14595 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14596 assert(MaybeODRUseExprs.empty() && 14597 "Leftover expressions for odr-use checking"); 14598 } 14599 14600 if (!IsInstantiation) 14601 PopDeclContext(); 14602 14603 PopFunctionScopeInfo(ActivePolicy, dcl); 14604 // If any errors have occurred, clear out any temporaries that may have 14605 // been leftover. This ensures that these temporaries won't be picked up for 14606 // deletion in some later function. 14607 if (getDiagnostics().hasUncompilableErrorOccurred()) { 14608 DiscardCleanupsInEvaluationContext(); 14609 } 14610 14611 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { 14612 auto ES = getEmissionStatus(FD); 14613 if (ES == Sema::FunctionEmissionStatus::Emitted || 14614 ES == Sema::FunctionEmissionStatus::Unknown) 14615 DeclsToCheckForDeferredDiags.push_back(FD); 14616 } 14617 14618 return dcl; 14619 } 14620 14621 /// When we finish delayed parsing of an attribute, we must attach it to the 14622 /// relevant Decl. 14623 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14624 ParsedAttributes &Attrs) { 14625 // Always attach attributes to the underlying decl. 14626 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14627 D = TD->getTemplatedDecl(); 14628 ProcessDeclAttributeList(S, D, Attrs); 14629 14630 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14631 if (Method->isStatic()) 14632 checkThisInStaticMemberFunctionAttributes(Method); 14633 } 14634 14635 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14636 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14637 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14638 IdentifierInfo &II, Scope *S) { 14639 // Find the scope in which the identifier is injected and the corresponding 14640 // DeclContext. 14641 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14642 // In that case, we inject the declaration into the translation unit scope 14643 // instead. 14644 Scope *BlockScope = S; 14645 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14646 BlockScope = BlockScope->getParent(); 14647 14648 Scope *ContextScope = BlockScope; 14649 while (!ContextScope->getEntity()) 14650 ContextScope = ContextScope->getParent(); 14651 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14652 14653 // Before we produce a declaration for an implicitly defined 14654 // function, see whether there was a locally-scoped declaration of 14655 // this name as a function or variable. If so, use that 14656 // (non-visible) declaration, and complain about it. 14657 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14658 if (ExternCPrev) { 14659 // We still need to inject the function into the enclosing block scope so 14660 // that later (non-call) uses can see it. 14661 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14662 14663 // C89 footnote 38: 14664 // If in fact it is not defined as having type "function returning int", 14665 // the behavior is undefined. 14666 if (!isa<FunctionDecl>(ExternCPrev) || 14667 !Context.typesAreCompatible( 14668 cast<FunctionDecl>(ExternCPrev)->getType(), 14669 Context.getFunctionNoProtoType(Context.IntTy))) { 14670 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14671 << ExternCPrev << !getLangOpts().C99; 14672 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14673 return ExternCPrev; 14674 } 14675 } 14676 14677 // Extension in C99. Legal in C90, but warn about it. 14678 unsigned diag_id; 14679 if (II.getName().startswith("__builtin_")) 14680 diag_id = diag::warn_builtin_unknown; 14681 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14682 else if (getLangOpts().OpenCL) 14683 diag_id = diag::err_opencl_implicit_function_decl; 14684 else if (getLangOpts().C99) 14685 diag_id = diag::ext_implicit_function_decl; 14686 else 14687 diag_id = diag::warn_implicit_function_decl; 14688 Diag(Loc, diag_id) << &II; 14689 14690 // If we found a prior declaration of this function, don't bother building 14691 // another one. We've already pushed that one into scope, so there's nothing 14692 // more to do. 14693 if (ExternCPrev) 14694 return ExternCPrev; 14695 14696 // Because typo correction is expensive, only do it if the implicit 14697 // function declaration is going to be treated as an error. 14698 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14699 TypoCorrection Corrected; 14700 DeclFilterCCC<FunctionDecl> CCC{}; 14701 if (S && (Corrected = 14702 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14703 S, nullptr, CCC, CTK_NonError))) 14704 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14705 /*ErrorRecovery*/false); 14706 } 14707 14708 // Set a Declarator for the implicit definition: int foo(); 14709 const char *Dummy; 14710 AttributeFactory attrFactory; 14711 DeclSpec DS(attrFactory); 14712 unsigned DiagID; 14713 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14714 Context.getPrintingPolicy()); 14715 (void)Error; // Silence warning. 14716 assert(!Error && "Error setting up implicit decl!"); 14717 SourceLocation NoLoc; 14718 Declarator D(DS, DeclaratorContext::BlockContext); 14719 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14720 /*IsAmbiguous=*/false, 14721 /*LParenLoc=*/NoLoc, 14722 /*Params=*/nullptr, 14723 /*NumParams=*/0, 14724 /*EllipsisLoc=*/NoLoc, 14725 /*RParenLoc=*/NoLoc, 14726 /*RefQualifierIsLvalueRef=*/true, 14727 /*RefQualifierLoc=*/NoLoc, 14728 /*MutableLoc=*/NoLoc, EST_None, 14729 /*ESpecRange=*/SourceRange(), 14730 /*Exceptions=*/nullptr, 14731 /*ExceptionRanges=*/nullptr, 14732 /*NumExceptions=*/0, 14733 /*NoexceptExpr=*/nullptr, 14734 /*ExceptionSpecTokens=*/nullptr, 14735 /*DeclsInPrototype=*/None, Loc, 14736 Loc, D), 14737 std::move(DS.getAttributes()), SourceLocation()); 14738 D.SetIdentifier(&II, Loc); 14739 14740 // Insert this function into the enclosing block scope. 14741 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14742 FD->setImplicit(); 14743 14744 AddKnownFunctionAttributes(FD); 14745 14746 return FD; 14747 } 14748 14749 /// If this function is a C++ replaceable global allocation function 14750 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14751 /// adds any function attributes that we know a priori based on the standard. 14752 /// 14753 /// We need to check for duplicate attributes both here and where user-written 14754 /// attributes are applied to declarations. 14755 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14756 FunctionDecl *FD) { 14757 if (FD->isInvalidDecl()) 14758 return; 14759 14760 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14761 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14762 return; 14763 14764 Optional<unsigned> AlignmentParam; 14765 bool IsNothrow = false; 14766 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14767 return; 14768 14769 // C++2a [basic.stc.dynamic.allocation]p4: 14770 // An allocation function that has a non-throwing exception specification 14771 // indicates failure by returning a null pointer value. Any other allocation 14772 // function never returns a null pointer value and indicates failure only by 14773 // throwing an exception [...] 14774 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14775 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14776 14777 // C++2a [basic.stc.dynamic.allocation]p2: 14778 // An allocation function attempts to allocate the requested amount of 14779 // storage. [...] If the request succeeds, the value returned by a 14780 // replaceable allocation function is a [...] pointer value p0 different 14781 // from any previously returned value p1 [...] 14782 // 14783 // However, this particular information is being added in codegen, 14784 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14785 14786 // C++2a [basic.stc.dynamic.allocation]p2: 14787 // An allocation function attempts to allocate the requested amount of 14788 // storage. If it is successful, it returns the address of the start of a 14789 // block of storage whose length in bytes is at least as large as the 14790 // requested size. 14791 if (!FD->hasAttr<AllocSizeAttr>()) { 14792 FD->addAttr(AllocSizeAttr::CreateImplicit( 14793 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14794 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14795 } 14796 14797 // C++2a [basic.stc.dynamic.allocation]p3: 14798 // For an allocation function [...], the pointer returned on a successful 14799 // call shall represent the address of storage that is aligned as follows: 14800 // (3.1) If the allocation function takes an argument of type 14801 // std::align_val_t, the storage will have the alignment 14802 // specified by the value of this argument. 14803 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14804 FD->addAttr(AllocAlignAttr::CreateImplicit( 14805 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14806 } 14807 14808 // FIXME: 14809 // C++2a [basic.stc.dynamic.allocation]p3: 14810 // For an allocation function [...], the pointer returned on a successful 14811 // call shall represent the address of storage that is aligned as follows: 14812 // (3.2) Otherwise, if the allocation function is named operator new[], 14813 // the storage is aligned for any object that does not have 14814 // new-extended alignment ([basic.align]) and is no larger than the 14815 // requested size. 14816 // (3.3) Otherwise, the storage is aligned for any object that does not 14817 // have new-extended alignment and is of the requested size. 14818 } 14819 14820 /// Adds any function attributes that we know a priori based on 14821 /// the declaration of this function. 14822 /// 14823 /// These attributes can apply both to implicitly-declared builtins 14824 /// (like __builtin___printf_chk) or to library-declared functions 14825 /// like NSLog or printf. 14826 /// 14827 /// We need to check for duplicate attributes both here and where user-written 14828 /// attributes are applied to declarations. 14829 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14830 if (FD->isInvalidDecl()) 14831 return; 14832 14833 // If this is a built-in function, map its builtin attributes to 14834 // actual attributes. 14835 if (unsigned BuiltinID = FD->getBuiltinID()) { 14836 // Handle printf-formatting attributes. 14837 unsigned FormatIdx; 14838 bool HasVAListArg; 14839 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14840 if (!FD->hasAttr<FormatAttr>()) { 14841 const char *fmt = "printf"; 14842 unsigned int NumParams = FD->getNumParams(); 14843 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14844 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14845 fmt = "NSString"; 14846 FD->addAttr(FormatAttr::CreateImplicit(Context, 14847 &Context.Idents.get(fmt), 14848 FormatIdx+1, 14849 HasVAListArg ? 0 : FormatIdx+2, 14850 FD->getLocation())); 14851 } 14852 } 14853 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14854 HasVAListArg)) { 14855 if (!FD->hasAttr<FormatAttr>()) 14856 FD->addAttr(FormatAttr::CreateImplicit(Context, 14857 &Context.Idents.get("scanf"), 14858 FormatIdx+1, 14859 HasVAListArg ? 0 : FormatIdx+2, 14860 FD->getLocation())); 14861 } 14862 14863 // Handle automatically recognized callbacks. 14864 SmallVector<int, 4> Encoding; 14865 if (!FD->hasAttr<CallbackAttr>() && 14866 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14867 FD->addAttr(CallbackAttr::CreateImplicit( 14868 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14869 14870 // Mark const if we don't care about errno and that is the only thing 14871 // preventing the function from being const. This allows IRgen to use LLVM 14872 // intrinsics for such functions. 14873 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14874 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14875 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14876 14877 // We make "fma" on some platforms const because we know it does not set 14878 // errno in those environments even though it could set errno based on the 14879 // C standard. 14880 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14881 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14882 !FD->hasAttr<ConstAttr>()) { 14883 switch (BuiltinID) { 14884 case Builtin::BI__builtin_fma: 14885 case Builtin::BI__builtin_fmaf: 14886 case Builtin::BI__builtin_fmal: 14887 case Builtin::BIfma: 14888 case Builtin::BIfmaf: 14889 case Builtin::BIfmal: 14890 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14891 break; 14892 default: 14893 break; 14894 } 14895 } 14896 14897 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14898 !FD->hasAttr<ReturnsTwiceAttr>()) 14899 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14900 FD->getLocation())); 14901 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14902 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14903 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14904 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14905 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14906 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14907 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14908 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14909 // Add the appropriate attribute, depending on the CUDA compilation mode 14910 // and which target the builtin belongs to. For example, during host 14911 // compilation, aux builtins are __device__, while the rest are __host__. 14912 if (getLangOpts().CUDAIsDevice != 14913 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14914 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14915 else 14916 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14917 } 14918 } 14919 14920 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14921 14922 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14923 // throw, add an implicit nothrow attribute to any extern "C" function we come 14924 // across. 14925 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14926 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14927 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14928 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14929 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14930 } 14931 14932 IdentifierInfo *Name = FD->getIdentifier(); 14933 if (!Name) 14934 return; 14935 if ((!getLangOpts().CPlusPlus && 14936 FD->getDeclContext()->isTranslationUnit()) || 14937 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14938 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14939 LinkageSpecDecl::lang_c)) { 14940 // Okay: this could be a libc/libm/Objective-C function we know 14941 // about. 14942 } else 14943 return; 14944 14945 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14946 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14947 // target-specific builtins, perhaps? 14948 if (!FD->hasAttr<FormatAttr>()) 14949 FD->addAttr(FormatAttr::CreateImplicit(Context, 14950 &Context.Idents.get("printf"), 2, 14951 Name->isStr("vasprintf") ? 0 : 3, 14952 FD->getLocation())); 14953 } 14954 14955 if (Name->isStr("__CFStringMakeConstantString")) { 14956 // We already have a __builtin___CFStringMakeConstantString, 14957 // but builds that use -fno-constant-cfstrings don't go through that. 14958 if (!FD->hasAttr<FormatArgAttr>()) 14959 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14960 FD->getLocation())); 14961 } 14962 } 14963 14964 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14965 TypeSourceInfo *TInfo) { 14966 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14967 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14968 14969 if (!TInfo) { 14970 assert(D.isInvalidType() && "no declarator info for valid type"); 14971 TInfo = Context.getTrivialTypeSourceInfo(T); 14972 } 14973 14974 // Scope manipulation handled by caller. 14975 TypedefDecl *NewTD = 14976 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14977 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14978 14979 // Bail out immediately if we have an invalid declaration. 14980 if (D.isInvalidType()) { 14981 NewTD->setInvalidDecl(); 14982 return NewTD; 14983 } 14984 14985 if (D.getDeclSpec().isModulePrivateSpecified()) { 14986 if (CurContext->isFunctionOrMethod()) 14987 Diag(NewTD->getLocation(), diag::err_module_private_local) 14988 << 2 << NewTD 14989 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14990 << FixItHint::CreateRemoval( 14991 D.getDeclSpec().getModulePrivateSpecLoc()); 14992 else 14993 NewTD->setModulePrivate(); 14994 } 14995 14996 // C++ [dcl.typedef]p8: 14997 // If the typedef declaration defines an unnamed class (or 14998 // enum), the first typedef-name declared by the declaration 14999 // to be that class type (or enum type) is used to denote the 15000 // class type (or enum type) for linkage purposes only. 15001 // We need to check whether the type was declared in the declaration. 15002 switch (D.getDeclSpec().getTypeSpecType()) { 15003 case TST_enum: 15004 case TST_struct: 15005 case TST_interface: 15006 case TST_union: 15007 case TST_class: { 15008 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15009 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15010 break; 15011 } 15012 15013 default: 15014 break; 15015 } 15016 15017 return NewTD; 15018 } 15019 15020 /// Check that this is a valid underlying type for an enum declaration. 15021 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15022 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15023 QualType T = TI->getType(); 15024 15025 if (T->isDependentType()) 15026 return false; 15027 15028 // This doesn't use 'isIntegralType' despite the error message mentioning 15029 // integral type because isIntegralType would also allow enum types in C. 15030 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15031 if (BT->isInteger()) 15032 return false; 15033 15034 if (T->isExtIntType()) 15035 return false; 15036 15037 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15038 } 15039 15040 /// Check whether this is a valid redeclaration of a previous enumeration. 15041 /// \return true if the redeclaration was invalid. 15042 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15043 QualType EnumUnderlyingTy, bool IsFixed, 15044 const EnumDecl *Prev) { 15045 if (IsScoped != Prev->isScoped()) { 15046 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15047 << Prev->isScoped(); 15048 Diag(Prev->getLocation(), diag::note_previous_declaration); 15049 return true; 15050 } 15051 15052 if (IsFixed && Prev->isFixed()) { 15053 if (!EnumUnderlyingTy->isDependentType() && 15054 !Prev->getIntegerType()->isDependentType() && 15055 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15056 Prev->getIntegerType())) { 15057 // TODO: Highlight the underlying type of the redeclaration. 15058 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15059 << EnumUnderlyingTy << Prev->getIntegerType(); 15060 Diag(Prev->getLocation(), diag::note_previous_declaration) 15061 << Prev->getIntegerTypeRange(); 15062 return true; 15063 } 15064 } else if (IsFixed != Prev->isFixed()) { 15065 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15066 << Prev->isFixed(); 15067 Diag(Prev->getLocation(), diag::note_previous_declaration); 15068 return true; 15069 } 15070 15071 return false; 15072 } 15073 15074 /// Get diagnostic %select index for tag kind for 15075 /// redeclaration diagnostic message. 15076 /// WARNING: Indexes apply to particular diagnostics only! 15077 /// 15078 /// \returns diagnostic %select index. 15079 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15080 switch (Tag) { 15081 case TTK_Struct: return 0; 15082 case TTK_Interface: return 1; 15083 case TTK_Class: return 2; 15084 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15085 } 15086 } 15087 15088 /// Determine if tag kind is a class-key compatible with 15089 /// class for redeclaration (class, struct, or __interface). 15090 /// 15091 /// \returns true iff the tag kind is compatible. 15092 static bool isClassCompatTagKind(TagTypeKind Tag) 15093 { 15094 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15095 } 15096 15097 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15098 TagTypeKind TTK) { 15099 if (isa<TypedefDecl>(PrevDecl)) 15100 return NTK_Typedef; 15101 else if (isa<TypeAliasDecl>(PrevDecl)) 15102 return NTK_TypeAlias; 15103 else if (isa<ClassTemplateDecl>(PrevDecl)) 15104 return NTK_Template; 15105 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15106 return NTK_TypeAliasTemplate; 15107 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15108 return NTK_TemplateTemplateArgument; 15109 switch (TTK) { 15110 case TTK_Struct: 15111 case TTK_Interface: 15112 case TTK_Class: 15113 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15114 case TTK_Union: 15115 return NTK_NonUnion; 15116 case TTK_Enum: 15117 return NTK_NonEnum; 15118 } 15119 llvm_unreachable("invalid TTK"); 15120 } 15121 15122 /// Determine whether a tag with a given kind is acceptable 15123 /// as a redeclaration of the given tag declaration. 15124 /// 15125 /// \returns true if the new tag kind is acceptable, false otherwise. 15126 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15127 TagTypeKind NewTag, bool isDefinition, 15128 SourceLocation NewTagLoc, 15129 const IdentifierInfo *Name) { 15130 // C++ [dcl.type.elab]p3: 15131 // The class-key or enum keyword present in the 15132 // elaborated-type-specifier shall agree in kind with the 15133 // declaration to which the name in the elaborated-type-specifier 15134 // refers. This rule also applies to the form of 15135 // elaborated-type-specifier that declares a class-name or 15136 // friend class since it can be construed as referring to the 15137 // definition of the class. Thus, in any 15138 // elaborated-type-specifier, the enum keyword shall be used to 15139 // refer to an enumeration (7.2), the union class-key shall be 15140 // used to refer to a union (clause 9), and either the class or 15141 // struct class-key shall be used to refer to a class (clause 9) 15142 // declared using the class or struct class-key. 15143 TagTypeKind OldTag = Previous->getTagKind(); 15144 if (OldTag != NewTag && 15145 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15146 return false; 15147 15148 // Tags are compatible, but we might still want to warn on mismatched tags. 15149 // Non-class tags can't be mismatched at this point. 15150 if (!isClassCompatTagKind(NewTag)) 15151 return true; 15152 15153 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15154 // by our warning analysis. We don't want to warn about mismatches with (eg) 15155 // declarations in system headers that are designed to be specialized, but if 15156 // a user asks us to warn, we should warn if their code contains mismatched 15157 // declarations. 15158 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15159 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15160 Loc); 15161 }; 15162 if (IsIgnoredLoc(NewTagLoc)) 15163 return true; 15164 15165 auto IsIgnored = [&](const TagDecl *Tag) { 15166 return IsIgnoredLoc(Tag->getLocation()); 15167 }; 15168 while (IsIgnored(Previous)) { 15169 Previous = Previous->getPreviousDecl(); 15170 if (!Previous) 15171 return true; 15172 OldTag = Previous->getTagKind(); 15173 } 15174 15175 bool isTemplate = false; 15176 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15177 isTemplate = Record->getDescribedClassTemplate(); 15178 15179 if (inTemplateInstantiation()) { 15180 if (OldTag != NewTag) { 15181 // In a template instantiation, do not offer fix-its for tag mismatches 15182 // since they usually mess up the template instead of fixing the problem. 15183 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15184 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15185 << getRedeclDiagFromTagKind(OldTag); 15186 // FIXME: Note previous location? 15187 } 15188 return true; 15189 } 15190 15191 if (isDefinition) { 15192 // On definitions, check all previous tags and issue a fix-it for each 15193 // one that doesn't match the current tag. 15194 if (Previous->getDefinition()) { 15195 // Don't suggest fix-its for redefinitions. 15196 return true; 15197 } 15198 15199 bool previousMismatch = false; 15200 for (const TagDecl *I : Previous->redecls()) { 15201 if (I->getTagKind() != NewTag) { 15202 // Ignore previous declarations for which the warning was disabled. 15203 if (IsIgnored(I)) 15204 continue; 15205 15206 if (!previousMismatch) { 15207 previousMismatch = true; 15208 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15209 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15210 << getRedeclDiagFromTagKind(I->getTagKind()); 15211 } 15212 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15213 << getRedeclDiagFromTagKind(NewTag) 15214 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15215 TypeWithKeyword::getTagTypeKindName(NewTag)); 15216 } 15217 } 15218 return true; 15219 } 15220 15221 // Identify the prevailing tag kind: this is the kind of the definition (if 15222 // there is a non-ignored definition), or otherwise the kind of the prior 15223 // (non-ignored) declaration. 15224 const TagDecl *PrevDef = Previous->getDefinition(); 15225 if (PrevDef && IsIgnored(PrevDef)) 15226 PrevDef = nullptr; 15227 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15228 if (Redecl->getTagKind() != NewTag) { 15229 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15230 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15231 << getRedeclDiagFromTagKind(OldTag); 15232 Diag(Redecl->getLocation(), diag::note_previous_use); 15233 15234 // If there is a previous definition, suggest a fix-it. 15235 if (PrevDef) { 15236 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15237 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15238 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15239 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15240 } 15241 } 15242 15243 return true; 15244 } 15245 15246 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15247 /// from an outer enclosing namespace or file scope inside a friend declaration. 15248 /// This should provide the commented out code in the following snippet: 15249 /// namespace N { 15250 /// struct X; 15251 /// namespace M { 15252 /// struct Y { friend struct /*N::*/ X; }; 15253 /// } 15254 /// } 15255 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15256 SourceLocation NameLoc) { 15257 // While the decl is in a namespace, do repeated lookup of that name and see 15258 // if we get the same namespace back. If we do not, continue until 15259 // translation unit scope, at which point we have a fully qualified NNS. 15260 SmallVector<IdentifierInfo *, 4> Namespaces; 15261 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15262 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15263 // This tag should be declared in a namespace, which can only be enclosed by 15264 // other namespaces. Bail if there's an anonymous namespace in the chain. 15265 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15266 if (!Namespace || Namespace->isAnonymousNamespace()) 15267 return FixItHint(); 15268 IdentifierInfo *II = Namespace->getIdentifier(); 15269 Namespaces.push_back(II); 15270 NamedDecl *Lookup = SemaRef.LookupSingleName( 15271 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15272 if (Lookup == Namespace) 15273 break; 15274 } 15275 15276 // Once we have all the namespaces, reverse them to go outermost first, and 15277 // build an NNS. 15278 SmallString<64> Insertion; 15279 llvm::raw_svector_ostream OS(Insertion); 15280 if (DC->isTranslationUnit()) 15281 OS << "::"; 15282 std::reverse(Namespaces.begin(), Namespaces.end()); 15283 for (auto *II : Namespaces) 15284 OS << II->getName() << "::"; 15285 return FixItHint::CreateInsertion(NameLoc, Insertion); 15286 } 15287 15288 /// Determine whether a tag originally declared in context \p OldDC can 15289 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15290 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15291 /// using-declaration). 15292 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15293 DeclContext *NewDC) { 15294 OldDC = OldDC->getRedeclContext(); 15295 NewDC = NewDC->getRedeclContext(); 15296 15297 if (OldDC->Equals(NewDC)) 15298 return true; 15299 15300 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15301 // encloses the other). 15302 if (S.getLangOpts().MSVCCompat && 15303 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15304 return true; 15305 15306 return false; 15307 } 15308 15309 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15310 /// former case, Name will be non-null. In the later case, Name will be null. 15311 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15312 /// reference/declaration/definition of a tag. 15313 /// 15314 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15315 /// trailing-type-specifier) other than one in an alias-declaration. 15316 /// 15317 /// \param SkipBody If non-null, will be set to indicate if the caller should 15318 /// skip the definition of this tag and treat it as if it were a declaration. 15319 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15320 SourceLocation KWLoc, CXXScopeSpec &SS, 15321 IdentifierInfo *Name, SourceLocation NameLoc, 15322 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15323 SourceLocation ModulePrivateLoc, 15324 MultiTemplateParamsArg TemplateParameterLists, 15325 bool &OwnedDecl, bool &IsDependent, 15326 SourceLocation ScopedEnumKWLoc, 15327 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15328 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15329 SkipBodyInfo *SkipBody) { 15330 // If this is not a definition, it must have a name. 15331 IdentifierInfo *OrigName = Name; 15332 assert((Name != nullptr || TUK == TUK_Definition) && 15333 "Nameless record must be a definition!"); 15334 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15335 15336 OwnedDecl = false; 15337 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15338 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15339 15340 // FIXME: Check member specializations more carefully. 15341 bool isMemberSpecialization = false; 15342 bool Invalid = false; 15343 15344 // We only need to do this matching if we have template parameters 15345 // or a scope specifier, which also conveniently avoids this work 15346 // for non-C++ cases. 15347 if (TemplateParameterLists.size() > 0 || 15348 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15349 if (TemplateParameterList *TemplateParams = 15350 MatchTemplateParametersToScopeSpecifier( 15351 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15352 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15353 if (Kind == TTK_Enum) { 15354 Diag(KWLoc, diag::err_enum_template); 15355 return nullptr; 15356 } 15357 15358 if (TemplateParams->size() > 0) { 15359 // This is a declaration or definition of a class template (which may 15360 // be a member of another template). 15361 15362 if (Invalid) 15363 return nullptr; 15364 15365 OwnedDecl = false; 15366 DeclResult Result = CheckClassTemplate( 15367 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15368 AS, ModulePrivateLoc, 15369 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15370 TemplateParameterLists.data(), SkipBody); 15371 return Result.get(); 15372 } else { 15373 // The "template<>" header is extraneous. 15374 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15375 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15376 isMemberSpecialization = true; 15377 } 15378 } 15379 15380 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15381 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15382 return nullptr; 15383 } 15384 15385 // Figure out the underlying type if this a enum declaration. We need to do 15386 // this early, because it's needed to detect if this is an incompatible 15387 // redeclaration. 15388 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15389 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15390 15391 if (Kind == TTK_Enum) { 15392 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15393 // No underlying type explicitly specified, or we failed to parse the 15394 // type, default to int. 15395 EnumUnderlying = Context.IntTy.getTypePtr(); 15396 } else if (UnderlyingType.get()) { 15397 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15398 // integral type; any cv-qualification is ignored. 15399 TypeSourceInfo *TI = nullptr; 15400 GetTypeFromParser(UnderlyingType.get(), &TI); 15401 EnumUnderlying = TI; 15402 15403 if (CheckEnumUnderlyingType(TI)) 15404 // Recover by falling back to int. 15405 EnumUnderlying = Context.IntTy.getTypePtr(); 15406 15407 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15408 UPPC_FixedUnderlyingType)) 15409 EnumUnderlying = Context.IntTy.getTypePtr(); 15410 15411 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15412 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15413 // of 'int'. However, if this is an unfixed forward declaration, don't set 15414 // the underlying type unless the user enables -fms-compatibility. This 15415 // makes unfixed forward declared enums incomplete and is more conforming. 15416 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15417 EnumUnderlying = Context.IntTy.getTypePtr(); 15418 } 15419 } 15420 15421 DeclContext *SearchDC = CurContext; 15422 DeclContext *DC = CurContext; 15423 bool isStdBadAlloc = false; 15424 bool isStdAlignValT = false; 15425 15426 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15427 if (TUK == TUK_Friend || TUK == TUK_Reference) 15428 Redecl = NotForRedeclaration; 15429 15430 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15431 /// implemented asks for structural equivalence checking, the returned decl 15432 /// here is passed back to the parser, allowing the tag body to be parsed. 15433 auto createTagFromNewDecl = [&]() -> TagDecl * { 15434 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15435 // If there is an identifier, use the location of the identifier as the 15436 // location of the decl, otherwise use the location of the struct/union 15437 // keyword. 15438 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15439 TagDecl *New = nullptr; 15440 15441 if (Kind == TTK_Enum) { 15442 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15443 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15444 // If this is an undefined enum, bail. 15445 if (TUK != TUK_Definition && !Invalid) 15446 return nullptr; 15447 if (EnumUnderlying) { 15448 EnumDecl *ED = cast<EnumDecl>(New); 15449 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15450 ED->setIntegerTypeSourceInfo(TI); 15451 else 15452 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15453 ED->setPromotionType(ED->getIntegerType()); 15454 } 15455 } else { // struct/union 15456 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15457 nullptr); 15458 } 15459 15460 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15461 // Add alignment attributes if necessary; these attributes are checked 15462 // when the ASTContext lays out the structure. 15463 // 15464 // It is important for implementing the correct semantics that this 15465 // happen here (in ActOnTag). The #pragma pack stack is 15466 // maintained as a result of parser callbacks which can occur at 15467 // many points during the parsing of a struct declaration (because 15468 // the #pragma tokens are effectively skipped over during the 15469 // parsing of the struct). 15470 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15471 AddAlignmentAttributesForRecord(RD); 15472 AddMsStructLayoutForRecord(RD); 15473 } 15474 } 15475 New->setLexicalDeclContext(CurContext); 15476 return New; 15477 }; 15478 15479 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15480 if (Name && SS.isNotEmpty()) { 15481 // We have a nested-name tag ('struct foo::bar'). 15482 15483 // Check for invalid 'foo::'. 15484 if (SS.isInvalid()) { 15485 Name = nullptr; 15486 goto CreateNewDecl; 15487 } 15488 15489 // If this is a friend or a reference to a class in a dependent 15490 // context, don't try to make a decl for it. 15491 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15492 DC = computeDeclContext(SS, false); 15493 if (!DC) { 15494 IsDependent = true; 15495 return nullptr; 15496 } 15497 } else { 15498 DC = computeDeclContext(SS, true); 15499 if (!DC) { 15500 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15501 << SS.getRange(); 15502 return nullptr; 15503 } 15504 } 15505 15506 if (RequireCompleteDeclContext(SS, DC)) 15507 return nullptr; 15508 15509 SearchDC = DC; 15510 // Look-up name inside 'foo::'. 15511 LookupQualifiedName(Previous, DC); 15512 15513 if (Previous.isAmbiguous()) 15514 return nullptr; 15515 15516 if (Previous.empty()) { 15517 // Name lookup did not find anything. However, if the 15518 // nested-name-specifier refers to the current instantiation, 15519 // and that current instantiation has any dependent base 15520 // classes, we might find something at instantiation time: treat 15521 // this as a dependent elaborated-type-specifier. 15522 // But this only makes any sense for reference-like lookups. 15523 if (Previous.wasNotFoundInCurrentInstantiation() && 15524 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15525 IsDependent = true; 15526 return nullptr; 15527 } 15528 15529 // A tag 'foo::bar' must already exist. 15530 Diag(NameLoc, diag::err_not_tag_in_scope) 15531 << Kind << Name << DC << SS.getRange(); 15532 Name = nullptr; 15533 Invalid = true; 15534 goto CreateNewDecl; 15535 } 15536 } else if (Name) { 15537 // C++14 [class.mem]p14: 15538 // If T is the name of a class, then each of the following shall have a 15539 // name different from T: 15540 // -- every member of class T that is itself a type 15541 if (TUK != TUK_Reference && TUK != TUK_Friend && 15542 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15543 return nullptr; 15544 15545 // If this is a named struct, check to see if there was a previous forward 15546 // declaration or definition. 15547 // FIXME: We're looking into outer scopes here, even when we 15548 // shouldn't be. Doing so can result in ambiguities that we 15549 // shouldn't be diagnosing. 15550 LookupName(Previous, S); 15551 15552 // When declaring or defining a tag, ignore ambiguities introduced 15553 // by types using'ed into this scope. 15554 if (Previous.isAmbiguous() && 15555 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15556 LookupResult::Filter F = Previous.makeFilter(); 15557 while (F.hasNext()) { 15558 NamedDecl *ND = F.next(); 15559 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15560 SearchDC->getRedeclContext())) 15561 F.erase(); 15562 } 15563 F.done(); 15564 } 15565 15566 // C++11 [namespace.memdef]p3: 15567 // If the name in a friend declaration is neither qualified nor 15568 // a template-id and the declaration is a function or an 15569 // elaborated-type-specifier, the lookup to determine whether 15570 // the entity has been previously declared shall not consider 15571 // any scopes outside the innermost enclosing namespace. 15572 // 15573 // MSVC doesn't implement the above rule for types, so a friend tag 15574 // declaration may be a redeclaration of a type declared in an enclosing 15575 // scope. They do implement this rule for friend functions. 15576 // 15577 // Does it matter that this should be by scope instead of by 15578 // semantic context? 15579 if (!Previous.empty() && TUK == TUK_Friend) { 15580 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15581 LookupResult::Filter F = Previous.makeFilter(); 15582 bool FriendSawTagOutsideEnclosingNamespace = false; 15583 while (F.hasNext()) { 15584 NamedDecl *ND = F.next(); 15585 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15586 if (DC->isFileContext() && 15587 !EnclosingNS->Encloses(ND->getDeclContext())) { 15588 if (getLangOpts().MSVCCompat) 15589 FriendSawTagOutsideEnclosingNamespace = true; 15590 else 15591 F.erase(); 15592 } 15593 } 15594 F.done(); 15595 15596 // Diagnose this MSVC extension in the easy case where lookup would have 15597 // unambiguously found something outside the enclosing namespace. 15598 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15599 NamedDecl *ND = Previous.getFoundDecl(); 15600 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15601 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15602 } 15603 } 15604 15605 // Note: there used to be some attempt at recovery here. 15606 if (Previous.isAmbiguous()) 15607 return nullptr; 15608 15609 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15610 // FIXME: This makes sure that we ignore the contexts associated 15611 // with C structs, unions, and enums when looking for a matching 15612 // tag declaration or definition. See the similar lookup tweak 15613 // in Sema::LookupName; is there a better way to deal with this? 15614 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15615 SearchDC = SearchDC->getParent(); 15616 } 15617 } 15618 15619 if (Previous.isSingleResult() && 15620 Previous.getFoundDecl()->isTemplateParameter()) { 15621 // Maybe we will complain about the shadowed template parameter. 15622 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15623 // Just pretend that we didn't see the previous declaration. 15624 Previous.clear(); 15625 } 15626 15627 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15628 DC->Equals(getStdNamespace())) { 15629 if (Name->isStr("bad_alloc")) { 15630 // This is a declaration of or a reference to "std::bad_alloc". 15631 isStdBadAlloc = true; 15632 15633 // If std::bad_alloc has been implicitly declared (but made invisible to 15634 // name lookup), fill in this implicit declaration as the previous 15635 // declaration, so that the declarations get chained appropriately. 15636 if (Previous.empty() && StdBadAlloc) 15637 Previous.addDecl(getStdBadAlloc()); 15638 } else if (Name->isStr("align_val_t")) { 15639 isStdAlignValT = true; 15640 if (Previous.empty() && StdAlignValT) 15641 Previous.addDecl(getStdAlignValT()); 15642 } 15643 } 15644 15645 // If we didn't find a previous declaration, and this is a reference 15646 // (or friend reference), move to the correct scope. In C++, we 15647 // also need to do a redeclaration lookup there, just in case 15648 // there's a shadow friend decl. 15649 if (Name && Previous.empty() && 15650 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15651 if (Invalid) goto CreateNewDecl; 15652 assert(SS.isEmpty()); 15653 15654 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15655 // C++ [basic.scope.pdecl]p5: 15656 // -- for an elaborated-type-specifier of the form 15657 // 15658 // class-key identifier 15659 // 15660 // if the elaborated-type-specifier is used in the 15661 // decl-specifier-seq or parameter-declaration-clause of a 15662 // function defined in namespace scope, the identifier is 15663 // declared as a class-name in the namespace that contains 15664 // the declaration; otherwise, except as a friend 15665 // declaration, the identifier is declared in the smallest 15666 // non-class, non-function-prototype scope that contains the 15667 // declaration. 15668 // 15669 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15670 // C structs and unions. 15671 // 15672 // It is an error in C++ to declare (rather than define) an enum 15673 // type, including via an elaborated type specifier. We'll 15674 // diagnose that later; for now, declare the enum in the same 15675 // scope as we would have picked for any other tag type. 15676 // 15677 // GNU C also supports this behavior as part of its incomplete 15678 // enum types extension, while GNU C++ does not. 15679 // 15680 // Find the context where we'll be declaring the tag. 15681 // FIXME: We would like to maintain the current DeclContext as the 15682 // lexical context, 15683 SearchDC = getTagInjectionContext(SearchDC); 15684 15685 // Find the scope where we'll be declaring the tag. 15686 S = getTagInjectionScope(S, getLangOpts()); 15687 } else { 15688 assert(TUK == TUK_Friend); 15689 // C++ [namespace.memdef]p3: 15690 // If a friend declaration in a non-local class first declares a 15691 // class or function, the friend class or function is a member of 15692 // the innermost enclosing namespace. 15693 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15694 } 15695 15696 // In C++, we need to do a redeclaration lookup to properly 15697 // diagnose some problems. 15698 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15699 // hidden declaration so that we don't get ambiguity errors when using a 15700 // type declared by an elaborated-type-specifier. In C that is not correct 15701 // and we should instead merge compatible types found by lookup. 15702 if (getLangOpts().CPlusPlus) { 15703 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15704 LookupQualifiedName(Previous, SearchDC); 15705 } else { 15706 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15707 LookupName(Previous, S); 15708 } 15709 } 15710 15711 // If we have a known previous declaration to use, then use it. 15712 if (Previous.empty() && SkipBody && SkipBody->Previous) 15713 Previous.addDecl(SkipBody->Previous); 15714 15715 if (!Previous.empty()) { 15716 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15717 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15718 15719 // It's okay to have a tag decl in the same scope as a typedef 15720 // which hides a tag decl in the same scope. Finding this 15721 // insanity with a redeclaration lookup can only actually happen 15722 // in C++. 15723 // 15724 // This is also okay for elaborated-type-specifiers, which is 15725 // technically forbidden by the current standard but which is 15726 // okay according to the likely resolution of an open issue; 15727 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15728 if (getLangOpts().CPlusPlus) { 15729 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15730 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15731 TagDecl *Tag = TT->getDecl(); 15732 if (Tag->getDeclName() == Name && 15733 Tag->getDeclContext()->getRedeclContext() 15734 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15735 PrevDecl = Tag; 15736 Previous.clear(); 15737 Previous.addDecl(Tag); 15738 Previous.resolveKind(); 15739 } 15740 } 15741 } 15742 } 15743 15744 // If this is a redeclaration of a using shadow declaration, it must 15745 // declare a tag in the same context. In MSVC mode, we allow a 15746 // redefinition if either context is within the other. 15747 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15748 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15749 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15750 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15751 !(OldTag && isAcceptableTagRedeclContext( 15752 *this, OldTag->getDeclContext(), SearchDC))) { 15753 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15754 Diag(Shadow->getTargetDecl()->getLocation(), 15755 diag::note_using_decl_target); 15756 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15757 << 0; 15758 // Recover by ignoring the old declaration. 15759 Previous.clear(); 15760 goto CreateNewDecl; 15761 } 15762 } 15763 15764 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15765 // If this is a use of a previous tag, or if the tag is already declared 15766 // in the same scope (so that the definition/declaration completes or 15767 // rementions the tag), reuse the decl. 15768 if (TUK == TUK_Reference || TUK == TUK_Friend || 15769 isDeclInScope(DirectPrevDecl, SearchDC, S, 15770 SS.isNotEmpty() || isMemberSpecialization)) { 15771 // Make sure that this wasn't declared as an enum and now used as a 15772 // struct or something similar. 15773 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15774 TUK == TUK_Definition, KWLoc, 15775 Name)) { 15776 bool SafeToContinue 15777 = (PrevTagDecl->getTagKind() != TTK_Enum && 15778 Kind != TTK_Enum); 15779 if (SafeToContinue) 15780 Diag(KWLoc, diag::err_use_with_wrong_tag) 15781 << Name 15782 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15783 PrevTagDecl->getKindName()); 15784 else 15785 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15786 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15787 15788 if (SafeToContinue) 15789 Kind = PrevTagDecl->getTagKind(); 15790 else { 15791 // Recover by making this an anonymous redefinition. 15792 Name = nullptr; 15793 Previous.clear(); 15794 Invalid = true; 15795 } 15796 } 15797 15798 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15799 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15800 if (TUK == TUK_Reference || TUK == TUK_Friend) 15801 return PrevTagDecl; 15802 15803 QualType EnumUnderlyingTy; 15804 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15805 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15806 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15807 EnumUnderlyingTy = QualType(T, 0); 15808 15809 // All conflicts with previous declarations are recovered by 15810 // returning the previous declaration, unless this is a definition, 15811 // in which case we want the caller to bail out. 15812 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15813 ScopedEnum, EnumUnderlyingTy, 15814 IsFixed, PrevEnum)) 15815 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15816 } 15817 15818 // C++11 [class.mem]p1: 15819 // A member shall not be declared twice in the member-specification, 15820 // except that a nested class or member class template can be declared 15821 // and then later defined. 15822 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15823 S->isDeclScope(PrevDecl)) { 15824 Diag(NameLoc, diag::ext_member_redeclared); 15825 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15826 } 15827 15828 if (!Invalid) { 15829 // If this is a use, just return the declaration we found, unless 15830 // we have attributes. 15831 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15832 if (!Attrs.empty()) { 15833 // FIXME: Diagnose these attributes. For now, we create a new 15834 // declaration to hold them. 15835 } else if (TUK == TUK_Reference && 15836 (PrevTagDecl->getFriendObjectKind() == 15837 Decl::FOK_Undeclared || 15838 PrevDecl->getOwningModule() != getCurrentModule()) && 15839 SS.isEmpty()) { 15840 // This declaration is a reference to an existing entity, but 15841 // has different visibility from that entity: it either makes 15842 // a friend visible or it makes a type visible in a new module. 15843 // In either case, create a new declaration. We only do this if 15844 // the declaration would have meant the same thing if no prior 15845 // declaration were found, that is, if it was found in the same 15846 // scope where we would have injected a declaration. 15847 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15848 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15849 return PrevTagDecl; 15850 // This is in the injected scope, create a new declaration in 15851 // that scope. 15852 S = getTagInjectionScope(S, getLangOpts()); 15853 } else { 15854 return PrevTagDecl; 15855 } 15856 } 15857 15858 // Diagnose attempts to redefine a tag. 15859 if (TUK == TUK_Definition) { 15860 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15861 // If we're defining a specialization and the previous definition 15862 // is from an implicit instantiation, don't emit an error 15863 // here; we'll catch this in the general case below. 15864 bool IsExplicitSpecializationAfterInstantiation = false; 15865 if (isMemberSpecialization) { 15866 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15867 IsExplicitSpecializationAfterInstantiation = 15868 RD->getTemplateSpecializationKind() != 15869 TSK_ExplicitSpecialization; 15870 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15871 IsExplicitSpecializationAfterInstantiation = 15872 ED->getTemplateSpecializationKind() != 15873 TSK_ExplicitSpecialization; 15874 } 15875 15876 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15877 // not keep more that one definition around (merge them). However, 15878 // ensure the decl passes the structural compatibility check in 15879 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15880 NamedDecl *Hidden = nullptr; 15881 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15882 // There is a definition of this tag, but it is not visible. We 15883 // explicitly make use of C++'s one definition rule here, and 15884 // assume that this definition is identical to the hidden one 15885 // we already have. Make the existing definition visible and 15886 // use it in place of this one. 15887 if (!getLangOpts().CPlusPlus) { 15888 // Postpone making the old definition visible until after we 15889 // complete parsing the new one and do the structural 15890 // comparison. 15891 SkipBody->CheckSameAsPrevious = true; 15892 SkipBody->New = createTagFromNewDecl(); 15893 SkipBody->Previous = Def; 15894 return Def; 15895 } else { 15896 SkipBody->ShouldSkip = true; 15897 SkipBody->Previous = Def; 15898 makeMergedDefinitionVisible(Hidden); 15899 // Carry on and handle it like a normal definition. We'll 15900 // skip starting the definitiion later. 15901 } 15902 } else if (!IsExplicitSpecializationAfterInstantiation) { 15903 // A redeclaration in function prototype scope in C isn't 15904 // visible elsewhere, so merely issue a warning. 15905 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15906 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15907 else 15908 Diag(NameLoc, diag::err_redefinition) << Name; 15909 notePreviousDefinition(Def, 15910 NameLoc.isValid() ? NameLoc : KWLoc); 15911 // If this is a redefinition, recover by making this 15912 // struct be anonymous, which will make any later 15913 // references get the previous definition. 15914 Name = nullptr; 15915 Previous.clear(); 15916 Invalid = true; 15917 } 15918 } else { 15919 // If the type is currently being defined, complain 15920 // about a nested redefinition. 15921 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15922 if (TD->isBeingDefined()) { 15923 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15924 Diag(PrevTagDecl->getLocation(), 15925 diag::note_previous_definition); 15926 Name = nullptr; 15927 Previous.clear(); 15928 Invalid = true; 15929 } 15930 } 15931 15932 // Okay, this is definition of a previously declared or referenced 15933 // tag. We're going to create a new Decl for it. 15934 } 15935 15936 // Okay, we're going to make a redeclaration. If this is some kind 15937 // of reference, make sure we build the redeclaration in the same DC 15938 // as the original, and ignore the current access specifier. 15939 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15940 SearchDC = PrevTagDecl->getDeclContext(); 15941 AS = AS_none; 15942 } 15943 } 15944 // If we get here we have (another) forward declaration or we 15945 // have a definition. Just create a new decl. 15946 15947 } else { 15948 // If we get here, this is a definition of a new tag type in a nested 15949 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15950 // new decl/type. We set PrevDecl to NULL so that the entities 15951 // have distinct types. 15952 Previous.clear(); 15953 } 15954 // If we get here, we're going to create a new Decl. If PrevDecl 15955 // is non-NULL, it's a definition of the tag declared by 15956 // PrevDecl. If it's NULL, we have a new definition. 15957 15958 // Otherwise, PrevDecl is not a tag, but was found with tag 15959 // lookup. This is only actually possible in C++, where a few 15960 // things like templates still live in the tag namespace. 15961 } else { 15962 // Use a better diagnostic if an elaborated-type-specifier 15963 // found the wrong kind of type on the first 15964 // (non-redeclaration) lookup. 15965 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15966 !Previous.isForRedeclaration()) { 15967 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15968 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15969 << Kind; 15970 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15971 Invalid = true; 15972 15973 // Otherwise, only diagnose if the declaration is in scope. 15974 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15975 SS.isNotEmpty() || isMemberSpecialization)) { 15976 // do nothing 15977 15978 // Diagnose implicit declarations introduced by elaborated types. 15979 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15980 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15981 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15982 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15983 Invalid = true; 15984 15985 // Otherwise it's a declaration. Call out a particularly common 15986 // case here. 15987 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15988 unsigned Kind = 0; 15989 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15990 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15991 << Name << Kind << TND->getUnderlyingType(); 15992 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15993 Invalid = true; 15994 15995 // Otherwise, diagnose. 15996 } else { 15997 // The tag name clashes with something else in the target scope, 15998 // issue an error and recover by making this tag be anonymous. 15999 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16000 notePreviousDefinition(PrevDecl, NameLoc); 16001 Name = nullptr; 16002 Invalid = true; 16003 } 16004 16005 // The existing declaration isn't relevant to us; we're in a 16006 // new scope, so clear out the previous declaration. 16007 Previous.clear(); 16008 } 16009 } 16010 16011 CreateNewDecl: 16012 16013 TagDecl *PrevDecl = nullptr; 16014 if (Previous.isSingleResult()) 16015 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16016 16017 // If there is an identifier, use the location of the identifier as the 16018 // location of the decl, otherwise use the location of the struct/union 16019 // keyword. 16020 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16021 16022 // Otherwise, create a new declaration. If there is a previous 16023 // declaration of the same entity, the two will be linked via 16024 // PrevDecl. 16025 TagDecl *New; 16026 16027 if (Kind == TTK_Enum) { 16028 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16029 // enum X { A, B, C } D; D should chain to X. 16030 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16031 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16032 ScopedEnumUsesClassTag, IsFixed); 16033 16034 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16035 StdAlignValT = cast<EnumDecl>(New); 16036 16037 // If this is an undefined enum, warn. 16038 if (TUK != TUK_Definition && !Invalid) { 16039 TagDecl *Def; 16040 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16041 // C++0x: 7.2p2: opaque-enum-declaration. 16042 // Conflicts are diagnosed above. Do nothing. 16043 } 16044 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16045 Diag(Loc, diag::ext_forward_ref_enum_def) 16046 << New; 16047 Diag(Def->getLocation(), diag::note_previous_definition); 16048 } else { 16049 unsigned DiagID = diag::ext_forward_ref_enum; 16050 if (getLangOpts().MSVCCompat) 16051 DiagID = diag::ext_ms_forward_ref_enum; 16052 else if (getLangOpts().CPlusPlus) 16053 DiagID = diag::err_forward_ref_enum; 16054 Diag(Loc, DiagID); 16055 } 16056 } 16057 16058 if (EnumUnderlying) { 16059 EnumDecl *ED = cast<EnumDecl>(New); 16060 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16061 ED->setIntegerTypeSourceInfo(TI); 16062 else 16063 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16064 ED->setPromotionType(ED->getIntegerType()); 16065 assert(ED->isComplete() && "enum with type should be complete"); 16066 } 16067 } else { 16068 // struct/union/class 16069 16070 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16071 // struct X { int A; } D; D should chain to X. 16072 if (getLangOpts().CPlusPlus) { 16073 // FIXME: Look for a way to use RecordDecl for simple structs. 16074 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16075 cast_or_null<CXXRecordDecl>(PrevDecl)); 16076 16077 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16078 StdBadAlloc = cast<CXXRecordDecl>(New); 16079 } else 16080 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16081 cast_or_null<RecordDecl>(PrevDecl)); 16082 } 16083 16084 // C++11 [dcl.type]p3: 16085 // A type-specifier-seq shall not define a class or enumeration [...]. 16086 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16087 TUK == TUK_Definition) { 16088 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16089 << Context.getTagDeclType(New); 16090 Invalid = true; 16091 } 16092 16093 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16094 DC->getDeclKind() == Decl::Enum) { 16095 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16096 << Context.getTagDeclType(New); 16097 Invalid = true; 16098 } 16099 16100 // Maybe add qualifier info. 16101 if (SS.isNotEmpty()) { 16102 if (SS.isSet()) { 16103 // If this is either a declaration or a definition, check the 16104 // nested-name-specifier against the current context. 16105 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16106 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16107 isMemberSpecialization)) 16108 Invalid = true; 16109 16110 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16111 if (TemplateParameterLists.size() > 0) { 16112 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16113 } 16114 } 16115 else 16116 Invalid = true; 16117 } 16118 16119 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16120 // Add alignment attributes if necessary; these attributes are checked when 16121 // the ASTContext lays out the structure. 16122 // 16123 // It is important for implementing the correct semantics that this 16124 // happen here (in ActOnTag). The #pragma pack stack is 16125 // maintained as a result of parser callbacks which can occur at 16126 // many points during the parsing of a struct declaration (because 16127 // the #pragma tokens are effectively skipped over during the 16128 // parsing of the struct). 16129 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16130 AddAlignmentAttributesForRecord(RD); 16131 AddMsStructLayoutForRecord(RD); 16132 } 16133 } 16134 16135 if (ModulePrivateLoc.isValid()) { 16136 if (isMemberSpecialization) 16137 Diag(New->getLocation(), diag::err_module_private_specialization) 16138 << 2 16139 << FixItHint::CreateRemoval(ModulePrivateLoc); 16140 // __module_private__ does not apply to local classes. However, we only 16141 // diagnose this as an error when the declaration specifiers are 16142 // freestanding. Here, we just ignore the __module_private__. 16143 else if (!SearchDC->isFunctionOrMethod()) 16144 New->setModulePrivate(); 16145 } 16146 16147 // If this is a specialization of a member class (of a class template), 16148 // check the specialization. 16149 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16150 Invalid = true; 16151 16152 // If we're declaring or defining a tag in function prototype scope in C, 16153 // note that this type can only be used within the function and add it to 16154 // the list of decls to inject into the function definition scope. 16155 if ((Name || Kind == TTK_Enum) && 16156 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16157 if (getLangOpts().CPlusPlus) { 16158 // C++ [dcl.fct]p6: 16159 // Types shall not be defined in return or parameter types. 16160 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16161 Diag(Loc, diag::err_type_defined_in_param_type) 16162 << Name; 16163 Invalid = true; 16164 } 16165 } else if (!PrevDecl) { 16166 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16167 } 16168 } 16169 16170 if (Invalid) 16171 New->setInvalidDecl(); 16172 16173 // Set the lexical context. If the tag has a C++ scope specifier, the 16174 // lexical context will be different from the semantic context. 16175 New->setLexicalDeclContext(CurContext); 16176 16177 // Mark this as a friend decl if applicable. 16178 // In Microsoft mode, a friend declaration also acts as a forward 16179 // declaration so we always pass true to setObjectOfFriendDecl to make 16180 // the tag name visible. 16181 if (TUK == TUK_Friend) 16182 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16183 16184 // Set the access specifier. 16185 if (!Invalid && SearchDC->isRecord()) 16186 SetMemberAccessSpecifier(New, PrevDecl, AS); 16187 16188 if (PrevDecl) 16189 CheckRedeclarationModuleOwnership(New, PrevDecl); 16190 16191 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16192 New->startDefinition(); 16193 16194 ProcessDeclAttributeList(S, New, Attrs); 16195 AddPragmaAttributes(S, New); 16196 16197 // If this has an identifier, add it to the scope stack. 16198 if (TUK == TUK_Friend) { 16199 // We might be replacing an existing declaration in the lookup tables; 16200 // if so, borrow its access specifier. 16201 if (PrevDecl) 16202 New->setAccess(PrevDecl->getAccess()); 16203 16204 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16205 DC->makeDeclVisibleInContext(New); 16206 if (Name) // can be null along some error paths 16207 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16208 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16209 } else if (Name) { 16210 S = getNonFieldDeclScope(S); 16211 PushOnScopeChains(New, S, true); 16212 } else { 16213 CurContext->addDecl(New); 16214 } 16215 16216 // If this is the C FILE type, notify the AST context. 16217 if (IdentifierInfo *II = New->getIdentifier()) 16218 if (!New->isInvalidDecl() && 16219 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16220 II->isStr("FILE")) 16221 Context.setFILEDecl(New); 16222 16223 if (PrevDecl) 16224 mergeDeclAttributes(New, PrevDecl); 16225 16226 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16227 inferGslOwnerPointerAttribute(CXXRD); 16228 16229 // If there's a #pragma GCC visibility in scope, set the visibility of this 16230 // record. 16231 AddPushedVisibilityAttribute(New); 16232 16233 if (isMemberSpecialization && !New->isInvalidDecl()) 16234 CompleteMemberSpecialization(New, Previous); 16235 16236 OwnedDecl = true; 16237 // In C++, don't return an invalid declaration. We can't recover well from 16238 // the cases where we make the type anonymous. 16239 if (Invalid && getLangOpts().CPlusPlus) { 16240 if (New->isBeingDefined()) 16241 if (auto RD = dyn_cast<RecordDecl>(New)) 16242 RD->completeDefinition(); 16243 return nullptr; 16244 } else if (SkipBody && SkipBody->ShouldSkip) { 16245 return SkipBody->Previous; 16246 } else { 16247 return New; 16248 } 16249 } 16250 16251 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16252 AdjustDeclIfTemplate(TagD); 16253 TagDecl *Tag = cast<TagDecl>(TagD); 16254 16255 // Enter the tag context. 16256 PushDeclContext(S, Tag); 16257 16258 ActOnDocumentableDecl(TagD); 16259 16260 // If there's a #pragma GCC visibility in scope, set the visibility of this 16261 // record. 16262 AddPushedVisibilityAttribute(Tag); 16263 } 16264 16265 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16266 SkipBodyInfo &SkipBody) { 16267 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16268 return false; 16269 16270 // Make the previous decl visible. 16271 makeMergedDefinitionVisible(SkipBody.Previous); 16272 return true; 16273 } 16274 16275 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16276 assert(isa<ObjCContainerDecl>(IDecl) && 16277 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16278 DeclContext *OCD = cast<DeclContext>(IDecl); 16279 assert(OCD->getLexicalParent() == CurContext && 16280 "The next DeclContext should be lexically contained in the current one."); 16281 CurContext = OCD; 16282 return IDecl; 16283 } 16284 16285 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16286 SourceLocation FinalLoc, 16287 bool IsFinalSpelledSealed, 16288 SourceLocation LBraceLoc) { 16289 AdjustDeclIfTemplate(TagD); 16290 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16291 16292 FieldCollector->StartClass(); 16293 16294 if (!Record->getIdentifier()) 16295 return; 16296 16297 if (FinalLoc.isValid()) 16298 Record->addAttr(FinalAttr::Create( 16299 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16300 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16301 16302 // C++ [class]p2: 16303 // [...] The class-name is also inserted into the scope of the 16304 // class itself; this is known as the injected-class-name. For 16305 // purposes of access checking, the injected-class-name is treated 16306 // as if it were a public member name. 16307 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16308 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16309 Record->getLocation(), Record->getIdentifier(), 16310 /*PrevDecl=*/nullptr, 16311 /*DelayTypeCreation=*/true); 16312 Context.getTypeDeclType(InjectedClassName, Record); 16313 InjectedClassName->setImplicit(); 16314 InjectedClassName->setAccess(AS_public); 16315 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16316 InjectedClassName->setDescribedClassTemplate(Template); 16317 PushOnScopeChains(InjectedClassName, S); 16318 assert(InjectedClassName->isInjectedClassName() && 16319 "Broken injected-class-name"); 16320 } 16321 16322 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16323 SourceRange BraceRange) { 16324 AdjustDeclIfTemplate(TagD); 16325 TagDecl *Tag = cast<TagDecl>(TagD); 16326 Tag->setBraceRange(BraceRange); 16327 16328 // Make sure we "complete" the definition even it is invalid. 16329 if (Tag->isBeingDefined()) { 16330 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16331 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16332 RD->completeDefinition(); 16333 } 16334 16335 if (isa<CXXRecordDecl>(Tag)) { 16336 FieldCollector->FinishClass(); 16337 } 16338 16339 // Exit this scope of this tag's definition. 16340 PopDeclContext(); 16341 16342 if (getCurLexicalContext()->isObjCContainer() && 16343 Tag->getDeclContext()->isFileContext()) 16344 Tag->setTopLevelDeclInObjCContainer(); 16345 16346 // Notify the consumer that we've defined a tag. 16347 if (!Tag->isInvalidDecl()) 16348 Consumer.HandleTagDeclDefinition(Tag); 16349 } 16350 16351 void Sema::ActOnObjCContainerFinishDefinition() { 16352 // Exit this scope of this interface definition. 16353 PopDeclContext(); 16354 } 16355 16356 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16357 assert(DC == CurContext && "Mismatch of container contexts"); 16358 OriginalLexicalContext = DC; 16359 ActOnObjCContainerFinishDefinition(); 16360 } 16361 16362 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16363 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16364 OriginalLexicalContext = nullptr; 16365 } 16366 16367 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16368 AdjustDeclIfTemplate(TagD); 16369 TagDecl *Tag = cast<TagDecl>(TagD); 16370 Tag->setInvalidDecl(); 16371 16372 // Make sure we "complete" the definition even it is invalid. 16373 if (Tag->isBeingDefined()) { 16374 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16375 RD->completeDefinition(); 16376 } 16377 16378 // We're undoing ActOnTagStartDefinition here, not 16379 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16380 // the FieldCollector. 16381 16382 PopDeclContext(); 16383 } 16384 16385 // Note that FieldName may be null for anonymous bitfields. 16386 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16387 IdentifierInfo *FieldName, 16388 QualType FieldTy, bool IsMsStruct, 16389 Expr *BitWidth, bool *ZeroWidth) { 16390 assert(BitWidth); 16391 if (BitWidth->containsErrors()) 16392 return ExprError(); 16393 16394 // Default to true; that shouldn't confuse checks for emptiness 16395 if (ZeroWidth) 16396 *ZeroWidth = true; 16397 16398 // C99 6.7.2.1p4 - verify the field type. 16399 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16400 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16401 // Handle incomplete and sizeless types with a specific error. 16402 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16403 diag::err_field_incomplete_or_sizeless)) 16404 return ExprError(); 16405 if (FieldName) 16406 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16407 << FieldName << FieldTy << BitWidth->getSourceRange(); 16408 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16409 << FieldTy << BitWidth->getSourceRange(); 16410 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16411 UPPC_BitFieldWidth)) 16412 return ExprError(); 16413 16414 // If the bit-width is type- or value-dependent, don't try to check 16415 // it now. 16416 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16417 return BitWidth; 16418 16419 llvm::APSInt Value; 16420 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16421 if (ICE.isInvalid()) 16422 return ICE; 16423 BitWidth = ICE.get(); 16424 16425 if (Value != 0 && ZeroWidth) 16426 *ZeroWidth = false; 16427 16428 // Zero-width bitfield is ok for anonymous field. 16429 if (Value == 0 && FieldName) 16430 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16431 16432 if (Value.isSigned() && Value.isNegative()) { 16433 if (FieldName) 16434 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16435 << FieldName << Value.toString(10); 16436 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16437 << Value.toString(10); 16438 } 16439 16440 if (!FieldTy->isDependentType()) { 16441 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16442 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16443 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16444 16445 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16446 // ABI. 16447 bool CStdConstraintViolation = 16448 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16449 bool MSBitfieldViolation = 16450 Value.ugt(TypeStorageSize) && 16451 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16452 if (CStdConstraintViolation || MSBitfieldViolation) { 16453 unsigned DiagWidth = 16454 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16455 if (FieldName) 16456 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16457 << FieldName << (unsigned)Value.getZExtValue() 16458 << !CStdConstraintViolation << DiagWidth; 16459 16460 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16461 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16462 << DiagWidth; 16463 } 16464 16465 // Warn on types where the user might conceivably expect to get all 16466 // specified bits as value bits: that's all integral types other than 16467 // 'bool'. 16468 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16469 if (FieldName) 16470 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16471 << FieldName << (unsigned)Value.getZExtValue() 16472 << (unsigned)TypeWidth; 16473 else 16474 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16475 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16476 } 16477 } 16478 16479 return BitWidth; 16480 } 16481 16482 /// ActOnField - Each field of a C struct/union is passed into this in order 16483 /// to create a FieldDecl object for it. 16484 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16485 Declarator &D, Expr *BitfieldWidth) { 16486 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16487 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16488 /*InitStyle=*/ICIS_NoInit, AS_public); 16489 return Res; 16490 } 16491 16492 /// HandleField - Analyze a field of a C struct or a C++ data member. 16493 /// 16494 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16495 SourceLocation DeclStart, 16496 Declarator &D, Expr *BitWidth, 16497 InClassInitStyle InitStyle, 16498 AccessSpecifier AS) { 16499 if (D.isDecompositionDeclarator()) { 16500 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16501 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16502 << Decomp.getSourceRange(); 16503 return nullptr; 16504 } 16505 16506 IdentifierInfo *II = D.getIdentifier(); 16507 SourceLocation Loc = DeclStart; 16508 if (II) Loc = D.getIdentifierLoc(); 16509 16510 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16511 QualType T = TInfo->getType(); 16512 if (getLangOpts().CPlusPlus) { 16513 CheckExtraCXXDefaultArguments(D); 16514 16515 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16516 UPPC_DataMemberType)) { 16517 D.setInvalidType(); 16518 T = Context.IntTy; 16519 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16520 } 16521 } 16522 16523 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16524 16525 if (D.getDeclSpec().isInlineSpecified()) 16526 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16527 << getLangOpts().CPlusPlus17; 16528 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16529 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16530 diag::err_invalid_thread) 16531 << DeclSpec::getSpecifierName(TSCS); 16532 16533 // Check to see if this name was declared as a member previously 16534 NamedDecl *PrevDecl = nullptr; 16535 LookupResult Previous(*this, II, Loc, LookupMemberName, 16536 ForVisibleRedeclaration); 16537 LookupName(Previous, S); 16538 switch (Previous.getResultKind()) { 16539 case LookupResult::Found: 16540 case LookupResult::FoundUnresolvedValue: 16541 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16542 break; 16543 16544 case LookupResult::FoundOverloaded: 16545 PrevDecl = Previous.getRepresentativeDecl(); 16546 break; 16547 16548 case LookupResult::NotFound: 16549 case LookupResult::NotFoundInCurrentInstantiation: 16550 case LookupResult::Ambiguous: 16551 break; 16552 } 16553 Previous.suppressDiagnostics(); 16554 16555 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16556 // Maybe we will complain about the shadowed template parameter. 16557 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16558 // Just pretend that we didn't see the previous declaration. 16559 PrevDecl = nullptr; 16560 } 16561 16562 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16563 PrevDecl = nullptr; 16564 16565 bool Mutable 16566 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16567 SourceLocation TSSL = D.getBeginLoc(); 16568 FieldDecl *NewFD 16569 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16570 TSSL, AS, PrevDecl, &D); 16571 16572 if (NewFD->isInvalidDecl()) 16573 Record->setInvalidDecl(); 16574 16575 if (D.getDeclSpec().isModulePrivateSpecified()) 16576 NewFD->setModulePrivate(); 16577 16578 if (NewFD->isInvalidDecl() && PrevDecl) { 16579 // Don't introduce NewFD into scope; there's already something 16580 // with the same name in the same scope. 16581 } else if (II) { 16582 PushOnScopeChains(NewFD, S); 16583 } else 16584 Record->addDecl(NewFD); 16585 16586 return NewFD; 16587 } 16588 16589 /// Build a new FieldDecl and check its well-formedness. 16590 /// 16591 /// This routine builds a new FieldDecl given the fields name, type, 16592 /// record, etc. \p PrevDecl should refer to any previous declaration 16593 /// with the same name and in the same scope as the field to be 16594 /// created. 16595 /// 16596 /// \returns a new FieldDecl. 16597 /// 16598 /// \todo The Declarator argument is a hack. It will be removed once 16599 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16600 TypeSourceInfo *TInfo, 16601 RecordDecl *Record, SourceLocation Loc, 16602 bool Mutable, Expr *BitWidth, 16603 InClassInitStyle InitStyle, 16604 SourceLocation TSSL, 16605 AccessSpecifier AS, NamedDecl *PrevDecl, 16606 Declarator *D) { 16607 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16608 bool InvalidDecl = false; 16609 if (D) InvalidDecl = D->isInvalidType(); 16610 16611 // If we receive a broken type, recover by assuming 'int' and 16612 // marking this declaration as invalid. 16613 if (T.isNull() || T->containsErrors()) { 16614 InvalidDecl = true; 16615 T = Context.IntTy; 16616 } 16617 16618 QualType EltTy = Context.getBaseElementType(T); 16619 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16620 if (RequireCompleteSizedType(Loc, EltTy, 16621 diag::err_field_incomplete_or_sizeless)) { 16622 // Fields of incomplete type force their record to be invalid. 16623 Record->setInvalidDecl(); 16624 InvalidDecl = true; 16625 } else { 16626 NamedDecl *Def; 16627 EltTy->isIncompleteType(&Def); 16628 if (Def && Def->isInvalidDecl()) { 16629 Record->setInvalidDecl(); 16630 InvalidDecl = true; 16631 } 16632 } 16633 } 16634 16635 // TR 18037 does not allow fields to be declared with address space 16636 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16637 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16638 Diag(Loc, diag::err_field_with_address_space); 16639 Record->setInvalidDecl(); 16640 InvalidDecl = true; 16641 } 16642 16643 if (LangOpts.OpenCL) { 16644 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16645 // used as structure or union field: image, sampler, event or block types. 16646 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16647 T->isBlockPointerType()) { 16648 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16649 Record->setInvalidDecl(); 16650 InvalidDecl = true; 16651 } 16652 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16653 if (BitWidth) { 16654 Diag(Loc, diag::err_opencl_bitfields); 16655 InvalidDecl = true; 16656 } 16657 } 16658 16659 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16660 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16661 T.hasQualifiers()) { 16662 InvalidDecl = true; 16663 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16664 } 16665 16666 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16667 // than a variably modified type. 16668 if (!InvalidDecl && T->isVariablyModifiedType()) { 16669 bool SizeIsNegative; 16670 llvm::APSInt Oversized; 16671 16672 TypeSourceInfo *FixedTInfo = 16673 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16674 SizeIsNegative, 16675 Oversized); 16676 if (FixedTInfo) { 16677 Diag(Loc, diag::warn_illegal_constant_array_size); 16678 TInfo = FixedTInfo; 16679 T = FixedTInfo->getType(); 16680 } else { 16681 if (SizeIsNegative) 16682 Diag(Loc, diag::err_typecheck_negative_array_size); 16683 else if (Oversized.getBoolValue()) 16684 Diag(Loc, diag::err_array_too_large) 16685 << Oversized.toString(10); 16686 else 16687 Diag(Loc, diag::err_typecheck_field_variable_size); 16688 InvalidDecl = true; 16689 } 16690 } 16691 16692 // Fields can not have abstract class types 16693 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16694 diag::err_abstract_type_in_decl, 16695 AbstractFieldType)) 16696 InvalidDecl = true; 16697 16698 bool ZeroWidth = false; 16699 if (InvalidDecl) 16700 BitWidth = nullptr; 16701 // If this is declared as a bit-field, check the bit-field. 16702 if (BitWidth) { 16703 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16704 &ZeroWidth).get(); 16705 if (!BitWidth) { 16706 InvalidDecl = true; 16707 BitWidth = nullptr; 16708 ZeroWidth = false; 16709 } 16710 16711 // Only data members can have in-class initializers. 16712 if (BitWidth && !II && InitStyle) { 16713 Diag(Loc, diag::err_anon_bitfield_init); 16714 InvalidDecl = true; 16715 BitWidth = nullptr; 16716 ZeroWidth = false; 16717 } 16718 } 16719 16720 // Check that 'mutable' is consistent with the type of the declaration. 16721 if (!InvalidDecl && Mutable) { 16722 unsigned DiagID = 0; 16723 if (T->isReferenceType()) 16724 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16725 : diag::err_mutable_reference; 16726 else if (T.isConstQualified()) 16727 DiagID = diag::err_mutable_const; 16728 16729 if (DiagID) { 16730 SourceLocation ErrLoc = Loc; 16731 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16732 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16733 Diag(ErrLoc, DiagID); 16734 if (DiagID != diag::ext_mutable_reference) { 16735 Mutable = false; 16736 InvalidDecl = true; 16737 } 16738 } 16739 } 16740 16741 // C++11 [class.union]p8 (DR1460): 16742 // At most one variant member of a union may have a 16743 // brace-or-equal-initializer. 16744 if (InitStyle != ICIS_NoInit) 16745 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16746 16747 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16748 BitWidth, Mutable, InitStyle); 16749 if (InvalidDecl) 16750 NewFD->setInvalidDecl(); 16751 16752 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16753 Diag(Loc, diag::err_duplicate_member) << II; 16754 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16755 NewFD->setInvalidDecl(); 16756 } 16757 16758 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16759 if (Record->isUnion()) { 16760 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16761 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16762 if (RDecl->getDefinition()) { 16763 // C++ [class.union]p1: An object of a class with a non-trivial 16764 // constructor, a non-trivial copy constructor, a non-trivial 16765 // destructor, or a non-trivial copy assignment operator 16766 // cannot be a member of a union, nor can an array of such 16767 // objects. 16768 if (CheckNontrivialField(NewFD)) 16769 NewFD->setInvalidDecl(); 16770 } 16771 } 16772 16773 // C++ [class.union]p1: If a union contains a member of reference type, 16774 // the program is ill-formed, except when compiling with MSVC extensions 16775 // enabled. 16776 if (EltTy->isReferenceType()) { 16777 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16778 diag::ext_union_member_of_reference_type : 16779 diag::err_union_member_of_reference_type) 16780 << NewFD->getDeclName() << EltTy; 16781 if (!getLangOpts().MicrosoftExt) 16782 NewFD->setInvalidDecl(); 16783 } 16784 } 16785 } 16786 16787 // FIXME: We need to pass in the attributes given an AST 16788 // representation, not a parser representation. 16789 if (D) { 16790 // FIXME: The current scope is almost... but not entirely... correct here. 16791 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16792 16793 if (NewFD->hasAttrs()) 16794 CheckAlignasUnderalignment(NewFD); 16795 } 16796 16797 // In auto-retain/release, infer strong retension for fields of 16798 // retainable type. 16799 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16800 NewFD->setInvalidDecl(); 16801 16802 if (T.isObjCGCWeak()) 16803 Diag(Loc, diag::warn_attribute_weak_on_field); 16804 16805 NewFD->setAccess(AS); 16806 return NewFD; 16807 } 16808 16809 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16810 assert(FD); 16811 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16812 16813 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16814 return false; 16815 16816 QualType EltTy = Context.getBaseElementType(FD->getType()); 16817 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16818 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16819 if (RDecl->getDefinition()) { 16820 // We check for copy constructors before constructors 16821 // because otherwise we'll never get complaints about 16822 // copy constructors. 16823 16824 CXXSpecialMember member = CXXInvalid; 16825 // We're required to check for any non-trivial constructors. Since the 16826 // implicit default constructor is suppressed if there are any 16827 // user-declared constructors, we just need to check that there is a 16828 // trivial default constructor and a trivial copy constructor. (We don't 16829 // worry about move constructors here, since this is a C++98 check.) 16830 if (RDecl->hasNonTrivialCopyConstructor()) 16831 member = CXXCopyConstructor; 16832 else if (!RDecl->hasTrivialDefaultConstructor()) 16833 member = CXXDefaultConstructor; 16834 else if (RDecl->hasNonTrivialCopyAssignment()) 16835 member = CXXCopyAssignment; 16836 else if (RDecl->hasNonTrivialDestructor()) 16837 member = CXXDestructor; 16838 16839 if (member != CXXInvalid) { 16840 if (!getLangOpts().CPlusPlus11 && 16841 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16842 // Objective-C++ ARC: it is an error to have a non-trivial field of 16843 // a union. However, system headers in Objective-C programs 16844 // occasionally have Objective-C lifetime objects within unions, 16845 // and rather than cause the program to fail, we make those 16846 // members unavailable. 16847 SourceLocation Loc = FD->getLocation(); 16848 if (getSourceManager().isInSystemHeader(Loc)) { 16849 if (!FD->hasAttr<UnavailableAttr>()) 16850 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16851 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16852 return false; 16853 } 16854 } 16855 16856 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16857 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16858 diag::err_illegal_union_or_anon_struct_member) 16859 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16860 DiagnoseNontrivial(RDecl, member); 16861 return !getLangOpts().CPlusPlus11; 16862 } 16863 } 16864 } 16865 16866 return false; 16867 } 16868 16869 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16870 /// AST enum value. 16871 static ObjCIvarDecl::AccessControl 16872 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16873 switch (ivarVisibility) { 16874 default: llvm_unreachable("Unknown visitibility kind"); 16875 case tok::objc_private: return ObjCIvarDecl::Private; 16876 case tok::objc_public: return ObjCIvarDecl::Public; 16877 case tok::objc_protected: return ObjCIvarDecl::Protected; 16878 case tok::objc_package: return ObjCIvarDecl::Package; 16879 } 16880 } 16881 16882 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16883 /// in order to create an IvarDecl object for it. 16884 Decl *Sema::ActOnIvar(Scope *S, 16885 SourceLocation DeclStart, 16886 Declarator &D, Expr *BitfieldWidth, 16887 tok::ObjCKeywordKind Visibility) { 16888 16889 IdentifierInfo *II = D.getIdentifier(); 16890 Expr *BitWidth = (Expr*)BitfieldWidth; 16891 SourceLocation Loc = DeclStart; 16892 if (II) Loc = D.getIdentifierLoc(); 16893 16894 // FIXME: Unnamed fields can be handled in various different ways, for 16895 // example, unnamed unions inject all members into the struct namespace! 16896 16897 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16898 QualType T = TInfo->getType(); 16899 16900 if (BitWidth) { 16901 // 6.7.2.1p3, 6.7.2.1p4 16902 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16903 if (!BitWidth) 16904 D.setInvalidType(); 16905 } else { 16906 // Not a bitfield. 16907 16908 // validate II. 16909 16910 } 16911 if (T->isReferenceType()) { 16912 Diag(Loc, diag::err_ivar_reference_type); 16913 D.setInvalidType(); 16914 } 16915 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16916 // than a variably modified type. 16917 else if (T->isVariablyModifiedType()) { 16918 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16919 D.setInvalidType(); 16920 } 16921 16922 // Get the visibility (access control) for this ivar. 16923 ObjCIvarDecl::AccessControl ac = 16924 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16925 : ObjCIvarDecl::None; 16926 // Must set ivar's DeclContext to its enclosing interface. 16927 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16928 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16929 return nullptr; 16930 ObjCContainerDecl *EnclosingContext; 16931 if (ObjCImplementationDecl *IMPDecl = 16932 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16933 if (LangOpts.ObjCRuntime.isFragile()) { 16934 // Case of ivar declared in an implementation. Context is that of its class. 16935 EnclosingContext = IMPDecl->getClassInterface(); 16936 assert(EnclosingContext && "Implementation has no class interface!"); 16937 } 16938 else 16939 EnclosingContext = EnclosingDecl; 16940 } else { 16941 if (ObjCCategoryDecl *CDecl = 16942 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16943 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16944 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16945 return nullptr; 16946 } 16947 } 16948 EnclosingContext = EnclosingDecl; 16949 } 16950 16951 // Construct the decl. 16952 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16953 DeclStart, Loc, II, T, 16954 TInfo, ac, (Expr *)BitfieldWidth); 16955 16956 if (II) { 16957 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16958 ForVisibleRedeclaration); 16959 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16960 && !isa<TagDecl>(PrevDecl)) { 16961 Diag(Loc, diag::err_duplicate_member) << II; 16962 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16963 NewID->setInvalidDecl(); 16964 } 16965 } 16966 16967 // Process attributes attached to the ivar. 16968 ProcessDeclAttributes(S, NewID, D); 16969 16970 if (D.isInvalidType()) 16971 NewID->setInvalidDecl(); 16972 16973 // In ARC, infer 'retaining' for ivars of retainable type. 16974 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16975 NewID->setInvalidDecl(); 16976 16977 if (D.getDeclSpec().isModulePrivateSpecified()) 16978 NewID->setModulePrivate(); 16979 16980 if (II) { 16981 // FIXME: When interfaces are DeclContexts, we'll need to add 16982 // these to the interface. 16983 S->AddDecl(NewID); 16984 IdResolver.AddDecl(NewID); 16985 } 16986 16987 if (LangOpts.ObjCRuntime.isNonFragile() && 16988 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16989 Diag(Loc, diag::warn_ivars_in_interface); 16990 16991 return NewID; 16992 } 16993 16994 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16995 /// class and class extensions. For every class \@interface and class 16996 /// extension \@interface, if the last ivar is a bitfield of any type, 16997 /// then add an implicit `char :0` ivar to the end of that interface. 16998 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16999 SmallVectorImpl<Decl *> &AllIvarDecls) { 17000 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17001 return; 17002 17003 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17004 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17005 17006 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17007 return; 17008 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17009 if (!ID) { 17010 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17011 if (!CD->IsClassExtension()) 17012 return; 17013 } 17014 // No need to add this to end of @implementation. 17015 else 17016 return; 17017 } 17018 // All conditions are met. Add a new bitfield to the tail end of ivars. 17019 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17020 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17021 17022 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17023 DeclLoc, DeclLoc, nullptr, 17024 Context.CharTy, 17025 Context.getTrivialTypeSourceInfo(Context.CharTy, 17026 DeclLoc), 17027 ObjCIvarDecl::Private, BW, 17028 true); 17029 AllIvarDecls.push_back(Ivar); 17030 } 17031 17032 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17033 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17034 SourceLocation RBrac, 17035 const ParsedAttributesView &Attrs) { 17036 assert(EnclosingDecl && "missing record or interface decl"); 17037 17038 // If this is an Objective-C @implementation or category and we have 17039 // new fields here we should reset the layout of the interface since 17040 // it will now change. 17041 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17042 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17043 switch (DC->getKind()) { 17044 default: break; 17045 case Decl::ObjCCategory: 17046 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17047 break; 17048 case Decl::ObjCImplementation: 17049 Context. 17050 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17051 break; 17052 } 17053 } 17054 17055 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17056 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17057 17058 // Start counting up the number of named members; make sure to include 17059 // members of anonymous structs and unions in the total. 17060 unsigned NumNamedMembers = 0; 17061 if (Record) { 17062 for (const auto *I : Record->decls()) { 17063 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17064 if (IFD->getDeclName()) 17065 ++NumNamedMembers; 17066 } 17067 } 17068 17069 // Verify that all the fields are okay. 17070 SmallVector<FieldDecl*, 32> RecFields; 17071 17072 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17073 i != end; ++i) { 17074 FieldDecl *FD = cast<FieldDecl>(*i); 17075 17076 // Get the type for the field. 17077 const Type *FDTy = FD->getType().getTypePtr(); 17078 17079 if (!FD->isAnonymousStructOrUnion()) { 17080 // Remember all fields written by the user. 17081 RecFields.push_back(FD); 17082 } 17083 17084 // If the field is already invalid for some reason, don't emit more 17085 // diagnostics about it. 17086 if (FD->isInvalidDecl()) { 17087 EnclosingDecl->setInvalidDecl(); 17088 continue; 17089 } 17090 17091 // C99 6.7.2.1p2: 17092 // A structure or union shall not contain a member with 17093 // incomplete or function type (hence, a structure shall not 17094 // contain an instance of itself, but may contain a pointer to 17095 // an instance of itself), except that the last member of a 17096 // structure with more than one named member may have incomplete 17097 // array type; such a structure (and any union containing, 17098 // possibly recursively, a member that is such a structure) 17099 // shall not be a member of a structure or an element of an 17100 // array. 17101 bool IsLastField = (i + 1 == Fields.end()); 17102 if (FDTy->isFunctionType()) { 17103 // Field declared as a function. 17104 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17105 << FD->getDeclName(); 17106 FD->setInvalidDecl(); 17107 EnclosingDecl->setInvalidDecl(); 17108 continue; 17109 } else if (FDTy->isIncompleteArrayType() && 17110 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17111 if (Record) { 17112 // Flexible array member. 17113 // Microsoft and g++ is more permissive regarding flexible array. 17114 // It will accept flexible array in union and also 17115 // as the sole element of a struct/class. 17116 unsigned DiagID = 0; 17117 if (!Record->isUnion() && !IsLastField) { 17118 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17119 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17120 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17121 FD->setInvalidDecl(); 17122 EnclosingDecl->setInvalidDecl(); 17123 continue; 17124 } else if (Record->isUnion()) 17125 DiagID = getLangOpts().MicrosoftExt 17126 ? diag::ext_flexible_array_union_ms 17127 : getLangOpts().CPlusPlus 17128 ? diag::ext_flexible_array_union_gnu 17129 : diag::err_flexible_array_union; 17130 else if (NumNamedMembers < 1) 17131 DiagID = getLangOpts().MicrosoftExt 17132 ? diag::ext_flexible_array_empty_aggregate_ms 17133 : getLangOpts().CPlusPlus 17134 ? diag::ext_flexible_array_empty_aggregate_gnu 17135 : diag::err_flexible_array_empty_aggregate; 17136 17137 if (DiagID) 17138 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17139 << Record->getTagKind(); 17140 // While the layout of types that contain virtual bases is not specified 17141 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17142 // virtual bases after the derived members. This would make a flexible 17143 // array member declared at the end of an object not adjacent to the end 17144 // of the type. 17145 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17146 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17147 << FD->getDeclName() << Record->getTagKind(); 17148 if (!getLangOpts().C99) 17149 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17150 << FD->getDeclName() << Record->getTagKind(); 17151 17152 // If the element type has a non-trivial destructor, we would not 17153 // implicitly destroy the elements, so disallow it for now. 17154 // 17155 // FIXME: GCC allows this. We should probably either implicitly delete 17156 // the destructor of the containing class, or just allow this. 17157 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17158 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17159 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17160 << FD->getDeclName() << FD->getType(); 17161 FD->setInvalidDecl(); 17162 EnclosingDecl->setInvalidDecl(); 17163 continue; 17164 } 17165 // Okay, we have a legal flexible array member at the end of the struct. 17166 Record->setHasFlexibleArrayMember(true); 17167 } else { 17168 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17169 // unless they are followed by another ivar. That check is done 17170 // elsewhere, after synthesized ivars are known. 17171 } 17172 } else if (!FDTy->isDependentType() && 17173 RequireCompleteSizedType( 17174 FD->getLocation(), FD->getType(), 17175 diag::err_field_incomplete_or_sizeless)) { 17176 // Incomplete type 17177 FD->setInvalidDecl(); 17178 EnclosingDecl->setInvalidDecl(); 17179 continue; 17180 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17181 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17182 // A type which contains a flexible array member is considered to be a 17183 // flexible array member. 17184 Record->setHasFlexibleArrayMember(true); 17185 if (!Record->isUnion()) { 17186 // If this is a struct/class and this is not the last element, reject 17187 // it. Note that GCC supports variable sized arrays in the middle of 17188 // structures. 17189 if (!IsLastField) 17190 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17191 << FD->getDeclName() << FD->getType(); 17192 else { 17193 // We support flexible arrays at the end of structs in 17194 // other structs as an extension. 17195 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17196 << FD->getDeclName(); 17197 } 17198 } 17199 } 17200 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17201 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17202 diag::err_abstract_type_in_decl, 17203 AbstractIvarType)) { 17204 // Ivars can not have abstract class types 17205 FD->setInvalidDecl(); 17206 } 17207 if (Record && FDTTy->getDecl()->hasObjectMember()) 17208 Record->setHasObjectMember(true); 17209 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17210 Record->setHasVolatileMember(true); 17211 } else if (FDTy->isObjCObjectType()) { 17212 /// A field cannot be an Objective-c object 17213 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17214 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17215 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17216 FD->setType(T); 17217 } else if (Record && Record->isUnion() && 17218 FD->getType().hasNonTrivialObjCLifetime() && 17219 getSourceManager().isInSystemHeader(FD->getLocation()) && 17220 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17221 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17222 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17223 // For backward compatibility, fields of C unions declared in system 17224 // headers that have non-trivial ObjC ownership qualifications are marked 17225 // as unavailable unless the qualifier is explicit and __strong. This can 17226 // break ABI compatibility between programs compiled with ARC and MRR, but 17227 // is a better option than rejecting programs using those unions under 17228 // ARC. 17229 FD->addAttr(UnavailableAttr::CreateImplicit( 17230 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17231 FD->getLocation())); 17232 } else if (getLangOpts().ObjC && 17233 getLangOpts().getGC() != LangOptions::NonGC && Record && 17234 !Record->hasObjectMember()) { 17235 if (FD->getType()->isObjCObjectPointerType() || 17236 FD->getType().isObjCGCStrong()) 17237 Record->setHasObjectMember(true); 17238 else if (Context.getAsArrayType(FD->getType())) { 17239 QualType BaseType = Context.getBaseElementType(FD->getType()); 17240 if (BaseType->isRecordType() && 17241 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17242 Record->setHasObjectMember(true); 17243 else if (BaseType->isObjCObjectPointerType() || 17244 BaseType.isObjCGCStrong()) 17245 Record->setHasObjectMember(true); 17246 } 17247 } 17248 17249 if (Record && !getLangOpts().CPlusPlus && 17250 !shouldIgnoreForRecordTriviality(FD)) { 17251 QualType FT = FD->getType(); 17252 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17253 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17254 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17255 Record->isUnion()) 17256 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17257 } 17258 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17259 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17260 Record->setNonTrivialToPrimitiveCopy(true); 17261 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17262 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17263 } 17264 if (FT.isDestructedType()) { 17265 Record->setNonTrivialToPrimitiveDestroy(true); 17266 Record->setParamDestroyedInCallee(true); 17267 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17268 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17269 } 17270 17271 if (const auto *RT = FT->getAs<RecordType>()) { 17272 if (RT->getDecl()->getArgPassingRestrictions() == 17273 RecordDecl::APK_CanNeverPassInRegs) 17274 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17275 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17276 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17277 } 17278 17279 if (Record && FD->getType().isVolatileQualified()) 17280 Record->setHasVolatileMember(true); 17281 // Keep track of the number of named members. 17282 if (FD->getIdentifier()) 17283 ++NumNamedMembers; 17284 } 17285 17286 // Okay, we successfully defined 'Record'. 17287 if (Record) { 17288 bool Completed = false; 17289 if (CXXRecord) { 17290 if (!CXXRecord->isInvalidDecl()) { 17291 // Set access bits correctly on the directly-declared conversions. 17292 for (CXXRecordDecl::conversion_iterator 17293 I = CXXRecord->conversion_begin(), 17294 E = CXXRecord->conversion_end(); I != E; ++I) 17295 I.setAccess((*I)->getAccess()); 17296 } 17297 17298 // Add any implicitly-declared members to this class. 17299 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17300 17301 if (!CXXRecord->isDependentType()) { 17302 if (!CXXRecord->isInvalidDecl()) { 17303 // If we have virtual base classes, we may end up finding multiple 17304 // final overriders for a given virtual function. Check for this 17305 // problem now. 17306 if (CXXRecord->getNumVBases()) { 17307 CXXFinalOverriderMap FinalOverriders; 17308 CXXRecord->getFinalOverriders(FinalOverriders); 17309 17310 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17311 MEnd = FinalOverriders.end(); 17312 M != MEnd; ++M) { 17313 for (OverridingMethods::iterator SO = M->second.begin(), 17314 SOEnd = M->second.end(); 17315 SO != SOEnd; ++SO) { 17316 assert(SO->second.size() > 0 && 17317 "Virtual function without overriding functions?"); 17318 if (SO->second.size() == 1) 17319 continue; 17320 17321 // C++ [class.virtual]p2: 17322 // In a derived class, if a virtual member function of a base 17323 // class subobject has more than one final overrider the 17324 // program is ill-formed. 17325 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17326 << (const NamedDecl *)M->first << Record; 17327 Diag(M->first->getLocation(), 17328 diag::note_overridden_virtual_function); 17329 for (OverridingMethods::overriding_iterator 17330 OM = SO->second.begin(), 17331 OMEnd = SO->second.end(); 17332 OM != OMEnd; ++OM) 17333 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17334 << (const NamedDecl *)M->first << OM->Method->getParent(); 17335 17336 Record->setInvalidDecl(); 17337 } 17338 } 17339 CXXRecord->completeDefinition(&FinalOverriders); 17340 Completed = true; 17341 } 17342 } 17343 } 17344 } 17345 17346 if (!Completed) 17347 Record->completeDefinition(); 17348 17349 // Handle attributes before checking the layout. 17350 ProcessDeclAttributeList(S, Record, Attrs); 17351 17352 // We may have deferred checking for a deleted destructor. Check now. 17353 if (CXXRecord) { 17354 auto *Dtor = CXXRecord->getDestructor(); 17355 if (Dtor && Dtor->isImplicit() && 17356 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17357 CXXRecord->setImplicitDestructorIsDeleted(); 17358 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17359 } 17360 } 17361 17362 if (Record->hasAttrs()) { 17363 CheckAlignasUnderalignment(Record); 17364 17365 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17366 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17367 IA->getRange(), IA->getBestCase(), 17368 IA->getInheritanceModel()); 17369 } 17370 17371 // Check if the structure/union declaration is a type that can have zero 17372 // size in C. For C this is a language extension, for C++ it may cause 17373 // compatibility problems. 17374 bool CheckForZeroSize; 17375 if (!getLangOpts().CPlusPlus) { 17376 CheckForZeroSize = true; 17377 } else { 17378 // For C++ filter out types that cannot be referenced in C code. 17379 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17380 CheckForZeroSize = 17381 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17382 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17383 CXXRecord->isCLike(); 17384 } 17385 if (CheckForZeroSize) { 17386 bool ZeroSize = true; 17387 bool IsEmpty = true; 17388 unsigned NonBitFields = 0; 17389 for (RecordDecl::field_iterator I = Record->field_begin(), 17390 E = Record->field_end(); 17391 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17392 IsEmpty = false; 17393 if (I->isUnnamedBitfield()) { 17394 if (!I->isZeroLengthBitField(Context)) 17395 ZeroSize = false; 17396 } else { 17397 ++NonBitFields; 17398 QualType FieldType = I->getType(); 17399 if (FieldType->isIncompleteType() || 17400 !Context.getTypeSizeInChars(FieldType).isZero()) 17401 ZeroSize = false; 17402 } 17403 } 17404 17405 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17406 // allowed in C++, but warn if its declaration is inside 17407 // extern "C" block. 17408 if (ZeroSize) { 17409 Diag(RecLoc, getLangOpts().CPlusPlus ? 17410 diag::warn_zero_size_struct_union_in_extern_c : 17411 diag::warn_zero_size_struct_union_compat) 17412 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17413 } 17414 17415 // Structs without named members are extension in C (C99 6.7.2.1p7), 17416 // but are accepted by GCC. 17417 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17418 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17419 diag::ext_no_named_members_in_struct_union) 17420 << Record->isUnion(); 17421 } 17422 } 17423 } else { 17424 ObjCIvarDecl **ClsFields = 17425 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17426 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17427 ID->setEndOfDefinitionLoc(RBrac); 17428 // Add ivar's to class's DeclContext. 17429 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17430 ClsFields[i]->setLexicalDeclContext(ID); 17431 ID->addDecl(ClsFields[i]); 17432 } 17433 // Must enforce the rule that ivars in the base classes may not be 17434 // duplicates. 17435 if (ID->getSuperClass()) 17436 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17437 } else if (ObjCImplementationDecl *IMPDecl = 17438 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17439 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17440 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17441 // Ivar declared in @implementation never belongs to the implementation. 17442 // Only it is in implementation's lexical context. 17443 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17444 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17445 IMPDecl->setIvarLBraceLoc(LBrac); 17446 IMPDecl->setIvarRBraceLoc(RBrac); 17447 } else if (ObjCCategoryDecl *CDecl = 17448 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17449 // case of ivars in class extension; all other cases have been 17450 // reported as errors elsewhere. 17451 // FIXME. Class extension does not have a LocEnd field. 17452 // CDecl->setLocEnd(RBrac); 17453 // Add ivar's to class extension's DeclContext. 17454 // Diagnose redeclaration of private ivars. 17455 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17456 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17457 if (IDecl) { 17458 if (const ObjCIvarDecl *ClsIvar = 17459 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17460 Diag(ClsFields[i]->getLocation(), 17461 diag::err_duplicate_ivar_declaration); 17462 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17463 continue; 17464 } 17465 for (const auto *Ext : IDecl->known_extensions()) { 17466 if (const ObjCIvarDecl *ClsExtIvar 17467 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17468 Diag(ClsFields[i]->getLocation(), 17469 diag::err_duplicate_ivar_declaration); 17470 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17471 continue; 17472 } 17473 } 17474 } 17475 ClsFields[i]->setLexicalDeclContext(CDecl); 17476 CDecl->addDecl(ClsFields[i]); 17477 } 17478 CDecl->setIvarLBraceLoc(LBrac); 17479 CDecl->setIvarRBraceLoc(RBrac); 17480 } 17481 } 17482 } 17483 17484 /// Determine whether the given integral value is representable within 17485 /// the given type T. 17486 static bool isRepresentableIntegerValue(ASTContext &Context, 17487 llvm::APSInt &Value, 17488 QualType T) { 17489 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17490 "Integral type required!"); 17491 unsigned BitWidth = Context.getIntWidth(T); 17492 17493 if (Value.isUnsigned() || Value.isNonNegative()) { 17494 if (T->isSignedIntegerOrEnumerationType()) 17495 --BitWidth; 17496 return Value.getActiveBits() <= BitWidth; 17497 } 17498 return Value.getMinSignedBits() <= BitWidth; 17499 } 17500 17501 // Given an integral type, return the next larger integral type 17502 // (or a NULL type of no such type exists). 17503 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17504 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17505 // enum checking below. 17506 assert((T->isIntegralType(Context) || 17507 T->isEnumeralType()) && "Integral type required!"); 17508 const unsigned NumTypes = 4; 17509 QualType SignedIntegralTypes[NumTypes] = { 17510 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17511 }; 17512 QualType UnsignedIntegralTypes[NumTypes] = { 17513 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17514 Context.UnsignedLongLongTy 17515 }; 17516 17517 unsigned BitWidth = Context.getTypeSize(T); 17518 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17519 : UnsignedIntegralTypes; 17520 for (unsigned I = 0; I != NumTypes; ++I) 17521 if (Context.getTypeSize(Types[I]) > BitWidth) 17522 return Types[I]; 17523 17524 return QualType(); 17525 } 17526 17527 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17528 EnumConstantDecl *LastEnumConst, 17529 SourceLocation IdLoc, 17530 IdentifierInfo *Id, 17531 Expr *Val) { 17532 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17533 llvm::APSInt EnumVal(IntWidth); 17534 QualType EltTy; 17535 17536 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17537 Val = nullptr; 17538 17539 if (Val) 17540 Val = DefaultLvalueConversion(Val).get(); 17541 17542 if (Val) { 17543 if (Enum->isDependentType() || Val->isTypeDependent()) 17544 EltTy = Context.DependentTy; 17545 else { 17546 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17547 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17548 // constant-expression in the enumerator-definition shall be a converted 17549 // constant expression of the underlying type. 17550 EltTy = Enum->getIntegerType(); 17551 ExprResult Converted = 17552 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17553 CCEK_Enumerator); 17554 if (Converted.isInvalid()) 17555 Val = nullptr; 17556 else 17557 Val = Converted.get(); 17558 } else if (!Val->isValueDependent() && 17559 !(Val = VerifyIntegerConstantExpression(Val, 17560 &EnumVal).get())) { 17561 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17562 } else { 17563 if (Enum->isComplete()) { 17564 EltTy = Enum->getIntegerType(); 17565 17566 // In Obj-C and Microsoft mode, require the enumeration value to be 17567 // representable in the underlying type of the enumeration. In C++11, 17568 // we perform a non-narrowing conversion as part of converted constant 17569 // expression checking. 17570 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17571 if (Context.getTargetInfo() 17572 .getTriple() 17573 .isWindowsMSVCEnvironment()) { 17574 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17575 } else { 17576 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17577 } 17578 } 17579 17580 // Cast to the underlying type. 17581 Val = ImpCastExprToType(Val, EltTy, 17582 EltTy->isBooleanType() ? CK_IntegralToBoolean 17583 : CK_IntegralCast) 17584 .get(); 17585 } else if (getLangOpts().CPlusPlus) { 17586 // C++11 [dcl.enum]p5: 17587 // If the underlying type is not fixed, the type of each enumerator 17588 // is the type of its initializing value: 17589 // - If an initializer is specified for an enumerator, the 17590 // initializing value has the same type as the expression. 17591 EltTy = Val->getType(); 17592 } else { 17593 // C99 6.7.2.2p2: 17594 // The expression that defines the value of an enumeration constant 17595 // shall be an integer constant expression that has a value 17596 // representable as an int. 17597 17598 // Complain if the value is not representable in an int. 17599 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17600 Diag(IdLoc, diag::ext_enum_value_not_int) 17601 << EnumVal.toString(10) << Val->getSourceRange() 17602 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17603 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17604 // Force the type of the expression to 'int'. 17605 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17606 } 17607 EltTy = Val->getType(); 17608 } 17609 } 17610 } 17611 } 17612 17613 if (!Val) { 17614 if (Enum->isDependentType()) 17615 EltTy = Context.DependentTy; 17616 else if (!LastEnumConst) { 17617 // C++0x [dcl.enum]p5: 17618 // If the underlying type is not fixed, the type of each enumerator 17619 // is the type of its initializing value: 17620 // - If no initializer is specified for the first enumerator, the 17621 // initializing value has an unspecified integral type. 17622 // 17623 // GCC uses 'int' for its unspecified integral type, as does 17624 // C99 6.7.2.2p3. 17625 if (Enum->isFixed()) { 17626 EltTy = Enum->getIntegerType(); 17627 } 17628 else { 17629 EltTy = Context.IntTy; 17630 } 17631 } else { 17632 // Assign the last value + 1. 17633 EnumVal = LastEnumConst->getInitVal(); 17634 ++EnumVal; 17635 EltTy = LastEnumConst->getType(); 17636 17637 // Check for overflow on increment. 17638 if (EnumVal < LastEnumConst->getInitVal()) { 17639 // C++0x [dcl.enum]p5: 17640 // If the underlying type is not fixed, the type of each enumerator 17641 // is the type of its initializing value: 17642 // 17643 // - Otherwise the type of the initializing value is the same as 17644 // the type of the initializing value of the preceding enumerator 17645 // unless the incremented value is not representable in that type, 17646 // in which case the type is an unspecified integral type 17647 // sufficient to contain the incremented value. If no such type 17648 // exists, the program is ill-formed. 17649 QualType T = getNextLargerIntegralType(Context, EltTy); 17650 if (T.isNull() || Enum->isFixed()) { 17651 // There is no integral type larger enough to represent this 17652 // value. Complain, then allow the value to wrap around. 17653 EnumVal = LastEnumConst->getInitVal(); 17654 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17655 ++EnumVal; 17656 if (Enum->isFixed()) 17657 // When the underlying type is fixed, this is ill-formed. 17658 Diag(IdLoc, diag::err_enumerator_wrapped) 17659 << EnumVal.toString(10) 17660 << EltTy; 17661 else 17662 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17663 << EnumVal.toString(10); 17664 } else { 17665 EltTy = T; 17666 } 17667 17668 // Retrieve the last enumerator's value, extent that type to the 17669 // type that is supposed to be large enough to represent the incremented 17670 // value, then increment. 17671 EnumVal = LastEnumConst->getInitVal(); 17672 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17673 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17674 ++EnumVal; 17675 17676 // If we're not in C++, diagnose the overflow of enumerator values, 17677 // which in C99 means that the enumerator value is not representable in 17678 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17679 // permits enumerator values that are representable in some larger 17680 // integral type. 17681 if (!getLangOpts().CPlusPlus && !T.isNull()) 17682 Diag(IdLoc, diag::warn_enum_value_overflow); 17683 } else if (!getLangOpts().CPlusPlus && 17684 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17685 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17686 Diag(IdLoc, diag::ext_enum_value_not_int) 17687 << EnumVal.toString(10) << 1; 17688 } 17689 } 17690 } 17691 17692 if (!EltTy->isDependentType()) { 17693 // Make the enumerator value match the signedness and size of the 17694 // enumerator's type. 17695 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17696 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17697 } 17698 17699 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17700 Val, EnumVal); 17701 } 17702 17703 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17704 SourceLocation IILoc) { 17705 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17706 !getLangOpts().CPlusPlus) 17707 return SkipBodyInfo(); 17708 17709 // We have an anonymous enum definition. Look up the first enumerator to 17710 // determine if we should merge the definition with an existing one and 17711 // skip the body. 17712 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17713 forRedeclarationInCurContext()); 17714 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17715 if (!PrevECD) 17716 return SkipBodyInfo(); 17717 17718 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17719 NamedDecl *Hidden; 17720 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17721 SkipBodyInfo Skip; 17722 Skip.Previous = Hidden; 17723 return Skip; 17724 } 17725 17726 return SkipBodyInfo(); 17727 } 17728 17729 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17730 SourceLocation IdLoc, IdentifierInfo *Id, 17731 const ParsedAttributesView &Attrs, 17732 SourceLocation EqualLoc, Expr *Val) { 17733 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17734 EnumConstantDecl *LastEnumConst = 17735 cast_or_null<EnumConstantDecl>(lastEnumConst); 17736 17737 // The scope passed in may not be a decl scope. Zip up the scope tree until 17738 // we find one that is. 17739 S = getNonFieldDeclScope(S); 17740 17741 // Verify that there isn't already something declared with this name in this 17742 // scope. 17743 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17744 LookupName(R, S); 17745 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17746 17747 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17748 // Maybe we will complain about the shadowed template parameter. 17749 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17750 // Just pretend that we didn't see the previous declaration. 17751 PrevDecl = nullptr; 17752 } 17753 17754 // C++ [class.mem]p15: 17755 // If T is the name of a class, then each of the following shall have a name 17756 // different from T: 17757 // - every enumerator of every member of class T that is an unscoped 17758 // enumerated type 17759 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17760 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17761 DeclarationNameInfo(Id, IdLoc)); 17762 17763 EnumConstantDecl *New = 17764 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17765 if (!New) 17766 return nullptr; 17767 17768 if (PrevDecl) { 17769 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17770 // Check for other kinds of shadowing not already handled. 17771 CheckShadow(New, PrevDecl, R); 17772 } 17773 17774 // When in C++, we may get a TagDecl with the same name; in this case the 17775 // enum constant will 'hide' the tag. 17776 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17777 "Received TagDecl when not in C++!"); 17778 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17779 if (isa<EnumConstantDecl>(PrevDecl)) 17780 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17781 else 17782 Diag(IdLoc, diag::err_redefinition) << Id; 17783 notePreviousDefinition(PrevDecl, IdLoc); 17784 return nullptr; 17785 } 17786 } 17787 17788 // Process attributes. 17789 ProcessDeclAttributeList(S, New, Attrs); 17790 AddPragmaAttributes(S, New); 17791 17792 // Register this decl in the current scope stack. 17793 New->setAccess(TheEnumDecl->getAccess()); 17794 PushOnScopeChains(New, S); 17795 17796 ActOnDocumentableDecl(New); 17797 17798 return New; 17799 } 17800 17801 // Returns true when the enum initial expression does not trigger the 17802 // duplicate enum warning. A few common cases are exempted as follows: 17803 // Element2 = Element1 17804 // Element2 = Element1 + 1 17805 // Element2 = Element1 - 1 17806 // Where Element2 and Element1 are from the same enum. 17807 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17808 Expr *InitExpr = ECD->getInitExpr(); 17809 if (!InitExpr) 17810 return true; 17811 InitExpr = InitExpr->IgnoreImpCasts(); 17812 17813 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17814 if (!BO->isAdditiveOp()) 17815 return true; 17816 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17817 if (!IL) 17818 return true; 17819 if (IL->getValue() != 1) 17820 return true; 17821 17822 InitExpr = BO->getLHS(); 17823 } 17824 17825 // This checks if the elements are from the same enum. 17826 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17827 if (!DRE) 17828 return true; 17829 17830 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17831 if (!EnumConstant) 17832 return true; 17833 17834 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17835 Enum) 17836 return true; 17837 17838 return false; 17839 } 17840 17841 // Emits a warning when an element is implicitly set a value that 17842 // a previous element has already been set to. 17843 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17844 EnumDecl *Enum, QualType EnumType) { 17845 // Avoid anonymous enums 17846 if (!Enum->getIdentifier()) 17847 return; 17848 17849 // Only check for small enums. 17850 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17851 return; 17852 17853 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17854 return; 17855 17856 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17857 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17858 17859 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17860 17861 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17862 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17863 17864 // Use int64_t as a key to avoid needing special handling for map keys. 17865 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17866 llvm::APSInt Val = D->getInitVal(); 17867 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17868 }; 17869 17870 DuplicatesVector DupVector; 17871 ValueToVectorMap EnumMap; 17872 17873 // Populate the EnumMap with all values represented by enum constants without 17874 // an initializer. 17875 for (auto *Element : Elements) { 17876 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17877 17878 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17879 // this constant. Skip this enum since it may be ill-formed. 17880 if (!ECD) { 17881 return; 17882 } 17883 17884 // Constants with initalizers are handled in the next loop. 17885 if (ECD->getInitExpr()) 17886 continue; 17887 17888 // Duplicate values are handled in the next loop. 17889 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17890 } 17891 17892 if (EnumMap.size() == 0) 17893 return; 17894 17895 // Create vectors for any values that has duplicates. 17896 for (auto *Element : Elements) { 17897 // The last loop returned if any constant was null. 17898 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17899 if (!ValidDuplicateEnum(ECD, Enum)) 17900 continue; 17901 17902 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17903 if (Iter == EnumMap.end()) 17904 continue; 17905 17906 DeclOrVector& Entry = Iter->second; 17907 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17908 // Ensure constants are different. 17909 if (D == ECD) 17910 continue; 17911 17912 // Create new vector and push values onto it. 17913 auto Vec = std::make_unique<ECDVector>(); 17914 Vec->push_back(D); 17915 Vec->push_back(ECD); 17916 17917 // Update entry to point to the duplicates vector. 17918 Entry = Vec.get(); 17919 17920 // Store the vector somewhere we can consult later for quick emission of 17921 // diagnostics. 17922 DupVector.emplace_back(std::move(Vec)); 17923 continue; 17924 } 17925 17926 ECDVector *Vec = Entry.get<ECDVector*>(); 17927 // Make sure constants are not added more than once. 17928 if (*Vec->begin() == ECD) 17929 continue; 17930 17931 Vec->push_back(ECD); 17932 } 17933 17934 // Emit diagnostics. 17935 for (const auto &Vec : DupVector) { 17936 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17937 17938 // Emit warning for one enum constant. 17939 auto *FirstECD = Vec->front(); 17940 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17941 << FirstECD << FirstECD->getInitVal().toString(10) 17942 << FirstECD->getSourceRange(); 17943 17944 // Emit one note for each of the remaining enum constants with 17945 // the same value. 17946 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17947 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17948 << ECD << ECD->getInitVal().toString(10) 17949 << ECD->getSourceRange(); 17950 } 17951 } 17952 17953 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17954 bool AllowMask) const { 17955 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17956 assert(ED->isCompleteDefinition() && "expected enum definition"); 17957 17958 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17959 llvm::APInt &FlagBits = R.first->second; 17960 17961 if (R.second) { 17962 for (auto *E : ED->enumerators()) { 17963 const auto &EVal = E->getInitVal(); 17964 // Only single-bit enumerators introduce new flag values. 17965 if (EVal.isPowerOf2()) 17966 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17967 } 17968 } 17969 17970 // A value is in a flag enum if either its bits are a subset of the enum's 17971 // flag bits (the first condition) or we are allowing masks and the same is 17972 // true of its complement (the second condition). When masks are allowed, we 17973 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17974 // 17975 // While it's true that any value could be used as a mask, the assumption is 17976 // that a mask will have all of the insignificant bits set. Anything else is 17977 // likely a logic error. 17978 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17979 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17980 } 17981 17982 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17983 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17984 const ParsedAttributesView &Attrs) { 17985 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17986 QualType EnumType = Context.getTypeDeclType(Enum); 17987 17988 ProcessDeclAttributeList(S, Enum, Attrs); 17989 17990 if (Enum->isDependentType()) { 17991 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17992 EnumConstantDecl *ECD = 17993 cast_or_null<EnumConstantDecl>(Elements[i]); 17994 if (!ECD) continue; 17995 17996 ECD->setType(EnumType); 17997 } 17998 17999 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18000 return; 18001 } 18002 18003 // TODO: If the result value doesn't fit in an int, it must be a long or long 18004 // long value. ISO C does not support this, but GCC does as an extension, 18005 // emit a warning. 18006 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18007 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18008 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18009 18010 // Verify that all the values are okay, compute the size of the values, and 18011 // reverse the list. 18012 unsigned NumNegativeBits = 0; 18013 unsigned NumPositiveBits = 0; 18014 18015 // Keep track of whether all elements have type int. 18016 bool AllElementsInt = true; 18017 18018 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18019 EnumConstantDecl *ECD = 18020 cast_or_null<EnumConstantDecl>(Elements[i]); 18021 if (!ECD) continue; // Already issued a diagnostic. 18022 18023 const llvm::APSInt &InitVal = ECD->getInitVal(); 18024 18025 // Keep track of the size of positive and negative values. 18026 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18027 NumPositiveBits = std::max(NumPositiveBits, 18028 (unsigned)InitVal.getActiveBits()); 18029 else 18030 NumNegativeBits = std::max(NumNegativeBits, 18031 (unsigned)InitVal.getMinSignedBits()); 18032 18033 // Keep track of whether every enum element has type int (very common). 18034 if (AllElementsInt) 18035 AllElementsInt = ECD->getType() == Context.IntTy; 18036 } 18037 18038 // Figure out the type that should be used for this enum. 18039 QualType BestType; 18040 unsigned BestWidth; 18041 18042 // C++0x N3000 [conv.prom]p3: 18043 // An rvalue of an unscoped enumeration type whose underlying 18044 // type is not fixed can be converted to an rvalue of the first 18045 // of the following types that can represent all the values of 18046 // the enumeration: int, unsigned int, long int, unsigned long 18047 // int, long long int, or unsigned long long int. 18048 // C99 6.4.4.3p2: 18049 // An identifier declared as an enumeration constant has type int. 18050 // The C99 rule is modified by a gcc extension 18051 QualType BestPromotionType; 18052 18053 bool Packed = Enum->hasAttr<PackedAttr>(); 18054 // -fshort-enums is the equivalent to specifying the packed attribute on all 18055 // enum definitions. 18056 if (LangOpts.ShortEnums) 18057 Packed = true; 18058 18059 // If the enum already has a type because it is fixed or dictated by the 18060 // target, promote that type instead of analyzing the enumerators. 18061 if (Enum->isComplete()) { 18062 BestType = Enum->getIntegerType(); 18063 if (BestType->isPromotableIntegerType()) 18064 BestPromotionType = Context.getPromotedIntegerType(BestType); 18065 else 18066 BestPromotionType = BestType; 18067 18068 BestWidth = Context.getIntWidth(BestType); 18069 } 18070 else if (NumNegativeBits) { 18071 // If there is a negative value, figure out the smallest integer type (of 18072 // int/long/longlong) that fits. 18073 // If it's packed, check also if it fits a char or a short. 18074 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18075 BestType = Context.SignedCharTy; 18076 BestWidth = CharWidth; 18077 } else if (Packed && NumNegativeBits <= ShortWidth && 18078 NumPositiveBits < ShortWidth) { 18079 BestType = Context.ShortTy; 18080 BestWidth = ShortWidth; 18081 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18082 BestType = Context.IntTy; 18083 BestWidth = IntWidth; 18084 } else { 18085 BestWidth = Context.getTargetInfo().getLongWidth(); 18086 18087 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18088 BestType = Context.LongTy; 18089 } else { 18090 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18091 18092 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18093 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18094 BestType = Context.LongLongTy; 18095 } 18096 } 18097 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18098 } else { 18099 // If there is no negative value, figure out the smallest type that fits 18100 // all of the enumerator values. 18101 // If it's packed, check also if it fits a char or a short. 18102 if (Packed && NumPositiveBits <= CharWidth) { 18103 BestType = Context.UnsignedCharTy; 18104 BestPromotionType = Context.IntTy; 18105 BestWidth = CharWidth; 18106 } else if (Packed && NumPositiveBits <= ShortWidth) { 18107 BestType = Context.UnsignedShortTy; 18108 BestPromotionType = Context.IntTy; 18109 BestWidth = ShortWidth; 18110 } else if (NumPositiveBits <= IntWidth) { 18111 BestType = Context.UnsignedIntTy; 18112 BestWidth = IntWidth; 18113 BestPromotionType 18114 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18115 ? Context.UnsignedIntTy : Context.IntTy; 18116 } else if (NumPositiveBits <= 18117 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18118 BestType = Context.UnsignedLongTy; 18119 BestPromotionType 18120 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18121 ? Context.UnsignedLongTy : Context.LongTy; 18122 } else { 18123 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18124 assert(NumPositiveBits <= BestWidth && 18125 "How could an initializer get larger than ULL?"); 18126 BestType = Context.UnsignedLongLongTy; 18127 BestPromotionType 18128 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18129 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18130 } 18131 } 18132 18133 // Loop over all of the enumerator constants, changing their types to match 18134 // the type of the enum if needed. 18135 for (auto *D : Elements) { 18136 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18137 if (!ECD) continue; // Already issued a diagnostic. 18138 18139 // Standard C says the enumerators have int type, but we allow, as an 18140 // extension, the enumerators to be larger than int size. If each 18141 // enumerator value fits in an int, type it as an int, otherwise type it the 18142 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18143 // that X has type 'int', not 'unsigned'. 18144 18145 // Determine whether the value fits into an int. 18146 llvm::APSInt InitVal = ECD->getInitVal(); 18147 18148 // If it fits into an integer type, force it. Otherwise force it to match 18149 // the enum decl type. 18150 QualType NewTy; 18151 unsigned NewWidth; 18152 bool NewSign; 18153 if (!getLangOpts().CPlusPlus && 18154 !Enum->isFixed() && 18155 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18156 NewTy = Context.IntTy; 18157 NewWidth = IntWidth; 18158 NewSign = true; 18159 } else if (ECD->getType() == BestType) { 18160 // Already the right type! 18161 if (getLangOpts().CPlusPlus) 18162 // C++ [dcl.enum]p4: Following the closing brace of an 18163 // enum-specifier, each enumerator has the type of its 18164 // enumeration. 18165 ECD->setType(EnumType); 18166 continue; 18167 } else { 18168 NewTy = BestType; 18169 NewWidth = BestWidth; 18170 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18171 } 18172 18173 // Adjust the APSInt value. 18174 InitVal = InitVal.extOrTrunc(NewWidth); 18175 InitVal.setIsSigned(NewSign); 18176 ECD->setInitVal(InitVal); 18177 18178 // Adjust the Expr initializer and type. 18179 if (ECD->getInitExpr() && 18180 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18181 ECD->setInitExpr(ImplicitCastExpr::Create( 18182 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18183 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); 18184 if (getLangOpts().CPlusPlus) 18185 // C++ [dcl.enum]p4: Following the closing brace of an 18186 // enum-specifier, each enumerator has the type of its 18187 // enumeration. 18188 ECD->setType(EnumType); 18189 else 18190 ECD->setType(NewTy); 18191 } 18192 18193 Enum->completeDefinition(BestType, BestPromotionType, 18194 NumPositiveBits, NumNegativeBits); 18195 18196 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18197 18198 if (Enum->isClosedFlag()) { 18199 for (Decl *D : Elements) { 18200 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18201 if (!ECD) continue; // Already issued a diagnostic. 18202 18203 llvm::APSInt InitVal = ECD->getInitVal(); 18204 if (InitVal != 0 && !InitVal.isPowerOf2() && 18205 !IsValueInFlagEnum(Enum, InitVal, true)) 18206 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18207 << ECD << Enum; 18208 } 18209 } 18210 18211 // Now that the enum type is defined, ensure it's not been underaligned. 18212 if (Enum->hasAttrs()) 18213 CheckAlignasUnderalignment(Enum); 18214 } 18215 18216 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18217 SourceLocation StartLoc, 18218 SourceLocation EndLoc) { 18219 StringLiteral *AsmString = cast<StringLiteral>(expr); 18220 18221 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18222 AsmString, StartLoc, 18223 EndLoc); 18224 CurContext->addDecl(New); 18225 return New; 18226 } 18227 18228 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18229 IdentifierInfo* AliasName, 18230 SourceLocation PragmaLoc, 18231 SourceLocation NameLoc, 18232 SourceLocation AliasNameLoc) { 18233 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18234 LookupOrdinaryName); 18235 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18236 AttributeCommonInfo::AS_Pragma); 18237 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18238 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18239 18240 // If a declaration that: 18241 // 1) declares a function or a variable 18242 // 2) has external linkage 18243 // already exists, add a label attribute to it. 18244 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18245 if (isDeclExternC(PrevDecl)) 18246 PrevDecl->addAttr(Attr); 18247 else 18248 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18249 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18250 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18251 } else 18252 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18253 } 18254 18255 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18256 SourceLocation PragmaLoc, 18257 SourceLocation NameLoc) { 18258 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18259 18260 if (PrevDecl) { 18261 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18262 } else { 18263 (void)WeakUndeclaredIdentifiers.insert( 18264 std::pair<IdentifierInfo*,WeakInfo> 18265 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18266 } 18267 } 18268 18269 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18270 IdentifierInfo* AliasName, 18271 SourceLocation PragmaLoc, 18272 SourceLocation NameLoc, 18273 SourceLocation AliasNameLoc) { 18274 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18275 LookupOrdinaryName); 18276 WeakInfo W = WeakInfo(Name, NameLoc); 18277 18278 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18279 if (!PrevDecl->hasAttr<AliasAttr>()) 18280 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18281 DeclApplyPragmaWeak(TUScope, ND, W); 18282 } else { 18283 (void)WeakUndeclaredIdentifiers.insert( 18284 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18285 } 18286 } 18287 18288 Decl *Sema::getObjCDeclContext() const { 18289 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18290 } 18291 18292 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18293 bool Final) { 18294 // SYCL functions can be template, so we check if they have appropriate 18295 // attribute prior to checking if it is a template. 18296 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18297 return FunctionEmissionStatus::Emitted; 18298 18299 // Templates are emitted when they're instantiated. 18300 if (FD->isDependentContext()) 18301 return FunctionEmissionStatus::TemplateDiscarded; 18302 18303 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18304 if (LangOpts.OpenMPIsDevice) { 18305 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18306 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18307 if (DevTy.hasValue()) { 18308 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18309 OMPES = FunctionEmissionStatus::OMPDiscarded; 18310 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18311 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18312 OMPES = FunctionEmissionStatus::Emitted; 18313 } 18314 } 18315 } else if (LangOpts.OpenMP) { 18316 // In OpenMP 4.5 all the functions are host functions. 18317 if (LangOpts.OpenMP <= 45) { 18318 OMPES = FunctionEmissionStatus::Emitted; 18319 } else { 18320 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18321 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18322 // In OpenMP 5.0 or above, DevTy may be changed later by 18323 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18324 // having no value does not imply host. The emission status will be 18325 // checked again at the end of compilation unit. 18326 if (DevTy.hasValue()) { 18327 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18328 OMPES = FunctionEmissionStatus::OMPDiscarded; 18329 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18330 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18331 OMPES = FunctionEmissionStatus::Emitted; 18332 } else if (Final) 18333 OMPES = FunctionEmissionStatus::Emitted; 18334 } 18335 } 18336 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18337 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18338 return OMPES; 18339 18340 if (LangOpts.CUDA) { 18341 // When compiling for device, host functions are never emitted. Similarly, 18342 // when compiling for host, device and global functions are never emitted. 18343 // (Technically, we do emit a host-side stub for global functions, but this 18344 // doesn't count for our purposes here.) 18345 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18346 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18347 return FunctionEmissionStatus::CUDADiscarded; 18348 if (!LangOpts.CUDAIsDevice && 18349 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18350 return FunctionEmissionStatus::CUDADiscarded; 18351 18352 // Check whether this function is externally visible -- if so, it's 18353 // known-emitted. 18354 // 18355 // We have to check the GVA linkage of the function's *definition* -- if we 18356 // only have a declaration, we don't know whether or not the function will 18357 // be emitted, because (say) the definition could include "inline". 18358 FunctionDecl *Def = FD->getDefinition(); 18359 18360 if (Def && 18361 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18362 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18363 return FunctionEmissionStatus::Emitted; 18364 } 18365 18366 // Otherwise, the function is known-emitted if it's in our set of 18367 // known-emitted functions. 18368 return FunctionEmissionStatus::Unknown; 18369 } 18370 18371 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18372 // Host-side references to a __global__ function refer to the stub, so the 18373 // function itself is never emitted and therefore should not be marked. 18374 // If we have host fn calls kernel fn calls host+device, the HD function 18375 // does not get instantiated on the host. We model this by omitting at the 18376 // call to the kernel from the callgraph. This ensures that, when compiling 18377 // for host, only HD functions actually called from the host get marked as 18378 // known-emitted. 18379 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18380 IdentifyCUDATarget(Callee) == CFT_Global; 18381 } 18382