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___ibm128: 145 case tok::kw_wchar_t: 146 case tok::kw_bool: 147 case tok::kw___underlying_type: 148 case tok::kw___auto_type: 149 return true; 150 151 case tok::annot_typename: 152 case tok::kw_char16_t: 153 case tok::kw_char32_t: 154 case tok::kw_typeof: 155 case tok::annot_decltype: 156 case tok::kw_decltype: 157 return getLangOpts().CPlusPlus; 158 159 case tok::kw_char8_t: 160 return getLangOpts().Char8; 161 162 default: 163 break; 164 } 165 166 return false; 167 } 168 169 namespace { 170 enum class UnqualifiedTypeNameLookupResult { 171 NotFound, 172 FoundNonType, 173 FoundType 174 }; 175 } // end anonymous namespace 176 177 /// Tries to perform unqualified lookup of the type decls in bases for 178 /// dependent class. 179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 180 /// type decl, \a FoundType if only type decls are found. 181 static UnqualifiedTypeNameLookupResult 182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 183 SourceLocation NameLoc, 184 const CXXRecordDecl *RD) { 185 if (!RD->hasDefinition()) 186 return UnqualifiedTypeNameLookupResult::NotFound; 187 // Look for type decls in base classes. 188 UnqualifiedTypeNameLookupResult FoundTypeDecl = 189 UnqualifiedTypeNameLookupResult::NotFound; 190 for (const auto &Base : RD->bases()) { 191 const CXXRecordDecl *BaseRD = nullptr; 192 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 193 BaseRD = BaseTT->getAsCXXRecordDecl(); 194 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 195 // Look for type decls in dependent base classes that have known primary 196 // templates. 197 if (!TST || !TST->isDependentType()) 198 continue; 199 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 200 if (!TD) 201 continue; 202 if (auto *BasePrimaryTemplate = 203 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 204 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 205 BaseRD = BasePrimaryTemplate; 206 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 207 if (const ClassTemplatePartialSpecializationDecl *PS = 208 CTD->findPartialSpecialization(Base.getType())) 209 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 210 BaseRD = PS; 211 } 212 } 213 } 214 if (BaseRD) { 215 for (NamedDecl *ND : BaseRD->lookup(&II)) { 216 if (!isa<TypeDecl>(ND)) 217 return UnqualifiedTypeNameLookupResult::FoundNonType; 218 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 219 } 220 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 221 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 222 case UnqualifiedTypeNameLookupResult::FoundNonType: 223 return UnqualifiedTypeNameLookupResult::FoundNonType; 224 case UnqualifiedTypeNameLookupResult::FoundType: 225 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 226 break; 227 case UnqualifiedTypeNameLookupResult::NotFound: 228 break; 229 } 230 } 231 } 232 } 233 234 return FoundTypeDecl; 235 } 236 237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 238 const IdentifierInfo &II, 239 SourceLocation NameLoc) { 240 // Lookup in the parent class template context, if any. 241 const CXXRecordDecl *RD = nullptr; 242 UnqualifiedTypeNameLookupResult FoundTypeDecl = 243 UnqualifiedTypeNameLookupResult::NotFound; 244 for (DeclContext *DC = S.CurContext; 245 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 246 DC = DC->getParent()) { 247 // Look for type decls in dependent base classes that have known primary 248 // templates. 249 RD = dyn_cast<CXXRecordDecl>(DC); 250 if (RD && RD->getDescribedClassTemplate()) 251 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 252 } 253 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 254 return nullptr; 255 256 // We found some types in dependent base classes. Recover as if the user 257 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 258 // lookup during template instantiation. 259 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 260 261 ASTContext &Context = S.Context; 262 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 263 cast<Type>(Context.getRecordType(RD))); 264 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 265 266 CXXScopeSpec SS; 267 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 268 269 TypeLocBuilder Builder; 270 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 271 DepTL.setNameLoc(NameLoc); 272 DepTL.setElaboratedKeywordLoc(SourceLocation()); 273 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 274 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 275 } 276 277 /// If the identifier refers to a type name within this scope, 278 /// return the declaration of that type. 279 /// 280 /// This routine performs ordinary name lookup of the identifier II 281 /// within the given scope, with optional C++ scope specifier SS, to 282 /// determine whether the name refers to a type. If so, returns an 283 /// opaque pointer (actually a QualType) corresponding to that 284 /// type. Otherwise, returns NULL. 285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 286 Scope *S, CXXScopeSpec *SS, 287 bool isClassName, bool HasTrailingDot, 288 ParsedType ObjectTypePtr, 289 bool IsCtorOrDtorName, 290 bool WantNontrivialTypeSourceInfo, 291 bool IsClassTemplateDeductionContext, 292 IdentifierInfo **CorrectedII) { 293 // FIXME: Consider allowing this outside C++1z mode as an extension. 294 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 295 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 296 !isClassName && !HasTrailingDot; 297 298 // Determine where we will perform name lookup. 299 DeclContext *LookupCtx = nullptr; 300 if (ObjectTypePtr) { 301 QualType ObjectType = ObjectTypePtr.get(); 302 if (ObjectType->isRecordType()) 303 LookupCtx = computeDeclContext(ObjectType); 304 } else if (SS && SS->isNotEmpty()) { 305 LookupCtx = computeDeclContext(*SS, false); 306 307 if (!LookupCtx) { 308 if (isDependentScopeSpecifier(*SS)) { 309 // C++ [temp.res]p3: 310 // A qualified-id that refers to a type and in which the 311 // nested-name-specifier depends on a template-parameter (14.6.2) 312 // shall be prefixed by the keyword typename to indicate that the 313 // qualified-id denotes a type, forming an 314 // elaborated-type-specifier (7.1.5.3). 315 // 316 // We therefore do not perform any name lookup if the result would 317 // refer to a member of an unknown specialization. 318 if (!isClassName && !IsCtorOrDtorName) 319 return nullptr; 320 321 // We know from the grammar that this name refers to a type, 322 // so build a dependent node to describe the type. 323 if (WantNontrivialTypeSourceInfo) 324 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 325 326 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 327 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 328 II, NameLoc); 329 return ParsedType::make(T); 330 } 331 332 return nullptr; 333 } 334 335 if (!LookupCtx->isDependentContext() && 336 RequireCompleteDeclContext(*SS, LookupCtx)) 337 return nullptr; 338 } 339 340 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 341 // lookup for class-names. 342 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 343 LookupOrdinaryName; 344 LookupResult Result(*this, &II, NameLoc, Kind); 345 if (LookupCtx) { 346 // Perform "qualified" name lookup into the declaration context we 347 // computed, which is either the type of the base of a member access 348 // expression or the declaration context associated with a prior 349 // nested-name-specifier. 350 LookupQualifiedName(Result, LookupCtx); 351 352 if (ObjectTypePtr && Result.empty()) { 353 // C++ [basic.lookup.classref]p3: 354 // If the unqualified-id is ~type-name, the type-name is looked up 355 // in the context of the entire postfix-expression. If the type T of 356 // the object expression is of a class type C, the type-name is also 357 // looked up in the scope of class C. At least one of the lookups shall 358 // find a name that refers to (possibly cv-qualified) T. 359 LookupName(Result, S); 360 } 361 } else { 362 // Perform unqualified name lookup. 363 LookupName(Result, S); 364 365 // For unqualified lookup in a class template in MSVC mode, look into 366 // dependent base classes where the primary class template is known. 367 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 368 if (ParsedType TypeInBase = 369 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 370 return TypeInBase; 371 } 372 } 373 374 NamedDecl *IIDecl = nullptr; 375 UsingShadowDecl *FoundUsingShadow = nullptr; 376 switch (Result.getResultKind()) { 377 case LookupResult::NotFound: 378 case LookupResult::NotFoundInCurrentInstantiation: 379 if (CorrectedII) { 380 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 381 AllowDeducedTemplate); 382 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 383 S, SS, CCC, CTK_ErrorRecovery); 384 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 385 TemplateTy Template; 386 bool MemberOfUnknownSpecialization; 387 UnqualifiedId TemplateName; 388 TemplateName.setIdentifier(NewII, NameLoc); 389 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 390 CXXScopeSpec NewSS, *NewSSPtr = SS; 391 if (SS && NNS) { 392 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 393 NewSSPtr = &NewSS; 394 } 395 if (Correction && (NNS || NewII != &II) && 396 // Ignore a correction to a template type as the to-be-corrected 397 // identifier is not a template (typo correction for template names 398 // is handled elsewhere). 399 !(getLangOpts().CPlusPlus && NewSSPtr && 400 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 401 Template, MemberOfUnknownSpecialization))) { 402 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 403 isClassName, HasTrailingDot, ObjectTypePtr, 404 IsCtorOrDtorName, 405 WantNontrivialTypeSourceInfo, 406 IsClassTemplateDeductionContext); 407 if (Ty) { 408 diagnoseTypo(Correction, 409 PDiag(diag::err_unknown_type_or_class_name_suggest) 410 << Result.getLookupName() << isClassName); 411 if (SS && NNS) 412 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 413 *CorrectedII = NewII; 414 return Ty; 415 } 416 } 417 } 418 // If typo correction failed or was not performed, fall through 419 LLVM_FALLTHROUGH; 420 case LookupResult::FoundOverloaded: 421 case LookupResult::FoundUnresolvedValue: 422 Result.suppressDiagnostics(); 423 return nullptr; 424 425 case LookupResult::Ambiguous: 426 // Recover from type-hiding ambiguities by hiding the type. We'll 427 // do the lookup again when looking for an object, and we can 428 // diagnose the error then. If we don't do this, then the error 429 // about hiding the type will be immediately followed by an error 430 // that only makes sense if the identifier was treated like a type. 431 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 432 Result.suppressDiagnostics(); 433 return nullptr; 434 } 435 436 // Look to see if we have a type anywhere in the list of results. 437 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 438 Res != ResEnd; ++Res) { 439 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 440 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 441 RealRes) || 442 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 443 if (!IIDecl || 444 // Make the selection of the recovery decl deterministic. 445 RealRes->getLocation() < IIDecl->getLocation()) { 446 IIDecl = RealRes; 447 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); 448 } 449 } 450 } 451 452 if (!IIDecl) { 453 // None of the entities we found is a type, so there is no way 454 // to even assume that the result is a type. In this case, don't 455 // complain about the ambiguity. The parser will either try to 456 // perform this lookup again (e.g., as an object name), which 457 // will produce the ambiguity, or will complain that it expected 458 // a type name. 459 Result.suppressDiagnostics(); 460 return nullptr; 461 } 462 463 // We found a type within the ambiguous lookup; diagnose the 464 // ambiguity and then return that type. This might be the right 465 // answer, or it might not be, but it suppresses any attempt to 466 // perform the name lookup again. 467 break; 468 469 case LookupResult::Found: 470 IIDecl = Result.getFoundDecl(); 471 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); 472 break; 473 } 474 475 assert(IIDecl && "Didn't find decl"); 476 477 QualType T; 478 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 479 // C++ [class.qual]p2: A lookup that would find the injected-class-name 480 // instead names the constructors of the class, except when naming a class. 481 // This is ill-formed when we're not actually forming a ctor or dtor name. 482 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 483 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 484 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 485 FoundRD->isInjectedClassName() && 486 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 487 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 488 << &II << /*Type*/1; 489 490 DiagnoseUseOfDecl(IIDecl, NameLoc); 491 492 T = Context.getTypeDeclType(TD); 493 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 494 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 495 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 496 if (!HasTrailingDot) 497 T = Context.getObjCInterfaceType(IDecl); 498 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. 499 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 500 (void)DiagnoseUseOfDecl(UD, NameLoc); 501 // Recover with 'int' 502 T = Context.IntTy; 503 FoundUsingShadow = nullptr; 504 } else if (AllowDeducedTemplate) { 505 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { 506 // FIXME: TemplateName should include FoundUsingShadow sugar. 507 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 508 QualType(), false); 509 // Don't wrap in a further UsingType. 510 FoundUsingShadow = nullptr; 511 } 512 } 513 514 if (T.isNull()) { 515 // If it's not plausibly a type, suppress diagnostics. 516 Result.suppressDiagnostics(); 517 return nullptr; 518 } 519 520 if (FoundUsingShadow) 521 T = Context.getUsingType(FoundUsingShadow, T); 522 523 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 524 // constructor or destructor name (in such a case, the scope specifier 525 // will be attached to the enclosing Expr or Decl node). 526 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 527 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { 528 if (WantNontrivialTypeSourceInfo) { 529 // Construct a type with type-source information. 530 TypeLocBuilder Builder; 531 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 532 533 T = getElaboratedType(ETK_None, *SS, T); 534 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 535 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 536 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 537 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 538 } else { 539 T = getElaboratedType(ETK_None, *SS, T); 540 } 541 } 542 543 return ParsedType::make(T); 544 } 545 546 // Builds a fake NNS for the given decl context. 547 static NestedNameSpecifier * 548 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 549 for (;; DC = DC->getLookupParent()) { 550 DC = DC->getPrimaryContext(); 551 auto *ND = dyn_cast<NamespaceDecl>(DC); 552 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 553 return NestedNameSpecifier::Create(Context, nullptr, ND); 554 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 555 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 556 RD->getTypeForDecl()); 557 else if (isa<TranslationUnitDecl>(DC)) 558 return NestedNameSpecifier::GlobalSpecifier(Context); 559 } 560 llvm_unreachable("something isn't in TU scope?"); 561 } 562 563 /// Find the parent class with dependent bases of the innermost enclosing method 564 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 565 /// up allowing unqualified dependent type names at class-level, which MSVC 566 /// correctly rejects. 567 static const CXXRecordDecl * 568 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 569 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 570 DC = DC->getPrimaryContext(); 571 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 572 if (MD->getParent()->hasAnyDependentBases()) 573 return MD->getParent(); 574 } 575 return nullptr; 576 } 577 578 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 579 SourceLocation NameLoc, 580 bool IsTemplateTypeArg) { 581 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 582 583 NestedNameSpecifier *NNS = nullptr; 584 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 585 // If we weren't able to parse a default template argument, delay lookup 586 // until instantiation time by making a non-dependent DependentTypeName. We 587 // pretend we saw a NestedNameSpecifier referring to the current scope, and 588 // lookup is retried. 589 // FIXME: This hurts our diagnostic quality, since we get errors like "no 590 // type named 'Foo' in 'current_namespace'" when the user didn't write any 591 // name specifiers. 592 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 593 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 594 } else if (const CXXRecordDecl *RD = 595 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 596 // Build a DependentNameType that will perform lookup into RD at 597 // instantiation time. 598 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 599 RD->getTypeForDecl()); 600 601 // Diagnose that this identifier was undeclared, and retry the lookup during 602 // template instantiation. 603 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 604 << RD; 605 } else { 606 // This is not a situation that we should recover from. 607 return ParsedType(); 608 } 609 610 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 611 612 // Build type location information. We synthesized the qualifier, so we have 613 // to build a fake NestedNameSpecifierLoc. 614 NestedNameSpecifierLocBuilder NNSLocBuilder; 615 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 616 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 617 618 TypeLocBuilder Builder; 619 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 620 DepTL.setNameLoc(NameLoc); 621 DepTL.setElaboratedKeywordLoc(SourceLocation()); 622 DepTL.setQualifierLoc(QualifierLoc); 623 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 624 } 625 626 /// isTagName() - This method is called *for error recovery purposes only* 627 /// to determine if the specified name is a valid tag name ("struct foo"). If 628 /// so, this returns the TST for the tag corresponding to it (TST_enum, 629 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 630 /// cases in C where the user forgot to specify the tag. 631 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 632 // Do a tag name lookup in this scope. 633 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 634 LookupName(R, S, false); 635 R.suppressDiagnostics(); 636 if (R.getResultKind() == LookupResult::Found) 637 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 638 switch (TD->getTagKind()) { 639 case TTK_Struct: return DeclSpec::TST_struct; 640 case TTK_Interface: return DeclSpec::TST_interface; 641 case TTK_Union: return DeclSpec::TST_union; 642 case TTK_Class: return DeclSpec::TST_class; 643 case TTK_Enum: return DeclSpec::TST_enum; 644 } 645 } 646 647 return DeclSpec::TST_unspecified; 648 } 649 650 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 651 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 652 /// then downgrade the missing typename error to a warning. 653 /// This is needed for MSVC compatibility; Example: 654 /// @code 655 /// template<class T> class A { 656 /// public: 657 /// typedef int TYPE; 658 /// }; 659 /// template<class T> class B : public A<T> { 660 /// public: 661 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 662 /// }; 663 /// @endcode 664 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 665 if (CurContext->isRecord()) { 666 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 667 return true; 668 669 const Type *Ty = SS->getScopeRep()->getAsType(); 670 671 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 672 for (const auto &Base : RD->bases()) 673 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 674 return true; 675 return S->isFunctionPrototypeScope(); 676 } 677 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 678 } 679 680 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 681 SourceLocation IILoc, 682 Scope *S, 683 CXXScopeSpec *SS, 684 ParsedType &SuggestedType, 685 bool IsTemplateName) { 686 // Don't report typename errors for editor placeholders. 687 if (II->isEditorPlaceholder()) 688 return; 689 // We don't have anything to suggest (yet). 690 SuggestedType = nullptr; 691 692 // There may have been a typo in the name of the type. Look up typo 693 // results, in case we have something that we can suggest. 694 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 695 /*AllowTemplates=*/IsTemplateName, 696 /*AllowNonTemplates=*/!IsTemplateName); 697 if (TypoCorrection Corrected = 698 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 699 CCC, CTK_ErrorRecovery)) { 700 // FIXME: Support error recovery for the template-name case. 701 bool CanRecover = !IsTemplateName; 702 if (Corrected.isKeyword()) { 703 // We corrected to a keyword. 704 diagnoseTypo(Corrected, 705 PDiag(IsTemplateName ? diag::err_no_template_suggest 706 : diag::err_unknown_typename_suggest) 707 << II); 708 II = Corrected.getCorrectionAsIdentifierInfo(); 709 } else { 710 // We found a similarly-named type or interface; suggest that. 711 if (!SS || !SS->isSet()) { 712 diagnoseTypo(Corrected, 713 PDiag(IsTemplateName ? diag::err_no_template_suggest 714 : diag::err_unknown_typename_suggest) 715 << II, CanRecover); 716 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 717 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 718 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 719 II->getName().equals(CorrectedStr); 720 diagnoseTypo(Corrected, 721 PDiag(IsTemplateName 722 ? diag::err_no_member_template_suggest 723 : diag::err_unknown_nested_typename_suggest) 724 << II << DC << DroppedSpecifier << SS->getRange(), 725 CanRecover); 726 } else { 727 llvm_unreachable("could not have corrected a typo here"); 728 } 729 730 if (!CanRecover) 731 return; 732 733 CXXScopeSpec tmpSS; 734 if (Corrected.getCorrectionSpecifier()) 735 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 736 SourceRange(IILoc)); 737 // FIXME: Support class template argument deduction here. 738 SuggestedType = 739 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 740 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 741 /*IsCtorOrDtorName=*/false, 742 /*WantNontrivialTypeSourceInfo=*/true); 743 } 744 return; 745 } 746 747 if (getLangOpts().CPlusPlus && !IsTemplateName) { 748 // See if II is a class template that the user forgot to pass arguments to. 749 UnqualifiedId Name; 750 Name.setIdentifier(II, IILoc); 751 CXXScopeSpec EmptySS; 752 TemplateTy TemplateResult; 753 bool MemberOfUnknownSpecialization; 754 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 755 Name, nullptr, true, TemplateResult, 756 MemberOfUnknownSpecialization) == TNK_Type_template) { 757 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 758 return; 759 } 760 } 761 762 // FIXME: Should we move the logic that tries to recover from a missing tag 763 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 764 765 if (!SS || (!SS->isSet() && !SS->isInvalid())) 766 Diag(IILoc, IsTemplateName ? diag::err_no_template 767 : diag::err_unknown_typename) 768 << II; 769 else if (DeclContext *DC = computeDeclContext(*SS, false)) 770 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 771 : diag::err_typename_nested_not_found) 772 << II << DC << SS->getRange(); 773 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 774 SuggestedType = 775 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 776 } else if (isDependentScopeSpecifier(*SS)) { 777 unsigned DiagID = diag::err_typename_missing; 778 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 779 DiagID = diag::ext_typename_missing; 780 781 Diag(SS->getRange().getBegin(), DiagID) 782 << SS->getScopeRep() << II->getName() 783 << SourceRange(SS->getRange().getBegin(), IILoc) 784 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 785 SuggestedType = ActOnTypenameType(S, SourceLocation(), 786 *SS, *II, IILoc).get(); 787 } else { 788 assert(SS && SS->isInvalid() && 789 "Invalid scope specifier has already been diagnosed"); 790 } 791 } 792 793 /// Determine whether the given result set contains either a type name 794 /// or 795 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 796 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 797 NextToken.is(tok::less); 798 799 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 800 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 801 return true; 802 803 if (CheckTemplate && isa<TemplateDecl>(*I)) 804 return true; 805 } 806 807 return false; 808 } 809 810 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 811 Scope *S, CXXScopeSpec &SS, 812 IdentifierInfo *&Name, 813 SourceLocation NameLoc) { 814 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 815 SemaRef.LookupParsedName(R, S, &SS); 816 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 817 StringRef FixItTagName; 818 switch (Tag->getTagKind()) { 819 case TTK_Class: 820 FixItTagName = "class "; 821 break; 822 823 case TTK_Enum: 824 FixItTagName = "enum "; 825 break; 826 827 case TTK_Struct: 828 FixItTagName = "struct "; 829 break; 830 831 case TTK_Interface: 832 FixItTagName = "__interface "; 833 break; 834 835 case TTK_Union: 836 FixItTagName = "union "; 837 break; 838 } 839 840 StringRef TagName = FixItTagName.drop_back(); 841 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 842 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 843 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 844 845 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 846 I != IEnd; ++I) 847 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 848 << Name << TagName; 849 850 // Replace lookup results with just the tag decl. 851 Result.clear(Sema::LookupTagName); 852 SemaRef.LookupParsedName(Result, S, &SS); 853 return true; 854 } 855 856 return false; 857 } 858 859 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 860 IdentifierInfo *&Name, 861 SourceLocation NameLoc, 862 const Token &NextToken, 863 CorrectionCandidateCallback *CCC) { 864 DeclarationNameInfo NameInfo(Name, NameLoc); 865 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 866 867 assert(NextToken.isNot(tok::coloncolon) && 868 "parse nested name specifiers before calling ClassifyName"); 869 if (getLangOpts().CPlusPlus && SS.isSet() && 870 isCurrentClassName(*Name, S, &SS)) { 871 // Per [class.qual]p2, this names the constructors of SS, not the 872 // injected-class-name. We don't have a classification for that. 873 // There's not much point caching this result, since the parser 874 // will reject it later. 875 return NameClassification::Unknown(); 876 } 877 878 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 879 LookupParsedName(Result, S, &SS, !CurMethod); 880 881 if (SS.isInvalid()) 882 return NameClassification::Error(); 883 884 // For unqualified lookup in a class template in MSVC mode, look into 885 // dependent base classes where the primary class template is known. 886 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 887 if (ParsedType TypeInBase = 888 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 889 return TypeInBase; 890 } 891 892 // Perform lookup for Objective-C instance variables (including automatically 893 // synthesized instance variables), if we're in an Objective-C method. 894 // FIXME: This lookup really, really needs to be folded in to the normal 895 // unqualified lookup mechanism. 896 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 897 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 898 if (Ivar.isInvalid()) 899 return NameClassification::Error(); 900 if (Ivar.isUsable()) 901 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 902 903 // We defer builtin creation until after ivar lookup inside ObjC methods. 904 if (Result.empty()) 905 LookupBuiltin(Result); 906 } 907 908 bool SecondTry = false; 909 bool IsFilteredTemplateName = false; 910 911 Corrected: 912 switch (Result.getResultKind()) { 913 case LookupResult::NotFound: 914 // If an unqualified-id is followed by a '(', then we have a function 915 // call. 916 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 917 // In C++, this is an ADL-only call. 918 // FIXME: Reference? 919 if (getLangOpts().CPlusPlus) 920 return NameClassification::UndeclaredNonType(); 921 922 // C90 6.3.2.2: 923 // If the expression that precedes the parenthesized argument list in a 924 // function call consists solely of an identifier, and if no 925 // declaration is visible for this identifier, the identifier is 926 // implicitly declared exactly as if, in the innermost block containing 927 // the function call, the declaration 928 // 929 // extern int identifier (); 930 // 931 // appeared. 932 // 933 // We also allow this in C99 as an extension. 934 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 935 return NameClassification::NonType(D); 936 } 937 938 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 939 // In C++20 onwards, this could be an ADL-only call to a function 940 // template, and we're required to assume that this is a template name. 941 // 942 // FIXME: Find a way to still do typo correction in this case. 943 TemplateName Template = 944 Context.getAssumedTemplateName(NameInfo.getName()); 945 return NameClassification::UndeclaredTemplate(Template); 946 } 947 948 // In C, we first see whether there is a tag type by the same name, in 949 // which case it's likely that the user just forgot to write "enum", 950 // "struct", or "union". 951 if (!getLangOpts().CPlusPlus && !SecondTry && 952 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 953 break; 954 } 955 956 // Perform typo correction to determine if there is another name that is 957 // close to this name. 958 if (!SecondTry && CCC) { 959 SecondTry = true; 960 if (TypoCorrection Corrected = 961 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 962 &SS, *CCC, CTK_ErrorRecovery)) { 963 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 964 unsigned QualifiedDiag = diag::err_no_member_suggest; 965 966 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 967 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 968 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 969 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 970 UnqualifiedDiag = diag::err_no_template_suggest; 971 QualifiedDiag = diag::err_no_member_template_suggest; 972 } else if (UnderlyingFirstDecl && 973 (isa<TypeDecl>(UnderlyingFirstDecl) || 974 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 975 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 976 UnqualifiedDiag = diag::err_unknown_typename_suggest; 977 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 978 } 979 980 if (SS.isEmpty()) { 981 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 982 } else {// FIXME: is this even reachable? Test it. 983 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 984 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 985 Name->getName().equals(CorrectedStr); 986 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 987 << Name << computeDeclContext(SS, false) 988 << DroppedSpecifier << SS.getRange()); 989 } 990 991 // Update the name, so that the caller has the new name. 992 Name = Corrected.getCorrectionAsIdentifierInfo(); 993 994 // Typo correction corrected to a keyword. 995 if (Corrected.isKeyword()) 996 return Name; 997 998 // Also update the LookupResult... 999 // FIXME: This should probably go away at some point 1000 Result.clear(); 1001 Result.setLookupName(Corrected.getCorrection()); 1002 if (FirstDecl) 1003 Result.addDecl(FirstDecl); 1004 1005 // If we found an Objective-C instance variable, let 1006 // LookupInObjCMethod build the appropriate expression to 1007 // reference the ivar. 1008 // FIXME: This is a gross hack. 1009 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1010 DeclResult R = 1011 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1012 if (R.isInvalid()) 1013 return NameClassification::Error(); 1014 if (R.isUsable()) 1015 return NameClassification::NonType(Ivar); 1016 } 1017 1018 goto Corrected; 1019 } 1020 } 1021 1022 // We failed to correct; just fall through and let the parser deal with it. 1023 Result.suppressDiagnostics(); 1024 return NameClassification::Unknown(); 1025 1026 case LookupResult::NotFoundInCurrentInstantiation: { 1027 // We performed name lookup into the current instantiation, and there were 1028 // dependent bases, so we treat this result the same way as any other 1029 // dependent nested-name-specifier. 1030 1031 // C++ [temp.res]p2: 1032 // A name used in a template declaration or definition and that is 1033 // dependent on a template-parameter is assumed not to name a type 1034 // unless the applicable name lookup finds a type name or the name is 1035 // qualified by the keyword typename. 1036 // 1037 // FIXME: If the next token is '<', we might want to ask the parser to 1038 // perform some heroics to see if we actually have a 1039 // template-argument-list, which would indicate a missing 'template' 1040 // keyword here. 1041 return NameClassification::DependentNonType(); 1042 } 1043 1044 case LookupResult::Found: 1045 case LookupResult::FoundOverloaded: 1046 case LookupResult::FoundUnresolvedValue: 1047 break; 1048 1049 case LookupResult::Ambiguous: 1050 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1051 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1052 /*AllowDependent=*/false)) { 1053 // C++ [temp.local]p3: 1054 // A lookup that finds an injected-class-name (10.2) can result in an 1055 // ambiguity in certain cases (for example, if it is found in more than 1056 // one base class). If all of the injected-class-names that are found 1057 // refer to specializations of the same class template, and if the name 1058 // is followed by a template-argument-list, the reference refers to the 1059 // class template itself and not a specialization thereof, and is not 1060 // ambiguous. 1061 // 1062 // This filtering can make an ambiguous result into an unambiguous one, 1063 // so try again after filtering out template names. 1064 FilterAcceptableTemplateNames(Result); 1065 if (!Result.isAmbiguous()) { 1066 IsFilteredTemplateName = true; 1067 break; 1068 } 1069 } 1070 1071 // Diagnose the ambiguity and return an error. 1072 return NameClassification::Error(); 1073 } 1074 1075 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1076 (IsFilteredTemplateName || 1077 hasAnyAcceptableTemplateNames( 1078 Result, /*AllowFunctionTemplates=*/true, 1079 /*AllowDependent=*/false, 1080 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1081 getLangOpts().CPlusPlus20))) { 1082 // C++ [temp.names]p3: 1083 // After name lookup (3.4) finds that a name is a template-name or that 1084 // an operator-function-id or a literal- operator-id refers to a set of 1085 // overloaded functions any member of which is a function template if 1086 // this is followed by a <, the < is always taken as the delimiter of a 1087 // template-argument-list and never as the less-than operator. 1088 // C++2a [temp.names]p2: 1089 // A name is also considered to refer to a template if it is an 1090 // unqualified-id followed by a < and name lookup finds either one 1091 // or more functions or finds nothing. 1092 if (!IsFilteredTemplateName) 1093 FilterAcceptableTemplateNames(Result); 1094 1095 bool IsFunctionTemplate; 1096 bool IsVarTemplate; 1097 TemplateName Template; 1098 if (Result.end() - Result.begin() > 1) { 1099 IsFunctionTemplate = true; 1100 Template = Context.getOverloadedTemplateName(Result.begin(), 1101 Result.end()); 1102 } else if (!Result.empty()) { 1103 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1104 *Result.begin(), /*AllowFunctionTemplates=*/true, 1105 /*AllowDependent=*/false)); 1106 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1107 IsVarTemplate = isa<VarTemplateDecl>(TD); 1108 1109 if (SS.isNotEmpty()) 1110 Template = 1111 Context.getQualifiedTemplateName(SS.getScopeRep(), 1112 /*TemplateKeyword=*/false, TD); 1113 else 1114 Template = TemplateName(TD); 1115 } else { 1116 // All results were non-template functions. This is a function template 1117 // name. 1118 IsFunctionTemplate = true; 1119 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1120 } 1121 1122 if (IsFunctionTemplate) { 1123 // Function templates always go through overload resolution, at which 1124 // point we'll perform the various checks (e.g., accessibility) we need 1125 // to based on which function we selected. 1126 Result.suppressDiagnostics(); 1127 1128 return NameClassification::FunctionTemplate(Template); 1129 } 1130 1131 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1132 : NameClassification::TypeTemplate(Template); 1133 } 1134 1135 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { 1136 QualType T = Context.getTypeDeclType(Type); 1137 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) 1138 T = Context.getUsingType(USD, T); 1139 1140 if (SS.isEmpty()) // No elaborated type, trivial location info 1141 return ParsedType::make(T); 1142 1143 TypeLocBuilder Builder; 1144 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 1145 T = getElaboratedType(ETK_None, SS, T); 1146 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 1147 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 1148 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 1149 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 1150 }; 1151 1152 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1153 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1154 DiagnoseUseOfDecl(Type, NameLoc); 1155 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1156 return BuildTypeFor(Type, *Result.begin()); 1157 } 1158 1159 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1160 if (!Class) { 1161 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1162 if (ObjCCompatibleAliasDecl *Alias = 1163 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1164 Class = Alias->getClassInterface(); 1165 } 1166 1167 if (Class) { 1168 DiagnoseUseOfDecl(Class, NameLoc); 1169 1170 if (NextToken.is(tok::period)) { 1171 // Interface. <something> is parsed as a property reference expression. 1172 // Just return "unknown" as a fall-through for now. 1173 Result.suppressDiagnostics(); 1174 return NameClassification::Unknown(); 1175 } 1176 1177 QualType T = Context.getObjCInterfaceType(Class); 1178 return ParsedType::make(T); 1179 } 1180 1181 if (isa<ConceptDecl>(FirstDecl)) 1182 return NameClassification::Concept( 1183 TemplateName(cast<TemplateDecl>(FirstDecl))); 1184 1185 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1186 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1187 return NameClassification::Error(); 1188 } 1189 1190 // We can have a type template here if we're classifying a template argument. 1191 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1192 !isa<VarTemplateDecl>(FirstDecl)) 1193 return NameClassification::TypeTemplate( 1194 TemplateName(cast<TemplateDecl>(FirstDecl))); 1195 1196 // Check for a tag type hidden by a non-type decl in a few cases where it 1197 // seems likely a type is wanted instead of the non-type that was found. 1198 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1199 if ((NextToken.is(tok::identifier) || 1200 (NextIsOp && 1201 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1202 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1203 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1204 DiagnoseUseOfDecl(Type, NameLoc); 1205 return BuildTypeFor(Type, *Result.begin()); 1206 } 1207 1208 // If we already know which single declaration is referenced, just annotate 1209 // that declaration directly. Defer resolving even non-overloaded class 1210 // member accesses, as we need to defer certain access checks until we know 1211 // the context. 1212 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1213 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1214 return NameClassification::NonType(Result.getRepresentativeDecl()); 1215 1216 // Otherwise, this is an overload set that we will need to resolve later. 1217 Result.suppressDiagnostics(); 1218 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1219 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1220 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1221 Result.begin(), Result.end())); 1222 } 1223 1224 ExprResult 1225 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1226 SourceLocation NameLoc) { 1227 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1228 CXXScopeSpec SS; 1229 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1230 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1231 } 1232 1233 ExprResult 1234 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1235 IdentifierInfo *Name, 1236 SourceLocation NameLoc, 1237 bool IsAddressOfOperand) { 1238 DeclarationNameInfo NameInfo(Name, NameLoc); 1239 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1240 NameInfo, IsAddressOfOperand, 1241 /*TemplateArgs=*/nullptr); 1242 } 1243 1244 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1245 NamedDecl *Found, 1246 SourceLocation NameLoc, 1247 const Token &NextToken) { 1248 if (getCurMethodDecl() && SS.isEmpty()) 1249 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1250 return BuildIvarRefExpr(S, NameLoc, Ivar); 1251 1252 // Reconstruct the lookup result. 1253 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1254 Result.addDecl(Found); 1255 Result.resolveKind(); 1256 1257 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1258 return BuildDeclarationNameExpr(SS, Result, ADL); 1259 } 1260 1261 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1262 // For an implicit class member access, transform the result into a member 1263 // access expression if necessary. 1264 auto *ULE = cast<UnresolvedLookupExpr>(E); 1265 if ((*ULE->decls_begin())->isCXXClassMember()) { 1266 CXXScopeSpec SS; 1267 SS.Adopt(ULE->getQualifierLoc()); 1268 1269 // Reconstruct the lookup result. 1270 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1271 LookupOrdinaryName); 1272 Result.setNamingClass(ULE->getNamingClass()); 1273 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1274 Result.addDecl(*I, I.getAccess()); 1275 Result.resolveKind(); 1276 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1277 nullptr, S); 1278 } 1279 1280 // Otherwise, this is already in the form we needed, and no further checks 1281 // are necessary. 1282 return ULE; 1283 } 1284 1285 Sema::TemplateNameKindForDiagnostics 1286 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1287 auto *TD = Name.getAsTemplateDecl(); 1288 if (!TD) 1289 return TemplateNameKindForDiagnostics::DependentTemplate; 1290 if (isa<ClassTemplateDecl>(TD)) 1291 return TemplateNameKindForDiagnostics::ClassTemplate; 1292 if (isa<FunctionTemplateDecl>(TD)) 1293 return TemplateNameKindForDiagnostics::FunctionTemplate; 1294 if (isa<VarTemplateDecl>(TD)) 1295 return TemplateNameKindForDiagnostics::VarTemplate; 1296 if (isa<TypeAliasTemplateDecl>(TD)) 1297 return TemplateNameKindForDiagnostics::AliasTemplate; 1298 if (isa<TemplateTemplateParmDecl>(TD)) 1299 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1300 if (isa<ConceptDecl>(TD)) 1301 return TemplateNameKindForDiagnostics::Concept; 1302 return TemplateNameKindForDiagnostics::DependentTemplate; 1303 } 1304 1305 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1306 assert(DC->getLexicalParent() == CurContext && 1307 "The next DeclContext should be lexically contained in the current one."); 1308 CurContext = DC; 1309 S->setEntity(DC); 1310 } 1311 1312 void Sema::PopDeclContext() { 1313 assert(CurContext && "DeclContext imbalance!"); 1314 1315 CurContext = CurContext->getLexicalParent(); 1316 assert(CurContext && "Popped translation unit!"); 1317 } 1318 1319 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1320 Decl *D) { 1321 // Unlike PushDeclContext, the context to which we return is not necessarily 1322 // the containing DC of TD, because the new context will be some pre-existing 1323 // TagDecl definition instead of a fresh one. 1324 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1325 CurContext = cast<TagDecl>(D)->getDefinition(); 1326 assert(CurContext && "skipping definition of undefined tag"); 1327 // Start lookups from the parent of the current context; we don't want to look 1328 // into the pre-existing complete definition. 1329 S->setEntity(CurContext->getLookupParent()); 1330 return Result; 1331 } 1332 1333 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1334 CurContext = static_cast<decltype(CurContext)>(Context); 1335 } 1336 1337 /// EnterDeclaratorContext - Used when we must lookup names in the context 1338 /// of a declarator's nested name specifier. 1339 /// 1340 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1341 // C++0x [basic.lookup.unqual]p13: 1342 // A name used in the definition of a static data member of class 1343 // X (after the qualified-id of the static member) is looked up as 1344 // if the name was used in a member function of X. 1345 // C++0x [basic.lookup.unqual]p14: 1346 // If a variable member of a namespace is defined outside of the 1347 // scope of its namespace then any name used in the definition of 1348 // the variable member (after the declarator-id) is looked up as 1349 // if the definition of the variable member occurred in its 1350 // namespace. 1351 // Both of these imply that we should push a scope whose context 1352 // is the semantic context of the declaration. We can't use 1353 // PushDeclContext here because that context is not necessarily 1354 // lexically contained in the current context. Fortunately, 1355 // the containing scope should have the appropriate information. 1356 1357 assert(!S->getEntity() && "scope already has entity"); 1358 1359 #ifndef NDEBUG 1360 Scope *Ancestor = S->getParent(); 1361 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1362 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1363 #endif 1364 1365 CurContext = DC; 1366 S->setEntity(DC); 1367 1368 if (S->getParent()->isTemplateParamScope()) { 1369 // Also set the corresponding entities for all immediately-enclosing 1370 // template parameter scopes. 1371 EnterTemplatedContext(S->getParent(), DC); 1372 } 1373 } 1374 1375 void Sema::ExitDeclaratorContext(Scope *S) { 1376 assert(S->getEntity() == CurContext && "Context imbalance!"); 1377 1378 // Switch back to the lexical context. The safety of this is 1379 // enforced by an assert in EnterDeclaratorContext. 1380 Scope *Ancestor = S->getParent(); 1381 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1382 CurContext = Ancestor->getEntity(); 1383 1384 // We don't need to do anything with the scope, which is going to 1385 // disappear. 1386 } 1387 1388 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1389 assert(S->isTemplateParamScope() && 1390 "expected to be initializing a template parameter scope"); 1391 1392 // C++20 [temp.local]p7: 1393 // In the definition of a member of a class template that appears outside 1394 // of the class template definition, the name of a member of the class 1395 // template hides the name of a template-parameter of any enclosing class 1396 // templates (but not a template-parameter of the member if the member is a 1397 // class or function template). 1398 // C++20 [temp.local]p9: 1399 // In the definition of a class template or in the definition of a member 1400 // of such a template that appears outside of the template definition, for 1401 // each non-dependent base class (13.8.2.1), if the name of the base class 1402 // or the name of a member of the base class is the same as the name of a 1403 // template-parameter, the base class name or member name hides the 1404 // template-parameter name (6.4.10). 1405 // 1406 // This means that a template parameter scope should be searched immediately 1407 // after searching the DeclContext for which it is a template parameter 1408 // scope. For example, for 1409 // template<typename T> template<typename U> template<typename V> 1410 // void N::A<T>::B<U>::f(...) 1411 // we search V then B<U> (and base classes) then U then A<T> (and base 1412 // classes) then T then N then ::. 1413 unsigned ScopeDepth = getTemplateDepth(S); 1414 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1415 DeclContext *SearchDCAfterScope = DC; 1416 for (; DC; DC = DC->getLookupParent()) { 1417 if (const TemplateParameterList *TPL = 1418 cast<Decl>(DC)->getDescribedTemplateParams()) { 1419 unsigned DCDepth = TPL->getDepth() + 1; 1420 if (DCDepth > ScopeDepth) 1421 continue; 1422 if (ScopeDepth == DCDepth) 1423 SearchDCAfterScope = DC = DC->getLookupParent(); 1424 break; 1425 } 1426 } 1427 S->setLookupEntity(SearchDCAfterScope); 1428 } 1429 } 1430 1431 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1432 // We assume that the caller has already called 1433 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1434 FunctionDecl *FD = D->getAsFunction(); 1435 if (!FD) 1436 return; 1437 1438 // Same implementation as PushDeclContext, but enters the context 1439 // from the lexical parent, rather than the top-level class. 1440 assert(CurContext == FD->getLexicalParent() && 1441 "The next DeclContext should be lexically contained in the current one."); 1442 CurContext = FD; 1443 S->setEntity(CurContext); 1444 1445 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1446 ParmVarDecl *Param = FD->getParamDecl(P); 1447 // If the parameter has an identifier, then add it to the scope 1448 if (Param->getIdentifier()) { 1449 S->AddDecl(Param); 1450 IdResolver.AddDecl(Param); 1451 } 1452 } 1453 } 1454 1455 void Sema::ActOnExitFunctionContext() { 1456 // Same implementation as PopDeclContext, but returns to the lexical parent, 1457 // rather than the top-level class. 1458 assert(CurContext && "DeclContext imbalance!"); 1459 CurContext = CurContext->getLexicalParent(); 1460 assert(CurContext && "Popped translation unit!"); 1461 } 1462 1463 /// Determine whether we allow overloading of the function 1464 /// PrevDecl with another declaration. 1465 /// 1466 /// This routine determines whether overloading is possible, not 1467 /// whether some new function is actually an overload. It will return 1468 /// true in C++ (where we can always provide overloads) or, as an 1469 /// extension, in C when the previous function is already an 1470 /// overloaded function declaration or has the "overloadable" 1471 /// attribute. 1472 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1473 ASTContext &Context, 1474 const FunctionDecl *New) { 1475 if (Context.getLangOpts().CPlusPlus) 1476 return true; 1477 1478 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1479 return true; 1480 1481 return Previous.getResultKind() == LookupResult::Found && 1482 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1483 New->hasAttr<OverloadableAttr>()); 1484 } 1485 1486 /// Add this decl to the scope shadowed decl chains. 1487 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1488 // Move up the scope chain until we find the nearest enclosing 1489 // non-transparent context. The declaration will be introduced into this 1490 // scope. 1491 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1492 S = S->getParent(); 1493 1494 // Add scoped declarations into their context, so that they can be 1495 // found later. Declarations without a context won't be inserted 1496 // into any context. 1497 if (AddToContext) 1498 CurContext->addDecl(D); 1499 1500 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1501 // are function-local declarations. 1502 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1503 return; 1504 1505 // Template instantiations should also not be pushed into scope. 1506 if (isa<FunctionDecl>(D) && 1507 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1508 return; 1509 1510 // If this replaces anything in the current scope, 1511 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1512 IEnd = IdResolver.end(); 1513 for (; I != IEnd; ++I) { 1514 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1515 S->RemoveDecl(*I); 1516 IdResolver.RemoveDecl(*I); 1517 1518 // Should only need to replace one decl. 1519 break; 1520 } 1521 } 1522 1523 S->AddDecl(D); 1524 1525 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1526 // Implicitly-generated labels may end up getting generated in an order that 1527 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1528 // the label at the appropriate place in the identifier chain. 1529 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1530 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1531 if (IDC == CurContext) { 1532 if (!S->isDeclScope(*I)) 1533 continue; 1534 } else if (IDC->Encloses(CurContext)) 1535 break; 1536 } 1537 1538 IdResolver.InsertDeclAfter(I, D); 1539 } else { 1540 IdResolver.AddDecl(D); 1541 } 1542 warnOnReservedIdentifier(D); 1543 } 1544 1545 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1546 bool AllowInlineNamespace) { 1547 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1548 } 1549 1550 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1551 DeclContext *TargetDC = DC->getPrimaryContext(); 1552 do { 1553 if (DeclContext *ScopeDC = S->getEntity()) 1554 if (ScopeDC->getPrimaryContext() == TargetDC) 1555 return S; 1556 } while ((S = S->getParent())); 1557 1558 return nullptr; 1559 } 1560 1561 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1562 DeclContext*, 1563 ASTContext&); 1564 1565 /// Filters out lookup results that don't fall within the given scope 1566 /// as determined by isDeclInScope. 1567 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1568 bool ConsiderLinkage, 1569 bool AllowInlineNamespace) { 1570 LookupResult::Filter F = R.makeFilter(); 1571 while (F.hasNext()) { 1572 NamedDecl *D = F.next(); 1573 1574 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1575 continue; 1576 1577 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1578 continue; 1579 1580 F.erase(); 1581 } 1582 1583 F.done(); 1584 } 1585 1586 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1587 /// have compatible owning modules. 1588 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1589 // FIXME: The Modules TS is not clear about how friend declarations are 1590 // to be treated. It's not meaningful to have different owning modules for 1591 // linkage in redeclarations of the same entity, so for now allow the 1592 // redeclaration and change the owning modules to match. 1593 if (New->getFriendObjectKind() && 1594 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1595 New->setLocalOwningModule(Old->getOwningModule()); 1596 makeMergedDefinitionVisible(New); 1597 return false; 1598 } 1599 1600 Module *NewM = New->getOwningModule(); 1601 Module *OldM = Old->getOwningModule(); 1602 1603 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1604 NewM = NewM->Parent; 1605 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1606 OldM = OldM->Parent; 1607 1608 if (NewM == OldM) 1609 return false; 1610 1611 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1612 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1613 if (NewIsModuleInterface || OldIsModuleInterface) { 1614 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1615 // if a declaration of D [...] appears in the purview of a module, all 1616 // other such declarations shall appear in the purview of the same module 1617 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1618 << New 1619 << NewIsModuleInterface 1620 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1621 << OldIsModuleInterface 1622 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1623 Diag(Old->getLocation(), diag::note_previous_declaration); 1624 New->setInvalidDecl(); 1625 return true; 1626 } 1627 1628 return false; 1629 } 1630 1631 static bool isUsingDecl(NamedDecl *D) { 1632 return isa<UsingShadowDecl>(D) || 1633 isa<UnresolvedUsingTypenameDecl>(D) || 1634 isa<UnresolvedUsingValueDecl>(D); 1635 } 1636 1637 /// Removes using shadow declarations from the lookup results. 1638 static void RemoveUsingDecls(LookupResult &R) { 1639 LookupResult::Filter F = R.makeFilter(); 1640 while (F.hasNext()) 1641 if (isUsingDecl(F.next())) 1642 F.erase(); 1643 1644 F.done(); 1645 } 1646 1647 /// Check for this common pattern: 1648 /// @code 1649 /// class S { 1650 /// S(const S&); // DO NOT IMPLEMENT 1651 /// void operator=(const S&); // DO NOT IMPLEMENT 1652 /// }; 1653 /// @endcode 1654 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1655 // FIXME: Should check for private access too but access is set after we get 1656 // the decl here. 1657 if (D->doesThisDeclarationHaveABody()) 1658 return false; 1659 1660 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1661 return CD->isCopyConstructor(); 1662 return D->isCopyAssignmentOperator(); 1663 } 1664 1665 // We need this to handle 1666 // 1667 // typedef struct { 1668 // void *foo() { return 0; } 1669 // } A; 1670 // 1671 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1672 // for example. If 'A', foo will have external linkage. If we have '*A', 1673 // foo will have no linkage. Since we can't know until we get to the end 1674 // of the typedef, this function finds out if D might have non-external linkage. 1675 // Callers should verify at the end of the TU if it D has external linkage or 1676 // not. 1677 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1678 const DeclContext *DC = D->getDeclContext(); 1679 while (!DC->isTranslationUnit()) { 1680 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1681 if (!RD->hasNameForLinkage()) 1682 return true; 1683 } 1684 DC = DC->getParent(); 1685 } 1686 1687 return !D->isExternallyVisible(); 1688 } 1689 1690 // FIXME: This needs to be refactored; some other isInMainFile users want 1691 // these semantics. 1692 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1693 if (S.TUKind != TU_Complete) 1694 return false; 1695 return S.SourceMgr.isInMainFile(Loc); 1696 } 1697 1698 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1699 assert(D); 1700 1701 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1702 return false; 1703 1704 // Ignore all entities declared within templates, and out-of-line definitions 1705 // of members of class templates. 1706 if (D->getDeclContext()->isDependentContext() || 1707 D->getLexicalDeclContext()->isDependentContext()) 1708 return false; 1709 1710 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1711 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1712 return false; 1713 // A non-out-of-line declaration of a member specialization was implicitly 1714 // instantiated; it's the out-of-line declaration that we're interested in. 1715 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1716 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1717 return false; 1718 1719 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1720 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1721 return false; 1722 } else { 1723 // 'static inline' functions are defined in headers; don't warn. 1724 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1725 return false; 1726 } 1727 1728 if (FD->doesThisDeclarationHaveABody() && 1729 Context.DeclMustBeEmitted(FD)) 1730 return false; 1731 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1732 // Constants and utility variables are defined in headers with internal 1733 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1734 // like "inline".) 1735 if (!isMainFileLoc(*this, VD->getLocation())) 1736 return false; 1737 1738 if (Context.DeclMustBeEmitted(VD)) 1739 return false; 1740 1741 if (VD->isStaticDataMember() && 1742 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1743 return false; 1744 if (VD->isStaticDataMember() && 1745 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1746 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1747 return false; 1748 1749 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1750 return false; 1751 } else { 1752 return false; 1753 } 1754 1755 // Only warn for unused decls internal to the translation unit. 1756 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1757 // for inline functions defined in the main source file, for instance. 1758 return mightHaveNonExternalLinkage(D); 1759 } 1760 1761 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1762 if (!D) 1763 return; 1764 1765 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1766 const FunctionDecl *First = FD->getFirstDecl(); 1767 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1768 return; // First should already be in the vector. 1769 } 1770 1771 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1772 const VarDecl *First = VD->getFirstDecl(); 1773 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1774 return; // First should already be in the vector. 1775 } 1776 1777 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1778 UnusedFileScopedDecls.push_back(D); 1779 } 1780 1781 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1782 if (D->isInvalidDecl()) 1783 return false; 1784 1785 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1786 // For a decomposition declaration, warn if none of the bindings are 1787 // referenced, instead of if the variable itself is referenced (which 1788 // it is, by the bindings' expressions). 1789 for (auto *BD : DD->bindings()) 1790 if (BD->isReferenced()) 1791 return false; 1792 } else if (!D->getDeclName()) { 1793 return false; 1794 } else if (D->isReferenced() || D->isUsed()) { 1795 return false; 1796 } 1797 1798 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1799 return false; 1800 1801 if (isa<LabelDecl>(D)) 1802 return true; 1803 1804 // Except for labels, we only care about unused decls that are local to 1805 // functions. 1806 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1807 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1808 // For dependent types, the diagnostic is deferred. 1809 WithinFunction = 1810 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1811 if (!WithinFunction) 1812 return false; 1813 1814 if (isa<TypedefNameDecl>(D)) 1815 return true; 1816 1817 // White-list anything that isn't a local variable. 1818 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1819 return false; 1820 1821 // Types of valid local variables should be complete, so this should succeed. 1822 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1823 1824 // White-list anything with an __attribute__((unused)) type. 1825 const auto *Ty = VD->getType().getTypePtr(); 1826 1827 // Only look at the outermost level of typedef. 1828 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1829 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1830 return false; 1831 } 1832 1833 // If we failed to complete the type for some reason, or if the type is 1834 // dependent, don't diagnose the variable. 1835 if (Ty->isIncompleteType() || Ty->isDependentType()) 1836 return false; 1837 1838 // Look at the element type to ensure that the warning behaviour is 1839 // consistent for both scalars and arrays. 1840 Ty = Ty->getBaseElementTypeUnsafe(); 1841 1842 if (const TagType *TT = Ty->getAs<TagType>()) { 1843 const TagDecl *Tag = TT->getDecl(); 1844 if (Tag->hasAttr<UnusedAttr>()) 1845 return false; 1846 1847 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1848 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1849 return false; 1850 1851 if (const Expr *Init = VD->getInit()) { 1852 if (const ExprWithCleanups *Cleanups = 1853 dyn_cast<ExprWithCleanups>(Init)) 1854 Init = Cleanups->getSubExpr(); 1855 const CXXConstructExpr *Construct = 1856 dyn_cast<CXXConstructExpr>(Init); 1857 if (Construct && !Construct->isElidable()) { 1858 CXXConstructorDecl *CD = Construct->getConstructor(); 1859 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1860 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1861 return false; 1862 } 1863 1864 // Suppress the warning if we don't know how this is constructed, and 1865 // it could possibly be non-trivial constructor. 1866 if (Init->isTypeDependent()) 1867 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1868 if (!Ctor->isTrivial()) 1869 return false; 1870 } 1871 } 1872 } 1873 1874 // TODO: __attribute__((unused)) templates? 1875 } 1876 1877 return true; 1878 } 1879 1880 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1881 FixItHint &Hint) { 1882 if (isa<LabelDecl>(D)) { 1883 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1884 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1885 true); 1886 if (AfterColon.isInvalid()) 1887 return; 1888 Hint = FixItHint::CreateRemoval( 1889 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1890 } 1891 } 1892 1893 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1894 if (D->getTypeForDecl()->isDependentType()) 1895 return; 1896 1897 for (auto *TmpD : D->decls()) { 1898 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1899 DiagnoseUnusedDecl(T); 1900 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1901 DiagnoseUnusedNestedTypedefs(R); 1902 } 1903 } 1904 1905 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1906 /// unless they are marked attr(unused). 1907 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1908 if (!ShouldDiagnoseUnusedDecl(D)) 1909 return; 1910 1911 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1912 // typedefs can be referenced later on, so the diagnostics are emitted 1913 // at end-of-translation-unit. 1914 UnusedLocalTypedefNameCandidates.insert(TD); 1915 return; 1916 } 1917 1918 FixItHint Hint; 1919 GenerateFixForUnusedDecl(D, Context, Hint); 1920 1921 unsigned DiagID; 1922 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1923 DiagID = diag::warn_unused_exception_param; 1924 else if (isa<LabelDecl>(D)) 1925 DiagID = diag::warn_unused_label; 1926 else 1927 DiagID = diag::warn_unused_variable; 1928 1929 Diag(D->getLocation(), DiagID) << D << Hint; 1930 } 1931 1932 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 1933 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 1934 // it's not really unused. 1935 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 1936 VD->hasAttr<CleanupAttr>()) 1937 return; 1938 1939 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 1940 1941 if (Ty->isReferenceType() || Ty->isDependentType()) 1942 return; 1943 1944 if (const TagType *TT = Ty->getAs<TagType>()) { 1945 const TagDecl *Tag = TT->getDecl(); 1946 if (Tag->hasAttr<UnusedAttr>()) 1947 return; 1948 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 1949 // mimic gcc's behavior. 1950 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1951 if (!RD->hasAttr<WarnUnusedAttr>()) 1952 return; 1953 } 1954 } 1955 1956 // Don't warn about __block Objective-C pointer variables, as they might 1957 // be assigned in the block but not used elsewhere for the purpose of lifetime 1958 // extension. 1959 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 1960 return; 1961 1962 auto iter = RefsMinusAssignments.find(VD); 1963 if (iter == RefsMinusAssignments.end()) 1964 return; 1965 1966 assert(iter->getSecond() >= 0 && 1967 "Found a negative number of references to a VarDecl"); 1968 if (iter->getSecond() != 0) 1969 return; 1970 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 1971 : diag::warn_unused_but_set_variable; 1972 Diag(VD->getLocation(), DiagID) << VD; 1973 } 1974 1975 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1976 // Verify that we have no forward references left. If so, there was a goto 1977 // or address of a label taken, but no definition of it. Label fwd 1978 // definitions are indicated with a null substmt which is also not a resolved 1979 // MS inline assembly label name. 1980 bool Diagnose = false; 1981 if (L->isMSAsmLabel()) 1982 Diagnose = !L->isResolvedMSAsmLabel(); 1983 else 1984 Diagnose = L->getStmt() == nullptr; 1985 if (Diagnose) 1986 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 1987 } 1988 1989 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1990 S->mergeNRVOIntoParent(); 1991 1992 if (S->decl_empty()) return; 1993 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1994 "Scope shouldn't contain decls!"); 1995 1996 for (auto *TmpD : S->decls()) { 1997 assert(TmpD && "This decl didn't get pushed??"); 1998 1999 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2000 NamedDecl *D = cast<NamedDecl>(TmpD); 2001 2002 // Diagnose unused variables in this scope. 2003 if (!S->hasUnrecoverableErrorOccurred()) { 2004 DiagnoseUnusedDecl(D); 2005 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2006 DiagnoseUnusedNestedTypedefs(RD); 2007 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2008 DiagnoseUnusedButSetDecl(VD); 2009 RefsMinusAssignments.erase(VD); 2010 } 2011 } 2012 2013 if (!D->getDeclName()) continue; 2014 2015 // If this was a forward reference to a label, verify it was defined. 2016 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2017 CheckPoppedLabel(LD, *this); 2018 2019 // Remove this name from our lexical scope, and warn on it if we haven't 2020 // already. 2021 IdResolver.RemoveDecl(D); 2022 auto ShadowI = ShadowingDecls.find(D); 2023 if (ShadowI != ShadowingDecls.end()) { 2024 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2025 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2026 << D << FD << FD->getParent(); 2027 Diag(FD->getLocation(), diag::note_previous_declaration); 2028 } 2029 ShadowingDecls.erase(ShadowI); 2030 } 2031 } 2032 } 2033 2034 /// Look for an Objective-C class in the translation unit. 2035 /// 2036 /// \param Id The name of the Objective-C class we're looking for. If 2037 /// typo-correction fixes this name, the Id will be updated 2038 /// to the fixed name. 2039 /// 2040 /// \param IdLoc The location of the name in the translation unit. 2041 /// 2042 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2043 /// if there is no class with the given name. 2044 /// 2045 /// \returns The declaration of the named Objective-C class, or NULL if the 2046 /// class could not be found. 2047 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2048 SourceLocation IdLoc, 2049 bool DoTypoCorrection) { 2050 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2051 // creation from this context. 2052 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2053 2054 if (!IDecl && DoTypoCorrection) { 2055 // Perform typo correction at the given location, but only if we 2056 // find an Objective-C class name. 2057 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2058 if (TypoCorrection C = 2059 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2060 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2061 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2062 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2063 Id = IDecl->getIdentifier(); 2064 } 2065 } 2066 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2067 // This routine must always return a class definition, if any. 2068 if (Def && Def->getDefinition()) 2069 Def = Def->getDefinition(); 2070 return Def; 2071 } 2072 2073 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2074 /// from S, where a non-field would be declared. This routine copes 2075 /// with the difference between C and C++ scoping rules in structs and 2076 /// unions. For example, the following code is well-formed in C but 2077 /// ill-formed in C++: 2078 /// @code 2079 /// struct S6 { 2080 /// enum { BAR } e; 2081 /// }; 2082 /// 2083 /// void test_S6() { 2084 /// struct S6 a; 2085 /// a.e = BAR; 2086 /// } 2087 /// @endcode 2088 /// For the declaration of BAR, this routine will return a different 2089 /// scope. The scope S will be the scope of the unnamed enumeration 2090 /// within S6. In C++, this routine will return the scope associated 2091 /// with S6, because the enumeration's scope is a transparent 2092 /// context but structures can contain non-field names. In C, this 2093 /// routine will return the translation unit scope, since the 2094 /// enumeration's scope is a transparent context and structures cannot 2095 /// contain non-field names. 2096 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2097 while (((S->getFlags() & Scope::DeclScope) == 0) || 2098 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2099 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2100 S = S->getParent(); 2101 return S; 2102 } 2103 2104 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2105 ASTContext::GetBuiltinTypeError Error) { 2106 switch (Error) { 2107 case ASTContext::GE_None: 2108 return ""; 2109 case ASTContext::GE_Missing_type: 2110 return BuiltinInfo.getHeaderName(ID); 2111 case ASTContext::GE_Missing_stdio: 2112 return "stdio.h"; 2113 case ASTContext::GE_Missing_setjmp: 2114 return "setjmp.h"; 2115 case ASTContext::GE_Missing_ucontext: 2116 return "ucontext.h"; 2117 } 2118 llvm_unreachable("unhandled error kind"); 2119 } 2120 2121 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2122 unsigned ID, SourceLocation Loc) { 2123 DeclContext *Parent = Context.getTranslationUnitDecl(); 2124 2125 if (getLangOpts().CPlusPlus) { 2126 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2127 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2128 CLinkageDecl->setImplicit(); 2129 Parent->addDecl(CLinkageDecl); 2130 Parent = CLinkageDecl; 2131 } 2132 2133 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2134 /*TInfo=*/nullptr, SC_Extern, 2135 getCurFPFeatures().isFPConstrained(), 2136 false, Type->isFunctionProtoType()); 2137 New->setImplicit(); 2138 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2139 2140 // Create Decl objects for each parameter, adding them to the 2141 // FunctionDecl. 2142 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2143 SmallVector<ParmVarDecl *, 16> Params; 2144 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2145 ParmVarDecl *parm = ParmVarDecl::Create( 2146 Context, New, SourceLocation(), SourceLocation(), nullptr, 2147 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2148 parm->setScopeInfo(0, i); 2149 Params.push_back(parm); 2150 } 2151 New->setParams(Params); 2152 } 2153 2154 AddKnownFunctionAttributes(New); 2155 return New; 2156 } 2157 2158 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2159 /// file scope. lazily create a decl for it. ForRedeclaration is true 2160 /// if we're creating this built-in in anticipation of redeclaring the 2161 /// built-in. 2162 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2163 Scope *S, bool ForRedeclaration, 2164 SourceLocation Loc) { 2165 LookupNecessaryTypesForBuiltin(S, ID); 2166 2167 ASTContext::GetBuiltinTypeError Error; 2168 QualType R = Context.GetBuiltinType(ID, Error); 2169 if (Error) { 2170 if (!ForRedeclaration) 2171 return nullptr; 2172 2173 // If we have a builtin without an associated type we should not emit a 2174 // warning when we were not able to find a type for it. 2175 if (Error == ASTContext::GE_Missing_type || 2176 Context.BuiltinInfo.allowTypeMismatch(ID)) 2177 return nullptr; 2178 2179 // If we could not find a type for setjmp it is because the jmp_buf type was 2180 // not defined prior to the setjmp declaration. 2181 if (Error == ASTContext::GE_Missing_setjmp) { 2182 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2183 << Context.BuiltinInfo.getName(ID); 2184 return nullptr; 2185 } 2186 2187 // Generally, we emit a warning that the declaration requires the 2188 // appropriate header. 2189 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2190 << getHeaderName(Context.BuiltinInfo, ID, Error) 2191 << Context.BuiltinInfo.getName(ID); 2192 return nullptr; 2193 } 2194 2195 if (!ForRedeclaration && 2196 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2197 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2198 Diag(Loc, diag::ext_implicit_lib_function_decl) 2199 << Context.BuiltinInfo.getName(ID) << R; 2200 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2201 Diag(Loc, diag::note_include_header_or_declare) 2202 << Header << Context.BuiltinInfo.getName(ID); 2203 } 2204 2205 if (R.isNull()) 2206 return nullptr; 2207 2208 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2209 RegisterLocallyScopedExternCDecl(New, S); 2210 2211 // TUScope is the translation-unit scope to insert this function into. 2212 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2213 // relate Scopes to DeclContexts, and probably eliminate CurContext 2214 // entirely, but we're not there yet. 2215 DeclContext *SavedContext = CurContext; 2216 CurContext = New->getDeclContext(); 2217 PushOnScopeChains(New, TUScope); 2218 CurContext = SavedContext; 2219 return New; 2220 } 2221 2222 /// Typedef declarations don't have linkage, but they still denote the same 2223 /// entity if their types are the same. 2224 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2225 /// isSameEntity. 2226 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2227 TypedefNameDecl *Decl, 2228 LookupResult &Previous) { 2229 // This is only interesting when modules are enabled. 2230 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2231 return; 2232 2233 // Empty sets are uninteresting. 2234 if (Previous.empty()) 2235 return; 2236 2237 LookupResult::Filter Filter = Previous.makeFilter(); 2238 while (Filter.hasNext()) { 2239 NamedDecl *Old = Filter.next(); 2240 2241 // Non-hidden declarations are never ignored. 2242 if (S.isVisible(Old)) 2243 continue; 2244 2245 // Declarations of the same entity are not ignored, even if they have 2246 // different linkages. 2247 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2248 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2249 Decl->getUnderlyingType())) 2250 continue; 2251 2252 // If both declarations give a tag declaration a typedef name for linkage 2253 // purposes, then they declare the same entity. 2254 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2255 Decl->getAnonDeclWithTypedefName()) 2256 continue; 2257 } 2258 2259 Filter.erase(); 2260 } 2261 2262 Filter.done(); 2263 } 2264 2265 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2266 QualType OldType; 2267 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2268 OldType = OldTypedef->getUnderlyingType(); 2269 else 2270 OldType = Context.getTypeDeclType(Old); 2271 QualType NewType = New->getUnderlyingType(); 2272 2273 if (NewType->isVariablyModifiedType()) { 2274 // Must not redefine a typedef with a variably-modified type. 2275 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2276 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2277 << Kind << NewType; 2278 if (Old->getLocation().isValid()) 2279 notePreviousDefinition(Old, New->getLocation()); 2280 New->setInvalidDecl(); 2281 return true; 2282 } 2283 2284 if (OldType != NewType && 2285 !OldType->isDependentType() && 2286 !NewType->isDependentType() && 2287 !Context.hasSameType(OldType, NewType)) { 2288 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2289 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2290 << Kind << NewType << OldType; 2291 if (Old->getLocation().isValid()) 2292 notePreviousDefinition(Old, New->getLocation()); 2293 New->setInvalidDecl(); 2294 return true; 2295 } 2296 return false; 2297 } 2298 2299 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2300 /// same name and scope as a previous declaration 'Old'. Figure out 2301 /// how to resolve this situation, merging decls or emitting 2302 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2303 /// 2304 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2305 LookupResult &OldDecls) { 2306 // If the new decl is known invalid already, don't bother doing any 2307 // merging checks. 2308 if (New->isInvalidDecl()) return; 2309 2310 // Allow multiple definitions for ObjC built-in typedefs. 2311 // FIXME: Verify the underlying types are equivalent! 2312 if (getLangOpts().ObjC) { 2313 const IdentifierInfo *TypeID = New->getIdentifier(); 2314 switch (TypeID->getLength()) { 2315 default: break; 2316 case 2: 2317 { 2318 if (!TypeID->isStr("id")) 2319 break; 2320 QualType T = New->getUnderlyingType(); 2321 if (!T->isPointerType()) 2322 break; 2323 if (!T->isVoidPointerType()) { 2324 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2325 if (!PT->isStructureType()) 2326 break; 2327 } 2328 Context.setObjCIdRedefinitionType(T); 2329 // Install the built-in type for 'id', ignoring the current definition. 2330 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2331 return; 2332 } 2333 case 5: 2334 if (!TypeID->isStr("Class")) 2335 break; 2336 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2337 // Install the built-in type for 'Class', ignoring the current definition. 2338 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2339 return; 2340 case 3: 2341 if (!TypeID->isStr("SEL")) 2342 break; 2343 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2344 // Install the built-in type for 'SEL', ignoring the current definition. 2345 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2346 return; 2347 } 2348 // Fall through - the typedef name was not a builtin type. 2349 } 2350 2351 // Verify the old decl was also a type. 2352 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2353 if (!Old) { 2354 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2355 << New->getDeclName(); 2356 2357 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2358 if (OldD->getLocation().isValid()) 2359 notePreviousDefinition(OldD, New->getLocation()); 2360 2361 return New->setInvalidDecl(); 2362 } 2363 2364 // If the old declaration is invalid, just give up here. 2365 if (Old->isInvalidDecl()) 2366 return New->setInvalidDecl(); 2367 2368 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2369 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2370 auto *NewTag = New->getAnonDeclWithTypedefName(); 2371 NamedDecl *Hidden = nullptr; 2372 if (OldTag && NewTag && 2373 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2374 !hasVisibleDefinition(OldTag, &Hidden)) { 2375 // There is a definition of this tag, but it is not visible. Use it 2376 // instead of our tag. 2377 New->setTypeForDecl(OldTD->getTypeForDecl()); 2378 if (OldTD->isModed()) 2379 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2380 OldTD->getUnderlyingType()); 2381 else 2382 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2383 2384 // Make the old tag definition visible. 2385 makeMergedDefinitionVisible(Hidden); 2386 2387 // If this was an unscoped enumeration, yank all of its enumerators 2388 // out of the scope. 2389 if (isa<EnumDecl>(NewTag)) { 2390 Scope *EnumScope = getNonFieldDeclScope(S); 2391 for (auto *D : NewTag->decls()) { 2392 auto *ED = cast<EnumConstantDecl>(D); 2393 assert(EnumScope->isDeclScope(ED)); 2394 EnumScope->RemoveDecl(ED); 2395 IdResolver.RemoveDecl(ED); 2396 ED->getLexicalDeclContext()->removeDecl(ED); 2397 } 2398 } 2399 } 2400 } 2401 2402 // If the typedef types are not identical, reject them in all languages and 2403 // with any extensions enabled. 2404 if (isIncompatibleTypedef(Old, New)) 2405 return; 2406 2407 // The types match. Link up the redeclaration chain and merge attributes if 2408 // the old declaration was a typedef. 2409 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2410 New->setPreviousDecl(Typedef); 2411 mergeDeclAttributes(New, Old); 2412 } 2413 2414 if (getLangOpts().MicrosoftExt) 2415 return; 2416 2417 if (getLangOpts().CPlusPlus) { 2418 // C++ [dcl.typedef]p2: 2419 // In a given non-class scope, a typedef specifier can be used to 2420 // redefine the name of any type declared in that scope to refer 2421 // to the type to which it already refers. 2422 if (!isa<CXXRecordDecl>(CurContext)) 2423 return; 2424 2425 // C++0x [dcl.typedef]p4: 2426 // In a given class scope, a typedef specifier can be used to redefine 2427 // any class-name declared in that scope that is not also a typedef-name 2428 // to refer to the type to which it already refers. 2429 // 2430 // This wording came in via DR424, which was a correction to the 2431 // wording in DR56, which accidentally banned code like: 2432 // 2433 // struct S { 2434 // typedef struct A { } A; 2435 // }; 2436 // 2437 // in the C++03 standard. We implement the C++0x semantics, which 2438 // allow the above but disallow 2439 // 2440 // struct S { 2441 // typedef int I; 2442 // typedef int I; 2443 // }; 2444 // 2445 // since that was the intent of DR56. 2446 if (!isa<TypedefNameDecl>(Old)) 2447 return; 2448 2449 Diag(New->getLocation(), diag::err_redefinition) 2450 << New->getDeclName(); 2451 notePreviousDefinition(Old, New->getLocation()); 2452 return New->setInvalidDecl(); 2453 } 2454 2455 // Modules always permit redefinition of typedefs, as does C11. 2456 if (getLangOpts().Modules || getLangOpts().C11) 2457 return; 2458 2459 // If we have a redefinition of a typedef in C, emit a warning. This warning 2460 // is normally mapped to an error, but can be controlled with 2461 // -Wtypedef-redefinition. If either the original or the redefinition is 2462 // in a system header, don't emit this for compatibility with GCC. 2463 if (getDiagnostics().getSuppressSystemWarnings() && 2464 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2465 (Old->isImplicit() || 2466 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2467 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2468 return; 2469 2470 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2471 << New->getDeclName(); 2472 notePreviousDefinition(Old, New->getLocation()); 2473 } 2474 2475 /// DeclhasAttr - returns true if decl Declaration already has the target 2476 /// attribute. 2477 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2478 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2479 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2480 for (const auto *i : D->attrs()) 2481 if (i->getKind() == A->getKind()) { 2482 if (Ann) { 2483 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2484 return true; 2485 continue; 2486 } 2487 // FIXME: Don't hardcode this check 2488 if (OA && isa<OwnershipAttr>(i)) 2489 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2490 return true; 2491 } 2492 2493 return false; 2494 } 2495 2496 static bool isAttributeTargetADefinition(Decl *D) { 2497 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2498 return VD->isThisDeclarationADefinition(); 2499 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2500 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2501 return true; 2502 } 2503 2504 /// Merge alignment attributes from \p Old to \p New, taking into account the 2505 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2506 /// 2507 /// \return \c true if any attributes were added to \p New. 2508 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2509 // Look for alignas attributes on Old, and pick out whichever attribute 2510 // specifies the strictest alignment requirement. 2511 AlignedAttr *OldAlignasAttr = nullptr; 2512 AlignedAttr *OldStrictestAlignAttr = nullptr; 2513 unsigned OldAlign = 0; 2514 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2515 // FIXME: We have no way of representing inherited dependent alignments 2516 // in a case like: 2517 // template<int A, int B> struct alignas(A) X; 2518 // template<int A, int B> struct alignas(B) X {}; 2519 // For now, we just ignore any alignas attributes which are not on the 2520 // definition in such a case. 2521 if (I->isAlignmentDependent()) 2522 return false; 2523 2524 if (I->isAlignas()) 2525 OldAlignasAttr = I; 2526 2527 unsigned Align = I->getAlignment(S.Context); 2528 if (Align > OldAlign) { 2529 OldAlign = Align; 2530 OldStrictestAlignAttr = I; 2531 } 2532 } 2533 2534 // Look for alignas attributes on New. 2535 AlignedAttr *NewAlignasAttr = nullptr; 2536 unsigned NewAlign = 0; 2537 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2538 if (I->isAlignmentDependent()) 2539 return false; 2540 2541 if (I->isAlignas()) 2542 NewAlignasAttr = I; 2543 2544 unsigned Align = I->getAlignment(S.Context); 2545 if (Align > NewAlign) 2546 NewAlign = Align; 2547 } 2548 2549 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2550 // Both declarations have 'alignas' attributes. We require them to match. 2551 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2552 // fall short. (If two declarations both have alignas, they must both match 2553 // every definition, and so must match each other if there is a definition.) 2554 2555 // If either declaration only contains 'alignas(0)' specifiers, then it 2556 // specifies the natural alignment for the type. 2557 if (OldAlign == 0 || NewAlign == 0) { 2558 QualType Ty; 2559 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2560 Ty = VD->getType(); 2561 else 2562 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2563 2564 if (OldAlign == 0) 2565 OldAlign = S.Context.getTypeAlign(Ty); 2566 if (NewAlign == 0) 2567 NewAlign = S.Context.getTypeAlign(Ty); 2568 } 2569 2570 if (OldAlign != NewAlign) { 2571 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2572 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2573 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2574 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2575 } 2576 } 2577 2578 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2579 // C++11 [dcl.align]p6: 2580 // if any declaration of an entity has an alignment-specifier, 2581 // every defining declaration of that entity shall specify an 2582 // equivalent alignment. 2583 // C11 6.7.5/7: 2584 // If the definition of an object does not have an alignment 2585 // specifier, any other declaration of that object shall also 2586 // have no alignment specifier. 2587 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2588 << OldAlignasAttr; 2589 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2590 << OldAlignasAttr; 2591 } 2592 2593 bool AnyAdded = false; 2594 2595 // Ensure we have an attribute representing the strictest alignment. 2596 if (OldAlign > NewAlign) { 2597 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2598 Clone->setInherited(true); 2599 New->addAttr(Clone); 2600 AnyAdded = true; 2601 } 2602 2603 // Ensure we have an alignas attribute if the old declaration had one. 2604 if (OldAlignasAttr && !NewAlignasAttr && 2605 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2606 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2607 Clone->setInherited(true); 2608 New->addAttr(Clone); 2609 AnyAdded = true; 2610 } 2611 2612 return AnyAdded; 2613 } 2614 2615 #define WANT_DECL_MERGE_LOGIC 2616 #include "clang/Sema/AttrParsedAttrImpl.inc" 2617 #undef WANT_DECL_MERGE_LOGIC 2618 2619 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2620 const InheritableAttr *Attr, 2621 Sema::AvailabilityMergeKind AMK) { 2622 // Diagnose any mutual exclusions between the attribute that we want to add 2623 // and attributes that already exist on the declaration. 2624 if (!DiagnoseMutualExclusions(S, D, Attr)) 2625 return false; 2626 2627 // This function copies an attribute Attr from a previous declaration to the 2628 // new declaration D if the new declaration doesn't itself have that attribute 2629 // yet or if that attribute allows duplicates. 2630 // If you're adding a new attribute that requires logic different from 2631 // "use explicit attribute on decl if present, else use attribute from 2632 // previous decl", for example if the attribute needs to be consistent 2633 // between redeclarations, you need to call a custom merge function here. 2634 InheritableAttr *NewAttr = nullptr; 2635 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2636 NewAttr = S.mergeAvailabilityAttr( 2637 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2638 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2639 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2640 AA->getPriority()); 2641 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2642 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2643 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2644 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2645 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2646 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2647 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2648 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2649 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2650 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2651 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2652 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2653 FA->getFirstArg()); 2654 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2655 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2656 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2657 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2658 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2659 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2660 IA->getInheritanceModel()); 2661 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2662 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2663 &S.Context.Idents.get(AA->getSpelling())); 2664 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2665 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2666 isa<CUDAGlobalAttr>(Attr))) { 2667 // CUDA target attributes are part of function signature for 2668 // overloading purposes and must not be merged. 2669 return false; 2670 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2671 NewAttr = S.mergeMinSizeAttr(D, *MA); 2672 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2673 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2674 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2675 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2676 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2677 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2678 else if (isa<AlignedAttr>(Attr)) 2679 // AlignedAttrs are handled separately, because we need to handle all 2680 // such attributes on a declaration at the same time. 2681 NewAttr = nullptr; 2682 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2683 (AMK == Sema::AMK_Override || 2684 AMK == Sema::AMK_ProtocolImplementation || 2685 AMK == Sema::AMK_OptionalProtocolImplementation)) 2686 NewAttr = nullptr; 2687 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2688 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2689 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2690 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2691 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2692 NewAttr = S.mergeImportNameAttr(D, *INA); 2693 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2694 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2695 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2696 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2697 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2698 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2699 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2700 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2701 2702 if (NewAttr) { 2703 NewAttr->setInherited(true); 2704 D->addAttr(NewAttr); 2705 if (isa<MSInheritanceAttr>(NewAttr)) 2706 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2707 return true; 2708 } 2709 2710 return false; 2711 } 2712 2713 static const NamedDecl *getDefinition(const Decl *D) { 2714 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2715 return TD->getDefinition(); 2716 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2717 const VarDecl *Def = VD->getDefinition(); 2718 if (Def) 2719 return Def; 2720 return VD->getActingDefinition(); 2721 } 2722 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2723 const FunctionDecl *Def = nullptr; 2724 if (FD->isDefined(Def, true)) 2725 return Def; 2726 } 2727 return nullptr; 2728 } 2729 2730 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2731 for (const auto *Attribute : D->attrs()) 2732 if (Attribute->getKind() == Kind) 2733 return true; 2734 return false; 2735 } 2736 2737 /// checkNewAttributesAfterDef - If we already have a definition, check that 2738 /// there are no new attributes in this declaration. 2739 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2740 if (!New->hasAttrs()) 2741 return; 2742 2743 const NamedDecl *Def = getDefinition(Old); 2744 if (!Def || Def == New) 2745 return; 2746 2747 AttrVec &NewAttributes = New->getAttrs(); 2748 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2749 const Attr *NewAttribute = NewAttributes[I]; 2750 2751 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2752 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2753 Sema::SkipBodyInfo SkipBody; 2754 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2755 2756 // If we're skipping this definition, drop the "alias" attribute. 2757 if (SkipBody.ShouldSkip) { 2758 NewAttributes.erase(NewAttributes.begin() + I); 2759 --E; 2760 continue; 2761 } 2762 } else { 2763 VarDecl *VD = cast<VarDecl>(New); 2764 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2765 VarDecl::TentativeDefinition 2766 ? diag::err_alias_after_tentative 2767 : diag::err_redefinition; 2768 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2769 if (Diag == diag::err_redefinition) 2770 S.notePreviousDefinition(Def, VD->getLocation()); 2771 else 2772 S.Diag(Def->getLocation(), diag::note_previous_definition); 2773 VD->setInvalidDecl(); 2774 } 2775 ++I; 2776 continue; 2777 } 2778 2779 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2780 // Tentative definitions are only interesting for the alias check above. 2781 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2782 ++I; 2783 continue; 2784 } 2785 } 2786 2787 if (hasAttribute(Def, NewAttribute->getKind())) { 2788 ++I; 2789 continue; // regular attr merging will take care of validating this. 2790 } 2791 2792 if (isa<C11NoReturnAttr>(NewAttribute)) { 2793 // C's _Noreturn is allowed to be added to a function after it is defined. 2794 ++I; 2795 continue; 2796 } else if (isa<UuidAttr>(NewAttribute)) { 2797 // msvc will allow a subsequent definition to add an uuid to a class 2798 ++I; 2799 continue; 2800 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2801 if (AA->isAlignas()) { 2802 // C++11 [dcl.align]p6: 2803 // if any declaration of an entity has an alignment-specifier, 2804 // every defining declaration of that entity shall specify an 2805 // equivalent alignment. 2806 // C11 6.7.5/7: 2807 // If the definition of an object does not have an alignment 2808 // specifier, any other declaration of that object shall also 2809 // have no alignment specifier. 2810 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2811 << AA; 2812 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2813 << AA; 2814 NewAttributes.erase(NewAttributes.begin() + I); 2815 --E; 2816 continue; 2817 } 2818 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2819 // If there is a C definition followed by a redeclaration with this 2820 // attribute then there are two different definitions. In C++, prefer the 2821 // standard diagnostics. 2822 if (!S.getLangOpts().CPlusPlus) { 2823 S.Diag(NewAttribute->getLocation(), 2824 diag::err_loader_uninitialized_redeclaration); 2825 S.Diag(Def->getLocation(), diag::note_previous_definition); 2826 NewAttributes.erase(NewAttributes.begin() + I); 2827 --E; 2828 continue; 2829 } 2830 } else if (isa<SelectAnyAttr>(NewAttribute) && 2831 cast<VarDecl>(New)->isInline() && 2832 !cast<VarDecl>(New)->isInlineSpecified()) { 2833 // Don't warn about applying selectany to implicitly inline variables. 2834 // Older compilers and language modes would require the use of selectany 2835 // to make such variables inline, and it would have no effect if we 2836 // honored it. 2837 ++I; 2838 continue; 2839 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2840 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2841 // declarations after defintions. 2842 ++I; 2843 continue; 2844 } 2845 2846 S.Diag(NewAttribute->getLocation(), 2847 diag::warn_attribute_precede_definition); 2848 S.Diag(Def->getLocation(), diag::note_previous_definition); 2849 NewAttributes.erase(NewAttributes.begin() + I); 2850 --E; 2851 } 2852 } 2853 2854 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2855 const ConstInitAttr *CIAttr, 2856 bool AttrBeforeInit) { 2857 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2858 2859 // Figure out a good way to write this specifier on the old declaration. 2860 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2861 // enough of the attribute list spelling information to extract that without 2862 // heroics. 2863 std::string SuitableSpelling; 2864 if (S.getLangOpts().CPlusPlus20) 2865 SuitableSpelling = std::string( 2866 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2867 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2868 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2869 InsertLoc, {tok::l_square, tok::l_square, 2870 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2871 S.PP.getIdentifierInfo("require_constant_initialization"), 2872 tok::r_square, tok::r_square})); 2873 if (SuitableSpelling.empty()) 2874 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2875 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2876 S.PP.getIdentifierInfo("require_constant_initialization"), 2877 tok::r_paren, tok::r_paren})); 2878 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2879 SuitableSpelling = "constinit"; 2880 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2881 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2882 if (SuitableSpelling.empty()) 2883 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2884 SuitableSpelling += " "; 2885 2886 if (AttrBeforeInit) { 2887 // extern constinit int a; 2888 // int a = 0; // error (missing 'constinit'), accepted as extension 2889 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2890 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2891 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2892 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2893 } else { 2894 // int a = 0; 2895 // constinit extern int a; // error (missing 'constinit') 2896 S.Diag(CIAttr->getLocation(), 2897 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2898 : diag::warn_require_const_init_added_too_late) 2899 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2900 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2901 << CIAttr->isConstinit() 2902 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2903 } 2904 } 2905 2906 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2907 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2908 AvailabilityMergeKind AMK) { 2909 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2910 UsedAttr *NewAttr = OldAttr->clone(Context); 2911 NewAttr->setInherited(true); 2912 New->addAttr(NewAttr); 2913 } 2914 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2915 RetainAttr *NewAttr = OldAttr->clone(Context); 2916 NewAttr->setInherited(true); 2917 New->addAttr(NewAttr); 2918 } 2919 2920 if (!Old->hasAttrs() && !New->hasAttrs()) 2921 return; 2922 2923 // [dcl.constinit]p1: 2924 // If the [constinit] specifier is applied to any declaration of a 2925 // variable, it shall be applied to the initializing declaration. 2926 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2927 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2928 if (bool(OldConstInit) != bool(NewConstInit)) { 2929 const auto *OldVD = cast<VarDecl>(Old); 2930 auto *NewVD = cast<VarDecl>(New); 2931 2932 // Find the initializing declaration. Note that we might not have linked 2933 // the new declaration into the redeclaration chain yet. 2934 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2935 if (!InitDecl && 2936 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2937 InitDecl = NewVD; 2938 2939 if (InitDecl == NewVD) { 2940 // This is the initializing declaration. If it would inherit 'constinit', 2941 // that's ill-formed. (Note that we do not apply this to the attribute 2942 // form). 2943 if (OldConstInit && OldConstInit->isConstinit()) 2944 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2945 /*AttrBeforeInit=*/true); 2946 } else if (NewConstInit) { 2947 // This is the first time we've been told that this declaration should 2948 // have a constant initializer. If we already saw the initializing 2949 // declaration, this is too late. 2950 if (InitDecl && InitDecl != NewVD) { 2951 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2952 /*AttrBeforeInit=*/false); 2953 NewVD->dropAttr<ConstInitAttr>(); 2954 } 2955 } 2956 } 2957 2958 // Attributes declared post-definition are currently ignored. 2959 checkNewAttributesAfterDef(*this, New, Old); 2960 2961 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2962 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2963 if (!OldA->isEquivalent(NewA)) { 2964 // This redeclaration changes __asm__ label. 2965 Diag(New->getLocation(), diag::err_different_asm_label); 2966 Diag(OldA->getLocation(), diag::note_previous_declaration); 2967 } 2968 } else if (Old->isUsed()) { 2969 // This redeclaration adds an __asm__ label to a declaration that has 2970 // already been ODR-used. 2971 Diag(New->getLocation(), diag::err_late_asm_label_name) 2972 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2973 } 2974 } 2975 2976 // Re-declaration cannot add abi_tag's. 2977 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2978 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2979 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2980 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 2981 Diag(NewAbiTagAttr->getLocation(), 2982 diag::err_new_abi_tag_on_redeclaration) 2983 << NewTag; 2984 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2985 } 2986 } 2987 } else { 2988 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2989 Diag(Old->getLocation(), diag::note_previous_declaration); 2990 } 2991 } 2992 2993 // This redeclaration adds a section attribute. 2994 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2995 if (auto *VD = dyn_cast<VarDecl>(New)) { 2996 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2997 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2998 Diag(Old->getLocation(), diag::note_previous_declaration); 2999 } 3000 } 3001 } 3002 3003 // Redeclaration adds code-seg attribute. 3004 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3005 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3006 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3007 Diag(New->getLocation(), diag::warn_mismatched_section) 3008 << 0 /*codeseg*/; 3009 Diag(Old->getLocation(), diag::note_previous_declaration); 3010 } 3011 3012 if (!Old->hasAttrs()) 3013 return; 3014 3015 bool foundAny = New->hasAttrs(); 3016 3017 // Ensure that any moving of objects within the allocated map is done before 3018 // we process them. 3019 if (!foundAny) New->setAttrs(AttrVec()); 3020 3021 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3022 // Ignore deprecated/unavailable/availability attributes if requested. 3023 AvailabilityMergeKind LocalAMK = AMK_None; 3024 if (isa<DeprecatedAttr>(I) || 3025 isa<UnavailableAttr>(I) || 3026 isa<AvailabilityAttr>(I)) { 3027 switch (AMK) { 3028 case AMK_None: 3029 continue; 3030 3031 case AMK_Redeclaration: 3032 case AMK_Override: 3033 case AMK_ProtocolImplementation: 3034 case AMK_OptionalProtocolImplementation: 3035 LocalAMK = AMK; 3036 break; 3037 } 3038 } 3039 3040 // Already handled. 3041 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3042 continue; 3043 3044 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3045 foundAny = true; 3046 } 3047 3048 if (mergeAlignedAttrs(*this, New, Old)) 3049 foundAny = true; 3050 3051 if (!foundAny) New->dropAttrs(); 3052 } 3053 3054 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3055 /// to the new one. 3056 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3057 const ParmVarDecl *oldDecl, 3058 Sema &S) { 3059 // C++11 [dcl.attr.depend]p2: 3060 // The first declaration of a function shall specify the 3061 // carries_dependency attribute for its declarator-id if any declaration 3062 // of the function specifies the carries_dependency attribute. 3063 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3064 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3065 S.Diag(CDA->getLocation(), 3066 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3067 // Find the first declaration of the parameter. 3068 // FIXME: Should we build redeclaration chains for function parameters? 3069 const FunctionDecl *FirstFD = 3070 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3071 const ParmVarDecl *FirstVD = 3072 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3073 S.Diag(FirstVD->getLocation(), 3074 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3075 } 3076 3077 if (!oldDecl->hasAttrs()) 3078 return; 3079 3080 bool foundAny = newDecl->hasAttrs(); 3081 3082 // Ensure that any moving of objects within the allocated map is 3083 // done before we process them. 3084 if (!foundAny) newDecl->setAttrs(AttrVec()); 3085 3086 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3087 if (!DeclHasAttr(newDecl, I)) { 3088 InheritableAttr *newAttr = 3089 cast<InheritableParamAttr>(I->clone(S.Context)); 3090 newAttr->setInherited(true); 3091 newDecl->addAttr(newAttr); 3092 foundAny = true; 3093 } 3094 } 3095 3096 if (!foundAny) newDecl->dropAttrs(); 3097 } 3098 3099 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3100 const ParmVarDecl *OldParam, 3101 Sema &S) { 3102 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3103 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3104 if (*Oldnullability != *Newnullability) { 3105 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3106 << DiagNullabilityKind( 3107 *Newnullability, 3108 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3109 != 0)) 3110 << DiagNullabilityKind( 3111 *Oldnullability, 3112 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3113 != 0)); 3114 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3115 } 3116 } else { 3117 QualType NewT = NewParam->getType(); 3118 NewT = S.Context.getAttributedType( 3119 AttributedType::getNullabilityAttrKind(*Oldnullability), 3120 NewT, NewT); 3121 NewParam->setType(NewT); 3122 } 3123 } 3124 } 3125 3126 namespace { 3127 3128 /// Used in MergeFunctionDecl to keep track of function parameters in 3129 /// C. 3130 struct GNUCompatibleParamWarning { 3131 ParmVarDecl *OldParm; 3132 ParmVarDecl *NewParm; 3133 QualType PromotedType; 3134 }; 3135 3136 } // end anonymous namespace 3137 3138 // Determine whether the previous declaration was a definition, implicit 3139 // declaration, or a declaration. 3140 template <typename T> 3141 static std::pair<diag::kind, SourceLocation> 3142 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3143 diag::kind PrevDiag; 3144 SourceLocation OldLocation = Old->getLocation(); 3145 if (Old->isThisDeclarationADefinition()) 3146 PrevDiag = diag::note_previous_definition; 3147 else if (Old->isImplicit()) { 3148 PrevDiag = diag::note_previous_implicit_declaration; 3149 if (OldLocation.isInvalid()) 3150 OldLocation = New->getLocation(); 3151 } else 3152 PrevDiag = diag::note_previous_declaration; 3153 return std::make_pair(PrevDiag, OldLocation); 3154 } 3155 3156 /// canRedefineFunction - checks if a function can be redefined. Currently, 3157 /// only extern inline functions can be redefined, and even then only in 3158 /// GNU89 mode. 3159 static bool canRedefineFunction(const FunctionDecl *FD, 3160 const LangOptions& LangOpts) { 3161 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3162 !LangOpts.CPlusPlus && 3163 FD->isInlineSpecified() && 3164 FD->getStorageClass() == SC_Extern); 3165 } 3166 3167 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3168 const AttributedType *AT = T->getAs<AttributedType>(); 3169 while (AT && !AT->isCallingConv()) 3170 AT = AT->getModifiedType()->getAs<AttributedType>(); 3171 return AT; 3172 } 3173 3174 template <typename T> 3175 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3176 const DeclContext *DC = Old->getDeclContext(); 3177 if (DC->isRecord()) 3178 return false; 3179 3180 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3181 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3182 return true; 3183 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3184 return true; 3185 return false; 3186 } 3187 3188 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3189 static bool isExternC(VarTemplateDecl *) { return false; } 3190 static bool isExternC(FunctionTemplateDecl *) { return false; } 3191 3192 /// Check whether a redeclaration of an entity introduced by a 3193 /// using-declaration is valid, given that we know it's not an overload 3194 /// (nor a hidden tag declaration). 3195 template<typename ExpectedDecl> 3196 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3197 ExpectedDecl *New) { 3198 // C++11 [basic.scope.declarative]p4: 3199 // Given a set of declarations in a single declarative region, each of 3200 // which specifies the same unqualified name, 3201 // -- they shall all refer to the same entity, or all refer to functions 3202 // and function templates; or 3203 // -- exactly one declaration shall declare a class name or enumeration 3204 // name that is not a typedef name and the other declarations shall all 3205 // refer to the same variable or enumerator, or all refer to functions 3206 // and function templates; in this case the class name or enumeration 3207 // name is hidden (3.3.10). 3208 3209 // C++11 [namespace.udecl]p14: 3210 // If a function declaration in namespace scope or block scope has the 3211 // same name and the same parameter-type-list as a function introduced 3212 // by a using-declaration, and the declarations do not declare the same 3213 // function, the program is ill-formed. 3214 3215 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3216 if (Old && 3217 !Old->getDeclContext()->getRedeclContext()->Equals( 3218 New->getDeclContext()->getRedeclContext()) && 3219 !(isExternC(Old) && isExternC(New))) 3220 Old = nullptr; 3221 3222 if (!Old) { 3223 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3224 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3225 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3226 return true; 3227 } 3228 return false; 3229 } 3230 3231 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3232 const FunctionDecl *B) { 3233 assert(A->getNumParams() == B->getNumParams()); 3234 3235 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3236 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3237 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3238 if (AttrA == AttrB) 3239 return true; 3240 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3241 AttrA->isDynamic() == AttrB->isDynamic(); 3242 }; 3243 3244 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3245 } 3246 3247 /// If necessary, adjust the semantic declaration context for a qualified 3248 /// declaration to name the correct inline namespace within the qualifier. 3249 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3250 DeclaratorDecl *OldD) { 3251 // The only case where we need to update the DeclContext is when 3252 // redeclaration lookup for a qualified name finds a declaration 3253 // in an inline namespace within the context named by the qualifier: 3254 // 3255 // inline namespace N { int f(); } 3256 // int ::f(); // Sema DC needs adjusting from :: to N::. 3257 // 3258 // For unqualified declarations, the semantic context *can* change 3259 // along the redeclaration chain (for local extern declarations, 3260 // extern "C" declarations, and friend declarations in particular). 3261 if (!NewD->getQualifier()) 3262 return; 3263 3264 // NewD is probably already in the right context. 3265 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3266 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3267 if (NamedDC->Equals(SemaDC)) 3268 return; 3269 3270 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3271 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3272 "unexpected context for redeclaration"); 3273 3274 auto *LexDC = NewD->getLexicalDeclContext(); 3275 auto FixSemaDC = [=](NamedDecl *D) { 3276 if (!D) 3277 return; 3278 D->setDeclContext(SemaDC); 3279 D->setLexicalDeclContext(LexDC); 3280 }; 3281 3282 FixSemaDC(NewD); 3283 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3284 FixSemaDC(FD->getDescribedFunctionTemplate()); 3285 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3286 FixSemaDC(VD->getDescribedVarTemplate()); 3287 } 3288 3289 /// MergeFunctionDecl - We just parsed a function 'New' from 3290 /// declarator D which has the same name and scope as a previous 3291 /// declaration 'Old'. Figure out how to resolve this situation, 3292 /// merging decls or emitting diagnostics as appropriate. 3293 /// 3294 /// In C++, New and Old must be declarations that are not 3295 /// overloaded. Use IsOverload to determine whether New and Old are 3296 /// overloaded, and to select the Old declaration that New should be 3297 /// merged with. 3298 /// 3299 /// Returns true if there was an error, false otherwise. 3300 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3301 Scope *S, bool MergeTypeWithOld) { 3302 // Verify the old decl was also a function. 3303 FunctionDecl *Old = OldD->getAsFunction(); 3304 if (!Old) { 3305 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3306 if (New->getFriendObjectKind()) { 3307 Diag(New->getLocation(), diag::err_using_decl_friend); 3308 Diag(Shadow->getTargetDecl()->getLocation(), 3309 diag::note_using_decl_target); 3310 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3311 << 0; 3312 return true; 3313 } 3314 3315 // Check whether the two declarations might declare the same function or 3316 // function template. 3317 if (FunctionTemplateDecl *NewTemplate = 3318 New->getDescribedFunctionTemplate()) { 3319 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3320 NewTemplate)) 3321 return true; 3322 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3323 ->getAsFunction(); 3324 } else { 3325 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3326 return true; 3327 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3328 } 3329 } else { 3330 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3331 << New->getDeclName(); 3332 notePreviousDefinition(OldD, New->getLocation()); 3333 return true; 3334 } 3335 } 3336 3337 // If the old declaration was found in an inline namespace and the new 3338 // declaration was qualified, update the DeclContext to match. 3339 adjustDeclContextForDeclaratorDecl(New, Old); 3340 3341 // If the old declaration is invalid, just give up here. 3342 if (Old->isInvalidDecl()) 3343 return true; 3344 3345 // Disallow redeclaration of some builtins. 3346 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3347 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3348 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3349 << Old << Old->getType(); 3350 return true; 3351 } 3352 3353 diag::kind PrevDiag; 3354 SourceLocation OldLocation; 3355 std::tie(PrevDiag, OldLocation) = 3356 getNoteDiagForInvalidRedeclaration(Old, New); 3357 3358 // Don't complain about this if we're in GNU89 mode and the old function 3359 // is an extern inline function. 3360 // Don't complain about specializations. They are not supposed to have 3361 // storage classes. 3362 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3363 New->getStorageClass() == SC_Static && 3364 Old->hasExternalFormalLinkage() && 3365 !New->getTemplateSpecializationInfo() && 3366 !canRedefineFunction(Old, getLangOpts())) { 3367 if (getLangOpts().MicrosoftExt) { 3368 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3369 Diag(OldLocation, PrevDiag); 3370 } else { 3371 Diag(New->getLocation(), diag::err_static_non_static) << New; 3372 Diag(OldLocation, PrevDiag); 3373 return true; 3374 } 3375 } 3376 3377 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3378 if (!Old->hasAttr<InternalLinkageAttr>()) { 3379 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3380 << ILA; 3381 Diag(Old->getLocation(), diag::note_previous_declaration); 3382 New->dropAttr<InternalLinkageAttr>(); 3383 } 3384 3385 if (auto *EA = New->getAttr<ErrorAttr>()) { 3386 if (!Old->hasAttr<ErrorAttr>()) { 3387 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3388 Diag(Old->getLocation(), diag::note_previous_declaration); 3389 New->dropAttr<ErrorAttr>(); 3390 } 3391 } 3392 3393 if (CheckRedeclarationModuleOwnership(New, Old)) 3394 return true; 3395 3396 if (!getLangOpts().CPlusPlus) { 3397 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3398 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3399 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3400 << New << OldOvl; 3401 3402 // Try our best to find a decl that actually has the overloadable 3403 // attribute for the note. In most cases (e.g. programs with only one 3404 // broken declaration/definition), this won't matter. 3405 // 3406 // FIXME: We could do this if we juggled some extra state in 3407 // OverloadableAttr, rather than just removing it. 3408 const Decl *DiagOld = Old; 3409 if (OldOvl) { 3410 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3411 const auto *A = D->getAttr<OverloadableAttr>(); 3412 return A && !A->isImplicit(); 3413 }); 3414 // If we've implicitly added *all* of the overloadable attrs to this 3415 // chain, emitting a "previous redecl" note is pointless. 3416 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3417 } 3418 3419 if (DiagOld) 3420 Diag(DiagOld->getLocation(), 3421 diag::note_attribute_overloadable_prev_overload) 3422 << OldOvl; 3423 3424 if (OldOvl) 3425 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3426 else 3427 New->dropAttr<OverloadableAttr>(); 3428 } 3429 } 3430 3431 // If a function is first declared with a calling convention, but is later 3432 // declared or defined without one, all following decls assume the calling 3433 // convention of the first. 3434 // 3435 // It's OK if a function is first declared without a calling convention, 3436 // but is later declared or defined with the default calling convention. 3437 // 3438 // To test if either decl has an explicit calling convention, we look for 3439 // AttributedType sugar nodes on the type as written. If they are missing or 3440 // were canonicalized away, we assume the calling convention was implicit. 3441 // 3442 // Note also that we DO NOT return at this point, because we still have 3443 // other tests to run. 3444 QualType OldQType = Context.getCanonicalType(Old->getType()); 3445 QualType NewQType = Context.getCanonicalType(New->getType()); 3446 const FunctionType *OldType = cast<FunctionType>(OldQType); 3447 const FunctionType *NewType = cast<FunctionType>(NewQType); 3448 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3449 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3450 bool RequiresAdjustment = false; 3451 3452 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3453 FunctionDecl *First = Old->getFirstDecl(); 3454 const FunctionType *FT = 3455 First->getType().getCanonicalType()->castAs<FunctionType>(); 3456 FunctionType::ExtInfo FI = FT->getExtInfo(); 3457 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3458 if (!NewCCExplicit) { 3459 // Inherit the CC from the previous declaration if it was specified 3460 // there but not here. 3461 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3462 RequiresAdjustment = true; 3463 } else if (Old->getBuiltinID()) { 3464 // Builtin attribute isn't propagated to the new one yet at this point, 3465 // so we check if the old one is a builtin. 3466 3467 // Calling Conventions on a Builtin aren't really useful and setting a 3468 // default calling convention and cdecl'ing some builtin redeclarations is 3469 // common, so warn and ignore the calling convention on the redeclaration. 3470 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3471 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3472 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3473 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3474 RequiresAdjustment = true; 3475 } else { 3476 // Calling conventions aren't compatible, so complain. 3477 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3478 Diag(New->getLocation(), diag::err_cconv_change) 3479 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3480 << !FirstCCExplicit 3481 << (!FirstCCExplicit ? "" : 3482 FunctionType::getNameForCallConv(FI.getCC())); 3483 3484 // Put the note on the first decl, since it is the one that matters. 3485 Diag(First->getLocation(), diag::note_previous_declaration); 3486 return true; 3487 } 3488 } 3489 3490 // FIXME: diagnose the other way around? 3491 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3492 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3493 RequiresAdjustment = true; 3494 } 3495 3496 // Merge regparm attribute. 3497 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3498 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3499 if (NewTypeInfo.getHasRegParm()) { 3500 Diag(New->getLocation(), diag::err_regparm_mismatch) 3501 << NewType->getRegParmType() 3502 << OldType->getRegParmType(); 3503 Diag(OldLocation, diag::note_previous_declaration); 3504 return true; 3505 } 3506 3507 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3508 RequiresAdjustment = true; 3509 } 3510 3511 // Merge ns_returns_retained attribute. 3512 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3513 if (NewTypeInfo.getProducesResult()) { 3514 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3515 << "'ns_returns_retained'"; 3516 Diag(OldLocation, diag::note_previous_declaration); 3517 return true; 3518 } 3519 3520 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3521 RequiresAdjustment = true; 3522 } 3523 3524 if (OldTypeInfo.getNoCallerSavedRegs() != 3525 NewTypeInfo.getNoCallerSavedRegs()) { 3526 if (NewTypeInfo.getNoCallerSavedRegs()) { 3527 AnyX86NoCallerSavedRegistersAttr *Attr = 3528 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3529 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3530 Diag(OldLocation, diag::note_previous_declaration); 3531 return true; 3532 } 3533 3534 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3535 RequiresAdjustment = true; 3536 } 3537 3538 if (RequiresAdjustment) { 3539 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3540 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3541 New->setType(QualType(AdjustedType, 0)); 3542 NewQType = Context.getCanonicalType(New->getType()); 3543 } 3544 3545 // If this redeclaration makes the function inline, we may need to add it to 3546 // UndefinedButUsed. 3547 if (!Old->isInlined() && New->isInlined() && 3548 !New->hasAttr<GNUInlineAttr>() && 3549 !getLangOpts().GNUInline && 3550 Old->isUsed(false) && 3551 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3552 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3553 SourceLocation())); 3554 3555 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3556 // about it. 3557 if (New->hasAttr<GNUInlineAttr>() && 3558 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3559 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3560 } 3561 3562 // If pass_object_size params don't match up perfectly, this isn't a valid 3563 // redeclaration. 3564 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3565 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3566 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3567 << New->getDeclName(); 3568 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3569 return true; 3570 } 3571 3572 if (getLangOpts().CPlusPlus) { 3573 // C++1z [over.load]p2 3574 // Certain function declarations cannot be overloaded: 3575 // -- Function declarations that differ only in the return type, 3576 // the exception specification, or both cannot be overloaded. 3577 3578 // Check the exception specifications match. This may recompute the type of 3579 // both Old and New if it resolved exception specifications, so grab the 3580 // types again after this. Because this updates the type, we do this before 3581 // any of the other checks below, which may update the "de facto" NewQType 3582 // but do not necessarily update the type of New. 3583 if (CheckEquivalentExceptionSpec(Old, New)) 3584 return true; 3585 OldQType = Context.getCanonicalType(Old->getType()); 3586 NewQType = Context.getCanonicalType(New->getType()); 3587 3588 // Go back to the type source info to compare the declared return types, 3589 // per C++1y [dcl.type.auto]p13: 3590 // Redeclarations or specializations of a function or function template 3591 // with a declared return type that uses a placeholder type shall also 3592 // use that placeholder, not a deduced type. 3593 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3594 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3595 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3596 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3597 OldDeclaredReturnType)) { 3598 QualType ResQT; 3599 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3600 OldDeclaredReturnType->isObjCObjectPointerType()) 3601 // FIXME: This does the wrong thing for a deduced return type. 3602 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3603 if (ResQT.isNull()) { 3604 if (New->isCXXClassMember() && New->isOutOfLine()) 3605 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3606 << New << New->getReturnTypeSourceRange(); 3607 else 3608 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3609 << New->getReturnTypeSourceRange(); 3610 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3611 << Old->getReturnTypeSourceRange(); 3612 return true; 3613 } 3614 else 3615 NewQType = ResQT; 3616 } 3617 3618 QualType OldReturnType = OldType->getReturnType(); 3619 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3620 if (OldReturnType != NewReturnType) { 3621 // If this function has a deduced return type and has already been 3622 // defined, copy the deduced value from the old declaration. 3623 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3624 if (OldAT && OldAT->isDeduced()) { 3625 QualType DT = OldAT->getDeducedType(); 3626 if (DT.isNull()) { 3627 New->setType(SubstAutoTypeDependent(New->getType())); 3628 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3629 } else { 3630 New->setType(SubstAutoType(New->getType(), DT)); 3631 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3632 } 3633 } 3634 } 3635 3636 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3637 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3638 if (OldMethod && NewMethod) { 3639 // Preserve triviality. 3640 NewMethod->setTrivial(OldMethod->isTrivial()); 3641 3642 // MSVC allows explicit template specialization at class scope: 3643 // 2 CXXMethodDecls referring to the same function will be injected. 3644 // We don't want a redeclaration error. 3645 bool IsClassScopeExplicitSpecialization = 3646 OldMethod->isFunctionTemplateSpecialization() && 3647 NewMethod->isFunctionTemplateSpecialization(); 3648 bool isFriend = NewMethod->getFriendObjectKind(); 3649 3650 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3651 !IsClassScopeExplicitSpecialization) { 3652 // -- Member function declarations with the same name and the 3653 // same parameter types cannot be overloaded if any of them 3654 // is a static member function declaration. 3655 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3656 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3657 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3658 return true; 3659 } 3660 3661 // C++ [class.mem]p1: 3662 // [...] A member shall not be declared twice in the 3663 // member-specification, except that a nested class or member 3664 // class template can be declared and then later defined. 3665 if (!inTemplateInstantiation()) { 3666 unsigned NewDiag; 3667 if (isa<CXXConstructorDecl>(OldMethod)) 3668 NewDiag = diag::err_constructor_redeclared; 3669 else if (isa<CXXDestructorDecl>(NewMethod)) 3670 NewDiag = diag::err_destructor_redeclared; 3671 else if (isa<CXXConversionDecl>(NewMethod)) 3672 NewDiag = diag::err_conv_function_redeclared; 3673 else 3674 NewDiag = diag::err_member_redeclared; 3675 3676 Diag(New->getLocation(), NewDiag); 3677 } else { 3678 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3679 << New << New->getType(); 3680 } 3681 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3682 return true; 3683 3684 // Complain if this is an explicit declaration of a special 3685 // member that was initially declared implicitly. 3686 // 3687 // As an exception, it's okay to befriend such methods in order 3688 // to permit the implicit constructor/destructor/operator calls. 3689 } else if (OldMethod->isImplicit()) { 3690 if (isFriend) { 3691 NewMethod->setImplicit(); 3692 } else { 3693 Diag(NewMethod->getLocation(), 3694 diag::err_definition_of_implicitly_declared_member) 3695 << New << getSpecialMember(OldMethod); 3696 return true; 3697 } 3698 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3699 Diag(NewMethod->getLocation(), 3700 diag::err_definition_of_explicitly_defaulted_member) 3701 << getSpecialMember(OldMethod); 3702 return true; 3703 } 3704 } 3705 3706 // C++11 [dcl.attr.noreturn]p1: 3707 // The first declaration of a function shall specify the noreturn 3708 // attribute if any declaration of that function specifies the noreturn 3709 // attribute. 3710 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3711 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3712 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3713 << NRA; 3714 Diag(Old->getLocation(), diag::note_previous_declaration); 3715 } 3716 3717 // C++11 [dcl.attr.depend]p2: 3718 // The first declaration of a function shall specify the 3719 // carries_dependency attribute for its declarator-id if any declaration 3720 // of the function specifies the carries_dependency attribute. 3721 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3722 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3723 Diag(CDA->getLocation(), 3724 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3725 Diag(Old->getFirstDecl()->getLocation(), 3726 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3727 } 3728 3729 // (C++98 8.3.5p3): 3730 // All declarations for a function shall agree exactly in both the 3731 // return type and the parameter-type-list. 3732 // We also want to respect all the extended bits except noreturn. 3733 3734 // noreturn should now match unless the old type info didn't have it. 3735 QualType OldQTypeForComparison = OldQType; 3736 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3737 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3738 const FunctionType *OldTypeForComparison 3739 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3740 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3741 assert(OldQTypeForComparison.isCanonical()); 3742 } 3743 3744 if (haveIncompatibleLanguageLinkages(Old, New)) { 3745 // As a special case, retain the language linkage from previous 3746 // declarations of a friend function as an extension. 3747 // 3748 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3749 // and is useful because there's otherwise no way to specify language 3750 // linkage within class scope. 3751 // 3752 // Check cautiously as the friend object kind isn't yet complete. 3753 if (New->getFriendObjectKind() != Decl::FOK_None) { 3754 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3755 Diag(OldLocation, PrevDiag); 3756 } else { 3757 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3758 Diag(OldLocation, PrevDiag); 3759 return true; 3760 } 3761 } 3762 3763 // If the function types are compatible, merge the declarations. Ignore the 3764 // exception specifier because it was already checked above in 3765 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3766 // about incompatible types under -fms-compatibility. 3767 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3768 NewQType)) 3769 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3770 3771 // If the types are imprecise (due to dependent constructs in friends or 3772 // local extern declarations), it's OK if they differ. We'll check again 3773 // during instantiation. 3774 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3775 return false; 3776 3777 // Fall through for conflicting redeclarations and redefinitions. 3778 } 3779 3780 // C: Function types need to be compatible, not identical. This handles 3781 // duplicate function decls like "void f(int); void f(enum X);" properly. 3782 if (!getLangOpts().CPlusPlus && 3783 Context.typesAreCompatible(OldQType, NewQType)) { 3784 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3785 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3786 const FunctionProtoType *OldProto = nullptr; 3787 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3788 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3789 // The old declaration provided a function prototype, but the 3790 // new declaration does not. Merge in the prototype. 3791 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3792 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3793 NewQType = 3794 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3795 OldProto->getExtProtoInfo()); 3796 New->setType(NewQType); 3797 New->setHasInheritedPrototype(); 3798 3799 // Synthesize parameters with the same types. 3800 SmallVector<ParmVarDecl*, 16> Params; 3801 for (const auto &ParamType : OldProto->param_types()) { 3802 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3803 SourceLocation(), nullptr, 3804 ParamType, /*TInfo=*/nullptr, 3805 SC_None, nullptr); 3806 Param->setScopeInfo(0, Params.size()); 3807 Param->setImplicit(); 3808 Params.push_back(Param); 3809 } 3810 3811 New->setParams(Params); 3812 } 3813 3814 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3815 } 3816 3817 // Check if the function types are compatible when pointer size address 3818 // spaces are ignored. 3819 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3820 return false; 3821 3822 // GNU C permits a K&R definition to follow a prototype declaration 3823 // if the declared types of the parameters in the K&R definition 3824 // match the types in the prototype declaration, even when the 3825 // promoted types of the parameters from the K&R definition differ 3826 // from the types in the prototype. GCC then keeps the types from 3827 // the prototype. 3828 // 3829 // If a variadic prototype is followed by a non-variadic K&R definition, 3830 // the K&R definition becomes variadic. This is sort of an edge case, but 3831 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3832 // C99 6.9.1p8. 3833 if (!getLangOpts().CPlusPlus && 3834 Old->hasPrototype() && !New->hasPrototype() && 3835 New->getType()->getAs<FunctionProtoType>() && 3836 Old->getNumParams() == New->getNumParams()) { 3837 SmallVector<QualType, 16> ArgTypes; 3838 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3839 const FunctionProtoType *OldProto 3840 = Old->getType()->getAs<FunctionProtoType>(); 3841 const FunctionProtoType *NewProto 3842 = New->getType()->getAs<FunctionProtoType>(); 3843 3844 // Determine whether this is the GNU C extension. 3845 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3846 NewProto->getReturnType()); 3847 bool LooseCompatible = !MergedReturn.isNull(); 3848 for (unsigned Idx = 0, End = Old->getNumParams(); 3849 LooseCompatible && Idx != End; ++Idx) { 3850 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3851 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3852 if (Context.typesAreCompatible(OldParm->getType(), 3853 NewProto->getParamType(Idx))) { 3854 ArgTypes.push_back(NewParm->getType()); 3855 } else if (Context.typesAreCompatible(OldParm->getType(), 3856 NewParm->getType(), 3857 /*CompareUnqualified=*/true)) { 3858 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3859 NewProto->getParamType(Idx) }; 3860 Warnings.push_back(Warn); 3861 ArgTypes.push_back(NewParm->getType()); 3862 } else 3863 LooseCompatible = false; 3864 } 3865 3866 if (LooseCompatible) { 3867 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3868 Diag(Warnings[Warn].NewParm->getLocation(), 3869 diag::ext_param_promoted_not_compatible_with_prototype) 3870 << Warnings[Warn].PromotedType 3871 << Warnings[Warn].OldParm->getType(); 3872 if (Warnings[Warn].OldParm->getLocation().isValid()) 3873 Diag(Warnings[Warn].OldParm->getLocation(), 3874 diag::note_previous_declaration); 3875 } 3876 3877 if (MergeTypeWithOld) 3878 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3879 OldProto->getExtProtoInfo())); 3880 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3881 } 3882 3883 // Fall through to diagnose conflicting types. 3884 } 3885 3886 // A function that has already been declared has been redeclared or 3887 // defined with a different type; show an appropriate diagnostic. 3888 3889 // If the previous declaration was an implicitly-generated builtin 3890 // declaration, then at the very least we should use a specialized note. 3891 unsigned BuiltinID; 3892 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3893 // If it's actually a library-defined builtin function like 'malloc' 3894 // or 'printf', just warn about the incompatible redeclaration. 3895 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3896 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3897 Diag(OldLocation, diag::note_previous_builtin_declaration) 3898 << Old << Old->getType(); 3899 return false; 3900 } 3901 3902 PrevDiag = diag::note_previous_builtin_declaration; 3903 } 3904 3905 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3906 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3907 return true; 3908 } 3909 3910 /// Completes the merge of two function declarations that are 3911 /// known to be compatible. 3912 /// 3913 /// This routine handles the merging of attributes and other 3914 /// properties of function declarations from the old declaration to 3915 /// the new declaration, once we know that New is in fact a 3916 /// redeclaration of Old. 3917 /// 3918 /// \returns false 3919 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3920 Scope *S, bool MergeTypeWithOld) { 3921 // Merge the attributes 3922 mergeDeclAttributes(New, Old); 3923 3924 // Merge "pure" flag. 3925 if (Old->isPure()) 3926 New->setPure(); 3927 3928 // Merge "used" flag. 3929 if (Old->getMostRecentDecl()->isUsed(false)) 3930 New->setIsUsed(); 3931 3932 // Merge attributes from the parameters. These can mismatch with K&R 3933 // declarations. 3934 if (New->getNumParams() == Old->getNumParams()) 3935 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3936 ParmVarDecl *NewParam = New->getParamDecl(i); 3937 ParmVarDecl *OldParam = Old->getParamDecl(i); 3938 mergeParamDeclAttributes(NewParam, OldParam, *this); 3939 mergeParamDeclTypes(NewParam, OldParam, *this); 3940 } 3941 3942 if (getLangOpts().CPlusPlus) 3943 return MergeCXXFunctionDecl(New, Old, S); 3944 3945 // Merge the function types so the we get the composite types for the return 3946 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3947 // was visible. 3948 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3949 if (!Merged.isNull() && MergeTypeWithOld) 3950 New->setType(Merged); 3951 3952 return false; 3953 } 3954 3955 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3956 ObjCMethodDecl *oldMethod) { 3957 // Merge the attributes, including deprecated/unavailable 3958 AvailabilityMergeKind MergeKind = 3959 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3960 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 3961 : AMK_ProtocolImplementation) 3962 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3963 : AMK_Override; 3964 3965 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3966 3967 // Merge attributes from the parameters. 3968 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3969 oe = oldMethod->param_end(); 3970 for (ObjCMethodDecl::param_iterator 3971 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3972 ni != ne && oi != oe; ++ni, ++oi) 3973 mergeParamDeclAttributes(*ni, *oi, *this); 3974 3975 CheckObjCMethodOverride(newMethod, oldMethod); 3976 } 3977 3978 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3979 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3980 3981 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3982 ? diag::err_redefinition_different_type 3983 : diag::err_redeclaration_different_type) 3984 << New->getDeclName() << New->getType() << Old->getType(); 3985 3986 diag::kind PrevDiag; 3987 SourceLocation OldLocation; 3988 std::tie(PrevDiag, OldLocation) 3989 = getNoteDiagForInvalidRedeclaration(Old, New); 3990 S.Diag(OldLocation, PrevDiag); 3991 New->setInvalidDecl(); 3992 } 3993 3994 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3995 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3996 /// emitting diagnostics as appropriate. 3997 /// 3998 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3999 /// to here in AddInitializerToDecl. We can't check them before the initializer 4000 /// is attached. 4001 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4002 bool MergeTypeWithOld) { 4003 if (New->isInvalidDecl() || Old->isInvalidDecl()) 4004 return; 4005 4006 QualType MergedT; 4007 if (getLangOpts().CPlusPlus) { 4008 if (New->getType()->isUndeducedType()) { 4009 // We don't know what the new type is until the initializer is attached. 4010 return; 4011 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4012 // These could still be something that needs exception specs checked. 4013 return MergeVarDeclExceptionSpecs(New, Old); 4014 } 4015 // C++ [basic.link]p10: 4016 // [...] the types specified by all declarations referring to a given 4017 // object or function shall be identical, except that declarations for an 4018 // array object can specify array types that differ by the presence or 4019 // absence of a major array bound (8.3.4). 4020 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4021 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4022 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4023 4024 // We are merging a variable declaration New into Old. If it has an array 4025 // bound, and that bound differs from Old's bound, we should diagnose the 4026 // mismatch. 4027 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4028 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4029 PrevVD = PrevVD->getPreviousDecl()) { 4030 QualType PrevVDTy = PrevVD->getType(); 4031 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4032 continue; 4033 4034 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4035 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4036 } 4037 } 4038 4039 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4040 if (Context.hasSameType(OldArray->getElementType(), 4041 NewArray->getElementType())) 4042 MergedT = New->getType(); 4043 } 4044 // FIXME: Check visibility. New is hidden but has a complete type. If New 4045 // has no array bound, it should not inherit one from Old, if Old is not 4046 // visible. 4047 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4048 if (Context.hasSameType(OldArray->getElementType(), 4049 NewArray->getElementType())) 4050 MergedT = Old->getType(); 4051 } 4052 } 4053 else if (New->getType()->isObjCObjectPointerType() && 4054 Old->getType()->isObjCObjectPointerType()) { 4055 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4056 Old->getType()); 4057 } 4058 } else { 4059 // C 6.2.7p2: 4060 // All declarations that refer to the same object or function shall have 4061 // compatible type. 4062 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4063 } 4064 if (MergedT.isNull()) { 4065 // It's OK if we couldn't merge types if either type is dependent, for a 4066 // block-scope variable. In other cases (static data members of class 4067 // templates, variable templates, ...), we require the types to be 4068 // equivalent. 4069 // FIXME: The C++ standard doesn't say anything about this. 4070 if ((New->getType()->isDependentType() || 4071 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4072 // If the old type was dependent, we can't merge with it, so the new type 4073 // becomes dependent for now. We'll reproduce the original type when we 4074 // instantiate the TypeSourceInfo for the variable. 4075 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4076 New->setType(Context.DependentTy); 4077 return; 4078 } 4079 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4080 } 4081 4082 // Don't actually update the type on the new declaration if the old 4083 // declaration was an extern declaration in a different scope. 4084 if (MergeTypeWithOld) 4085 New->setType(MergedT); 4086 } 4087 4088 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4089 LookupResult &Previous) { 4090 // C11 6.2.7p4: 4091 // For an identifier with internal or external linkage declared 4092 // in a scope in which a prior declaration of that identifier is 4093 // visible, if the prior declaration specifies internal or 4094 // external linkage, the type of the identifier at the later 4095 // declaration becomes the composite type. 4096 // 4097 // If the variable isn't visible, we do not merge with its type. 4098 if (Previous.isShadowed()) 4099 return false; 4100 4101 if (S.getLangOpts().CPlusPlus) { 4102 // C++11 [dcl.array]p3: 4103 // If there is a preceding declaration of the entity in the same 4104 // scope in which the bound was specified, an omitted array bound 4105 // is taken to be the same as in that earlier declaration. 4106 return NewVD->isPreviousDeclInSameBlockScope() || 4107 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4108 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4109 } else { 4110 // If the old declaration was function-local, don't merge with its 4111 // type unless we're in the same function. 4112 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4113 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4114 } 4115 } 4116 4117 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4118 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4119 /// situation, merging decls or emitting diagnostics as appropriate. 4120 /// 4121 /// Tentative definition rules (C99 6.9.2p2) are checked by 4122 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4123 /// definitions here, since the initializer hasn't been attached. 4124 /// 4125 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4126 // If the new decl is already invalid, don't do any other checking. 4127 if (New->isInvalidDecl()) 4128 return; 4129 4130 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4131 return; 4132 4133 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4134 4135 // Verify the old decl was also a variable or variable template. 4136 VarDecl *Old = nullptr; 4137 VarTemplateDecl *OldTemplate = nullptr; 4138 if (Previous.isSingleResult()) { 4139 if (NewTemplate) { 4140 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4141 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4142 4143 if (auto *Shadow = 4144 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4145 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4146 return New->setInvalidDecl(); 4147 } else { 4148 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4149 4150 if (auto *Shadow = 4151 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4152 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4153 return New->setInvalidDecl(); 4154 } 4155 } 4156 if (!Old) { 4157 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4158 << New->getDeclName(); 4159 notePreviousDefinition(Previous.getRepresentativeDecl(), 4160 New->getLocation()); 4161 return New->setInvalidDecl(); 4162 } 4163 4164 // If the old declaration was found in an inline namespace and the new 4165 // declaration was qualified, update the DeclContext to match. 4166 adjustDeclContextForDeclaratorDecl(New, Old); 4167 4168 // Ensure the template parameters are compatible. 4169 if (NewTemplate && 4170 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4171 OldTemplate->getTemplateParameters(), 4172 /*Complain=*/true, TPL_TemplateMatch)) 4173 return New->setInvalidDecl(); 4174 4175 // C++ [class.mem]p1: 4176 // A member shall not be declared twice in the member-specification [...] 4177 // 4178 // Here, we need only consider static data members. 4179 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4180 Diag(New->getLocation(), diag::err_duplicate_member) 4181 << New->getIdentifier(); 4182 Diag(Old->getLocation(), diag::note_previous_declaration); 4183 New->setInvalidDecl(); 4184 } 4185 4186 mergeDeclAttributes(New, Old); 4187 // Warn if an already-declared variable is made a weak_import in a subsequent 4188 // declaration 4189 if (New->hasAttr<WeakImportAttr>() && 4190 Old->getStorageClass() == SC_None && 4191 !Old->hasAttr<WeakImportAttr>()) { 4192 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4193 Diag(Old->getLocation(), diag::note_previous_declaration); 4194 // Remove weak_import attribute on new declaration. 4195 New->dropAttr<WeakImportAttr>(); 4196 } 4197 4198 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4199 if (!Old->hasAttr<InternalLinkageAttr>()) { 4200 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4201 << ILA; 4202 Diag(Old->getLocation(), diag::note_previous_declaration); 4203 New->dropAttr<InternalLinkageAttr>(); 4204 } 4205 4206 // Merge the types. 4207 VarDecl *MostRecent = Old->getMostRecentDecl(); 4208 if (MostRecent != Old) { 4209 MergeVarDeclTypes(New, MostRecent, 4210 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4211 if (New->isInvalidDecl()) 4212 return; 4213 } 4214 4215 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4216 if (New->isInvalidDecl()) 4217 return; 4218 4219 diag::kind PrevDiag; 4220 SourceLocation OldLocation; 4221 std::tie(PrevDiag, OldLocation) = 4222 getNoteDiagForInvalidRedeclaration(Old, New); 4223 4224 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4225 if (New->getStorageClass() == SC_Static && 4226 !New->isStaticDataMember() && 4227 Old->hasExternalFormalLinkage()) { 4228 if (getLangOpts().MicrosoftExt) { 4229 Diag(New->getLocation(), diag::ext_static_non_static) 4230 << New->getDeclName(); 4231 Diag(OldLocation, PrevDiag); 4232 } else { 4233 Diag(New->getLocation(), diag::err_static_non_static) 4234 << New->getDeclName(); 4235 Diag(OldLocation, PrevDiag); 4236 return New->setInvalidDecl(); 4237 } 4238 } 4239 // C99 6.2.2p4: 4240 // For an identifier declared with the storage-class specifier 4241 // extern in a scope in which a prior declaration of that 4242 // identifier is visible,23) if the prior declaration specifies 4243 // internal or external linkage, the linkage of the identifier at 4244 // the later declaration is the same as the linkage specified at 4245 // the prior declaration. If no prior declaration is visible, or 4246 // if the prior declaration specifies no linkage, then the 4247 // identifier has external linkage. 4248 if (New->hasExternalStorage() && Old->hasLinkage()) 4249 /* Okay */; 4250 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4251 !New->isStaticDataMember() && 4252 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4253 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4254 Diag(OldLocation, PrevDiag); 4255 return New->setInvalidDecl(); 4256 } 4257 4258 // Check if extern is followed by non-extern and vice-versa. 4259 if (New->hasExternalStorage() && 4260 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4261 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4262 Diag(OldLocation, PrevDiag); 4263 return New->setInvalidDecl(); 4264 } 4265 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4266 !New->hasExternalStorage()) { 4267 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4268 Diag(OldLocation, PrevDiag); 4269 return New->setInvalidDecl(); 4270 } 4271 4272 if (CheckRedeclarationModuleOwnership(New, Old)) 4273 return; 4274 4275 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4276 4277 // FIXME: The test for external storage here seems wrong? We still 4278 // need to check for mismatches. 4279 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4280 // Don't complain about out-of-line definitions of static members. 4281 !(Old->getLexicalDeclContext()->isRecord() && 4282 !New->getLexicalDeclContext()->isRecord())) { 4283 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4284 Diag(OldLocation, PrevDiag); 4285 return New->setInvalidDecl(); 4286 } 4287 4288 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4289 if (VarDecl *Def = Old->getDefinition()) { 4290 // C++1z [dcl.fcn.spec]p4: 4291 // If the definition of a variable appears in a translation unit before 4292 // its first declaration as inline, the program is ill-formed. 4293 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4294 Diag(Def->getLocation(), diag::note_previous_definition); 4295 } 4296 } 4297 4298 // If this redeclaration makes the variable inline, we may need to add it to 4299 // UndefinedButUsed. 4300 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4301 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4302 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4303 SourceLocation())); 4304 4305 if (New->getTLSKind() != Old->getTLSKind()) { 4306 if (!Old->getTLSKind()) { 4307 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4308 Diag(OldLocation, PrevDiag); 4309 } else if (!New->getTLSKind()) { 4310 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4311 Diag(OldLocation, PrevDiag); 4312 } else { 4313 // Do not allow redeclaration to change the variable between requiring 4314 // static and dynamic initialization. 4315 // FIXME: GCC allows this, but uses the TLS keyword on the first 4316 // declaration to determine the kind. Do we need to be compatible here? 4317 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4318 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4319 Diag(OldLocation, PrevDiag); 4320 } 4321 } 4322 4323 // C++ doesn't have tentative definitions, so go right ahead and check here. 4324 if (getLangOpts().CPlusPlus && 4325 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4326 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4327 Old->getCanonicalDecl()->isConstexpr()) { 4328 // This definition won't be a definition any more once it's been merged. 4329 Diag(New->getLocation(), 4330 diag::warn_deprecated_redundant_constexpr_static_def); 4331 } else if (VarDecl *Def = Old->getDefinition()) { 4332 if (checkVarDeclRedefinition(Def, New)) 4333 return; 4334 } 4335 } 4336 4337 if (haveIncompatibleLanguageLinkages(Old, New)) { 4338 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4339 Diag(OldLocation, PrevDiag); 4340 New->setInvalidDecl(); 4341 return; 4342 } 4343 4344 // Merge "used" flag. 4345 if (Old->getMostRecentDecl()->isUsed(false)) 4346 New->setIsUsed(); 4347 4348 // Keep a chain of previous declarations. 4349 New->setPreviousDecl(Old); 4350 if (NewTemplate) 4351 NewTemplate->setPreviousDecl(OldTemplate); 4352 4353 // Inherit access appropriately. 4354 New->setAccess(Old->getAccess()); 4355 if (NewTemplate) 4356 NewTemplate->setAccess(New->getAccess()); 4357 4358 if (Old->isInline()) 4359 New->setImplicitlyInline(); 4360 } 4361 4362 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4363 SourceManager &SrcMgr = getSourceManager(); 4364 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4365 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4366 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4367 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4368 auto &HSI = PP.getHeaderSearchInfo(); 4369 StringRef HdrFilename = 4370 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4371 4372 auto noteFromModuleOrInclude = [&](Module *Mod, 4373 SourceLocation IncLoc) -> bool { 4374 // Redefinition errors with modules are common with non modular mapped 4375 // headers, example: a non-modular header H in module A that also gets 4376 // included directly in a TU. Pointing twice to the same header/definition 4377 // is confusing, try to get better diagnostics when modules is on. 4378 if (IncLoc.isValid()) { 4379 if (Mod) { 4380 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4381 << HdrFilename.str() << Mod->getFullModuleName(); 4382 if (!Mod->DefinitionLoc.isInvalid()) 4383 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4384 << Mod->getFullModuleName(); 4385 } else { 4386 Diag(IncLoc, diag::note_redefinition_include_same_file) 4387 << HdrFilename.str(); 4388 } 4389 return true; 4390 } 4391 4392 return false; 4393 }; 4394 4395 // Is it the same file and same offset? Provide more information on why 4396 // this leads to a redefinition error. 4397 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4398 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4399 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4400 bool EmittedDiag = 4401 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4402 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4403 4404 // If the header has no guards, emit a note suggesting one. 4405 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4406 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4407 4408 if (EmittedDiag) 4409 return; 4410 } 4411 4412 // Redefinition coming from different files or couldn't do better above. 4413 if (Old->getLocation().isValid()) 4414 Diag(Old->getLocation(), diag::note_previous_definition); 4415 } 4416 4417 /// We've just determined that \p Old and \p New both appear to be definitions 4418 /// of the same variable. Either diagnose or fix the problem. 4419 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4420 if (!hasVisibleDefinition(Old) && 4421 (New->getFormalLinkage() == InternalLinkage || 4422 New->isInline() || 4423 New->getDescribedVarTemplate() || 4424 New->getNumTemplateParameterLists() || 4425 New->getDeclContext()->isDependentContext())) { 4426 // The previous definition is hidden, and multiple definitions are 4427 // permitted (in separate TUs). Demote this to a declaration. 4428 New->demoteThisDefinitionToDeclaration(); 4429 4430 // Make the canonical definition visible. 4431 if (auto *OldTD = Old->getDescribedVarTemplate()) 4432 makeMergedDefinitionVisible(OldTD); 4433 makeMergedDefinitionVisible(Old); 4434 return false; 4435 } else { 4436 Diag(New->getLocation(), diag::err_redefinition) << New; 4437 notePreviousDefinition(Old, New->getLocation()); 4438 New->setInvalidDecl(); 4439 return true; 4440 } 4441 } 4442 4443 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4444 /// no declarator (e.g. "struct foo;") is parsed. 4445 Decl * 4446 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4447 RecordDecl *&AnonRecord) { 4448 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4449 AnonRecord); 4450 } 4451 4452 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4453 // disambiguate entities defined in different scopes. 4454 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4455 // compatibility. 4456 // We will pick our mangling number depending on which version of MSVC is being 4457 // targeted. 4458 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4459 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4460 ? S->getMSCurManglingNumber() 4461 : S->getMSLastManglingNumber(); 4462 } 4463 4464 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4465 if (!Context.getLangOpts().CPlusPlus) 4466 return; 4467 4468 if (isa<CXXRecordDecl>(Tag->getParent())) { 4469 // If this tag is the direct child of a class, number it if 4470 // it is anonymous. 4471 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4472 return; 4473 MangleNumberingContext &MCtx = 4474 Context.getManglingNumberContext(Tag->getParent()); 4475 Context.setManglingNumber( 4476 Tag, MCtx.getManglingNumber( 4477 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4478 return; 4479 } 4480 4481 // If this tag isn't a direct child of a class, number it if it is local. 4482 MangleNumberingContext *MCtx; 4483 Decl *ManglingContextDecl; 4484 std::tie(MCtx, ManglingContextDecl) = 4485 getCurrentMangleNumberContext(Tag->getDeclContext()); 4486 if (MCtx) { 4487 Context.setManglingNumber( 4488 Tag, MCtx->getManglingNumber( 4489 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4490 } 4491 } 4492 4493 namespace { 4494 struct NonCLikeKind { 4495 enum { 4496 None, 4497 BaseClass, 4498 DefaultMemberInit, 4499 Lambda, 4500 Friend, 4501 OtherMember, 4502 Invalid, 4503 } Kind = None; 4504 SourceRange Range; 4505 4506 explicit operator bool() { return Kind != None; } 4507 }; 4508 } 4509 4510 /// Determine whether a class is C-like, according to the rules of C++ 4511 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4512 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4513 if (RD->isInvalidDecl()) 4514 return {NonCLikeKind::Invalid, {}}; 4515 4516 // C++ [dcl.typedef]p9: [P1766R1] 4517 // An unnamed class with a typedef name for linkage purposes shall not 4518 // 4519 // -- have any base classes 4520 if (RD->getNumBases()) 4521 return {NonCLikeKind::BaseClass, 4522 SourceRange(RD->bases_begin()->getBeginLoc(), 4523 RD->bases_end()[-1].getEndLoc())}; 4524 bool Invalid = false; 4525 for (Decl *D : RD->decls()) { 4526 // Don't complain about things we already diagnosed. 4527 if (D->isInvalidDecl()) { 4528 Invalid = true; 4529 continue; 4530 } 4531 4532 // -- have any [...] default member initializers 4533 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4534 if (FD->hasInClassInitializer()) { 4535 auto *Init = FD->getInClassInitializer(); 4536 return {NonCLikeKind::DefaultMemberInit, 4537 Init ? Init->getSourceRange() : D->getSourceRange()}; 4538 } 4539 continue; 4540 } 4541 4542 // FIXME: We don't allow friend declarations. This violates the wording of 4543 // P1766, but not the intent. 4544 if (isa<FriendDecl>(D)) 4545 return {NonCLikeKind::Friend, D->getSourceRange()}; 4546 4547 // -- declare any members other than non-static data members, member 4548 // enumerations, or member classes, 4549 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4550 isa<EnumDecl>(D)) 4551 continue; 4552 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4553 if (!MemberRD) { 4554 if (D->isImplicit()) 4555 continue; 4556 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4557 } 4558 4559 // -- contain a lambda-expression, 4560 if (MemberRD->isLambda()) 4561 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4562 4563 // and all member classes shall also satisfy these requirements 4564 // (recursively). 4565 if (MemberRD->isThisDeclarationADefinition()) { 4566 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4567 return Kind; 4568 } 4569 } 4570 4571 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4572 } 4573 4574 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4575 TypedefNameDecl *NewTD) { 4576 if (TagFromDeclSpec->isInvalidDecl()) 4577 return; 4578 4579 // Do nothing if the tag already has a name for linkage purposes. 4580 if (TagFromDeclSpec->hasNameForLinkage()) 4581 return; 4582 4583 // A well-formed anonymous tag must always be a TUK_Definition. 4584 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4585 4586 // The type must match the tag exactly; no qualifiers allowed. 4587 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4588 Context.getTagDeclType(TagFromDeclSpec))) { 4589 if (getLangOpts().CPlusPlus) 4590 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4591 return; 4592 } 4593 4594 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4595 // An unnamed class with a typedef name for linkage purposes shall [be 4596 // C-like]. 4597 // 4598 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4599 // shouldn't happen, but there are constructs that the language rule doesn't 4600 // disallow for which we can't reasonably avoid computing linkage early. 4601 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4602 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4603 : NonCLikeKind(); 4604 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4605 if (NonCLike || ChangesLinkage) { 4606 if (NonCLike.Kind == NonCLikeKind::Invalid) 4607 return; 4608 4609 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4610 if (ChangesLinkage) { 4611 // If the linkage changes, we can't accept this as an extension. 4612 if (NonCLike.Kind == NonCLikeKind::None) 4613 DiagID = diag::err_typedef_changes_linkage; 4614 else 4615 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4616 } 4617 4618 SourceLocation FixitLoc = 4619 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4620 llvm::SmallString<40> TextToInsert; 4621 TextToInsert += ' '; 4622 TextToInsert += NewTD->getIdentifier()->getName(); 4623 4624 Diag(FixitLoc, DiagID) 4625 << isa<TypeAliasDecl>(NewTD) 4626 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4627 if (NonCLike.Kind != NonCLikeKind::None) { 4628 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4629 << NonCLike.Kind - 1 << NonCLike.Range; 4630 } 4631 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4632 << NewTD << isa<TypeAliasDecl>(NewTD); 4633 4634 if (ChangesLinkage) 4635 return; 4636 } 4637 4638 // Otherwise, set this as the anon-decl typedef for the tag. 4639 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4640 } 4641 4642 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4643 switch (T) { 4644 case DeclSpec::TST_class: 4645 return 0; 4646 case DeclSpec::TST_struct: 4647 return 1; 4648 case DeclSpec::TST_interface: 4649 return 2; 4650 case DeclSpec::TST_union: 4651 return 3; 4652 case DeclSpec::TST_enum: 4653 return 4; 4654 default: 4655 llvm_unreachable("unexpected type specifier"); 4656 } 4657 } 4658 4659 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4660 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4661 /// parameters to cope with template friend declarations. 4662 Decl * 4663 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4664 MultiTemplateParamsArg TemplateParams, 4665 bool IsExplicitInstantiation, 4666 RecordDecl *&AnonRecord) { 4667 Decl *TagD = nullptr; 4668 TagDecl *Tag = nullptr; 4669 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4670 DS.getTypeSpecType() == DeclSpec::TST_struct || 4671 DS.getTypeSpecType() == DeclSpec::TST_interface || 4672 DS.getTypeSpecType() == DeclSpec::TST_union || 4673 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4674 TagD = DS.getRepAsDecl(); 4675 4676 if (!TagD) // We probably had an error 4677 return nullptr; 4678 4679 // Note that the above type specs guarantee that the 4680 // type rep is a Decl, whereas in many of the others 4681 // it's a Type. 4682 if (isa<TagDecl>(TagD)) 4683 Tag = cast<TagDecl>(TagD); 4684 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4685 Tag = CTD->getTemplatedDecl(); 4686 } 4687 4688 if (Tag) { 4689 handleTagNumbering(Tag, S); 4690 Tag->setFreeStanding(); 4691 if (Tag->isInvalidDecl()) 4692 return Tag; 4693 } 4694 4695 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4696 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4697 // or incomplete types shall not be restrict-qualified." 4698 if (TypeQuals & DeclSpec::TQ_restrict) 4699 Diag(DS.getRestrictSpecLoc(), 4700 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4701 << DS.getSourceRange(); 4702 } 4703 4704 if (DS.isInlineSpecified()) 4705 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4706 << getLangOpts().CPlusPlus17; 4707 4708 if (DS.hasConstexprSpecifier()) { 4709 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4710 // and definitions of functions and variables. 4711 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4712 // the declaration of a function or function template 4713 if (Tag) 4714 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4715 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4716 << static_cast<int>(DS.getConstexprSpecifier()); 4717 else 4718 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4719 << static_cast<int>(DS.getConstexprSpecifier()); 4720 // Don't emit warnings after this error. 4721 return TagD; 4722 } 4723 4724 DiagnoseFunctionSpecifiers(DS); 4725 4726 if (DS.isFriendSpecified()) { 4727 // If we're dealing with a decl but not a TagDecl, assume that 4728 // whatever routines created it handled the friendship aspect. 4729 if (TagD && !Tag) 4730 return nullptr; 4731 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4732 } 4733 4734 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4735 bool IsExplicitSpecialization = 4736 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4737 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4738 !IsExplicitInstantiation && !IsExplicitSpecialization && 4739 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4740 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4741 // nested-name-specifier unless it is an explicit instantiation 4742 // or an explicit specialization. 4743 // 4744 // FIXME: We allow class template partial specializations here too, per the 4745 // obvious intent of DR1819. 4746 // 4747 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4748 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4749 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4750 return nullptr; 4751 } 4752 4753 // Track whether this decl-specifier declares anything. 4754 bool DeclaresAnything = true; 4755 4756 // Handle anonymous struct definitions. 4757 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4758 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4759 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4760 if (getLangOpts().CPlusPlus || 4761 Record->getDeclContext()->isRecord()) { 4762 // If CurContext is a DeclContext that can contain statements, 4763 // RecursiveASTVisitor won't visit the decls that 4764 // BuildAnonymousStructOrUnion() will put into CurContext. 4765 // Also store them here so that they can be part of the 4766 // DeclStmt that gets created in this case. 4767 // FIXME: Also return the IndirectFieldDecls created by 4768 // BuildAnonymousStructOr union, for the same reason? 4769 if (CurContext->isFunctionOrMethod()) 4770 AnonRecord = Record; 4771 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4772 Context.getPrintingPolicy()); 4773 } 4774 4775 DeclaresAnything = false; 4776 } 4777 } 4778 4779 // C11 6.7.2.1p2: 4780 // A struct-declaration that does not declare an anonymous structure or 4781 // anonymous union shall contain a struct-declarator-list. 4782 // 4783 // This rule also existed in C89 and C99; the grammar for struct-declaration 4784 // did not permit a struct-declaration without a struct-declarator-list. 4785 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4786 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4787 // Check for Microsoft C extension: anonymous struct/union member. 4788 // Handle 2 kinds of anonymous struct/union: 4789 // struct STRUCT; 4790 // union UNION; 4791 // and 4792 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4793 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4794 if ((Tag && Tag->getDeclName()) || 4795 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4796 RecordDecl *Record = nullptr; 4797 if (Tag) 4798 Record = dyn_cast<RecordDecl>(Tag); 4799 else if (const RecordType *RT = 4800 DS.getRepAsType().get()->getAsStructureType()) 4801 Record = RT->getDecl(); 4802 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4803 Record = UT->getDecl(); 4804 4805 if (Record && getLangOpts().MicrosoftExt) { 4806 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4807 << Record->isUnion() << DS.getSourceRange(); 4808 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4809 } 4810 4811 DeclaresAnything = false; 4812 } 4813 } 4814 4815 // Skip all the checks below if we have a type error. 4816 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4817 (TagD && TagD->isInvalidDecl())) 4818 return TagD; 4819 4820 if (getLangOpts().CPlusPlus && 4821 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4822 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4823 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4824 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4825 DeclaresAnything = false; 4826 4827 if (!DS.isMissingDeclaratorOk()) { 4828 // Customize diagnostic for a typedef missing a name. 4829 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4830 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4831 << DS.getSourceRange(); 4832 else 4833 DeclaresAnything = false; 4834 } 4835 4836 if (DS.isModulePrivateSpecified() && 4837 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4838 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4839 << Tag->getTagKind() 4840 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4841 4842 ActOnDocumentableDecl(TagD); 4843 4844 // C 6.7/2: 4845 // A declaration [...] shall declare at least a declarator [...], a tag, 4846 // or the members of an enumeration. 4847 // C++ [dcl.dcl]p3: 4848 // [If there are no declarators], and except for the declaration of an 4849 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4850 // names into the program, or shall redeclare a name introduced by a 4851 // previous declaration. 4852 if (!DeclaresAnything) { 4853 // In C, we allow this as a (popular) extension / bug. Don't bother 4854 // producing further diagnostics for redundant qualifiers after this. 4855 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4856 ? diag::err_no_declarators 4857 : diag::ext_no_declarators) 4858 << DS.getSourceRange(); 4859 return TagD; 4860 } 4861 4862 // C++ [dcl.stc]p1: 4863 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4864 // init-declarator-list of the declaration shall not be empty. 4865 // C++ [dcl.fct.spec]p1: 4866 // If a cv-qualifier appears in a decl-specifier-seq, the 4867 // init-declarator-list of the declaration shall not be empty. 4868 // 4869 // Spurious qualifiers here appear to be valid in C. 4870 unsigned DiagID = diag::warn_standalone_specifier; 4871 if (getLangOpts().CPlusPlus) 4872 DiagID = diag::ext_standalone_specifier; 4873 4874 // Note that a linkage-specification sets a storage class, but 4875 // 'extern "C" struct foo;' is actually valid and not theoretically 4876 // useless. 4877 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4878 if (SCS == DeclSpec::SCS_mutable) 4879 // Since mutable is not a viable storage class specifier in C, there is 4880 // no reason to treat it as an extension. Instead, diagnose as an error. 4881 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4882 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4883 Diag(DS.getStorageClassSpecLoc(), DiagID) 4884 << DeclSpec::getSpecifierName(SCS); 4885 } 4886 4887 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4888 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4889 << DeclSpec::getSpecifierName(TSCS); 4890 if (DS.getTypeQualifiers()) { 4891 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4892 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4893 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4894 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4895 // Restrict is covered above. 4896 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4897 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4898 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4899 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4900 } 4901 4902 // Warn about ignored type attributes, for example: 4903 // __attribute__((aligned)) struct A; 4904 // Attributes should be placed after tag to apply to type declaration. 4905 if (!DS.getAttributes().empty()) { 4906 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4907 if (TypeSpecType == DeclSpec::TST_class || 4908 TypeSpecType == DeclSpec::TST_struct || 4909 TypeSpecType == DeclSpec::TST_interface || 4910 TypeSpecType == DeclSpec::TST_union || 4911 TypeSpecType == DeclSpec::TST_enum) { 4912 for (const ParsedAttr &AL : DS.getAttributes()) 4913 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4914 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4915 } 4916 } 4917 4918 return TagD; 4919 } 4920 4921 /// We are trying to inject an anonymous member into the given scope; 4922 /// check if there's an existing declaration that can't be overloaded. 4923 /// 4924 /// \return true if this is a forbidden redeclaration 4925 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4926 Scope *S, 4927 DeclContext *Owner, 4928 DeclarationName Name, 4929 SourceLocation NameLoc, 4930 bool IsUnion) { 4931 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4932 Sema::ForVisibleRedeclaration); 4933 if (!SemaRef.LookupName(R, S)) return false; 4934 4935 // Pick a representative declaration. 4936 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4937 assert(PrevDecl && "Expected a non-null Decl"); 4938 4939 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4940 return false; 4941 4942 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4943 << IsUnion << Name; 4944 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4945 4946 return true; 4947 } 4948 4949 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4950 /// anonymous struct or union AnonRecord into the owning context Owner 4951 /// and scope S. This routine will be invoked just after we realize 4952 /// that an unnamed union or struct is actually an anonymous union or 4953 /// struct, e.g., 4954 /// 4955 /// @code 4956 /// union { 4957 /// int i; 4958 /// float f; 4959 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4960 /// // f into the surrounding scope.x 4961 /// @endcode 4962 /// 4963 /// This routine is recursive, injecting the names of nested anonymous 4964 /// structs/unions into the owning context and scope as well. 4965 static bool 4966 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4967 RecordDecl *AnonRecord, AccessSpecifier AS, 4968 SmallVectorImpl<NamedDecl *> &Chaining) { 4969 bool Invalid = false; 4970 4971 // Look every FieldDecl and IndirectFieldDecl with a name. 4972 for (auto *D : AnonRecord->decls()) { 4973 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4974 cast<NamedDecl>(D)->getDeclName()) { 4975 ValueDecl *VD = cast<ValueDecl>(D); 4976 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4977 VD->getLocation(), 4978 AnonRecord->isUnion())) { 4979 // C++ [class.union]p2: 4980 // The names of the members of an anonymous union shall be 4981 // distinct from the names of any other entity in the 4982 // scope in which the anonymous union is declared. 4983 Invalid = true; 4984 } else { 4985 // C++ [class.union]p2: 4986 // For the purpose of name lookup, after the anonymous union 4987 // definition, the members of the anonymous union are 4988 // considered to have been defined in the scope in which the 4989 // anonymous union is declared. 4990 unsigned OldChainingSize = Chaining.size(); 4991 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4992 Chaining.append(IF->chain_begin(), IF->chain_end()); 4993 else 4994 Chaining.push_back(VD); 4995 4996 assert(Chaining.size() >= 2); 4997 NamedDecl **NamedChain = 4998 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4999 for (unsigned i = 0; i < Chaining.size(); i++) 5000 NamedChain[i] = Chaining[i]; 5001 5002 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5003 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5004 VD->getType(), {NamedChain, Chaining.size()}); 5005 5006 for (const auto *Attr : VD->attrs()) 5007 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5008 5009 IndirectField->setAccess(AS); 5010 IndirectField->setImplicit(); 5011 SemaRef.PushOnScopeChains(IndirectField, S); 5012 5013 // That includes picking up the appropriate access specifier. 5014 if (AS != AS_none) IndirectField->setAccess(AS); 5015 5016 Chaining.resize(OldChainingSize); 5017 } 5018 } 5019 } 5020 5021 return Invalid; 5022 } 5023 5024 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5025 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5026 /// illegal input values are mapped to SC_None. 5027 static StorageClass 5028 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5029 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5030 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5031 "Parser allowed 'typedef' as storage class VarDecl."); 5032 switch (StorageClassSpec) { 5033 case DeclSpec::SCS_unspecified: return SC_None; 5034 case DeclSpec::SCS_extern: 5035 if (DS.isExternInLinkageSpec()) 5036 return SC_None; 5037 return SC_Extern; 5038 case DeclSpec::SCS_static: return SC_Static; 5039 case DeclSpec::SCS_auto: return SC_Auto; 5040 case DeclSpec::SCS_register: return SC_Register; 5041 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5042 // Illegal SCSs map to None: error reporting is up to the caller. 5043 case DeclSpec::SCS_mutable: // Fall through. 5044 case DeclSpec::SCS_typedef: return SC_None; 5045 } 5046 llvm_unreachable("unknown storage class specifier"); 5047 } 5048 5049 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5050 assert(Record->hasInClassInitializer()); 5051 5052 for (const auto *I : Record->decls()) { 5053 const auto *FD = dyn_cast<FieldDecl>(I); 5054 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5055 FD = IFD->getAnonField(); 5056 if (FD && FD->hasInClassInitializer()) 5057 return FD->getLocation(); 5058 } 5059 5060 llvm_unreachable("couldn't find in-class initializer"); 5061 } 5062 5063 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5064 SourceLocation DefaultInitLoc) { 5065 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5066 return; 5067 5068 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5069 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5070 } 5071 5072 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5073 CXXRecordDecl *AnonUnion) { 5074 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5075 return; 5076 5077 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5078 } 5079 5080 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5081 /// anonymous structure or union. Anonymous unions are a C++ feature 5082 /// (C++ [class.union]) and a C11 feature; anonymous structures 5083 /// are a C11 feature and GNU C++ extension. 5084 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5085 AccessSpecifier AS, 5086 RecordDecl *Record, 5087 const PrintingPolicy &Policy) { 5088 DeclContext *Owner = Record->getDeclContext(); 5089 5090 // Diagnose whether this anonymous struct/union is an extension. 5091 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5092 Diag(Record->getLocation(), diag::ext_anonymous_union); 5093 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5094 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5095 else if (!Record->isUnion() && !getLangOpts().C11) 5096 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5097 5098 // C and C++ require different kinds of checks for anonymous 5099 // structs/unions. 5100 bool Invalid = false; 5101 if (getLangOpts().CPlusPlus) { 5102 const char *PrevSpec = nullptr; 5103 if (Record->isUnion()) { 5104 // C++ [class.union]p6: 5105 // C++17 [class.union.anon]p2: 5106 // Anonymous unions declared in a named namespace or in the 5107 // global namespace shall be declared static. 5108 unsigned DiagID; 5109 DeclContext *OwnerScope = Owner->getRedeclContext(); 5110 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5111 (OwnerScope->isTranslationUnit() || 5112 (OwnerScope->isNamespace() && 5113 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5114 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5115 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5116 5117 // Recover by adding 'static'. 5118 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5119 PrevSpec, DiagID, Policy); 5120 } 5121 // C++ [class.union]p6: 5122 // A storage class is not allowed in a declaration of an 5123 // anonymous union in a class scope. 5124 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5125 isa<RecordDecl>(Owner)) { 5126 Diag(DS.getStorageClassSpecLoc(), 5127 diag::err_anonymous_union_with_storage_spec) 5128 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5129 5130 // Recover by removing the storage specifier. 5131 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5132 SourceLocation(), 5133 PrevSpec, DiagID, Context.getPrintingPolicy()); 5134 } 5135 } 5136 5137 // Ignore const/volatile/restrict qualifiers. 5138 if (DS.getTypeQualifiers()) { 5139 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5140 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5141 << Record->isUnion() << "const" 5142 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5143 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5144 Diag(DS.getVolatileSpecLoc(), 5145 diag::ext_anonymous_struct_union_qualified) 5146 << Record->isUnion() << "volatile" 5147 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5148 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5149 Diag(DS.getRestrictSpecLoc(), 5150 diag::ext_anonymous_struct_union_qualified) 5151 << Record->isUnion() << "restrict" 5152 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5153 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5154 Diag(DS.getAtomicSpecLoc(), 5155 diag::ext_anonymous_struct_union_qualified) 5156 << Record->isUnion() << "_Atomic" 5157 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5158 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5159 Diag(DS.getUnalignedSpecLoc(), 5160 diag::ext_anonymous_struct_union_qualified) 5161 << Record->isUnion() << "__unaligned" 5162 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5163 5164 DS.ClearTypeQualifiers(); 5165 } 5166 5167 // C++ [class.union]p2: 5168 // The member-specification of an anonymous union shall only 5169 // define non-static data members. [Note: nested types and 5170 // functions cannot be declared within an anonymous union. ] 5171 for (auto *Mem : Record->decls()) { 5172 // Ignore invalid declarations; we already diagnosed them. 5173 if (Mem->isInvalidDecl()) 5174 continue; 5175 5176 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5177 // C++ [class.union]p3: 5178 // An anonymous union shall not have private or protected 5179 // members (clause 11). 5180 assert(FD->getAccess() != AS_none); 5181 if (FD->getAccess() != AS_public) { 5182 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5183 << Record->isUnion() << (FD->getAccess() == AS_protected); 5184 Invalid = true; 5185 } 5186 5187 // C++ [class.union]p1 5188 // An object of a class with a non-trivial constructor, a non-trivial 5189 // copy constructor, a non-trivial destructor, or a non-trivial copy 5190 // assignment operator cannot be a member of a union, nor can an 5191 // array of such objects. 5192 if (CheckNontrivialField(FD)) 5193 Invalid = true; 5194 } else if (Mem->isImplicit()) { 5195 // Any implicit members are fine. 5196 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5197 // This is a type that showed up in an 5198 // elaborated-type-specifier inside the anonymous struct or 5199 // union, but which actually declares a type outside of the 5200 // anonymous struct or union. It's okay. 5201 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5202 if (!MemRecord->isAnonymousStructOrUnion() && 5203 MemRecord->getDeclName()) { 5204 // Visual C++ allows type definition in anonymous struct or union. 5205 if (getLangOpts().MicrosoftExt) 5206 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5207 << Record->isUnion(); 5208 else { 5209 // This is a nested type declaration. 5210 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5211 << Record->isUnion(); 5212 Invalid = true; 5213 } 5214 } else { 5215 // This is an anonymous type definition within another anonymous type. 5216 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5217 // not part of standard C++. 5218 Diag(MemRecord->getLocation(), 5219 diag::ext_anonymous_record_with_anonymous_type) 5220 << Record->isUnion(); 5221 } 5222 } else if (isa<AccessSpecDecl>(Mem)) { 5223 // Any access specifier is fine. 5224 } else if (isa<StaticAssertDecl>(Mem)) { 5225 // In C++1z, static_assert declarations are also fine. 5226 } else { 5227 // We have something that isn't a non-static data 5228 // member. Complain about it. 5229 unsigned DK = diag::err_anonymous_record_bad_member; 5230 if (isa<TypeDecl>(Mem)) 5231 DK = diag::err_anonymous_record_with_type; 5232 else if (isa<FunctionDecl>(Mem)) 5233 DK = diag::err_anonymous_record_with_function; 5234 else if (isa<VarDecl>(Mem)) 5235 DK = diag::err_anonymous_record_with_static; 5236 5237 // Visual C++ allows type definition in anonymous struct or union. 5238 if (getLangOpts().MicrosoftExt && 5239 DK == diag::err_anonymous_record_with_type) 5240 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5241 << Record->isUnion(); 5242 else { 5243 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5244 Invalid = true; 5245 } 5246 } 5247 } 5248 5249 // C++11 [class.union]p8 (DR1460): 5250 // At most one variant member of a union may have a 5251 // brace-or-equal-initializer. 5252 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5253 Owner->isRecord()) 5254 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5255 cast<CXXRecordDecl>(Record)); 5256 } 5257 5258 if (!Record->isUnion() && !Owner->isRecord()) { 5259 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5260 << getLangOpts().CPlusPlus; 5261 Invalid = true; 5262 } 5263 5264 // C++ [dcl.dcl]p3: 5265 // [If there are no declarators], and except for the declaration of an 5266 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5267 // names into the program 5268 // C++ [class.mem]p2: 5269 // each such member-declaration shall either declare at least one member 5270 // name of the class or declare at least one unnamed bit-field 5271 // 5272 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5273 if (getLangOpts().CPlusPlus && Record->field_empty()) 5274 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5275 5276 // Mock up a declarator. 5277 Declarator Dc(DS, DeclaratorContext::Member); 5278 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5279 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5280 5281 // Create a declaration for this anonymous struct/union. 5282 NamedDecl *Anon = nullptr; 5283 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5284 Anon = FieldDecl::Create( 5285 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5286 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5287 /*BitWidth=*/nullptr, /*Mutable=*/false, 5288 /*InitStyle=*/ICIS_NoInit); 5289 Anon->setAccess(AS); 5290 ProcessDeclAttributes(S, Anon, Dc); 5291 5292 if (getLangOpts().CPlusPlus) 5293 FieldCollector->Add(cast<FieldDecl>(Anon)); 5294 } else { 5295 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5296 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5297 if (SCSpec == DeclSpec::SCS_mutable) { 5298 // mutable can only appear on non-static class members, so it's always 5299 // an error here 5300 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5301 Invalid = true; 5302 SC = SC_None; 5303 } 5304 5305 assert(DS.getAttributes().empty() && "No attribute expected"); 5306 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5307 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5308 Context.getTypeDeclType(Record), TInfo, SC); 5309 5310 // Default-initialize the implicit variable. This initialization will be 5311 // trivial in almost all cases, except if a union member has an in-class 5312 // initializer: 5313 // union { int n = 0; }; 5314 ActOnUninitializedDecl(Anon); 5315 } 5316 Anon->setImplicit(); 5317 5318 // Mark this as an anonymous struct/union type. 5319 Record->setAnonymousStructOrUnion(true); 5320 5321 // Add the anonymous struct/union object to the current 5322 // context. We'll be referencing this object when we refer to one of 5323 // its members. 5324 Owner->addDecl(Anon); 5325 5326 // Inject the members of the anonymous struct/union into the owning 5327 // context and into the identifier resolver chain for name lookup 5328 // purposes. 5329 SmallVector<NamedDecl*, 2> Chain; 5330 Chain.push_back(Anon); 5331 5332 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5333 Invalid = true; 5334 5335 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5336 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5337 MangleNumberingContext *MCtx; 5338 Decl *ManglingContextDecl; 5339 std::tie(MCtx, ManglingContextDecl) = 5340 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5341 if (MCtx) { 5342 Context.setManglingNumber( 5343 NewVD, MCtx->getManglingNumber( 5344 NewVD, getMSManglingNumber(getLangOpts(), S))); 5345 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5346 } 5347 } 5348 } 5349 5350 if (Invalid) 5351 Anon->setInvalidDecl(); 5352 5353 return Anon; 5354 } 5355 5356 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5357 /// Microsoft C anonymous structure. 5358 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5359 /// Example: 5360 /// 5361 /// struct A { int a; }; 5362 /// struct B { struct A; int b; }; 5363 /// 5364 /// void foo() { 5365 /// B var; 5366 /// var.a = 3; 5367 /// } 5368 /// 5369 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5370 RecordDecl *Record) { 5371 assert(Record && "expected a record!"); 5372 5373 // Mock up a declarator. 5374 Declarator Dc(DS, DeclaratorContext::TypeName); 5375 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5376 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5377 5378 auto *ParentDecl = cast<RecordDecl>(CurContext); 5379 QualType RecTy = Context.getTypeDeclType(Record); 5380 5381 // Create a declaration for this anonymous struct. 5382 NamedDecl *Anon = 5383 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5384 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5385 /*BitWidth=*/nullptr, /*Mutable=*/false, 5386 /*InitStyle=*/ICIS_NoInit); 5387 Anon->setImplicit(); 5388 5389 // Add the anonymous struct object to the current context. 5390 CurContext->addDecl(Anon); 5391 5392 // Inject the members of the anonymous struct into the current 5393 // context and into the identifier resolver chain for name lookup 5394 // purposes. 5395 SmallVector<NamedDecl*, 2> Chain; 5396 Chain.push_back(Anon); 5397 5398 RecordDecl *RecordDef = Record->getDefinition(); 5399 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5400 diag::err_field_incomplete_or_sizeless) || 5401 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5402 AS_none, Chain)) { 5403 Anon->setInvalidDecl(); 5404 ParentDecl->setInvalidDecl(); 5405 } 5406 5407 return Anon; 5408 } 5409 5410 /// GetNameForDeclarator - Determine the full declaration name for the 5411 /// given Declarator. 5412 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5413 return GetNameFromUnqualifiedId(D.getName()); 5414 } 5415 5416 /// Retrieves the declaration name from a parsed unqualified-id. 5417 DeclarationNameInfo 5418 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5419 DeclarationNameInfo NameInfo; 5420 NameInfo.setLoc(Name.StartLocation); 5421 5422 switch (Name.getKind()) { 5423 5424 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5425 case UnqualifiedIdKind::IK_Identifier: 5426 NameInfo.setName(Name.Identifier); 5427 return NameInfo; 5428 5429 case UnqualifiedIdKind::IK_DeductionGuideName: { 5430 // C++ [temp.deduct.guide]p3: 5431 // The simple-template-id shall name a class template specialization. 5432 // The template-name shall be the same identifier as the template-name 5433 // of the simple-template-id. 5434 // These together intend to imply that the template-name shall name a 5435 // class template. 5436 // FIXME: template<typename T> struct X {}; 5437 // template<typename T> using Y = X<T>; 5438 // Y(int) -> Y<int>; 5439 // satisfies these rules but does not name a class template. 5440 TemplateName TN = Name.TemplateName.get().get(); 5441 auto *Template = TN.getAsTemplateDecl(); 5442 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5443 Diag(Name.StartLocation, 5444 diag::err_deduction_guide_name_not_class_template) 5445 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5446 if (Template) 5447 Diag(Template->getLocation(), diag::note_template_decl_here); 5448 return DeclarationNameInfo(); 5449 } 5450 5451 NameInfo.setName( 5452 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5453 return NameInfo; 5454 } 5455 5456 case UnqualifiedIdKind::IK_OperatorFunctionId: 5457 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5458 Name.OperatorFunctionId.Operator)); 5459 NameInfo.setCXXOperatorNameRange(SourceRange( 5460 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5461 return NameInfo; 5462 5463 case UnqualifiedIdKind::IK_LiteralOperatorId: 5464 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5465 Name.Identifier)); 5466 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5467 return NameInfo; 5468 5469 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5470 TypeSourceInfo *TInfo; 5471 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5472 if (Ty.isNull()) 5473 return DeclarationNameInfo(); 5474 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5475 Context.getCanonicalType(Ty))); 5476 NameInfo.setNamedTypeInfo(TInfo); 5477 return NameInfo; 5478 } 5479 5480 case UnqualifiedIdKind::IK_ConstructorName: { 5481 TypeSourceInfo *TInfo; 5482 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5483 if (Ty.isNull()) 5484 return DeclarationNameInfo(); 5485 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5486 Context.getCanonicalType(Ty))); 5487 NameInfo.setNamedTypeInfo(TInfo); 5488 return NameInfo; 5489 } 5490 5491 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5492 // In well-formed code, we can only have a constructor 5493 // template-id that refers to the current context, so go there 5494 // to find the actual type being constructed. 5495 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5496 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5497 return DeclarationNameInfo(); 5498 5499 // Determine the type of the class being constructed. 5500 QualType CurClassType = Context.getTypeDeclType(CurClass); 5501 5502 // FIXME: Check two things: that the template-id names the same type as 5503 // CurClassType, and that the template-id does not occur when the name 5504 // was qualified. 5505 5506 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5507 Context.getCanonicalType(CurClassType))); 5508 // FIXME: should we retrieve TypeSourceInfo? 5509 NameInfo.setNamedTypeInfo(nullptr); 5510 return NameInfo; 5511 } 5512 5513 case UnqualifiedIdKind::IK_DestructorName: { 5514 TypeSourceInfo *TInfo; 5515 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5516 if (Ty.isNull()) 5517 return DeclarationNameInfo(); 5518 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5519 Context.getCanonicalType(Ty))); 5520 NameInfo.setNamedTypeInfo(TInfo); 5521 return NameInfo; 5522 } 5523 5524 case UnqualifiedIdKind::IK_TemplateId: { 5525 TemplateName TName = Name.TemplateId->Template.get(); 5526 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5527 return Context.getNameForTemplate(TName, TNameLoc); 5528 } 5529 5530 } // switch (Name.getKind()) 5531 5532 llvm_unreachable("Unknown name kind"); 5533 } 5534 5535 static QualType getCoreType(QualType Ty) { 5536 do { 5537 if (Ty->isPointerType() || Ty->isReferenceType()) 5538 Ty = Ty->getPointeeType(); 5539 else if (Ty->isArrayType()) 5540 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5541 else 5542 return Ty.withoutLocalFastQualifiers(); 5543 } while (true); 5544 } 5545 5546 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5547 /// and Definition have "nearly" matching parameters. This heuristic is 5548 /// used to improve diagnostics in the case where an out-of-line function 5549 /// definition doesn't match any declaration within the class or namespace. 5550 /// Also sets Params to the list of indices to the parameters that differ 5551 /// between the declaration and the definition. If hasSimilarParameters 5552 /// returns true and Params is empty, then all of the parameters match. 5553 static bool hasSimilarParameters(ASTContext &Context, 5554 FunctionDecl *Declaration, 5555 FunctionDecl *Definition, 5556 SmallVectorImpl<unsigned> &Params) { 5557 Params.clear(); 5558 if (Declaration->param_size() != Definition->param_size()) 5559 return false; 5560 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5561 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5562 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5563 5564 // The parameter types are identical 5565 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5566 continue; 5567 5568 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5569 QualType DefParamBaseTy = getCoreType(DefParamTy); 5570 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5571 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5572 5573 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5574 (DeclTyName && DeclTyName == DefTyName)) 5575 Params.push_back(Idx); 5576 else // The two parameters aren't even close 5577 return false; 5578 } 5579 5580 return true; 5581 } 5582 5583 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5584 /// declarator needs to be rebuilt in the current instantiation. 5585 /// Any bits of declarator which appear before the name are valid for 5586 /// consideration here. That's specifically the type in the decl spec 5587 /// and the base type in any member-pointer chunks. 5588 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5589 DeclarationName Name) { 5590 // The types we specifically need to rebuild are: 5591 // - typenames, typeofs, and decltypes 5592 // - types which will become injected class names 5593 // Of course, we also need to rebuild any type referencing such a 5594 // type. It's safest to just say "dependent", but we call out a 5595 // few cases here. 5596 5597 DeclSpec &DS = D.getMutableDeclSpec(); 5598 switch (DS.getTypeSpecType()) { 5599 case DeclSpec::TST_typename: 5600 case DeclSpec::TST_typeofType: 5601 case DeclSpec::TST_underlyingType: 5602 case DeclSpec::TST_atomic: { 5603 // Grab the type from the parser. 5604 TypeSourceInfo *TSI = nullptr; 5605 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5606 if (T.isNull() || !T->isInstantiationDependentType()) break; 5607 5608 // Make sure there's a type source info. This isn't really much 5609 // of a waste; most dependent types should have type source info 5610 // attached already. 5611 if (!TSI) 5612 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5613 5614 // Rebuild the type in the current instantiation. 5615 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5616 if (!TSI) return true; 5617 5618 // Store the new type back in the decl spec. 5619 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5620 DS.UpdateTypeRep(LocType); 5621 break; 5622 } 5623 5624 case DeclSpec::TST_decltype: 5625 case DeclSpec::TST_typeofExpr: { 5626 Expr *E = DS.getRepAsExpr(); 5627 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5628 if (Result.isInvalid()) return true; 5629 DS.UpdateExprRep(Result.get()); 5630 break; 5631 } 5632 5633 default: 5634 // Nothing to do for these decl specs. 5635 break; 5636 } 5637 5638 // It doesn't matter what order we do this in. 5639 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5640 DeclaratorChunk &Chunk = D.getTypeObject(I); 5641 5642 // The only type information in the declarator which can come 5643 // before the declaration name is the base type of a member 5644 // pointer. 5645 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5646 continue; 5647 5648 // Rebuild the scope specifier in-place. 5649 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5650 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5651 return true; 5652 } 5653 5654 return false; 5655 } 5656 5657 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5658 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5659 // of system decl. 5660 if (D->getPreviousDecl() || D->isImplicit()) 5661 return; 5662 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5663 if (Status != ReservedIdentifierStatus::NotReserved && 5664 !Context.getSourceManager().isInSystemHeader(D->getLocation())) 5665 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5666 << D << static_cast<int>(Status); 5667 } 5668 5669 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5670 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5671 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5672 5673 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5674 Dcl && Dcl->getDeclContext()->isFileContext()) 5675 Dcl->setTopLevelDeclInObjCContainer(); 5676 5677 return Dcl; 5678 } 5679 5680 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5681 /// If T is the name of a class, then each of the following shall have a 5682 /// name different from T: 5683 /// - every static data member of class T; 5684 /// - every member function of class T 5685 /// - every member of class T that is itself a type; 5686 /// \returns true if the declaration name violates these rules. 5687 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5688 DeclarationNameInfo NameInfo) { 5689 DeclarationName Name = NameInfo.getName(); 5690 5691 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5692 while (Record && Record->isAnonymousStructOrUnion()) 5693 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5694 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5695 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5696 return true; 5697 } 5698 5699 return false; 5700 } 5701 5702 /// Diagnose a declaration whose declarator-id has the given 5703 /// nested-name-specifier. 5704 /// 5705 /// \param SS The nested-name-specifier of the declarator-id. 5706 /// 5707 /// \param DC The declaration context to which the nested-name-specifier 5708 /// resolves. 5709 /// 5710 /// \param Name The name of the entity being declared. 5711 /// 5712 /// \param Loc The location of the name of the entity being declared. 5713 /// 5714 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5715 /// we're declaring an explicit / partial specialization / instantiation. 5716 /// 5717 /// \returns true if we cannot safely recover from this error, false otherwise. 5718 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5719 DeclarationName Name, 5720 SourceLocation Loc, bool IsTemplateId) { 5721 DeclContext *Cur = CurContext; 5722 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5723 Cur = Cur->getParent(); 5724 5725 // If the user provided a superfluous scope specifier that refers back to the 5726 // class in which the entity is already declared, diagnose and ignore it. 5727 // 5728 // class X { 5729 // void X::f(); 5730 // }; 5731 // 5732 // Note, it was once ill-formed to give redundant qualification in all 5733 // contexts, but that rule was removed by DR482. 5734 if (Cur->Equals(DC)) { 5735 if (Cur->isRecord()) { 5736 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5737 : diag::err_member_extra_qualification) 5738 << Name << FixItHint::CreateRemoval(SS.getRange()); 5739 SS.clear(); 5740 } else { 5741 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5742 } 5743 return false; 5744 } 5745 5746 // Check whether the qualifying scope encloses the scope of the original 5747 // declaration. For a template-id, we perform the checks in 5748 // CheckTemplateSpecializationScope. 5749 if (!Cur->Encloses(DC) && !IsTemplateId) { 5750 if (Cur->isRecord()) 5751 Diag(Loc, diag::err_member_qualification) 5752 << Name << SS.getRange(); 5753 else if (isa<TranslationUnitDecl>(DC)) 5754 Diag(Loc, diag::err_invalid_declarator_global_scope) 5755 << Name << SS.getRange(); 5756 else if (isa<FunctionDecl>(Cur)) 5757 Diag(Loc, diag::err_invalid_declarator_in_function) 5758 << Name << SS.getRange(); 5759 else if (isa<BlockDecl>(Cur)) 5760 Diag(Loc, diag::err_invalid_declarator_in_block) 5761 << Name << SS.getRange(); 5762 else 5763 Diag(Loc, diag::err_invalid_declarator_scope) 5764 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5765 5766 return true; 5767 } 5768 5769 if (Cur->isRecord()) { 5770 // Cannot qualify members within a class. 5771 Diag(Loc, diag::err_member_qualification) 5772 << Name << SS.getRange(); 5773 SS.clear(); 5774 5775 // C++ constructors and destructors with incorrect scopes can break 5776 // our AST invariants by having the wrong underlying types. If 5777 // that's the case, then drop this declaration entirely. 5778 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5779 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5780 !Context.hasSameType(Name.getCXXNameType(), 5781 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5782 return true; 5783 5784 return false; 5785 } 5786 5787 // C++11 [dcl.meaning]p1: 5788 // [...] "The nested-name-specifier of the qualified declarator-id shall 5789 // not begin with a decltype-specifer" 5790 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5791 while (SpecLoc.getPrefix()) 5792 SpecLoc = SpecLoc.getPrefix(); 5793 if (isa_and_nonnull<DecltypeType>( 5794 SpecLoc.getNestedNameSpecifier()->getAsType())) 5795 Diag(Loc, diag::err_decltype_in_declarator) 5796 << SpecLoc.getTypeLoc().getSourceRange(); 5797 5798 return false; 5799 } 5800 5801 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5802 MultiTemplateParamsArg TemplateParamLists) { 5803 // TODO: consider using NameInfo for diagnostic. 5804 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5805 DeclarationName Name = NameInfo.getName(); 5806 5807 // All of these full declarators require an identifier. If it doesn't have 5808 // one, the ParsedFreeStandingDeclSpec action should be used. 5809 if (D.isDecompositionDeclarator()) { 5810 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5811 } else if (!Name) { 5812 if (!D.isInvalidType()) // Reject this if we think it is valid. 5813 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5814 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5815 return nullptr; 5816 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5817 return nullptr; 5818 5819 // The scope passed in may not be a decl scope. Zip up the scope tree until 5820 // we find one that is. 5821 while ((S->getFlags() & Scope::DeclScope) == 0 || 5822 (S->getFlags() & Scope::TemplateParamScope) != 0) 5823 S = S->getParent(); 5824 5825 DeclContext *DC = CurContext; 5826 if (D.getCXXScopeSpec().isInvalid()) 5827 D.setInvalidType(); 5828 else if (D.getCXXScopeSpec().isSet()) { 5829 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5830 UPPC_DeclarationQualifier)) 5831 return nullptr; 5832 5833 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5834 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5835 if (!DC || isa<EnumDecl>(DC)) { 5836 // If we could not compute the declaration context, it's because the 5837 // declaration context is dependent but does not refer to a class, 5838 // class template, or class template partial specialization. Complain 5839 // and return early, to avoid the coming semantic disaster. 5840 Diag(D.getIdentifierLoc(), 5841 diag::err_template_qualified_declarator_no_match) 5842 << D.getCXXScopeSpec().getScopeRep() 5843 << D.getCXXScopeSpec().getRange(); 5844 return nullptr; 5845 } 5846 bool IsDependentContext = DC->isDependentContext(); 5847 5848 if (!IsDependentContext && 5849 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5850 return nullptr; 5851 5852 // If a class is incomplete, do not parse entities inside it. 5853 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5854 Diag(D.getIdentifierLoc(), 5855 diag::err_member_def_undefined_record) 5856 << Name << DC << D.getCXXScopeSpec().getRange(); 5857 return nullptr; 5858 } 5859 if (!D.getDeclSpec().isFriendSpecified()) { 5860 if (diagnoseQualifiedDeclaration( 5861 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5862 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5863 if (DC->isRecord()) 5864 return nullptr; 5865 5866 D.setInvalidType(); 5867 } 5868 } 5869 5870 // Check whether we need to rebuild the type of the given 5871 // declaration in the current instantiation. 5872 if (EnteringContext && IsDependentContext && 5873 TemplateParamLists.size() != 0) { 5874 ContextRAII SavedContext(*this, DC); 5875 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5876 D.setInvalidType(); 5877 } 5878 } 5879 5880 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5881 QualType R = TInfo->getType(); 5882 5883 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5884 UPPC_DeclarationType)) 5885 D.setInvalidType(); 5886 5887 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5888 forRedeclarationInCurContext()); 5889 5890 // See if this is a redefinition of a variable in the same scope. 5891 if (!D.getCXXScopeSpec().isSet()) { 5892 bool IsLinkageLookup = false; 5893 bool CreateBuiltins = false; 5894 5895 // If the declaration we're planning to build will be a function 5896 // or object with linkage, then look for another declaration with 5897 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5898 // 5899 // If the declaration we're planning to build will be declared with 5900 // external linkage in the translation unit, create any builtin with 5901 // the same name. 5902 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5903 /* Do nothing*/; 5904 else if (CurContext->isFunctionOrMethod() && 5905 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5906 R->isFunctionType())) { 5907 IsLinkageLookup = true; 5908 CreateBuiltins = 5909 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5910 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5911 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5912 CreateBuiltins = true; 5913 5914 if (IsLinkageLookup) { 5915 Previous.clear(LookupRedeclarationWithLinkage); 5916 Previous.setRedeclarationKind(ForExternalRedeclaration); 5917 } 5918 5919 LookupName(Previous, S, CreateBuiltins); 5920 } else { // Something like "int foo::x;" 5921 LookupQualifiedName(Previous, DC); 5922 5923 // C++ [dcl.meaning]p1: 5924 // When the declarator-id is qualified, the declaration shall refer to a 5925 // previously declared member of the class or namespace to which the 5926 // qualifier refers (or, in the case of a namespace, of an element of the 5927 // inline namespace set of that namespace (7.3.1)) or to a specialization 5928 // thereof; [...] 5929 // 5930 // Note that we already checked the context above, and that we do not have 5931 // enough information to make sure that Previous contains the declaration 5932 // we want to match. For example, given: 5933 // 5934 // class X { 5935 // void f(); 5936 // void f(float); 5937 // }; 5938 // 5939 // void X::f(int) { } // ill-formed 5940 // 5941 // In this case, Previous will point to the overload set 5942 // containing the two f's declared in X, but neither of them 5943 // matches. 5944 5945 // C++ [dcl.meaning]p1: 5946 // [...] the member shall not merely have been introduced by a 5947 // using-declaration in the scope of the class or namespace nominated by 5948 // the nested-name-specifier of the declarator-id. 5949 RemoveUsingDecls(Previous); 5950 } 5951 5952 if (Previous.isSingleResult() && 5953 Previous.getFoundDecl()->isTemplateParameter()) { 5954 // Maybe we will complain about the shadowed template parameter. 5955 if (!D.isInvalidType()) 5956 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5957 Previous.getFoundDecl()); 5958 5959 // Just pretend that we didn't see the previous declaration. 5960 Previous.clear(); 5961 } 5962 5963 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5964 // Forget that the previous declaration is the injected-class-name. 5965 Previous.clear(); 5966 5967 // In C++, the previous declaration we find might be a tag type 5968 // (class or enum). In this case, the new declaration will hide the 5969 // tag type. Note that this applies to functions, function templates, and 5970 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5971 if (Previous.isSingleTagDecl() && 5972 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5973 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5974 Previous.clear(); 5975 5976 // Check that there are no default arguments other than in the parameters 5977 // of a function declaration (C++ only). 5978 if (getLangOpts().CPlusPlus) 5979 CheckExtraCXXDefaultArguments(D); 5980 5981 NamedDecl *New; 5982 5983 bool AddToScope = true; 5984 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5985 if (TemplateParamLists.size()) { 5986 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5987 return nullptr; 5988 } 5989 5990 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5991 } else if (R->isFunctionType()) { 5992 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5993 TemplateParamLists, 5994 AddToScope); 5995 } else { 5996 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5997 AddToScope); 5998 } 5999 6000 if (!New) 6001 return nullptr; 6002 6003 // If this has an identifier and is not a function template specialization, 6004 // add it to the scope stack. 6005 if (New->getDeclName() && AddToScope) 6006 PushOnScopeChains(New, S); 6007 6008 if (isInOpenMPDeclareTargetContext()) 6009 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6010 6011 return New; 6012 } 6013 6014 /// Helper method to turn variable array types into constant array 6015 /// types in certain situations which would otherwise be errors (for 6016 /// GCC compatibility). 6017 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6018 ASTContext &Context, 6019 bool &SizeIsNegative, 6020 llvm::APSInt &Oversized) { 6021 // This method tries to turn a variable array into a constant 6022 // array even when the size isn't an ICE. This is necessary 6023 // for compatibility with code that depends on gcc's buggy 6024 // constant expression folding, like struct {char x[(int)(char*)2];} 6025 SizeIsNegative = false; 6026 Oversized = 0; 6027 6028 if (T->isDependentType()) 6029 return QualType(); 6030 6031 QualifierCollector Qs; 6032 const Type *Ty = Qs.strip(T); 6033 6034 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6035 QualType Pointee = PTy->getPointeeType(); 6036 QualType FixedType = 6037 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6038 Oversized); 6039 if (FixedType.isNull()) return FixedType; 6040 FixedType = Context.getPointerType(FixedType); 6041 return Qs.apply(Context, FixedType); 6042 } 6043 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6044 QualType Inner = PTy->getInnerType(); 6045 QualType FixedType = 6046 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6047 Oversized); 6048 if (FixedType.isNull()) return FixedType; 6049 FixedType = Context.getParenType(FixedType); 6050 return Qs.apply(Context, FixedType); 6051 } 6052 6053 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6054 if (!VLATy) 6055 return QualType(); 6056 6057 QualType ElemTy = VLATy->getElementType(); 6058 if (ElemTy->isVariablyModifiedType()) { 6059 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6060 SizeIsNegative, Oversized); 6061 if (ElemTy.isNull()) 6062 return QualType(); 6063 } 6064 6065 Expr::EvalResult Result; 6066 if (!VLATy->getSizeExpr() || 6067 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6068 return QualType(); 6069 6070 llvm::APSInt Res = Result.Val.getInt(); 6071 6072 // Check whether the array size is negative. 6073 if (Res.isSigned() && Res.isNegative()) { 6074 SizeIsNegative = true; 6075 return QualType(); 6076 } 6077 6078 // Check whether the array is too large to be addressed. 6079 unsigned ActiveSizeBits = 6080 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6081 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6082 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6083 : Res.getActiveBits(); 6084 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6085 Oversized = Res; 6086 return QualType(); 6087 } 6088 6089 QualType FoldedArrayType = Context.getConstantArrayType( 6090 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6091 return Qs.apply(Context, FoldedArrayType); 6092 } 6093 6094 static void 6095 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6096 SrcTL = SrcTL.getUnqualifiedLoc(); 6097 DstTL = DstTL.getUnqualifiedLoc(); 6098 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6099 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6100 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6101 DstPTL.getPointeeLoc()); 6102 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6103 return; 6104 } 6105 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6106 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6107 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6108 DstPTL.getInnerLoc()); 6109 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6110 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6111 return; 6112 } 6113 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6114 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6115 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6116 TypeLoc DstElemTL = DstATL.getElementLoc(); 6117 if (VariableArrayTypeLoc SrcElemATL = 6118 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6119 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6120 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6121 } else { 6122 DstElemTL.initializeFullCopy(SrcElemTL); 6123 } 6124 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6125 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6126 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6127 } 6128 6129 /// Helper method to turn variable array types into constant array 6130 /// types in certain situations which would otherwise be errors (for 6131 /// GCC compatibility). 6132 static TypeSourceInfo* 6133 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6134 ASTContext &Context, 6135 bool &SizeIsNegative, 6136 llvm::APSInt &Oversized) { 6137 QualType FixedTy 6138 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6139 SizeIsNegative, Oversized); 6140 if (FixedTy.isNull()) 6141 return nullptr; 6142 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6143 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6144 FixedTInfo->getTypeLoc()); 6145 return FixedTInfo; 6146 } 6147 6148 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6149 /// true if we were successful. 6150 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6151 QualType &T, SourceLocation Loc, 6152 unsigned FailedFoldDiagID) { 6153 bool SizeIsNegative; 6154 llvm::APSInt Oversized; 6155 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6156 TInfo, Context, SizeIsNegative, Oversized); 6157 if (FixedTInfo) { 6158 Diag(Loc, diag::ext_vla_folded_to_constant); 6159 TInfo = FixedTInfo; 6160 T = FixedTInfo->getType(); 6161 return true; 6162 } 6163 6164 if (SizeIsNegative) 6165 Diag(Loc, diag::err_typecheck_negative_array_size); 6166 else if (Oversized.getBoolValue()) 6167 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6168 else if (FailedFoldDiagID) 6169 Diag(Loc, FailedFoldDiagID); 6170 return false; 6171 } 6172 6173 /// Register the given locally-scoped extern "C" declaration so 6174 /// that it can be found later for redeclarations. We include any extern "C" 6175 /// declaration that is not visible in the translation unit here, not just 6176 /// function-scope declarations. 6177 void 6178 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6179 if (!getLangOpts().CPlusPlus && 6180 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6181 // Don't need to track declarations in the TU in C. 6182 return; 6183 6184 // Note that we have a locally-scoped external with this name. 6185 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6186 } 6187 6188 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6189 // FIXME: We can have multiple results via __attribute__((overloadable)). 6190 auto Result = Context.getExternCContextDecl()->lookup(Name); 6191 return Result.empty() ? nullptr : *Result.begin(); 6192 } 6193 6194 /// Diagnose function specifiers on a declaration of an identifier that 6195 /// does not identify a function. 6196 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6197 // FIXME: We should probably indicate the identifier in question to avoid 6198 // confusion for constructs like "virtual int a(), b;" 6199 if (DS.isVirtualSpecified()) 6200 Diag(DS.getVirtualSpecLoc(), 6201 diag::err_virtual_non_function); 6202 6203 if (DS.hasExplicitSpecifier()) 6204 Diag(DS.getExplicitSpecLoc(), 6205 diag::err_explicit_non_function); 6206 6207 if (DS.isNoreturnSpecified()) 6208 Diag(DS.getNoreturnSpecLoc(), 6209 diag::err_noreturn_non_function); 6210 } 6211 6212 NamedDecl* 6213 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6214 TypeSourceInfo *TInfo, LookupResult &Previous) { 6215 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6216 if (D.getCXXScopeSpec().isSet()) { 6217 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6218 << D.getCXXScopeSpec().getRange(); 6219 D.setInvalidType(); 6220 // Pretend we didn't see the scope specifier. 6221 DC = CurContext; 6222 Previous.clear(); 6223 } 6224 6225 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6226 6227 if (D.getDeclSpec().isInlineSpecified()) 6228 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6229 << getLangOpts().CPlusPlus17; 6230 if (D.getDeclSpec().hasConstexprSpecifier()) 6231 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6232 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6233 6234 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6235 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6236 Diag(D.getName().StartLocation, 6237 diag::err_deduction_guide_invalid_specifier) 6238 << "typedef"; 6239 else 6240 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6241 << D.getName().getSourceRange(); 6242 return nullptr; 6243 } 6244 6245 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6246 if (!NewTD) return nullptr; 6247 6248 // Handle attributes prior to checking for duplicates in MergeVarDecl 6249 ProcessDeclAttributes(S, NewTD, D); 6250 6251 CheckTypedefForVariablyModifiedType(S, NewTD); 6252 6253 bool Redeclaration = D.isRedeclaration(); 6254 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6255 D.setRedeclaration(Redeclaration); 6256 return ND; 6257 } 6258 6259 void 6260 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6261 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6262 // then it shall have block scope. 6263 // Note that variably modified types must be fixed before merging the decl so 6264 // that redeclarations will match. 6265 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6266 QualType T = TInfo->getType(); 6267 if (T->isVariablyModifiedType()) { 6268 setFunctionHasBranchProtectedScope(); 6269 6270 if (S->getFnParent() == nullptr) { 6271 bool SizeIsNegative; 6272 llvm::APSInt Oversized; 6273 TypeSourceInfo *FixedTInfo = 6274 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6275 SizeIsNegative, 6276 Oversized); 6277 if (FixedTInfo) { 6278 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6279 NewTD->setTypeSourceInfo(FixedTInfo); 6280 } else { 6281 if (SizeIsNegative) 6282 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6283 else if (T->isVariableArrayType()) 6284 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6285 else if (Oversized.getBoolValue()) 6286 Diag(NewTD->getLocation(), diag::err_array_too_large) 6287 << toString(Oversized, 10); 6288 else 6289 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6290 NewTD->setInvalidDecl(); 6291 } 6292 } 6293 } 6294 } 6295 6296 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6297 /// declares a typedef-name, either using the 'typedef' type specifier or via 6298 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6299 NamedDecl* 6300 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6301 LookupResult &Previous, bool &Redeclaration) { 6302 6303 // Find the shadowed declaration before filtering for scope. 6304 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6305 6306 // Merge the decl with the existing one if appropriate. If the decl is 6307 // in an outer scope, it isn't the same thing. 6308 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6309 /*AllowInlineNamespace*/false); 6310 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6311 if (!Previous.empty()) { 6312 Redeclaration = true; 6313 MergeTypedefNameDecl(S, NewTD, Previous); 6314 } else { 6315 inferGslPointerAttribute(NewTD); 6316 } 6317 6318 if (ShadowedDecl && !Redeclaration) 6319 CheckShadow(NewTD, ShadowedDecl, Previous); 6320 6321 // If this is the C FILE type, notify the AST context. 6322 if (IdentifierInfo *II = NewTD->getIdentifier()) 6323 if (!NewTD->isInvalidDecl() && 6324 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6325 if (II->isStr("FILE")) 6326 Context.setFILEDecl(NewTD); 6327 else if (II->isStr("jmp_buf")) 6328 Context.setjmp_bufDecl(NewTD); 6329 else if (II->isStr("sigjmp_buf")) 6330 Context.setsigjmp_bufDecl(NewTD); 6331 else if (II->isStr("ucontext_t")) 6332 Context.setucontext_tDecl(NewTD); 6333 } 6334 6335 return NewTD; 6336 } 6337 6338 /// Determines whether the given declaration is an out-of-scope 6339 /// previous declaration. 6340 /// 6341 /// This routine should be invoked when name lookup has found a 6342 /// previous declaration (PrevDecl) that is not in the scope where a 6343 /// new declaration by the same name is being introduced. If the new 6344 /// declaration occurs in a local scope, previous declarations with 6345 /// linkage may still be considered previous declarations (C99 6346 /// 6.2.2p4-5, C++ [basic.link]p6). 6347 /// 6348 /// \param PrevDecl the previous declaration found by name 6349 /// lookup 6350 /// 6351 /// \param DC the context in which the new declaration is being 6352 /// declared. 6353 /// 6354 /// \returns true if PrevDecl is an out-of-scope previous declaration 6355 /// for a new delcaration with the same name. 6356 static bool 6357 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6358 ASTContext &Context) { 6359 if (!PrevDecl) 6360 return false; 6361 6362 if (!PrevDecl->hasLinkage()) 6363 return false; 6364 6365 if (Context.getLangOpts().CPlusPlus) { 6366 // C++ [basic.link]p6: 6367 // If there is a visible declaration of an entity with linkage 6368 // having the same name and type, ignoring entities declared 6369 // outside the innermost enclosing namespace scope, the block 6370 // scope declaration declares that same entity and receives the 6371 // linkage of the previous declaration. 6372 DeclContext *OuterContext = DC->getRedeclContext(); 6373 if (!OuterContext->isFunctionOrMethod()) 6374 // This rule only applies to block-scope declarations. 6375 return false; 6376 6377 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6378 if (PrevOuterContext->isRecord()) 6379 // We found a member function: ignore it. 6380 return false; 6381 6382 // Find the innermost enclosing namespace for the new and 6383 // previous declarations. 6384 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6385 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6386 6387 // The previous declaration is in a different namespace, so it 6388 // isn't the same function. 6389 if (!OuterContext->Equals(PrevOuterContext)) 6390 return false; 6391 } 6392 6393 return true; 6394 } 6395 6396 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6397 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6398 if (!SS.isSet()) return; 6399 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6400 } 6401 6402 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6403 QualType type = decl->getType(); 6404 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6405 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6406 // Various kinds of declaration aren't allowed to be __autoreleasing. 6407 unsigned kind = -1U; 6408 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6409 if (var->hasAttr<BlocksAttr>()) 6410 kind = 0; // __block 6411 else if (!var->hasLocalStorage()) 6412 kind = 1; // global 6413 } else if (isa<ObjCIvarDecl>(decl)) { 6414 kind = 3; // ivar 6415 } else if (isa<FieldDecl>(decl)) { 6416 kind = 2; // field 6417 } 6418 6419 if (kind != -1U) { 6420 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6421 << kind; 6422 } 6423 } else if (lifetime == Qualifiers::OCL_None) { 6424 // Try to infer lifetime. 6425 if (!type->isObjCLifetimeType()) 6426 return false; 6427 6428 lifetime = type->getObjCARCImplicitLifetime(); 6429 type = Context.getLifetimeQualifiedType(type, lifetime); 6430 decl->setType(type); 6431 } 6432 6433 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6434 // Thread-local variables cannot have lifetime. 6435 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6436 var->getTLSKind()) { 6437 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6438 << var->getType(); 6439 return true; 6440 } 6441 } 6442 6443 return false; 6444 } 6445 6446 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6447 if (Decl->getType().hasAddressSpace()) 6448 return; 6449 if (Decl->getType()->isDependentType()) 6450 return; 6451 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6452 QualType Type = Var->getType(); 6453 if (Type->isSamplerT() || Type->isVoidType()) 6454 return; 6455 LangAS ImplAS = LangAS::opencl_private; 6456 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6457 // __opencl_c_program_scope_global_variables feature, the address space 6458 // for a variable at program scope or a static or extern variable inside 6459 // a function are inferred to be __global. 6460 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6461 Var->hasGlobalStorage()) 6462 ImplAS = LangAS::opencl_global; 6463 // If the original type from a decayed type is an array type and that array 6464 // type has no address space yet, deduce it now. 6465 if (auto DT = dyn_cast<DecayedType>(Type)) { 6466 auto OrigTy = DT->getOriginalType(); 6467 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6468 // Add the address space to the original array type and then propagate 6469 // that to the element type through `getAsArrayType`. 6470 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6471 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6472 // Re-generate the decayed type. 6473 Type = Context.getDecayedType(OrigTy); 6474 } 6475 } 6476 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6477 // Apply any qualifiers (including address space) from the array type to 6478 // the element type. This implements C99 6.7.3p8: "If the specification of 6479 // an array type includes any type qualifiers, the element type is so 6480 // qualified, not the array type." 6481 if (Type->isArrayType()) 6482 Type = QualType(Context.getAsArrayType(Type), 0); 6483 Decl->setType(Type); 6484 } 6485 } 6486 6487 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6488 // Ensure that an auto decl is deduced otherwise the checks below might cache 6489 // the wrong linkage. 6490 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6491 6492 // 'weak' only applies to declarations with external linkage. 6493 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6494 if (!ND.isExternallyVisible()) { 6495 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6496 ND.dropAttr<WeakAttr>(); 6497 } 6498 } 6499 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6500 if (ND.isExternallyVisible()) { 6501 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6502 ND.dropAttr<WeakRefAttr>(); 6503 ND.dropAttr<AliasAttr>(); 6504 } 6505 } 6506 6507 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6508 if (VD->hasInit()) { 6509 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6510 assert(VD->isThisDeclarationADefinition() && 6511 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6512 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6513 VD->dropAttr<AliasAttr>(); 6514 } 6515 } 6516 } 6517 6518 // 'selectany' only applies to externally visible variable declarations. 6519 // It does not apply to functions. 6520 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6521 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6522 S.Diag(Attr->getLocation(), 6523 diag::err_attribute_selectany_non_extern_data); 6524 ND.dropAttr<SelectAnyAttr>(); 6525 } 6526 } 6527 6528 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6529 auto *VD = dyn_cast<VarDecl>(&ND); 6530 bool IsAnonymousNS = false; 6531 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6532 if (VD) { 6533 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6534 while (NS && !IsAnonymousNS) { 6535 IsAnonymousNS = NS->isAnonymousNamespace(); 6536 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6537 } 6538 } 6539 // dll attributes require external linkage. Static locals may have external 6540 // linkage but still cannot be explicitly imported or exported. 6541 // In Microsoft mode, a variable defined in anonymous namespace must have 6542 // external linkage in order to be exported. 6543 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6544 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6545 (!AnonNSInMicrosoftMode && 6546 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6547 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6548 << &ND << Attr; 6549 ND.setInvalidDecl(); 6550 } 6551 } 6552 6553 // Check the attributes on the function type, if any. 6554 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6555 // Don't declare this variable in the second operand of the for-statement; 6556 // GCC miscompiles that by ending its lifetime before evaluating the 6557 // third operand. See gcc.gnu.org/PR86769. 6558 AttributedTypeLoc ATL; 6559 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6560 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6561 TL = ATL.getModifiedLoc()) { 6562 // The [[lifetimebound]] attribute can be applied to the implicit object 6563 // parameter of a non-static member function (other than a ctor or dtor) 6564 // by applying it to the function type. 6565 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6566 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6567 if (!MD || MD->isStatic()) { 6568 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6569 << !MD << A->getRange(); 6570 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6571 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6572 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6573 } 6574 } 6575 } 6576 } 6577 } 6578 6579 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6580 NamedDecl *NewDecl, 6581 bool IsSpecialization, 6582 bool IsDefinition) { 6583 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6584 return; 6585 6586 bool IsTemplate = false; 6587 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6588 OldDecl = OldTD->getTemplatedDecl(); 6589 IsTemplate = true; 6590 if (!IsSpecialization) 6591 IsDefinition = false; 6592 } 6593 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6594 NewDecl = NewTD->getTemplatedDecl(); 6595 IsTemplate = true; 6596 } 6597 6598 if (!OldDecl || !NewDecl) 6599 return; 6600 6601 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6602 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6603 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6604 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6605 6606 // dllimport and dllexport are inheritable attributes so we have to exclude 6607 // inherited attribute instances. 6608 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6609 (NewExportAttr && !NewExportAttr->isInherited()); 6610 6611 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6612 // the only exception being explicit specializations. 6613 // Implicitly generated declarations are also excluded for now because there 6614 // is no other way to switch these to use dllimport or dllexport. 6615 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6616 6617 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6618 // Allow with a warning for free functions and global variables. 6619 bool JustWarn = false; 6620 if (!OldDecl->isCXXClassMember()) { 6621 auto *VD = dyn_cast<VarDecl>(OldDecl); 6622 if (VD && !VD->getDescribedVarTemplate()) 6623 JustWarn = true; 6624 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6625 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6626 JustWarn = true; 6627 } 6628 6629 // We cannot change a declaration that's been used because IR has already 6630 // been emitted. Dllimported functions will still work though (modulo 6631 // address equality) as they can use the thunk. 6632 if (OldDecl->isUsed()) 6633 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6634 JustWarn = false; 6635 6636 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6637 : diag::err_attribute_dll_redeclaration; 6638 S.Diag(NewDecl->getLocation(), DiagID) 6639 << NewDecl 6640 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6641 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6642 if (!JustWarn) { 6643 NewDecl->setInvalidDecl(); 6644 return; 6645 } 6646 } 6647 6648 // A redeclaration is not allowed to drop a dllimport attribute, the only 6649 // exceptions being inline function definitions (except for function 6650 // templates), local extern declarations, qualified friend declarations or 6651 // special MSVC extension: in the last case, the declaration is treated as if 6652 // it were marked dllexport. 6653 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6654 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6655 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6656 // Ignore static data because out-of-line definitions are diagnosed 6657 // separately. 6658 IsStaticDataMember = VD->isStaticDataMember(); 6659 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6660 VarDecl::DeclarationOnly; 6661 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6662 IsInline = FD->isInlined(); 6663 IsQualifiedFriend = FD->getQualifier() && 6664 FD->getFriendObjectKind() == Decl::FOK_Declared; 6665 } 6666 6667 if (OldImportAttr && !HasNewAttr && 6668 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6669 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6670 if (IsMicrosoftABI && IsDefinition) { 6671 S.Diag(NewDecl->getLocation(), 6672 diag::warn_redeclaration_without_import_attribute) 6673 << NewDecl; 6674 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6675 NewDecl->dropAttr<DLLImportAttr>(); 6676 NewDecl->addAttr( 6677 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6678 } else { 6679 S.Diag(NewDecl->getLocation(), 6680 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6681 << NewDecl << OldImportAttr; 6682 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6683 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6684 OldDecl->dropAttr<DLLImportAttr>(); 6685 NewDecl->dropAttr<DLLImportAttr>(); 6686 } 6687 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6688 // In MinGW, seeing a function declared inline drops the dllimport 6689 // attribute. 6690 OldDecl->dropAttr<DLLImportAttr>(); 6691 NewDecl->dropAttr<DLLImportAttr>(); 6692 S.Diag(NewDecl->getLocation(), 6693 diag::warn_dllimport_dropped_from_inline_function) 6694 << NewDecl << OldImportAttr; 6695 } 6696 6697 // A specialization of a class template member function is processed here 6698 // since it's a redeclaration. If the parent class is dllexport, the 6699 // specialization inherits that attribute. This doesn't happen automatically 6700 // since the parent class isn't instantiated until later. 6701 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6702 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6703 !NewImportAttr && !NewExportAttr) { 6704 if (const DLLExportAttr *ParentExportAttr = 6705 MD->getParent()->getAttr<DLLExportAttr>()) { 6706 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6707 NewAttr->setInherited(true); 6708 NewDecl->addAttr(NewAttr); 6709 } 6710 } 6711 } 6712 } 6713 6714 /// Given that we are within the definition of the given function, 6715 /// will that definition behave like C99's 'inline', where the 6716 /// definition is discarded except for optimization purposes? 6717 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6718 // Try to avoid calling GetGVALinkageForFunction. 6719 6720 // All cases of this require the 'inline' keyword. 6721 if (!FD->isInlined()) return false; 6722 6723 // This is only possible in C++ with the gnu_inline attribute. 6724 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6725 return false; 6726 6727 // Okay, go ahead and call the relatively-more-expensive function. 6728 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6729 } 6730 6731 /// Determine whether a variable is extern "C" prior to attaching 6732 /// an initializer. We can't just call isExternC() here, because that 6733 /// will also compute and cache whether the declaration is externally 6734 /// visible, which might change when we attach the initializer. 6735 /// 6736 /// This can only be used if the declaration is known to not be a 6737 /// redeclaration of an internal linkage declaration. 6738 /// 6739 /// For instance: 6740 /// 6741 /// auto x = []{}; 6742 /// 6743 /// Attaching the initializer here makes this declaration not externally 6744 /// visible, because its type has internal linkage. 6745 /// 6746 /// FIXME: This is a hack. 6747 template<typename T> 6748 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6749 if (S.getLangOpts().CPlusPlus) { 6750 // In C++, the overloadable attribute negates the effects of extern "C". 6751 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6752 return false; 6753 6754 // So do CUDA's host/device attributes. 6755 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6756 D->template hasAttr<CUDAHostAttr>())) 6757 return false; 6758 } 6759 return D->isExternC(); 6760 } 6761 6762 static bool shouldConsiderLinkage(const VarDecl *VD) { 6763 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6764 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6765 isa<OMPDeclareMapperDecl>(DC)) 6766 return VD->hasExternalStorage(); 6767 if (DC->isFileContext()) 6768 return true; 6769 if (DC->isRecord()) 6770 return false; 6771 if (isa<RequiresExprBodyDecl>(DC)) 6772 return false; 6773 llvm_unreachable("Unexpected context"); 6774 } 6775 6776 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6777 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6778 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6779 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6780 return true; 6781 if (DC->isRecord()) 6782 return false; 6783 llvm_unreachable("Unexpected context"); 6784 } 6785 6786 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6787 ParsedAttr::Kind Kind) { 6788 // Check decl attributes on the DeclSpec. 6789 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6790 return true; 6791 6792 // Walk the declarator structure, checking decl attributes that were in a type 6793 // position to the decl itself. 6794 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6795 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6796 return true; 6797 } 6798 6799 // Finally, check attributes on the decl itself. 6800 return PD.getAttributes().hasAttribute(Kind); 6801 } 6802 6803 /// Adjust the \c DeclContext for a function or variable that might be a 6804 /// function-local external declaration. 6805 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6806 if (!DC->isFunctionOrMethod()) 6807 return false; 6808 6809 // If this is a local extern function or variable declared within a function 6810 // template, don't add it into the enclosing namespace scope until it is 6811 // instantiated; it might have a dependent type right now. 6812 if (DC->isDependentContext()) 6813 return true; 6814 6815 // C++11 [basic.link]p7: 6816 // When a block scope declaration of an entity with linkage is not found to 6817 // refer to some other declaration, then that entity is a member of the 6818 // innermost enclosing namespace. 6819 // 6820 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6821 // semantically-enclosing namespace, not a lexically-enclosing one. 6822 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6823 DC = DC->getParent(); 6824 return true; 6825 } 6826 6827 /// Returns true if given declaration has external C language linkage. 6828 static bool isDeclExternC(const Decl *D) { 6829 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6830 return FD->isExternC(); 6831 if (const auto *VD = dyn_cast<VarDecl>(D)) 6832 return VD->isExternC(); 6833 6834 llvm_unreachable("Unknown type of decl!"); 6835 } 6836 6837 /// Returns true if there hasn't been any invalid type diagnosed. 6838 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6839 DeclContext *DC = NewVD->getDeclContext(); 6840 QualType R = NewVD->getType(); 6841 6842 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6843 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6844 // argument. 6845 if (R->isImageType() || R->isPipeType()) { 6846 Se.Diag(NewVD->getLocation(), 6847 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6848 << R; 6849 NewVD->setInvalidDecl(); 6850 return false; 6851 } 6852 6853 // OpenCL v1.2 s6.9.r: 6854 // The event type cannot be used to declare a program scope variable. 6855 // OpenCL v2.0 s6.9.q: 6856 // The clk_event_t and reserve_id_t types cannot be declared in program 6857 // scope. 6858 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6859 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6860 Se.Diag(NewVD->getLocation(), 6861 diag::err_invalid_type_for_program_scope_var) 6862 << R; 6863 NewVD->setInvalidDecl(); 6864 return false; 6865 } 6866 } 6867 6868 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6869 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6870 Se.getLangOpts())) { 6871 QualType NR = R.getCanonicalType(); 6872 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6873 NR->isReferenceType()) { 6874 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6875 NR->isFunctionReferenceType()) { 6876 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6877 << NR->isReferenceType(); 6878 NewVD->setInvalidDecl(); 6879 return false; 6880 } 6881 NR = NR->getPointeeType(); 6882 } 6883 } 6884 6885 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6886 Se.getLangOpts())) { 6887 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6888 // half array type (unless the cl_khr_fp16 extension is enabled). 6889 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6890 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6891 NewVD->setInvalidDecl(); 6892 return false; 6893 } 6894 } 6895 6896 // OpenCL v1.2 s6.9.r: 6897 // The event type cannot be used with the __local, __constant and __global 6898 // address space qualifiers. 6899 if (R->isEventT()) { 6900 if (R.getAddressSpace() != LangAS::opencl_private) { 6901 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6902 NewVD->setInvalidDecl(); 6903 return false; 6904 } 6905 } 6906 6907 if (R->isSamplerT()) { 6908 // OpenCL v1.2 s6.9.b p4: 6909 // The sampler type cannot be used with the __local and __global address 6910 // space qualifiers. 6911 if (R.getAddressSpace() == LangAS::opencl_local || 6912 R.getAddressSpace() == LangAS::opencl_global) { 6913 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 6914 NewVD->setInvalidDecl(); 6915 } 6916 6917 // OpenCL v1.2 s6.12.14.1: 6918 // A global sampler must be declared with either the constant address 6919 // space qualifier or with the const qualifier. 6920 if (DC->isTranslationUnit() && 6921 !(R.getAddressSpace() == LangAS::opencl_constant || 6922 R.isConstQualified())) { 6923 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 6924 NewVD->setInvalidDecl(); 6925 } 6926 if (NewVD->isInvalidDecl()) 6927 return false; 6928 } 6929 6930 return true; 6931 } 6932 6933 template <typename AttrTy> 6934 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 6935 const TypedefNameDecl *TND = TT->getDecl(); 6936 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 6937 AttrTy *Clone = Attribute->clone(S.Context); 6938 Clone->setInherited(true); 6939 D->addAttr(Clone); 6940 } 6941 } 6942 6943 NamedDecl *Sema::ActOnVariableDeclarator( 6944 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6945 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6946 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6947 QualType R = TInfo->getType(); 6948 DeclarationName Name = GetNameForDeclarator(D).getName(); 6949 6950 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6951 6952 if (D.isDecompositionDeclarator()) { 6953 // Take the name of the first declarator as our name for diagnostic 6954 // purposes. 6955 auto &Decomp = D.getDecompositionDeclarator(); 6956 if (!Decomp.bindings().empty()) { 6957 II = Decomp.bindings()[0].Name; 6958 Name = II; 6959 } 6960 } else if (!II) { 6961 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6962 return nullptr; 6963 } 6964 6965 6966 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6967 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6968 6969 // dllimport globals without explicit storage class are treated as extern. We 6970 // have to change the storage class this early to get the right DeclContext. 6971 if (SC == SC_None && !DC->isRecord() && 6972 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6973 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6974 SC = SC_Extern; 6975 6976 DeclContext *OriginalDC = DC; 6977 bool IsLocalExternDecl = SC == SC_Extern && 6978 adjustContextForLocalExternDecl(DC); 6979 6980 if (SCSpec == DeclSpec::SCS_mutable) { 6981 // mutable can only appear on non-static class members, so it's always 6982 // an error here 6983 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6984 D.setInvalidType(); 6985 SC = SC_None; 6986 } 6987 6988 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6989 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6990 D.getDeclSpec().getStorageClassSpecLoc())) { 6991 // In C++11, the 'register' storage class specifier is deprecated. 6992 // Suppress the warning in system macros, it's used in macros in some 6993 // popular C system headers, such as in glibc's htonl() macro. 6994 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6995 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6996 : diag::warn_deprecated_register) 6997 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6998 } 6999 7000 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7001 7002 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7003 // C99 6.9p2: The storage-class specifiers auto and register shall not 7004 // appear in the declaration specifiers in an external declaration. 7005 // Global Register+Asm is a GNU extension we support. 7006 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7007 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7008 D.setInvalidType(); 7009 } 7010 } 7011 7012 // If this variable has a VLA type and an initializer, try to 7013 // fold to a constant-sized type. This is otherwise invalid. 7014 if (D.hasInitializer() && R->isVariableArrayType()) 7015 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7016 /*DiagID=*/0); 7017 7018 bool IsMemberSpecialization = false; 7019 bool IsVariableTemplateSpecialization = false; 7020 bool IsPartialSpecialization = false; 7021 bool IsVariableTemplate = false; 7022 VarDecl *NewVD = nullptr; 7023 VarTemplateDecl *NewTemplate = nullptr; 7024 TemplateParameterList *TemplateParams = nullptr; 7025 if (!getLangOpts().CPlusPlus) { 7026 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7027 II, R, TInfo, SC); 7028 7029 if (R->getContainedDeducedType()) 7030 ParsingInitForAutoVars.insert(NewVD); 7031 7032 if (D.isInvalidType()) 7033 NewVD->setInvalidDecl(); 7034 7035 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7036 NewVD->hasLocalStorage()) 7037 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7038 NTCUC_AutoVar, NTCUK_Destruct); 7039 } else { 7040 bool Invalid = false; 7041 7042 if (DC->isRecord() && !CurContext->isRecord()) { 7043 // This is an out-of-line definition of a static data member. 7044 switch (SC) { 7045 case SC_None: 7046 break; 7047 case SC_Static: 7048 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7049 diag::err_static_out_of_line) 7050 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7051 break; 7052 case SC_Auto: 7053 case SC_Register: 7054 case SC_Extern: 7055 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7056 // to names of variables declared in a block or to function parameters. 7057 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7058 // of class members 7059 7060 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7061 diag::err_storage_class_for_static_member) 7062 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7063 break; 7064 case SC_PrivateExtern: 7065 llvm_unreachable("C storage class in c++!"); 7066 } 7067 } 7068 7069 if (SC == SC_Static && CurContext->isRecord()) { 7070 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7071 // Walk up the enclosing DeclContexts to check for any that are 7072 // incompatible with static data members. 7073 const DeclContext *FunctionOrMethod = nullptr; 7074 const CXXRecordDecl *AnonStruct = nullptr; 7075 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7076 if (Ctxt->isFunctionOrMethod()) { 7077 FunctionOrMethod = Ctxt; 7078 break; 7079 } 7080 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7081 if (ParentDecl && !ParentDecl->getDeclName()) { 7082 AnonStruct = ParentDecl; 7083 break; 7084 } 7085 } 7086 if (FunctionOrMethod) { 7087 // C++ [class.static.data]p5: A local class shall not have static data 7088 // members. 7089 Diag(D.getIdentifierLoc(), 7090 diag::err_static_data_member_not_allowed_in_local_class) 7091 << Name << RD->getDeclName() << RD->getTagKind(); 7092 } else if (AnonStruct) { 7093 // C++ [class.static.data]p4: Unnamed classes and classes contained 7094 // directly or indirectly within unnamed classes shall not contain 7095 // static data members. 7096 Diag(D.getIdentifierLoc(), 7097 diag::err_static_data_member_not_allowed_in_anon_struct) 7098 << Name << AnonStruct->getTagKind(); 7099 Invalid = true; 7100 } else if (RD->isUnion()) { 7101 // C++98 [class.union]p1: If a union contains a static data member, 7102 // the program is ill-formed. C++11 drops this restriction. 7103 Diag(D.getIdentifierLoc(), 7104 getLangOpts().CPlusPlus11 7105 ? diag::warn_cxx98_compat_static_data_member_in_union 7106 : diag::ext_static_data_member_in_union) << Name; 7107 } 7108 } 7109 } 7110 7111 // Match up the template parameter lists with the scope specifier, then 7112 // determine whether we have a template or a template specialization. 7113 bool InvalidScope = false; 7114 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7115 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7116 D.getCXXScopeSpec(), 7117 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7118 ? D.getName().TemplateId 7119 : nullptr, 7120 TemplateParamLists, 7121 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7122 Invalid |= InvalidScope; 7123 7124 if (TemplateParams) { 7125 if (!TemplateParams->size() && 7126 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7127 // There is an extraneous 'template<>' for this variable. Complain 7128 // about it, but allow the declaration of the variable. 7129 Diag(TemplateParams->getTemplateLoc(), 7130 diag::err_template_variable_noparams) 7131 << II 7132 << SourceRange(TemplateParams->getTemplateLoc(), 7133 TemplateParams->getRAngleLoc()); 7134 TemplateParams = nullptr; 7135 } else { 7136 // Check that we can declare a template here. 7137 if (CheckTemplateDeclScope(S, TemplateParams)) 7138 return nullptr; 7139 7140 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7141 // This is an explicit specialization or a partial specialization. 7142 IsVariableTemplateSpecialization = true; 7143 IsPartialSpecialization = TemplateParams->size() > 0; 7144 } else { // if (TemplateParams->size() > 0) 7145 // This is a template declaration. 7146 IsVariableTemplate = true; 7147 7148 // Only C++1y supports variable templates (N3651). 7149 Diag(D.getIdentifierLoc(), 7150 getLangOpts().CPlusPlus14 7151 ? diag::warn_cxx11_compat_variable_template 7152 : diag::ext_variable_template); 7153 } 7154 } 7155 } else { 7156 // Check that we can declare a member specialization here. 7157 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7158 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7159 return nullptr; 7160 assert((Invalid || 7161 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7162 "should have a 'template<>' for this decl"); 7163 } 7164 7165 if (IsVariableTemplateSpecialization) { 7166 SourceLocation TemplateKWLoc = 7167 TemplateParamLists.size() > 0 7168 ? TemplateParamLists[0]->getTemplateLoc() 7169 : SourceLocation(); 7170 DeclResult Res = ActOnVarTemplateSpecialization( 7171 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7172 IsPartialSpecialization); 7173 if (Res.isInvalid()) 7174 return nullptr; 7175 NewVD = cast<VarDecl>(Res.get()); 7176 AddToScope = false; 7177 } else if (D.isDecompositionDeclarator()) { 7178 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7179 D.getIdentifierLoc(), R, TInfo, SC, 7180 Bindings); 7181 } else 7182 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7183 D.getIdentifierLoc(), II, R, TInfo, SC); 7184 7185 // If this is supposed to be a variable template, create it as such. 7186 if (IsVariableTemplate) { 7187 NewTemplate = 7188 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7189 TemplateParams, NewVD); 7190 NewVD->setDescribedVarTemplate(NewTemplate); 7191 } 7192 7193 // If this decl has an auto type in need of deduction, make a note of the 7194 // Decl so we can diagnose uses of it in its own initializer. 7195 if (R->getContainedDeducedType()) 7196 ParsingInitForAutoVars.insert(NewVD); 7197 7198 if (D.isInvalidType() || Invalid) { 7199 NewVD->setInvalidDecl(); 7200 if (NewTemplate) 7201 NewTemplate->setInvalidDecl(); 7202 } 7203 7204 SetNestedNameSpecifier(*this, NewVD, D); 7205 7206 // If we have any template parameter lists that don't directly belong to 7207 // the variable (matching the scope specifier), store them. 7208 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7209 if (TemplateParamLists.size() > VDTemplateParamLists) 7210 NewVD->setTemplateParameterListsInfo( 7211 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7212 } 7213 7214 if (D.getDeclSpec().isInlineSpecified()) { 7215 if (!getLangOpts().CPlusPlus) { 7216 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7217 << 0; 7218 } else if (CurContext->isFunctionOrMethod()) { 7219 // 'inline' is not allowed on block scope variable declaration. 7220 Diag(D.getDeclSpec().getInlineSpecLoc(), 7221 diag::err_inline_declaration_block_scope) << Name 7222 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7223 } else { 7224 Diag(D.getDeclSpec().getInlineSpecLoc(), 7225 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7226 : diag::ext_inline_variable); 7227 NewVD->setInlineSpecified(); 7228 } 7229 } 7230 7231 // Set the lexical context. If the declarator has a C++ scope specifier, the 7232 // lexical context will be different from the semantic context. 7233 NewVD->setLexicalDeclContext(CurContext); 7234 if (NewTemplate) 7235 NewTemplate->setLexicalDeclContext(CurContext); 7236 7237 if (IsLocalExternDecl) { 7238 if (D.isDecompositionDeclarator()) 7239 for (auto *B : Bindings) 7240 B->setLocalExternDecl(); 7241 else 7242 NewVD->setLocalExternDecl(); 7243 } 7244 7245 bool EmitTLSUnsupportedError = false; 7246 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7247 // C++11 [dcl.stc]p4: 7248 // When thread_local is applied to a variable of block scope the 7249 // storage-class-specifier static is implied if it does not appear 7250 // explicitly. 7251 // Core issue: 'static' is not implied if the variable is declared 7252 // 'extern'. 7253 if (NewVD->hasLocalStorage() && 7254 (SCSpec != DeclSpec::SCS_unspecified || 7255 TSCS != DeclSpec::TSCS_thread_local || 7256 !DC->isFunctionOrMethod())) 7257 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7258 diag::err_thread_non_global) 7259 << DeclSpec::getSpecifierName(TSCS); 7260 else if (!Context.getTargetInfo().isTLSSupported()) { 7261 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7262 getLangOpts().SYCLIsDevice) { 7263 // Postpone error emission until we've collected attributes required to 7264 // figure out whether it's a host or device variable and whether the 7265 // error should be ignored. 7266 EmitTLSUnsupportedError = true; 7267 // We still need to mark the variable as TLS so it shows up in AST with 7268 // proper storage class for other tools to use even if we're not going 7269 // to emit any code for it. 7270 NewVD->setTSCSpec(TSCS); 7271 } else 7272 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7273 diag::err_thread_unsupported); 7274 } else 7275 NewVD->setTSCSpec(TSCS); 7276 } 7277 7278 switch (D.getDeclSpec().getConstexprSpecifier()) { 7279 case ConstexprSpecKind::Unspecified: 7280 break; 7281 7282 case ConstexprSpecKind::Consteval: 7283 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7284 diag::err_constexpr_wrong_decl_kind) 7285 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7286 LLVM_FALLTHROUGH; 7287 7288 case ConstexprSpecKind::Constexpr: 7289 NewVD->setConstexpr(true); 7290 // C++1z [dcl.spec.constexpr]p1: 7291 // A static data member declared with the constexpr specifier is 7292 // implicitly an inline variable. 7293 if (NewVD->isStaticDataMember() && 7294 (getLangOpts().CPlusPlus17 || 7295 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7296 NewVD->setImplicitlyInline(); 7297 break; 7298 7299 case ConstexprSpecKind::Constinit: 7300 if (!NewVD->hasGlobalStorage()) 7301 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7302 diag::err_constinit_local_variable); 7303 else 7304 NewVD->addAttr(ConstInitAttr::Create( 7305 Context, D.getDeclSpec().getConstexprSpecLoc(), 7306 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7307 break; 7308 } 7309 7310 // C99 6.7.4p3 7311 // An inline definition of a function with external linkage shall 7312 // not contain a definition of a modifiable object with static or 7313 // thread storage duration... 7314 // We only apply this when the function is required to be defined 7315 // elsewhere, i.e. when the function is not 'extern inline'. Note 7316 // that a local variable with thread storage duration still has to 7317 // be marked 'static'. Also note that it's possible to get these 7318 // semantics in C++ using __attribute__((gnu_inline)). 7319 if (SC == SC_Static && S->getFnParent() != nullptr && 7320 !NewVD->getType().isConstQualified()) { 7321 FunctionDecl *CurFD = getCurFunctionDecl(); 7322 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7323 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7324 diag::warn_static_local_in_extern_inline); 7325 MaybeSuggestAddingStaticToDecl(CurFD); 7326 } 7327 } 7328 7329 if (D.getDeclSpec().isModulePrivateSpecified()) { 7330 if (IsVariableTemplateSpecialization) 7331 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7332 << (IsPartialSpecialization ? 1 : 0) 7333 << FixItHint::CreateRemoval( 7334 D.getDeclSpec().getModulePrivateSpecLoc()); 7335 else if (IsMemberSpecialization) 7336 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7337 << 2 7338 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7339 else if (NewVD->hasLocalStorage()) 7340 Diag(NewVD->getLocation(), diag::err_module_private_local) 7341 << 0 << NewVD 7342 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7343 << FixItHint::CreateRemoval( 7344 D.getDeclSpec().getModulePrivateSpecLoc()); 7345 else { 7346 NewVD->setModulePrivate(); 7347 if (NewTemplate) 7348 NewTemplate->setModulePrivate(); 7349 for (auto *B : Bindings) 7350 B->setModulePrivate(); 7351 } 7352 } 7353 7354 if (getLangOpts().OpenCL) { 7355 deduceOpenCLAddressSpace(NewVD); 7356 7357 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7358 if (TSC != TSCS_unspecified) { 7359 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7360 diag::err_opencl_unknown_type_specifier) 7361 << getLangOpts().getOpenCLVersionString() 7362 << DeclSpec::getSpecifierName(TSC) << 1; 7363 NewVD->setInvalidDecl(); 7364 } 7365 } 7366 7367 // Handle attributes prior to checking for duplicates in MergeVarDecl 7368 ProcessDeclAttributes(S, NewVD, D); 7369 7370 // FIXME: This is probably the wrong location to be doing this and we should 7371 // probably be doing this for more attributes (especially for function 7372 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7373 // the code to copy attributes would be generated by TableGen. 7374 if (R->isFunctionPointerType()) 7375 if (const auto *TT = R->getAs<TypedefType>()) 7376 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7377 7378 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7379 getLangOpts().SYCLIsDevice) { 7380 if (EmitTLSUnsupportedError && 7381 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7382 (getLangOpts().OpenMPIsDevice && 7383 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7384 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7385 diag::err_thread_unsupported); 7386 7387 if (EmitTLSUnsupportedError && 7388 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7389 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7390 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7391 // storage [duration]." 7392 if (SC == SC_None && S->getFnParent() != nullptr && 7393 (NewVD->hasAttr<CUDASharedAttr>() || 7394 NewVD->hasAttr<CUDAConstantAttr>())) { 7395 NewVD->setStorageClass(SC_Static); 7396 } 7397 } 7398 7399 // Ensure that dllimport globals without explicit storage class are treated as 7400 // extern. The storage class is set above using parsed attributes. Now we can 7401 // check the VarDecl itself. 7402 assert(!NewVD->hasAttr<DLLImportAttr>() || 7403 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7404 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7405 7406 // In auto-retain/release, infer strong retension for variables of 7407 // retainable type. 7408 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7409 NewVD->setInvalidDecl(); 7410 7411 // Handle GNU asm-label extension (encoded as an attribute). 7412 if (Expr *E = (Expr*)D.getAsmLabel()) { 7413 // The parser guarantees this is a string. 7414 StringLiteral *SE = cast<StringLiteral>(E); 7415 StringRef Label = SE->getString(); 7416 if (S->getFnParent() != nullptr) { 7417 switch (SC) { 7418 case SC_None: 7419 case SC_Auto: 7420 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7421 break; 7422 case SC_Register: 7423 // Local Named register 7424 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7425 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7426 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7427 break; 7428 case SC_Static: 7429 case SC_Extern: 7430 case SC_PrivateExtern: 7431 break; 7432 } 7433 } else if (SC == SC_Register) { 7434 // Global Named register 7435 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7436 const auto &TI = Context.getTargetInfo(); 7437 bool HasSizeMismatch; 7438 7439 if (!TI.isValidGCCRegisterName(Label)) 7440 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7441 else if (!TI.validateGlobalRegisterVariable(Label, 7442 Context.getTypeSize(R), 7443 HasSizeMismatch)) 7444 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7445 else if (HasSizeMismatch) 7446 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7447 } 7448 7449 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7450 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7451 NewVD->setInvalidDecl(true); 7452 } 7453 } 7454 7455 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7456 /*IsLiteralLabel=*/true, 7457 SE->getStrTokenLoc(0))); 7458 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7459 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7460 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7461 if (I != ExtnameUndeclaredIdentifiers.end()) { 7462 if (isDeclExternC(NewVD)) { 7463 NewVD->addAttr(I->second); 7464 ExtnameUndeclaredIdentifiers.erase(I); 7465 } else 7466 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7467 << /*Variable*/1 << NewVD; 7468 } 7469 } 7470 7471 // Find the shadowed declaration before filtering for scope. 7472 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7473 ? getShadowedDeclaration(NewVD, Previous) 7474 : nullptr; 7475 7476 // Don't consider existing declarations that are in a different 7477 // scope and are out-of-semantic-context declarations (if the new 7478 // declaration has linkage). 7479 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7480 D.getCXXScopeSpec().isNotEmpty() || 7481 IsMemberSpecialization || 7482 IsVariableTemplateSpecialization); 7483 7484 // Check whether the previous declaration is in the same block scope. This 7485 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7486 if (getLangOpts().CPlusPlus && 7487 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7488 NewVD->setPreviousDeclInSameBlockScope( 7489 Previous.isSingleResult() && !Previous.isShadowed() && 7490 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7491 7492 if (!getLangOpts().CPlusPlus) { 7493 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7494 } else { 7495 // If this is an explicit specialization of a static data member, check it. 7496 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7497 CheckMemberSpecialization(NewVD, Previous)) 7498 NewVD->setInvalidDecl(); 7499 7500 // Merge the decl with the existing one if appropriate. 7501 if (!Previous.empty()) { 7502 if (Previous.isSingleResult() && 7503 isa<FieldDecl>(Previous.getFoundDecl()) && 7504 D.getCXXScopeSpec().isSet()) { 7505 // The user tried to define a non-static data member 7506 // out-of-line (C++ [dcl.meaning]p1). 7507 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7508 << D.getCXXScopeSpec().getRange(); 7509 Previous.clear(); 7510 NewVD->setInvalidDecl(); 7511 } 7512 } else if (D.getCXXScopeSpec().isSet()) { 7513 // No previous declaration in the qualifying scope. 7514 Diag(D.getIdentifierLoc(), diag::err_no_member) 7515 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7516 << D.getCXXScopeSpec().getRange(); 7517 NewVD->setInvalidDecl(); 7518 } 7519 7520 if (!IsVariableTemplateSpecialization) 7521 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7522 7523 if (NewTemplate) { 7524 VarTemplateDecl *PrevVarTemplate = 7525 NewVD->getPreviousDecl() 7526 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7527 : nullptr; 7528 7529 // Check the template parameter list of this declaration, possibly 7530 // merging in the template parameter list from the previous variable 7531 // template declaration. 7532 if (CheckTemplateParameterList( 7533 TemplateParams, 7534 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7535 : nullptr, 7536 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7537 DC->isDependentContext()) 7538 ? TPC_ClassTemplateMember 7539 : TPC_VarTemplate)) 7540 NewVD->setInvalidDecl(); 7541 7542 // If we are providing an explicit specialization of a static variable 7543 // template, make a note of that. 7544 if (PrevVarTemplate && 7545 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7546 PrevVarTemplate->setMemberSpecialization(); 7547 } 7548 } 7549 7550 // Diagnose shadowed variables iff this isn't a redeclaration. 7551 if (ShadowedDecl && !D.isRedeclaration()) 7552 CheckShadow(NewVD, ShadowedDecl, Previous); 7553 7554 ProcessPragmaWeak(S, NewVD); 7555 7556 // If this is the first declaration of an extern C variable, update 7557 // the map of such variables. 7558 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7559 isIncompleteDeclExternC(*this, NewVD)) 7560 RegisterLocallyScopedExternCDecl(NewVD, S); 7561 7562 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7563 MangleNumberingContext *MCtx; 7564 Decl *ManglingContextDecl; 7565 std::tie(MCtx, ManglingContextDecl) = 7566 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7567 if (MCtx) { 7568 Context.setManglingNumber( 7569 NewVD, MCtx->getManglingNumber( 7570 NewVD, getMSManglingNumber(getLangOpts(), S))); 7571 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7572 } 7573 } 7574 7575 // Special handling of variable named 'main'. 7576 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7577 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7578 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7579 7580 // C++ [basic.start.main]p3 7581 // A program that declares a variable main at global scope is ill-formed. 7582 if (getLangOpts().CPlusPlus) 7583 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7584 7585 // In C, and external-linkage variable named main results in undefined 7586 // behavior. 7587 else if (NewVD->hasExternalFormalLinkage()) 7588 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7589 } 7590 7591 if (D.isRedeclaration() && !Previous.empty()) { 7592 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7593 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7594 D.isFunctionDefinition()); 7595 } 7596 7597 if (NewTemplate) { 7598 if (NewVD->isInvalidDecl()) 7599 NewTemplate->setInvalidDecl(); 7600 ActOnDocumentableDecl(NewTemplate); 7601 return NewTemplate; 7602 } 7603 7604 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7605 CompleteMemberSpecialization(NewVD, Previous); 7606 7607 return NewVD; 7608 } 7609 7610 /// Enum describing the %select options in diag::warn_decl_shadow. 7611 enum ShadowedDeclKind { 7612 SDK_Local, 7613 SDK_Global, 7614 SDK_StaticMember, 7615 SDK_Field, 7616 SDK_Typedef, 7617 SDK_Using, 7618 SDK_StructuredBinding 7619 }; 7620 7621 /// Determine what kind of declaration we're shadowing. 7622 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7623 const DeclContext *OldDC) { 7624 if (isa<TypeAliasDecl>(ShadowedDecl)) 7625 return SDK_Using; 7626 else if (isa<TypedefDecl>(ShadowedDecl)) 7627 return SDK_Typedef; 7628 else if (isa<BindingDecl>(ShadowedDecl)) 7629 return SDK_StructuredBinding; 7630 else if (isa<RecordDecl>(OldDC)) 7631 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7632 7633 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7634 } 7635 7636 /// Return the location of the capture if the given lambda captures the given 7637 /// variable \p VD, or an invalid source location otherwise. 7638 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7639 const VarDecl *VD) { 7640 for (const Capture &Capture : LSI->Captures) { 7641 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7642 return Capture.getLocation(); 7643 } 7644 return SourceLocation(); 7645 } 7646 7647 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7648 const LookupResult &R) { 7649 // Only diagnose if we're shadowing an unambiguous field or variable. 7650 if (R.getResultKind() != LookupResult::Found) 7651 return false; 7652 7653 // Return false if warning is ignored. 7654 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7655 } 7656 7657 /// Return the declaration shadowed by the given variable \p D, or null 7658 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7659 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7660 const LookupResult &R) { 7661 if (!shouldWarnIfShadowedDecl(Diags, R)) 7662 return nullptr; 7663 7664 // Don't diagnose declarations at file scope. 7665 if (D->hasGlobalStorage()) 7666 return nullptr; 7667 7668 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7669 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7670 : nullptr; 7671 } 7672 7673 /// Return the declaration shadowed by the given typedef \p D, or null 7674 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7675 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7676 const LookupResult &R) { 7677 // Don't warn if typedef declaration is part of a class 7678 if (D->getDeclContext()->isRecord()) 7679 return nullptr; 7680 7681 if (!shouldWarnIfShadowedDecl(Diags, R)) 7682 return nullptr; 7683 7684 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7685 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7686 } 7687 7688 /// Return the declaration shadowed by the given variable \p D, or null 7689 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7690 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7691 const LookupResult &R) { 7692 if (!shouldWarnIfShadowedDecl(Diags, R)) 7693 return nullptr; 7694 7695 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7696 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7697 : nullptr; 7698 } 7699 7700 /// Diagnose variable or built-in function shadowing. Implements 7701 /// -Wshadow. 7702 /// 7703 /// This method is called whenever a VarDecl is added to a "useful" 7704 /// scope. 7705 /// 7706 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7707 /// \param R the lookup of the name 7708 /// 7709 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7710 const LookupResult &R) { 7711 DeclContext *NewDC = D->getDeclContext(); 7712 7713 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7714 // Fields are not shadowed by variables in C++ static methods. 7715 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7716 if (MD->isStatic()) 7717 return; 7718 7719 // Fields shadowed by constructor parameters are a special case. Usually 7720 // the constructor initializes the field with the parameter. 7721 if (isa<CXXConstructorDecl>(NewDC)) 7722 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7723 // Remember that this was shadowed so we can either warn about its 7724 // modification or its existence depending on warning settings. 7725 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7726 return; 7727 } 7728 } 7729 7730 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7731 if (shadowedVar->isExternC()) { 7732 // For shadowing external vars, make sure that we point to the global 7733 // declaration, not a locally scoped extern declaration. 7734 for (auto I : shadowedVar->redecls()) 7735 if (I->isFileVarDecl()) { 7736 ShadowedDecl = I; 7737 break; 7738 } 7739 } 7740 7741 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7742 7743 unsigned WarningDiag = diag::warn_decl_shadow; 7744 SourceLocation CaptureLoc; 7745 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7746 isa<CXXMethodDecl>(NewDC)) { 7747 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7748 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7749 if (RD->getLambdaCaptureDefault() == LCD_None) { 7750 // Try to avoid warnings for lambdas with an explicit capture list. 7751 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7752 // Warn only when the lambda captures the shadowed decl explicitly. 7753 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7754 if (CaptureLoc.isInvalid()) 7755 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7756 } else { 7757 // Remember that this was shadowed so we can avoid the warning if the 7758 // shadowed decl isn't captured and the warning settings allow it. 7759 cast<LambdaScopeInfo>(getCurFunction()) 7760 ->ShadowingDecls.push_back( 7761 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7762 return; 7763 } 7764 } 7765 7766 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7767 // A variable can't shadow a local variable in an enclosing scope, if 7768 // they are separated by a non-capturing declaration context. 7769 for (DeclContext *ParentDC = NewDC; 7770 ParentDC && !ParentDC->Equals(OldDC); 7771 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7772 // Only block literals, captured statements, and lambda expressions 7773 // can capture; other scopes don't. 7774 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7775 !isLambdaCallOperator(ParentDC)) { 7776 return; 7777 } 7778 } 7779 } 7780 } 7781 } 7782 7783 // Only warn about certain kinds of shadowing for class members. 7784 if (NewDC && NewDC->isRecord()) { 7785 // In particular, don't warn about shadowing non-class members. 7786 if (!OldDC->isRecord()) 7787 return; 7788 7789 // TODO: should we warn about static data members shadowing 7790 // static data members from base classes? 7791 7792 // TODO: don't diagnose for inaccessible shadowed members. 7793 // This is hard to do perfectly because we might friend the 7794 // shadowing context, but that's just a false negative. 7795 } 7796 7797 7798 DeclarationName Name = R.getLookupName(); 7799 7800 // Emit warning and note. 7801 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7802 return; 7803 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7804 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7805 if (!CaptureLoc.isInvalid()) 7806 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7807 << Name << /*explicitly*/ 1; 7808 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7809 } 7810 7811 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7812 /// when these variables are captured by the lambda. 7813 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7814 for (const auto &Shadow : LSI->ShadowingDecls) { 7815 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7816 // Try to avoid the warning when the shadowed decl isn't captured. 7817 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7818 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7819 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7820 ? diag::warn_decl_shadow_uncaptured_local 7821 : diag::warn_decl_shadow) 7822 << Shadow.VD->getDeclName() 7823 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7824 if (!CaptureLoc.isInvalid()) 7825 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7826 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7827 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7828 } 7829 } 7830 7831 /// Check -Wshadow without the advantage of a previous lookup. 7832 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7833 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7834 return; 7835 7836 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7837 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7838 LookupName(R, S); 7839 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7840 CheckShadow(D, ShadowedDecl, R); 7841 } 7842 7843 /// Check if 'E', which is an expression that is about to be modified, refers 7844 /// to a constructor parameter that shadows a field. 7845 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7846 // Quickly ignore expressions that can't be shadowing ctor parameters. 7847 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7848 return; 7849 E = E->IgnoreParenImpCasts(); 7850 auto *DRE = dyn_cast<DeclRefExpr>(E); 7851 if (!DRE) 7852 return; 7853 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7854 auto I = ShadowingDecls.find(D); 7855 if (I == ShadowingDecls.end()) 7856 return; 7857 const NamedDecl *ShadowedDecl = I->second; 7858 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7859 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7860 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7861 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7862 7863 // Avoid issuing multiple warnings about the same decl. 7864 ShadowingDecls.erase(I); 7865 } 7866 7867 /// Check for conflict between this global or extern "C" declaration and 7868 /// previous global or extern "C" declarations. This is only used in C++. 7869 template<typename T> 7870 static bool checkGlobalOrExternCConflict( 7871 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7872 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7873 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7874 7875 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7876 // The common case: this global doesn't conflict with any extern "C" 7877 // declaration. 7878 return false; 7879 } 7880 7881 if (Prev) { 7882 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7883 // Both the old and new declarations have C language linkage. This is a 7884 // redeclaration. 7885 Previous.clear(); 7886 Previous.addDecl(Prev); 7887 return true; 7888 } 7889 7890 // This is a global, non-extern "C" declaration, and there is a previous 7891 // non-global extern "C" declaration. Diagnose if this is a variable 7892 // declaration. 7893 if (!isa<VarDecl>(ND)) 7894 return false; 7895 } else { 7896 // The declaration is extern "C". Check for any declaration in the 7897 // translation unit which might conflict. 7898 if (IsGlobal) { 7899 // We have already performed the lookup into the translation unit. 7900 IsGlobal = false; 7901 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7902 I != E; ++I) { 7903 if (isa<VarDecl>(*I)) { 7904 Prev = *I; 7905 break; 7906 } 7907 } 7908 } else { 7909 DeclContext::lookup_result R = 7910 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7911 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7912 I != E; ++I) { 7913 if (isa<VarDecl>(*I)) { 7914 Prev = *I; 7915 break; 7916 } 7917 // FIXME: If we have any other entity with this name in global scope, 7918 // the declaration is ill-formed, but that is a defect: it breaks the 7919 // 'stat' hack, for instance. Only variables can have mangled name 7920 // clashes with extern "C" declarations, so only they deserve a 7921 // diagnostic. 7922 } 7923 } 7924 7925 if (!Prev) 7926 return false; 7927 } 7928 7929 // Use the first declaration's location to ensure we point at something which 7930 // is lexically inside an extern "C" linkage-spec. 7931 assert(Prev && "should have found a previous declaration to diagnose"); 7932 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7933 Prev = FD->getFirstDecl(); 7934 else 7935 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7936 7937 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7938 << IsGlobal << ND; 7939 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7940 << IsGlobal; 7941 return false; 7942 } 7943 7944 /// Apply special rules for handling extern "C" declarations. Returns \c true 7945 /// if we have found that this is a redeclaration of some prior entity. 7946 /// 7947 /// Per C++ [dcl.link]p6: 7948 /// Two declarations [for a function or variable] with C language linkage 7949 /// with the same name that appear in different scopes refer to the same 7950 /// [entity]. An entity with C language linkage shall not be declared with 7951 /// the same name as an entity in global scope. 7952 template<typename T> 7953 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7954 LookupResult &Previous) { 7955 if (!S.getLangOpts().CPlusPlus) { 7956 // In C, when declaring a global variable, look for a corresponding 'extern' 7957 // variable declared in function scope. We don't need this in C++, because 7958 // we find local extern decls in the surrounding file-scope DeclContext. 7959 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7960 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7961 Previous.clear(); 7962 Previous.addDecl(Prev); 7963 return true; 7964 } 7965 } 7966 return false; 7967 } 7968 7969 // A declaration in the translation unit can conflict with an extern "C" 7970 // declaration. 7971 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7972 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7973 7974 // An extern "C" declaration can conflict with a declaration in the 7975 // translation unit or can be a redeclaration of an extern "C" declaration 7976 // in another scope. 7977 if (isIncompleteDeclExternC(S,ND)) 7978 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7979 7980 // Neither global nor extern "C": nothing to do. 7981 return false; 7982 } 7983 7984 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7985 // If the decl is already known invalid, don't check it. 7986 if (NewVD->isInvalidDecl()) 7987 return; 7988 7989 QualType T = NewVD->getType(); 7990 7991 // Defer checking an 'auto' type until its initializer is attached. 7992 if (T->isUndeducedType()) 7993 return; 7994 7995 if (NewVD->hasAttrs()) 7996 CheckAlignasUnderalignment(NewVD); 7997 7998 if (T->isObjCObjectType()) { 7999 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8000 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8001 T = Context.getObjCObjectPointerType(T); 8002 NewVD->setType(T); 8003 } 8004 8005 // Emit an error if an address space was applied to decl with local storage. 8006 // This includes arrays of objects with address space qualifiers, but not 8007 // automatic variables that point to other address spaces. 8008 // ISO/IEC TR 18037 S5.1.2 8009 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8010 T.getAddressSpace() != LangAS::Default) { 8011 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8012 NewVD->setInvalidDecl(); 8013 return; 8014 } 8015 8016 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8017 // scope. 8018 if (getLangOpts().OpenCLVersion == 120 && 8019 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8020 getLangOpts()) && 8021 NewVD->isStaticLocal()) { 8022 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8023 NewVD->setInvalidDecl(); 8024 return; 8025 } 8026 8027 if (getLangOpts().OpenCL) { 8028 if (!diagnoseOpenCLTypes(*this, NewVD)) 8029 return; 8030 8031 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8032 if (NewVD->hasAttr<BlocksAttr>()) { 8033 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8034 return; 8035 } 8036 8037 if (T->isBlockPointerType()) { 8038 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8039 // can't use 'extern' storage class. 8040 if (!T.isConstQualified()) { 8041 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8042 << 0 /*const*/; 8043 NewVD->setInvalidDecl(); 8044 return; 8045 } 8046 if (NewVD->hasExternalStorage()) { 8047 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8048 NewVD->setInvalidDecl(); 8049 return; 8050 } 8051 } 8052 8053 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8054 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8055 NewVD->hasExternalStorage()) { 8056 if (!T->isSamplerT() && !T->isDependentType() && 8057 !(T.getAddressSpace() == LangAS::opencl_constant || 8058 (T.getAddressSpace() == LangAS::opencl_global && 8059 getOpenCLOptions().areProgramScopeVariablesSupported( 8060 getLangOpts())))) { 8061 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8062 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8063 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8064 << Scope << "global or constant"; 8065 else 8066 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8067 << Scope << "constant"; 8068 NewVD->setInvalidDecl(); 8069 return; 8070 } 8071 } else { 8072 if (T.getAddressSpace() == LangAS::opencl_global) { 8073 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8074 << 1 /*is any function*/ << "global"; 8075 NewVD->setInvalidDecl(); 8076 return; 8077 } 8078 if (T.getAddressSpace() == LangAS::opencl_constant || 8079 T.getAddressSpace() == LangAS::opencl_local) { 8080 FunctionDecl *FD = getCurFunctionDecl(); 8081 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8082 // in functions. 8083 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8084 if (T.getAddressSpace() == LangAS::opencl_constant) 8085 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8086 << 0 /*non-kernel only*/ << "constant"; 8087 else 8088 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8089 << 0 /*non-kernel only*/ << "local"; 8090 NewVD->setInvalidDecl(); 8091 return; 8092 } 8093 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8094 // in the outermost scope of a kernel function. 8095 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8096 if (!getCurScope()->isFunctionScope()) { 8097 if (T.getAddressSpace() == LangAS::opencl_constant) 8098 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8099 << "constant"; 8100 else 8101 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8102 << "local"; 8103 NewVD->setInvalidDecl(); 8104 return; 8105 } 8106 } 8107 } else if (T.getAddressSpace() != LangAS::opencl_private && 8108 // If we are parsing a template we didn't deduce an addr 8109 // space yet. 8110 T.getAddressSpace() != LangAS::Default) { 8111 // Do not allow other address spaces on automatic variable. 8112 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8113 NewVD->setInvalidDecl(); 8114 return; 8115 } 8116 } 8117 } 8118 8119 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8120 && !NewVD->hasAttr<BlocksAttr>()) { 8121 if (getLangOpts().getGC() != LangOptions::NonGC) 8122 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8123 else { 8124 assert(!getLangOpts().ObjCAutoRefCount); 8125 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8126 } 8127 } 8128 8129 bool isVM = T->isVariablyModifiedType(); 8130 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8131 NewVD->hasAttr<BlocksAttr>()) 8132 setFunctionHasBranchProtectedScope(); 8133 8134 if ((isVM && NewVD->hasLinkage()) || 8135 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8136 bool SizeIsNegative; 8137 llvm::APSInt Oversized; 8138 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8139 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8140 QualType FixedT; 8141 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8142 FixedT = FixedTInfo->getType(); 8143 else if (FixedTInfo) { 8144 // Type and type-as-written are canonically different. We need to fix up 8145 // both types separately. 8146 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8147 Oversized); 8148 } 8149 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8150 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8151 // FIXME: This won't give the correct result for 8152 // int a[10][n]; 8153 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8154 8155 if (NewVD->isFileVarDecl()) 8156 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8157 << SizeRange; 8158 else if (NewVD->isStaticLocal()) 8159 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8160 << SizeRange; 8161 else 8162 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8163 << SizeRange; 8164 NewVD->setInvalidDecl(); 8165 return; 8166 } 8167 8168 if (!FixedTInfo) { 8169 if (NewVD->isFileVarDecl()) 8170 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8171 else 8172 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8173 NewVD->setInvalidDecl(); 8174 return; 8175 } 8176 8177 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8178 NewVD->setType(FixedT); 8179 NewVD->setTypeSourceInfo(FixedTInfo); 8180 } 8181 8182 if (T->isVoidType()) { 8183 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8184 // of objects and functions. 8185 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8186 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8187 << T; 8188 NewVD->setInvalidDecl(); 8189 return; 8190 } 8191 } 8192 8193 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8194 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8195 NewVD->setInvalidDecl(); 8196 return; 8197 } 8198 8199 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8200 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8201 NewVD->setInvalidDecl(); 8202 return; 8203 } 8204 8205 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8206 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8207 NewVD->setInvalidDecl(); 8208 return; 8209 } 8210 8211 if (NewVD->isConstexpr() && !T->isDependentType() && 8212 RequireLiteralType(NewVD->getLocation(), T, 8213 diag::err_constexpr_var_non_literal)) { 8214 NewVD->setInvalidDecl(); 8215 return; 8216 } 8217 8218 // PPC MMA non-pointer types are not allowed as non-local variable types. 8219 if (Context.getTargetInfo().getTriple().isPPC64() && 8220 !NewVD->isLocalVarDecl() && 8221 CheckPPCMMAType(T, NewVD->getLocation())) { 8222 NewVD->setInvalidDecl(); 8223 return; 8224 } 8225 } 8226 8227 /// Perform semantic checking on a newly-created variable 8228 /// declaration. 8229 /// 8230 /// This routine performs all of the type-checking required for a 8231 /// variable declaration once it has been built. It is used both to 8232 /// check variables after they have been parsed and their declarators 8233 /// have been translated into a declaration, and to check variables 8234 /// that have been instantiated from a template. 8235 /// 8236 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8237 /// 8238 /// Returns true if the variable declaration is a redeclaration. 8239 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8240 CheckVariableDeclarationType(NewVD); 8241 8242 // If the decl is already known invalid, don't check it. 8243 if (NewVD->isInvalidDecl()) 8244 return false; 8245 8246 // If we did not find anything by this name, look for a non-visible 8247 // extern "C" declaration with the same name. 8248 if (Previous.empty() && 8249 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8250 Previous.setShadowed(); 8251 8252 if (!Previous.empty()) { 8253 MergeVarDecl(NewVD, Previous); 8254 return true; 8255 } 8256 return false; 8257 } 8258 8259 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8260 /// and if so, check that it's a valid override and remember it. 8261 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8262 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8263 8264 // Look for methods in base classes that this method might override. 8265 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8266 /*DetectVirtual=*/false); 8267 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8268 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8269 DeclarationName Name = MD->getDeclName(); 8270 8271 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8272 // We really want to find the base class destructor here. 8273 QualType T = Context.getTypeDeclType(BaseRecord); 8274 CanQualType CT = Context.getCanonicalType(T); 8275 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8276 } 8277 8278 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8279 CXXMethodDecl *BaseMD = 8280 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8281 if (!BaseMD || !BaseMD->isVirtual() || 8282 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8283 /*ConsiderCudaAttrs=*/true, 8284 // C++2a [class.virtual]p2 does not consider requires 8285 // clauses when overriding. 8286 /*ConsiderRequiresClauses=*/false)) 8287 continue; 8288 8289 if (Overridden.insert(BaseMD).second) { 8290 MD->addOverriddenMethod(BaseMD); 8291 CheckOverridingFunctionReturnType(MD, BaseMD); 8292 CheckOverridingFunctionAttributes(MD, BaseMD); 8293 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8294 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8295 } 8296 8297 // A method can only override one function from each base class. We 8298 // don't track indirectly overridden methods from bases of bases. 8299 return true; 8300 } 8301 8302 return false; 8303 }; 8304 8305 DC->lookupInBases(VisitBase, Paths); 8306 return !Overridden.empty(); 8307 } 8308 8309 namespace { 8310 // Struct for holding all of the extra arguments needed by 8311 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8312 struct ActOnFDArgs { 8313 Scope *S; 8314 Declarator &D; 8315 MultiTemplateParamsArg TemplateParamLists; 8316 bool AddToScope; 8317 }; 8318 } // end anonymous namespace 8319 8320 namespace { 8321 8322 // Callback to only accept typo corrections that have a non-zero edit distance. 8323 // Also only accept corrections that have the same parent decl. 8324 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8325 public: 8326 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8327 CXXRecordDecl *Parent) 8328 : Context(Context), OriginalFD(TypoFD), 8329 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8330 8331 bool ValidateCandidate(const TypoCorrection &candidate) override { 8332 if (candidate.getEditDistance() == 0) 8333 return false; 8334 8335 SmallVector<unsigned, 1> MismatchedParams; 8336 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8337 CDeclEnd = candidate.end(); 8338 CDecl != CDeclEnd; ++CDecl) { 8339 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8340 8341 if (FD && !FD->hasBody() && 8342 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8343 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8344 CXXRecordDecl *Parent = MD->getParent(); 8345 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8346 return true; 8347 } else if (!ExpectedParent) { 8348 return true; 8349 } 8350 } 8351 } 8352 8353 return false; 8354 } 8355 8356 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8357 return std::make_unique<DifferentNameValidatorCCC>(*this); 8358 } 8359 8360 private: 8361 ASTContext &Context; 8362 FunctionDecl *OriginalFD; 8363 CXXRecordDecl *ExpectedParent; 8364 }; 8365 8366 } // end anonymous namespace 8367 8368 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8369 TypoCorrectedFunctionDefinitions.insert(F); 8370 } 8371 8372 /// Generate diagnostics for an invalid function redeclaration. 8373 /// 8374 /// This routine handles generating the diagnostic messages for an invalid 8375 /// function redeclaration, including finding possible similar declarations 8376 /// or performing typo correction if there are no previous declarations with 8377 /// the same name. 8378 /// 8379 /// Returns a NamedDecl iff typo correction was performed and substituting in 8380 /// the new declaration name does not cause new errors. 8381 static NamedDecl *DiagnoseInvalidRedeclaration( 8382 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8383 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8384 DeclarationName Name = NewFD->getDeclName(); 8385 DeclContext *NewDC = NewFD->getDeclContext(); 8386 SmallVector<unsigned, 1> MismatchedParams; 8387 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8388 TypoCorrection Correction; 8389 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8390 unsigned DiagMsg = 8391 IsLocalFriend ? diag::err_no_matching_local_friend : 8392 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8393 diag::err_member_decl_does_not_match; 8394 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8395 IsLocalFriend ? Sema::LookupLocalFriendName 8396 : Sema::LookupOrdinaryName, 8397 Sema::ForVisibleRedeclaration); 8398 8399 NewFD->setInvalidDecl(); 8400 if (IsLocalFriend) 8401 SemaRef.LookupName(Prev, S); 8402 else 8403 SemaRef.LookupQualifiedName(Prev, NewDC); 8404 assert(!Prev.isAmbiguous() && 8405 "Cannot have an ambiguity in previous-declaration lookup"); 8406 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8407 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8408 MD ? MD->getParent() : nullptr); 8409 if (!Prev.empty()) { 8410 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8411 Func != FuncEnd; ++Func) { 8412 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8413 if (FD && 8414 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8415 // Add 1 to the index so that 0 can mean the mismatch didn't 8416 // involve a parameter 8417 unsigned ParamNum = 8418 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8419 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8420 } 8421 } 8422 // If the qualified name lookup yielded nothing, try typo correction 8423 } else if ((Correction = SemaRef.CorrectTypo( 8424 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8425 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8426 IsLocalFriend ? nullptr : NewDC))) { 8427 // Set up everything for the call to ActOnFunctionDeclarator 8428 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8429 ExtraArgs.D.getIdentifierLoc()); 8430 Previous.clear(); 8431 Previous.setLookupName(Correction.getCorrection()); 8432 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8433 CDeclEnd = Correction.end(); 8434 CDecl != CDeclEnd; ++CDecl) { 8435 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8436 if (FD && !FD->hasBody() && 8437 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8438 Previous.addDecl(FD); 8439 } 8440 } 8441 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8442 8443 NamedDecl *Result; 8444 // Retry building the function declaration with the new previous 8445 // declarations, and with errors suppressed. 8446 { 8447 // Trap errors. 8448 Sema::SFINAETrap Trap(SemaRef); 8449 8450 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8451 // pieces need to verify the typo-corrected C++ declaration and hopefully 8452 // eliminate the need for the parameter pack ExtraArgs. 8453 Result = SemaRef.ActOnFunctionDeclarator( 8454 ExtraArgs.S, ExtraArgs.D, 8455 Correction.getCorrectionDecl()->getDeclContext(), 8456 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8457 ExtraArgs.AddToScope); 8458 8459 if (Trap.hasErrorOccurred()) 8460 Result = nullptr; 8461 } 8462 8463 if (Result) { 8464 // Determine which correction we picked. 8465 Decl *Canonical = Result->getCanonicalDecl(); 8466 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8467 I != E; ++I) 8468 if ((*I)->getCanonicalDecl() == Canonical) 8469 Correction.setCorrectionDecl(*I); 8470 8471 // Let Sema know about the correction. 8472 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8473 SemaRef.diagnoseTypo( 8474 Correction, 8475 SemaRef.PDiag(IsLocalFriend 8476 ? diag::err_no_matching_local_friend_suggest 8477 : diag::err_member_decl_does_not_match_suggest) 8478 << Name << NewDC << IsDefinition); 8479 return Result; 8480 } 8481 8482 // Pretend the typo correction never occurred 8483 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8484 ExtraArgs.D.getIdentifierLoc()); 8485 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8486 Previous.clear(); 8487 Previous.setLookupName(Name); 8488 } 8489 8490 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8491 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8492 8493 bool NewFDisConst = false; 8494 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8495 NewFDisConst = NewMD->isConst(); 8496 8497 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8498 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8499 NearMatch != NearMatchEnd; ++NearMatch) { 8500 FunctionDecl *FD = NearMatch->first; 8501 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8502 bool FDisConst = MD && MD->isConst(); 8503 bool IsMember = MD || !IsLocalFriend; 8504 8505 // FIXME: These notes are poorly worded for the local friend case. 8506 if (unsigned Idx = NearMatch->second) { 8507 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8508 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8509 if (Loc.isInvalid()) Loc = FD->getLocation(); 8510 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8511 : diag::note_local_decl_close_param_match) 8512 << Idx << FDParam->getType() 8513 << NewFD->getParamDecl(Idx - 1)->getType(); 8514 } else if (FDisConst != NewFDisConst) { 8515 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8516 << NewFDisConst << FD->getSourceRange().getEnd() 8517 << (NewFDisConst 8518 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 8519 .getConstQualifierLoc()) 8520 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 8521 .getRParenLoc() 8522 .getLocWithOffset(1), 8523 " const")); 8524 } else 8525 SemaRef.Diag(FD->getLocation(), 8526 IsMember ? diag::note_member_def_close_match 8527 : diag::note_local_decl_close_match); 8528 } 8529 return nullptr; 8530 } 8531 8532 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8533 switch (D.getDeclSpec().getStorageClassSpec()) { 8534 default: llvm_unreachable("Unknown storage class!"); 8535 case DeclSpec::SCS_auto: 8536 case DeclSpec::SCS_register: 8537 case DeclSpec::SCS_mutable: 8538 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8539 diag::err_typecheck_sclass_func); 8540 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8541 D.setInvalidType(); 8542 break; 8543 case DeclSpec::SCS_unspecified: break; 8544 case DeclSpec::SCS_extern: 8545 if (D.getDeclSpec().isExternInLinkageSpec()) 8546 return SC_None; 8547 return SC_Extern; 8548 case DeclSpec::SCS_static: { 8549 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8550 // C99 6.7.1p5: 8551 // The declaration of an identifier for a function that has 8552 // block scope shall have no explicit storage-class specifier 8553 // other than extern 8554 // See also (C++ [dcl.stc]p4). 8555 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8556 diag::err_static_block_func); 8557 break; 8558 } else 8559 return SC_Static; 8560 } 8561 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8562 } 8563 8564 // No explicit storage class has already been returned 8565 return SC_None; 8566 } 8567 8568 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8569 DeclContext *DC, QualType &R, 8570 TypeSourceInfo *TInfo, 8571 StorageClass SC, 8572 bool &IsVirtualOkay) { 8573 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8574 DeclarationName Name = NameInfo.getName(); 8575 8576 FunctionDecl *NewFD = nullptr; 8577 bool isInline = D.getDeclSpec().isInlineSpecified(); 8578 8579 if (!SemaRef.getLangOpts().CPlusPlus) { 8580 // Determine whether the function was written with a 8581 // prototype. This true when: 8582 // - there is a prototype in the declarator, or 8583 // - the type R of the function is some kind of typedef or other non- 8584 // attributed reference to a type name (which eventually refers to a 8585 // function type). 8586 bool HasPrototype = 8587 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8588 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8589 8590 NewFD = FunctionDecl::Create( 8591 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8592 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8593 ConstexprSpecKind::Unspecified, 8594 /*TrailingRequiresClause=*/nullptr); 8595 if (D.isInvalidType()) 8596 NewFD->setInvalidDecl(); 8597 8598 return NewFD; 8599 } 8600 8601 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8602 8603 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8604 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8605 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8606 diag::err_constexpr_wrong_decl_kind) 8607 << static_cast<int>(ConstexprKind); 8608 ConstexprKind = ConstexprSpecKind::Unspecified; 8609 D.getMutableDeclSpec().ClearConstexprSpec(); 8610 } 8611 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8612 8613 // Check that the return type is not an abstract class type. 8614 // For record types, this is done by the AbstractClassUsageDiagnoser once 8615 // the class has been completely parsed. 8616 if (!DC->isRecord() && 8617 SemaRef.RequireNonAbstractType( 8618 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8619 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8620 D.setInvalidType(); 8621 8622 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8623 // This is a C++ constructor declaration. 8624 assert(DC->isRecord() && 8625 "Constructors can only be declared in a member context"); 8626 8627 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8628 return CXXConstructorDecl::Create( 8629 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8630 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8631 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8632 InheritedConstructor(), TrailingRequiresClause); 8633 8634 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8635 // This is a C++ destructor declaration. 8636 if (DC->isRecord()) { 8637 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8638 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8639 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8640 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8641 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8642 /*isImplicitlyDeclared=*/false, ConstexprKind, 8643 TrailingRequiresClause); 8644 8645 // If the destructor needs an implicit exception specification, set it 8646 // now. FIXME: It'd be nice to be able to create the right type to start 8647 // with, but the type needs to reference the destructor declaration. 8648 if (SemaRef.getLangOpts().CPlusPlus11) 8649 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8650 8651 IsVirtualOkay = true; 8652 return NewDD; 8653 8654 } else { 8655 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8656 D.setInvalidType(); 8657 8658 // Create a FunctionDecl to satisfy the function definition parsing 8659 // code path. 8660 return FunctionDecl::Create( 8661 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8662 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8663 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8664 } 8665 8666 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8667 if (!DC->isRecord()) { 8668 SemaRef.Diag(D.getIdentifierLoc(), 8669 diag::err_conv_function_not_member); 8670 return nullptr; 8671 } 8672 8673 SemaRef.CheckConversionDeclarator(D, R, SC); 8674 if (D.isInvalidType()) 8675 return nullptr; 8676 8677 IsVirtualOkay = true; 8678 return CXXConversionDecl::Create( 8679 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8680 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8681 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8682 TrailingRequiresClause); 8683 8684 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8685 if (TrailingRequiresClause) 8686 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8687 diag::err_trailing_requires_clause_on_deduction_guide) 8688 << TrailingRequiresClause->getSourceRange(); 8689 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8690 8691 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8692 ExplicitSpecifier, NameInfo, R, TInfo, 8693 D.getEndLoc()); 8694 } else if (DC->isRecord()) { 8695 // If the name of the function is the same as the name of the record, 8696 // then this must be an invalid constructor that has a return type. 8697 // (The parser checks for a return type and makes the declarator a 8698 // constructor if it has no return type). 8699 if (Name.getAsIdentifierInfo() && 8700 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8701 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8702 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8703 << SourceRange(D.getIdentifierLoc()); 8704 return nullptr; 8705 } 8706 8707 // This is a C++ method declaration. 8708 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8709 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8710 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8711 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8712 IsVirtualOkay = !Ret->isStatic(); 8713 return Ret; 8714 } else { 8715 bool isFriend = 8716 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8717 if (!isFriend && SemaRef.CurContext->isRecord()) 8718 return nullptr; 8719 8720 // Determine whether the function was written with a 8721 // prototype. This true when: 8722 // - we're in C++ (where every function has a prototype), 8723 return FunctionDecl::Create( 8724 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8725 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8726 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8727 } 8728 } 8729 8730 enum OpenCLParamType { 8731 ValidKernelParam, 8732 PtrPtrKernelParam, 8733 PtrKernelParam, 8734 InvalidAddrSpacePtrKernelParam, 8735 InvalidKernelParam, 8736 RecordKernelParam 8737 }; 8738 8739 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8740 // Size dependent types are just typedefs to normal integer types 8741 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8742 // integers other than by their names. 8743 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8744 8745 // Remove typedefs one by one until we reach a typedef 8746 // for a size dependent type. 8747 QualType DesugaredTy = Ty; 8748 do { 8749 ArrayRef<StringRef> Names(SizeTypeNames); 8750 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8751 if (Names.end() != Match) 8752 return true; 8753 8754 Ty = DesugaredTy; 8755 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8756 } while (DesugaredTy != Ty); 8757 8758 return false; 8759 } 8760 8761 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8762 if (PT->isDependentType()) 8763 return InvalidKernelParam; 8764 8765 if (PT->isPointerType() || PT->isReferenceType()) { 8766 QualType PointeeType = PT->getPointeeType(); 8767 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8768 PointeeType.getAddressSpace() == LangAS::opencl_private || 8769 PointeeType.getAddressSpace() == LangAS::Default) 8770 return InvalidAddrSpacePtrKernelParam; 8771 8772 if (PointeeType->isPointerType()) { 8773 // This is a pointer to pointer parameter. 8774 // Recursively check inner type. 8775 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8776 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8777 ParamKind == InvalidKernelParam) 8778 return ParamKind; 8779 8780 return PtrPtrKernelParam; 8781 } 8782 8783 // C++ for OpenCL v1.0 s2.4: 8784 // Moreover the types used in parameters of the kernel functions must be: 8785 // Standard layout types for pointer parameters. The same applies to 8786 // reference if an implementation supports them in kernel parameters. 8787 if (S.getLangOpts().OpenCLCPlusPlus && 8788 !S.getOpenCLOptions().isAvailableOption( 8789 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8790 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8791 !PointeeType->isStandardLayoutType()) 8792 return InvalidKernelParam; 8793 8794 return PtrKernelParam; 8795 } 8796 8797 // OpenCL v1.2 s6.9.k: 8798 // Arguments to kernel functions in a program cannot be declared with the 8799 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8800 // uintptr_t or a struct and/or union that contain fields declared to be one 8801 // of these built-in scalar types. 8802 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8803 return InvalidKernelParam; 8804 8805 if (PT->isImageType()) 8806 return PtrKernelParam; 8807 8808 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8809 return InvalidKernelParam; 8810 8811 // OpenCL extension spec v1.2 s9.5: 8812 // This extension adds support for half scalar and vector types as built-in 8813 // types that can be used for arithmetic operations, conversions etc. 8814 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8815 PT->isHalfType()) 8816 return InvalidKernelParam; 8817 8818 // Look into an array argument to check if it has a forbidden type. 8819 if (PT->isArrayType()) { 8820 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8821 // Call ourself to check an underlying type of an array. Since the 8822 // getPointeeOrArrayElementType returns an innermost type which is not an 8823 // array, this recursive call only happens once. 8824 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8825 } 8826 8827 // C++ for OpenCL v1.0 s2.4: 8828 // Moreover the types used in parameters of the kernel functions must be: 8829 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8830 // types) for parameters passed by value; 8831 if (S.getLangOpts().OpenCLCPlusPlus && 8832 !S.getOpenCLOptions().isAvailableOption( 8833 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8834 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 8835 return InvalidKernelParam; 8836 8837 if (PT->isRecordType()) 8838 return RecordKernelParam; 8839 8840 return ValidKernelParam; 8841 } 8842 8843 static void checkIsValidOpenCLKernelParameter( 8844 Sema &S, 8845 Declarator &D, 8846 ParmVarDecl *Param, 8847 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8848 QualType PT = Param->getType(); 8849 8850 // Cache the valid types we encounter to avoid rechecking structs that are 8851 // used again 8852 if (ValidTypes.count(PT.getTypePtr())) 8853 return; 8854 8855 switch (getOpenCLKernelParameterType(S, PT)) { 8856 case PtrPtrKernelParam: 8857 // OpenCL v3.0 s6.11.a: 8858 // A kernel function argument cannot be declared as a pointer to a pointer 8859 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8860 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 8861 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8862 D.setInvalidType(); 8863 return; 8864 } 8865 8866 ValidTypes.insert(PT.getTypePtr()); 8867 return; 8868 8869 case InvalidAddrSpacePtrKernelParam: 8870 // OpenCL v1.0 s6.5: 8871 // __kernel function arguments declared to be a pointer of a type can point 8872 // to one of the following address spaces only : __global, __local or 8873 // __constant. 8874 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8875 D.setInvalidType(); 8876 return; 8877 8878 // OpenCL v1.2 s6.9.k: 8879 // Arguments to kernel functions in a program cannot be declared with the 8880 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8881 // uintptr_t or a struct and/or union that contain fields declared to be 8882 // one of these built-in scalar types. 8883 8884 case InvalidKernelParam: 8885 // OpenCL v1.2 s6.8 n: 8886 // A kernel function argument cannot be declared 8887 // of event_t type. 8888 // Do not diagnose half type since it is diagnosed as invalid argument 8889 // type for any function elsewhere. 8890 if (!PT->isHalfType()) { 8891 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8892 8893 // Explain what typedefs are involved. 8894 const TypedefType *Typedef = nullptr; 8895 while ((Typedef = PT->getAs<TypedefType>())) { 8896 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8897 // SourceLocation may be invalid for a built-in type. 8898 if (Loc.isValid()) 8899 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8900 PT = Typedef->desugar(); 8901 } 8902 } 8903 8904 D.setInvalidType(); 8905 return; 8906 8907 case PtrKernelParam: 8908 case ValidKernelParam: 8909 ValidTypes.insert(PT.getTypePtr()); 8910 return; 8911 8912 case RecordKernelParam: 8913 break; 8914 } 8915 8916 // Track nested structs we will inspect 8917 SmallVector<const Decl *, 4> VisitStack; 8918 8919 // Track where we are in the nested structs. Items will migrate from 8920 // VisitStack to HistoryStack as we do the DFS for bad field. 8921 SmallVector<const FieldDecl *, 4> HistoryStack; 8922 HistoryStack.push_back(nullptr); 8923 8924 // At this point we already handled everything except of a RecordType or 8925 // an ArrayType of a RecordType. 8926 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8927 const RecordType *RecTy = 8928 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8929 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8930 8931 VisitStack.push_back(RecTy->getDecl()); 8932 assert(VisitStack.back() && "First decl null?"); 8933 8934 do { 8935 const Decl *Next = VisitStack.pop_back_val(); 8936 if (!Next) { 8937 assert(!HistoryStack.empty()); 8938 // Found a marker, we have gone up a level 8939 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8940 ValidTypes.insert(Hist->getType().getTypePtr()); 8941 8942 continue; 8943 } 8944 8945 // Adds everything except the original parameter declaration (which is not a 8946 // field itself) to the history stack. 8947 const RecordDecl *RD; 8948 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8949 HistoryStack.push_back(Field); 8950 8951 QualType FieldTy = Field->getType(); 8952 // Other field types (known to be valid or invalid) are handled while we 8953 // walk around RecordDecl::fields(). 8954 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8955 "Unexpected type."); 8956 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8957 8958 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8959 } else { 8960 RD = cast<RecordDecl>(Next); 8961 } 8962 8963 // Add a null marker so we know when we've gone back up a level 8964 VisitStack.push_back(nullptr); 8965 8966 for (const auto *FD : RD->fields()) { 8967 QualType QT = FD->getType(); 8968 8969 if (ValidTypes.count(QT.getTypePtr())) 8970 continue; 8971 8972 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8973 if (ParamType == ValidKernelParam) 8974 continue; 8975 8976 if (ParamType == RecordKernelParam) { 8977 VisitStack.push_back(FD); 8978 continue; 8979 } 8980 8981 // OpenCL v1.2 s6.9.p: 8982 // Arguments to kernel functions that are declared to be a struct or union 8983 // do not allow OpenCL objects to be passed as elements of the struct or 8984 // union. 8985 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8986 ParamType == InvalidAddrSpacePtrKernelParam) { 8987 S.Diag(Param->getLocation(), 8988 diag::err_record_with_pointers_kernel_param) 8989 << PT->isUnionType() 8990 << PT; 8991 } else { 8992 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8993 } 8994 8995 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8996 << OrigRecDecl->getDeclName(); 8997 8998 // We have an error, now let's go back up through history and show where 8999 // the offending field came from 9000 for (ArrayRef<const FieldDecl *>::const_iterator 9001 I = HistoryStack.begin() + 1, 9002 E = HistoryStack.end(); 9003 I != E; ++I) { 9004 const FieldDecl *OuterField = *I; 9005 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9006 << OuterField->getType(); 9007 } 9008 9009 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9010 << QT->isPointerType() 9011 << QT; 9012 D.setInvalidType(); 9013 return; 9014 } 9015 } while (!VisitStack.empty()); 9016 } 9017 9018 /// Find the DeclContext in which a tag is implicitly declared if we see an 9019 /// elaborated type specifier in the specified context, and lookup finds 9020 /// nothing. 9021 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9022 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9023 DC = DC->getParent(); 9024 return DC; 9025 } 9026 9027 /// Find the Scope in which a tag is implicitly declared if we see an 9028 /// elaborated type specifier in the specified context, and lookup finds 9029 /// nothing. 9030 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9031 while (S->isClassScope() || 9032 (LangOpts.CPlusPlus && 9033 S->isFunctionPrototypeScope()) || 9034 ((S->getFlags() & Scope::DeclScope) == 0) || 9035 (S->getEntity() && S->getEntity()->isTransparentContext())) 9036 S = S->getParent(); 9037 return S; 9038 } 9039 9040 NamedDecl* 9041 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9042 TypeSourceInfo *TInfo, LookupResult &Previous, 9043 MultiTemplateParamsArg TemplateParamListsRef, 9044 bool &AddToScope) { 9045 QualType R = TInfo->getType(); 9046 9047 assert(R->isFunctionType()); 9048 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9049 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9050 9051 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9052 for (TemplateParameterList *TPL : TemplateParamListsRef) 9053 TemplateParamLists.push_back(TPL); 9054 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9055 if (!TemplateParamLists.empty() && 9056 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9057 TemplateParamLists.back() = Invented; 9058 else 9059 TemplateParamLists.push_back(Invented); 9060 } 9061 9062 // TODO: consider using NameInfo for diagnostic. 9063 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9064 DeclarationName Name = NameInfo.getName(); 9065 StorageClass SC = getFunctionStorageClass(*this, D); 9066 9067 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9068 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9069 diag::err_invalid_thread) 9070 << DeclSpec::getSpecifierName(TSCS); 9071 9072 if (D.isFirstDeclarationOfMember()) 9073 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9074 D.getIdentifierLoc()); 9075 9076 bool isFriend = false; 9077 FunctionTemplateDecl *FunctionTemplate = nullptr; 9078 bool isMemberSpecialization = false; 9079 bool isFunctionTemplateSpecialization = false; 9080 9081 bool isDependentClassScopeExplicitSpecialization = false; 9082 bool HasExplicitTemplateArgs = false; 9083 TemplateArgumentListInfo TemplateArgs; 9084 9085 bool isVirtualOkay = false; 9086 9087 DeclContext *OriginalDC = DC; 9088 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9089 9090 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9091 isVirtualOkay); 9092 if (!NewFD) return nullptr; 9093 9094 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9095 NewFD->setTopLevelDeclInObjCContainer(); 9096 9097 // Set the lexical context. If this is a function-scope declaration, or has a 9098 // C++ scope specifier, or is the object of a friend declaration, the lexical 9099 // context will be different from the semantic context. 9100 NewFD->setLexicalDeclContext(CurContext); 9101 9102 if (IsLocalExternDecl) 9103 NewFD->setLocalExternDecl(); 9104 9105 if (getLangOpts().CPlusPlus) { 9106 bool isInline = D.getDeclSpec().isInlineSpecified(); 9107 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9108 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9109 isFriend = D.getDeclSpec().isFriendSpecified(); 9110 if (isFriend && !isInline && D.isFunctionDefinition()) { 9111 // C++ [class.friend]p5 9112 // A function can be defined in a friend declaration of a 9113 // class . . . . Such a function is implicitly inline. 9114 NewFD->setImplicitlyInline(); 9115 } 9116 9117 // If this is a method defined in an __interface, and is not a constructor 9118 // or an overloaded operator, then set the pure flag (isVirtual will already 9119 // return true). 9120 if (const CXXRecordDecl *Parent = 9121 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9122 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9123 NewFD->setPure(true); 9124 9125 // C++ [class.union]p2 9126 // A union can have member functions, but not virtual functions. 9127 if (isVirtual && Parent->isUnion()) { 9128 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9129 NewFD->setInvalidDecl(); 9130 } 9131 } 9132 9133 SetNestedNameSpecifier(*this, NewFD, D); 9134 isMemberSpecialization = false; 9135 isFunctionTemplateSpecialization = false; 9136 if (D.isInvalidType()) 9137 NewFD->setInvalidDecl(); 9138 9139 // Match up the template parameter lists with the scope specifier, then 9140 // determine whether we have a template or a template specialization. 9141 bool Invalid = false; 9142 TemplateParameterList *TemplateParams = 9143 MatchTemplateParametersToScopeSpecifier( 9144 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9145 D.getCXXScopeSpec(), 9146 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9147 ? D.getName().TemplateId 9148 : nullptr, 9149 TemplateParamLists, isFriend, isMemberSpecialization, 9150 Invalid); 9151 if (TemplateParams) { 9152 // Check that we can declare a template here. 9153 if (CheckTemplateDeclScope(S, TemplateParams)) 9154 NewFD->setInvalidDecl(); 9155 9156 if (TemplateParams->size() > 0) { 9157 // This is a function template 9158 9159 // A destructor cannot be a template. 9160 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9161 Diag(NewFD->getLocation(), diag::err_destructor_template); 9162 NewFD->setInvalidDecl(); 9163 } 9164 9165 // If we're adding a template to a dependent context, we may need to 9166 // rebuilding some of the types used within the template parameter list, 9167 // now that we know what the current instantiation is. 9168 if (DC->isDependentContext()) { 9169 ContextRAII SavedContext(*this, DC); 9170 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9171 Invalid = true; 9172 } 9173 9174 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9175 NewFD->getLocation(), 9176 Name, TemplateParams, 9177 NewFD); 9178 FunctionTemplate->setLexicalDeclContext(CurContext); 9179 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9180 9181 // For source fidelity, store the other template param lists. 9182 if (TemplateParamLists.size() > 1) { 9183 NewFD->setTemplateParameterListsInfo(Context, 9184 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9185 .drop_back(1)); 9186 } 9187 } else { 9188 // This is a function template specialization. 9189 isFunctionTemplateSpecialization = true; 9190 // For source fidelity, store all the template param lists. 9191 if (TemplateParamLists.size() > 0) 9192 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9193 9194 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9195 if (isFriend) { 9196 // We want to remove the "template<>", found here. 9197 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9198 9199 // If we remove the template<> and the name is not a 9200 // template-id, we're actually silently creating a problem: 9201 // the friend declaration will refer to an untemplated decl, 9202 // and clearly the user wants a template specialization. So 9203 // we need to insert '<>' after the name. 9204 SourceLocation InsertLoc; 9205 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9206 InsertLoc = D.getName().getSourceRange().getEnd(); 9207 InsertLoc = getLocForEndOfToken(InsertLoc); 9208 } 9209 9210 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9211 << Name << RemoveRange 9212 << FixItHint::CreateRemoval(RemoveRange) 9213 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9214 Invalid = true; 9215 } 9216 } 9217 } else { 9218 // Check that we can declare a template here. 9219 if (!TemplateParamLists.empty() && isMemberSpecialization && 9220 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9221 NewFD->setInvalidDecl(); 9222 9223 // All template param lists were matched against the scope specifier: 9224 // this is NOT (an explicit specialization of) a template. 9225 if (TemplateParamLists.size() > 0) 9226 // For source fidelity, store all the template param lists. 9227 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9228 } 9229 9230 if (Invalid) { 9231 NewFD->setInvalidDecl(); 9232 if (FunctionTemplate) 9233 FunctionTemplate->setInvalidDecl(); 9234 } 9235 9236 // C++ [dcl.fct.spec]p5: 9237 // The virtual specifier shall only be used in declarations of 9238 // nonstatic class member functions that appear within a 9239 // member-specification of a class declaration; see 10.3. 9240 // 9241 if (isVirtual && !NewFD->isInvalidDecl()) { 9242 if (!isVirtualOkay) { 9243 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9244 diag::err_virtual_non_function); 9245 } else if (!CurContext->isRecord()) { 9246 // 'virtual' was specified outside of the class. 9247 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9248 diag::err_virtual_out_of_class) 9249 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9250 } else if (NewFD->getDescribedFunctionTemplate()) { 9251 // C++ [temp.mem]p3: 9252 // A member function template shall not be virtual. 9253 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9254 diag::err_virtual_member_function_template) 9255 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9256 } else { 9257 // Okay: Add virtual to the method. 9258 NewFD->setVirtualAsWritten(true); 9259 } 9260 9261 if (getLangOpts().CPlusPlus14 && 9262 NewFD->getReturnType()->isUndeducedType()) 9263 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9264 } 9265 9266 if (getLangOpts().CPlusPlus14 && 9267 (NewFD->isDependentContext() || 9268 (isFriend && CurContext->isDependentContext())) && 9269 NewFD->getReturnType()->isUndeducedType()) { 9270 // If the function template is referenced directly (for instance, as a 9271 // member of the current instantiation), pretend it has a dependent type. 9272 // This is not really justified by the standard, but is the only sane 9273 // thing to do. 9274 // FIXME: For a friend function, we have not marked the function as being 9275 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9276 const FunctionProtoType *FPT = 9277 NewFD->getType()->castAs<FunctionProtoType>(); 9278 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9279 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9280 FPT->getExtProtoInfo())); 9281 } 9282 9283 // C++ [dcl.fct.spec]p3: 9284 // The inline specifier shall not appear on a block scope function 9285 // declaration. 9286 if (isInline && !NewFD->isInvalidDecl()) { 9287 if (CurContext->isFunctionOrMethod()) { 9288 // 'inline' is not allowed on block scope function declaration. 9289 Diag(D.getDeclSpec().getInlineSpecLoc(), 9290 diag::err_inline_declaration_block_scope) << Name 9291 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9292 } 9293 } 9294 9295 // C++ [dcl.fct.spec]p6: 9296 // The explicit specifier shall be used only in the declaration of a 9297 // constructor or conversion function within its class definition; 9298 // see 12.3.1 and 12.3.2. 9299 if (hasExplicit && !NewFD->isInvalidDecl() && 9300 !isa<CXXDeductionGuideDecl>(NewFD)) { 9301 if (!CurContext->isRecord()) { 9302 // 'explicit' was specified outside of the class. 9303 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9304 diag::err_explicit_out_of_class) 9305 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9306 } else if (!isa<CXXConstructorDecl>(NewFD) && 9307 !isa<CXXConversionDecl>(NewFD)) { 9308 // 'explicit' was specified on a function that wasn't a constructor 9309 // or conversion function. 9310 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9311 diag::err_explicit_non_ctor_or_conv_function) 9312 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9313 } 9314 } 9315 9316 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9317 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9318 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9319 // are implicitly inline. 9320 NewFD->setImplicitlyInline(); 9321 9322 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9323 // be either constructors or to return a literal type. Therefore, 9324 // destructors cannot be declared constexpr. 9325 if (isa<CXXDestructorDecl>(NewFD) && 9326 (!getLangOpts().CPlusPlus20 || 9327 ConstexprKind == ConstexprSpecKind::Consteval)) { 9328 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9329 << static_cast<int>(ConstexprKind); 9330 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9331 ? ConstexprSpecKind::Unspecified 9332 : ConstexprSpecKind::Constexpr); 9333 } 9334 // C++20 [dcl.constexpr]p2: An allocation function, or a 9335 // deallocation function shall not be declared with the consteval 9336 // specifier. 9337 if (ConstexprKind == ConstexprSpecKind::Consteval && 9338 (NewFD->getOverloadedOperator() == OO_New || 9339 NewFD->getOverloadedOperator() == OO_Array_New || 9340 NewFD->getOverloadedOperator() == OO_Delete || 9341 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9342 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9343 diag::err_invalid_consteval_decl_kind) 9344 << NewFD; 9345 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9346 } 9347 } 9348 9349 // If __module_private__ was specified, mark the function accordingly. 9350 if (D.getDeclSpec().isModulePrivateSpecified()) { 9351 if (isFunctionTemplateSpecialization) { 9352 SourceLocation ModulePrivateLoc 9353 = D.getDeclSpec().getModulePrivateSpecLoc(); 9354 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9355 << 0 9356 << FixItHint::CreateRemoval(ModulePrivateLoc); 9357 } else { 9358 NewFD->setModulePrivate(); 9359 if (FunctionTemplate) 9360 FunctionTemplate->setModulePrivate(); 9361 } 9362 } 9363 9364 if (isFriend) { 9365 if (FunctionTemplate) { 9366 FunctionTemplate->setObjectOfFriendDecl(); 9367 FunctionTemplate->setAccess(AS_public); 9368 } 9369 NewFD->setObjectOfFriendDecl(); 9370 NewFD->setAccess(AS_public); 9371 } 9372 9373 // If a function is defined as defaulted or deleted, mark it as such now. 9374 // We'll do the relevant checks on defaulted / deleted functions later. 9375 switch (D.getFunctionDefinitionKind()) { 9376 case FunctionDefinitionKind::Declaration: 9377 case FunctionDefinitionKind::Definition: 9378 break; 9379 9380 case FunctionDefinitionKind::Defaulted: 9381 NewFD->setDefaulted(); 9382 break; 9383 9384 case FunctionDefinitionKind::Deleted: 9385 NewFD->setDeletedAsWritten(); 9386 break; 9387 } 9388 9389 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9390 D.isFunctionDefinition()) { 9391 // C++ [class.mfct]p2: 9392 // A member function may be defined (8.4) in its class definition, in 9393 // which case it is an inline member function (7.1.2) 9394 NewFD->setImplicitlyInline(); 9395 } 9396 9397 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9398 !CurContext->isRecord()) { 9399 // C++ [class.static]p1: 9400 // A data or function member of a class may be declared static 9401 // in a class definition, in which case it is a static member of 9402 // the class. 9403 9404 // Complain about the 'static' specifier if it's on an out-of-line 9405 // member function definition. 9406 9407 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9408 // member function template declaration and class member template 9409 // declaration (MSVC versions before 2015), warn about this. 9410 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9411 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9412 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9413 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9414 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9415 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9416 } 9417 9418 // C++11 [except.spec]p15: 9419 // A deallocation function with no exception-specification is treated 9420 // as if it were specified with noexcept(true). 9421 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9422 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9423 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9424 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9425 NewFD->setType(Context.getFunctionType( 9426 FPT->getReturnType(), FPT->getParamTypes(), 9427 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9428 } 9429 9430 // Filter out previous declarations that don't match the scope. 9431 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9432 D.getCXXScopeSpec().isNotEmpty() || 9433 isMemberSpecialization || 9434 isFunctionTemplateSpecialization); 9435 9436 // Handle GNU asm-label extension (encoded as an attribute). 9437 if (Expr *E = (Expr*) D.getAsmLabel()) { 9438 // The parser guarantees this is a string. 9439 StringLiteral *SE = cast<StringLiteral>(E); 9440 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9441 /*IsLiteralLabel=*/true, 9442 SE->getStrTokenLoc(0))); 9443 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9444 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9445 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9446 if (I != ExtnameUndeclaredIdentifiers.end()) { 9447 if (isDeclExternC(NewFD)) { 9448 NewFD->addAttr(I->second); 9449 ExtnameUndeclaredIdentifiers.erase(I); 9450 } else 9451 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9452 << /*Variable*/0 << NewFD; 9453 } 9454 } 9455 9456 // Copy the parameter declarations from the declarator D to the function 9457 // declaration NewFD, if they are available. First scavenge them into Params. 9458 SmallVector<ParmVarDecl*, 16> Params; 9459 unsigned FTIIdx; 9460 if (D.isFunctionDeclarator(FTIIdx)) { 9461 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9462 9463 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9464 // function that takes no arguments, not a function that takes a 9465 // single void argument. 9466 // We let through "const void" here because Sema::GetTypeForDeclarator 9467 // already checks for that case. 9468 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9469 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9470 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9471 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9472 Param->setDeclContext(NewFD); 9473 Params.push_back(Param); 9474 9475 if (Param->isInvalidDecl()) 9476 NewFD->setInvalidDecl(); 9477 } 9478 } 9479 9480 if (!getLangOpts().CPlusPlus) { 9481 // In C, find all the tag declarations from the prototype and move them 9482 // into the function DeclContext. Remove them from the surrounding tag 9483 // injection context of the function, which is typically but not always 9484 // the TU. 9485 DeclContext *PrototypeTagContext = 9486 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9487 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9488 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9489 9490 // We don't want to reparent enumerators. Look at their parent enum 9491 // instead. 9492 if (!TD) { 9493 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9494 TD = cast<EnumDecl>(ECD->getDeclContext()); 9495 } 9496 if (!TD) 9497 continue; 9498 DeclContext *TagDC = TD->getLexicalDeclContext(); 9499 if (!TagDC->containsDecl(TD)) 9500 continue; 9501 TagDC->removeDecl(TD); 9502 TD->setDeclContext(NewFD); 9503 NewFD->addDecl(TD); 9504 9505 // Preserve the lexical DeclContext if it is not the surrounding tag 9506 // injection context of the FD. In this example, the semantic context of 9507 // E will be f and the lexical context will be S, while both the 9508 // semantic and lexical contexts of S will be f: 9509 // void f(struct S { enum E { a } f; } s); 9510 if (TagDC != PrototypeTagContext) 9511 TD->setLexicalDeclContext(TagDC); 9512 } 9513 } 9514 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9515 // When we're declaring a function with a typedef, typeof, etc as in the 9516 // following example, we'll need to synthesize (unnamed) 9517 // parameters for use in the declaration. 9518 // 9519 // @code 9520 // typedef void fn(int); 9521 // fn f; 9522 // @endcode 9523 9524 // Synthesize a parameter for each argument type. 9525 for (const auto &AI : FT->param_types()) { 9526 ParmVarDecl *Param = 9527 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9528 Param->setScopeInfo(0, Params.size()); 9529 Params.push_back(Param); 9530 } 9531 } else { 9532 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9533 "Should not need args for typedef of non-prototype fn"); 9534 } 9535 9536 // Finally, we know we have the right number of parameters, install them. 9537 NewFD->setParams(Params); 9538 9539 if (D.getDeclSpec().isNoreturnSpecified()) 9540 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9541 D.getDeclSpec().getNoreturnSpecLoc(), 9542 AttributeCommonInfo::AS_Keyword)); 9543 9544 // Functions returning a variably modified type violate C99 6.7.5.2p2 9545 // because all functions have linkage. 9546 if (!NewFD->isInvalidDecl() && 9547 NewFD->getReturnType()->isVariablyModifiedType()) { 9548 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9549 NewFD->setInvalidDecl(); 9550 } 9551 9552 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9553 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9554 !NewFD->hasAttr<SectionAttr>()) 9555 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9556 Context, PragmaClangTextSection.SectionName, 9557 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9558 9559 // Apply an implicit SectionAttr if #pragma code_seg is active. 9560 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9561 !NewFD->hasAttr<SectionAttr>()) { 9562 NewFD->addAttr(SectionAttr::CreateImplicit( 9563 Context, CodeSegStack.CurrentValue->getString(), 9564 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9565 SectionAttr::Declspec_allocate)); 9566 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9567 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9568 ASTContext::PSF_Read, 9569 NewFD)) 9570 NewFD->dropAttr<SectionAttr>(); 9571 } 9572 9573 // Apply an implicit CodeSegAttr from class declspec or 9574 // apply an implicit SectionAttr from #pragma code_seg if active. 9575 if (!NewFD->hasAttr<CodeSegAttr>()) { 9576 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9577 D.isFunctionDefinition())) { 9578 NewFD->addAttr(SAttr); 9579 } 9580 } 9581 9582 // Handle attributes. 9583 ProcessDeclAttributes(S, NewFD, D); 9584 9585 if (getLangOpts().OpenCL) { 9586 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9587 // type declaration will generate a compilation error. 9588 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9589 if (AddressSpace != LangAS::Default) { 9590 Diag(NewFD->getLocation(), 9591 diag::err_opencl_return_value_with_address_space); 9592 NewFD->setInvalidDecl(); 9593 } 9594 } 9595 9596 if (!getLangOpts().CPlusPlus) { 9597 // Perform semantic checking on the function declaration. 9598 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9599 CheckMain(NewFD, D.getDeclSpec()); 9600 9601 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9602 CheckMSVCRTEntryPoint(NewFD); 9603 9604 if (!NewFD->isInvalidDecl()) 9605 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9606 isMemberSpecialization)); 9607 else if (!Previous.empty()) 9608 // Recover gracefully from an invalid redeclaration. 9609 D.setRedeclaration(true); 9610 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9611 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9612 "previous declaration set still overloaded"); 9613 9614 // Diagnose no-prototype function declarations with calling conventions that 9615 // don't support variadic calls. Only do this in C and do it after merging 9616 // possibly prototyped redeclarations. 9617 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9618 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9619 CallingConv CC = FT->getExtInfo().getCC(); 9620 if (!supportsVariadicCall(CC)) { 9621 // Windows system headers sometimes accidentally use stdcall without 9622 // (void) parameters, so we relax this to a warning. 9623 int DiagID = 9624 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9625 Diag(NewFD->getLocation(), DiagID) 9626 << FunctionType::getNameForCallConv(CC); 9627 } 9628 } 9629 9630 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9631 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9632 checkNonTrivialCUnion(NewFD->getReturnType(), 9633 NewFD->getReturnTypeSourceRange().getBegin(), 9634 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9635 } else { 9636 // C++11 [replacement.functions]p3: 9637 // The program's definitions shall not be specified as inline. 9638 // 9639 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9640 // 9641 // Suppress the diagnostic if the function is __attribute__((used)), since 9642 // that forces an external definition to be emitted. 9643 if (D.getDeclSpec().isInlineSpecified() && 9644 NewFD->isReplaceableGlobalAllocationFunction() && 9645 !NewFD->hasAttr<UsedAttr>()) 9646 Diag(D.getDeclSpec().getInlineSpecLoc(), 9647 diag::ext_operator_new_delete_declared_inline) 9648 << NewFD->getDeclName(); 9649 9650 // If the declarator is a template-id, translate the parser's template 9651 // argument list into our AST format. 9652 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9653 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9654 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9655 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9656 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9657 TemplateId->NumArgs); 9658 translateTemplateArguments(TemplateArgsPtr, 9659 TemplateArgs); 9660 9661 HasExplicitTemplateArgs = true; 9662 9663 if (NewFD->isInvalidDecl()) { 9664 HasExplicitTemplateArgs = false; 9665 } else if (FunctionTemplate) { 9666 // Function template with explicit template arguments. 9667 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9668 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9669 9670 HasExplicitTemplateArgs = false; 9671 } else { 9672 assert((isFunctionTemplateSpecialization || 9673 D.getDeclSpec().isFriendSpecified()) && 9674 "should have a 'template<>' for this decl"); 9675 // "friend void foo<>(int);" is an implicit specialization decl. 9676 isFunctionTemplateSpecialization = true; 9677 } 9678 } else if (isFriend && isFunctionTemplateSpecialization) { 9679 // This combination is only possible in a recovery case; the user 9680 // wrote something like: 9681 // template <> friend void foo(int); 9682 // which we're recovering from as if the user had written: 9683 // friend void foo<>(int); 9684 // Go ahead and fake up a template id. 9685 HasExplicitTemplateArgs = true; 9686 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9687 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9688 } 9689 9690 // We do not add HD attributes to specializations here because 9691 // they may have different constexpr-ness compared to their 9692 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9693 // may end up with different effective targets. Instead, a 9694 // specialization inherits its target attributes from its template 9695 // in the CheckFunctionTemplateSpecialization() call below. 9696 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9697 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9698 9699 // If it's a friend (and only if it's a friend), it's possible 9700 // that either the specialized function type or the specialized 9701 // template is dependent, and therefore matching will fail. In 9702 // this case, don't check the specialization yet. 9703 if (isFunctionTemplateSpecialization && isFriend && 9704 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9705 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9706 TemplateArgs.arguments()))) { 9707 assert(HasExplicitTemplateArgs && 9708 "friend function specialization without template args"); 9709 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9710 Previous)) 9711 NewFD->setInvalidDecl(); 9712 } else if (isFunctionTemplateSpecialization) { 9713 if (CurContext->isDependentContext() && CurContext->isRecord() 9714 && !isFriend) { 9715 isDependentClassScopeExplicitSpecialization = true; 9716 } else if (!NewFD->isInvalidDecl() && 9717 CheckFunctionTemplateSpecialization( 9718 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9719 Previous)) 9720 NewFD->setInvalidDecl(); 9721 9722 // C++ [dcl.stc]p1: 9723 // A storage-class-specifier shall not be specified in an explicit 9724 // specialization (14.7.3) 9725 FunctionTemplateSpecializationInfo *Info = 9726 NewFD->getTemplateSpecializationInfo(); 9727 if (Info && SC != SC_None) { 9728 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9729 Diag(NewFD->getLocation(), 9730 diag::err_explicit_specialization_inconsistent_storage_class) 9731 << SC 9732 << FixItHint::CreateRemoval( 9733 D.getDeclSpec().getStorageClassSpecLoc()); 9734 9735 else 9736 Diag(NewFD->getLocation(), 9737 diag::ext_explicit_specialization_storage_class) 9738 << FixItHint::CreateRemoval( 9739 D.getDeclSpec().getStorageClassSpecLoc()); 9740 } 9741 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9742 if (CheckMemberSpecialization(NewFD, Previous)) 9743 NewFD->setInvalidDecl(); 9744 } 9745 9746 // Perform semantic checking on the function declaration. 9747 if (!isDependentClassScopeExplicitSpecialization) { 9748 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9749 CheckMain(NewFD, D.getDeclSpec()); 9750 9751 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9752 CheckMSVCRTEntryPoint(NewFD); 9753 9754 if (!NewFD->isInvalidDecl()) 9755 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9756 isMemberSpecialization)); 9757 else if (!Previous.empty()) 9758 // Recover gracefully from an invalid redeclaration. 9759 D.setRedeclaration(true); 9760 } 9761 9762 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9763 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9764 "previous declaration set still overloaded"); 9765 9766 NamedDecl *PrincipalDecl = (FunctionTemplate 9767 ? cast<NamedDecl>(FunctionTemplate) 9768 : NewFD); 9769 9770 if (isFriend && NewFD->getPreviousDecl()) { 9771 AccessSpecifier Access = AS_public; 9772 if (!NewFD->isInvalidDecl()) 9773 Access = NewFD->getPreviousDecl()->getAccess(); 9774 9775 NewFD->setAccess(Access); 9776 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9777 } 9778 9779 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9780 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9781 PrincipalDecl->setNonMemberOperator(); 9782 9783 // If we have a function template, check the template parameter 9784 // list. This will check and merge default template arguments. 9785 if (FunctionTemplate) { 9786 FunctionTemplateDecl *PrevTemplate = 9787 FunctionTemplate->getPreviousDecl(); 9788 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9789 PrevTemplate ? PrevTemplate->getTemplateParameters() 9790 : nullptr, 9791 D.getDeclSpec().isFriendSpecified() 9792 ? (D.isFunctionDefinition() 9793 ? TPC_FriendFunctionTemplateDefinition 9794 : TPC_FriendFunctionTemplate) 9795 : (D.getCXXScopeSpec().isSet() && 9796 DC && DC->isRecord() && 9797 DC->isDependentContext()) 9798 ? TPC_ClassTemplateMember 9799 : TPC_FunctionTemplate); 9800 } 9801 9802 if (NewFD->isInvalidDecl()) { 9803 // Ignore all the rest of this. 9804 } else if (!D.isRedeclaration()) { 9805 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9806 AddToScope }; 9807 // Fake up an access specifier if it's supposed to be a class member. 9808 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9809 NewFD->setAccess(AS_public); 9810 9811 // Qualified decls generally require a previous declaration. 9812 if (D.getCXXScopeSpec().isSet()) { 9813 // ...with the major exception of templated-scope or 9814 // dependent-scope friend declarations. 9815 9816 // TODO: we currently also suppress this check in dependent 9817 // contexts because (1) the parameter depth will be off when 9818 // matching friend templates and (2) we might actually be 9819 // selecting a friend based on a dependent factor. But there 9820 // are situations where these conditions don't apply and we 9821 // can actually do this check immediately. 9822 // 9823 // Unless the scope is dependent, it's always an error if qualified 9824 // redeclaration lookup found nothing at all. Diagnose that now; 9825 // nothing will diagnose that error later. 9826 if (isFriend && 9827 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9828 (!Previous.empty() && CurContext->isDependentContext()))) { 9829 // ignore these 9830 } else if (NewFD->isCPUDispatchMultiVersion() || 9831 NewFD->isCPUSpecificMultiVersion()) { 9832 // ignore this, we allow the redeclaration behavior here to create new 9833 // versions of the function. 9834 } else { 9835 // The user tried to provide an out-of-line definition for a 9836 // function that is a member of a class or namespace, but there 9837 // was no such member function declared (C++ [class.mfct]p2, 9838 // C++ [namespace.memdef]p2). For example: 9839 // 9840 // class X { 9841 // void f() const; 9842 // }; 9843 // 9844 // void X::f() { } // ill-formed 9845 // 9846 // Complain about this problem, and attempt to suggest close 9847 // matches (e.g., those that differ only in cv-qualifiers and 9848 // whether the parameter types are references). 9849 9850 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9851 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9852 AddToScope = ExtraArgs.AddToScope; 9853 return Result; 9854 } 9855 } 9856 9857 // Unqualified local friend declarations are required to resolve 9858 // to something. 9859 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9860 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9861 *this, Previous, NewFD, ExtraArgs, true, S)) { 9862 AddToScope = ExtraArgs.AddToScope; 9863 return Result; 9864 } 9865 } 9866 } else if (!D.isFunctionDefinition() && 9867 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9868 !isFriend && !isFunctionTemplateSpecialization && 9869 !isMemberSpecialization) { 9870 // An out-of-line member function declaration must also be a 9871 // definition (C++ [class.mfct]p2). 9872 // Note that this is not the case for explicit specializations of 9873 // function templates or member functions of class templates, per 9874 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9875 // extension for compatibility with old SWIG code which likes to 9876 // generate them. 9877 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9878 << D.getCXXScopeSpec().getRange(); 9879 } 9880 } 9881 9882 // If this is the first declaration of a library builtin function, add 9883 // attributes as appropriate. 9884 if (!D.isRedeclaration() && 9885 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9886 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9887 if (unsigned BuiltinID = II->getBuiltinID()) { 9888 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9889 // Validate the type matches unless this builtin is specified as 9890 // matching regardless of its declared type. 9891 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9892 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9893 } else { 9894 ASTContext::GetBuiltinTypeError Error; 9895 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9896 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9897 9898 if (!Error && !BuiltinType.isNull() && 9899 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9900 NewFD->getType(), BuiltinType)) 9901 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9902 } 9903 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9904 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9905 // FIXME: We should consider this a builtin only in the std namespace. 9906 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9907 } 9908 } 9909 } 9910 } 9911 9912 ProcessPragmaWeak(S, NewFD); 9913 checkAttributesAfterMerging(*this, *NewFD); 9914 9915 AddKnownFunctionAttributes(NewFD); 9916 9917 if (NewFD->hasAttr<OverloadableAttr>() && 9918 !NewFD->getType()->getAs<FunctionProtoType>()) { 9919 Diag(NewFD->getLocation(), 9920 diag::err_attribute_overloadable_no_prototype) 9921 << NewFD; 9922 9923 // Turn this into a variadic function with no parameters. 9924 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9925 FunctionProtoType::ExtProtoInfo EPI( 9926 Context.getDefaultCallingConvention(true, false)); 9927 EPI.Variadic = true; 9928 EPI.ExtInfo = FT->getExtInfo(); 9929 9930 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9931 NewFD->setType(R); 9932 } 9933 9934 // If there's a #pragma GCC visibility in scope, and this isn't a class 9935 // member, set the visibility of this function. 9936 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9937 AddPushedVisibilityAttribute(NewFD); 9938 9939 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9940 // marking the function. 9941 AddCFAuditedAttribute(NewFD); 9942 9943 // If this is a function definition, check if we have to apply optnone due to 9944 // a pragma. 9945 if(D.isFunctionDefinition()) 9946 AddRangeBasedOptnone(NewFD); 9947 9948 // If this is the first declaration of an extern C variable, update 9949 // the map of such variables. 9950 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9951 isIncompleteDeclExternC(*this, NewFD)) 9952 RegisterLocallyScopedExternCDecl(NewFD, S); 9953 9954 // Set this FunctionDecl's range up to the right paren. 9955 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9956 9957 if (D.isRedeclaration() && !Previous.empty()) { 9958 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9959 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9960 isMemberSpecialization || 9961 isFunctionTemplateSpecialization, 9962 D.isFunctionDefinition()); 9963 } 9964 9965 if (getLangOpts().CUDA) { 9966 IdentifierInfo *II = NewFD->getIdentifier(); 9967 if (II && II->isStr(getCudaConfigureFuncName()) && 9968 !NewFD->isInvalidDecl() && 9969 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9970 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 9971 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9972 << getCudaConfigureFuncName(); 9973 Context.setcudaConfigureCallDecl(NewFD); 9974 } 9975 9976 // Variadic functions, other than a *declaration* of printf, are not allowed 9977 // in device-side CUDA code, unless someone passed 9978 // -fcuda-allow-variadic-functions. 9979 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9980 (NewFD->hasAttr<CUDADeviceAttr>() || 9981 NewFD->hasAttr<CUDAGlobalAttr>()) && 9982 !(II && II->isStr("printf") && NewFD->isExternC() && 9983 !D.isFunctionDefinition())) { 9984 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9985 } 9986 } 9987 9988 MarkUnusedFileScopedDecl(NewFD); 9989 9990 9991 9992 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9993 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9994 if (SC == SC_Static) { 9995 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9996 D.setInvalidType(); 9997 } 9998 9999 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10000 if (!NewFD->getReturnType()->isVoidType()) { 10001 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10002 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10003 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10004 : FixItHint()); 10005 D.setInvalidType(); 10006 } 10007 10008 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10009 for (auto Param : NewFD->parameters()) 10010 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10011 10012 if (getLangOpts().OpenCLCPlusPlus) { 10013 if (DC->isRecord()) { 10014 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10015 D.setInvalidType(); 10016 } 10017 if (FunctionTemplate) { 10018 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10019 D.setInvalidType(); 10020 } 10021 } 10022 } 10023 10024 if (getLangOpts().CPlusPlus) { 10025 if (FunctionTemplate) { 10026 if (NewFD->isInvalidDecl()) 10027 FunctionTemplate->setInvalidDecl(); 10028 return FunctionTemplate; 10029 } 10030 10031 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10032 CompleteMemberSpecialization(NewFD, Previous); 10033 } 10034 10035 for (const ParmVarDecl *Param : NewFD->parameters()) { 10036 QualType PT = Param->getType(); 10037 10038 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10039 // types. 10040 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10041 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10042 QualType ElemTy = PipeTy->getElementType(); 10043 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10044 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10045 D.setInvalidType(); 10046 } 10047 } 10048 } 10049 } 10050 10051 // Here we have an function template explicit specialization at class scope. 10052 // The actual specialization will be postponed to template instatiation 10053 // time via the ClassScopeFunctionSpecializationDecl node. 10054 if (isDependentClassScopeExplicitSpecialization) { 10055 ClassScopeFunctionSpecializationDecl *NewSpec = 10056 ClassScopeFunctionSpecializationDecl::Create( 10057 Context, CurContext, NewFD->getLocation(), 10058 cast<CXXMethodDecl>(NewFD), 10059 HasExplicitTemplateArgs, TemplateArgs); 10060 CurContext->addDecl(NewSpec); 10061 AddToScope = false; 10062 } 10063 10064 // Diagnose availability attributes. Availability cannot be used on functions 10065 // that are run during load/unload. 10066 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10067 if (NewFD->hasAttr<ConstructorAttr>()) { 10068 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10069 << 1; 10070 NewFD->dropAttr<AvailabilityAttr>(); 10071 } 10072 if (NewFD->hasAttr<DestructorAttr>()) { 10073 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10074 << 2; 10075 NewFD->dropAttr<AvailabilityAttr>(); 10076 } 10077 } 10078 10079 // Diagnose no_builtin attribute on function declaration that are not a 10080 // definition. 10081 // FIXME: We should really be doing this in 10082 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10083 // the FunctionDecl and at this point of the code 10084 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10085 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10086 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10087 switch (D.getFunctionDefinitionKind()) { 10088 case FunctionDefinitionKind::Defaulted: 10089 case FunctionDefinitionKind::Deleted: 10090 Diag(NBA->getLocation(), 10091 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10092 << NBA->getSpelling(); 10093 break; 10094 case FunctionDefinitionKind::Declaration: 10095 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10096 << NBA->getSpelling(); 10097 break; 10098 case FunctionDefinitionKind::Definition: 10099 break; 10100 } 10101 10102 return NewFD; 10103 } 10104 10105 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10106 /// when __declspec(code_seg) "is applied to a class, all member functions of 10107 /// the class and nested classes -- this includes compiler-generated special 10108 /// member functions -- are put in the specified segment." 10109 /// The actual behavior is a little more complicated. The Microsoft compiler 10110 /// won't check outer classes if there is an active value from #pragma code_seg. 10111 /// The CodeSeg is always applied from the direct parent but only from outer 10112 /// classes when the #pragma code_seg stack is empty. See: 10113 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10114 /// available since MS has removed the page. 10115 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10116 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10117 if (!Method) 10118 return nullptr; 10119 const CXXRecordDecl *Parent = Method->getParent(); 10120 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10121 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10122 NewAttr->setImplicit(true); 10123 return NewAttr; 10124 } 10125 10126 // The Microsoft compiler won't check outer classes for the CodeSeg 10127 // when the #pragma code_seg stack is active. 10128 if (S.CodeSegStack.CurrentValue) 10129 return nullptr; 10130 10131 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10132 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10133 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10134 NewAttr->setImplicit(true); 10135 return NewAttr; 10136 } 10137 } 10138 return nullptr; 10139 } 10140 10141 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10142 /// containing class. Otherwise it will return implicit SectionAttr if the 10143 /// function is a definition and there is an active value on CodeSegStack 10144 /// (from the current #pragma code-seg value). 10145 /// 10146 /// \param FD Function being declared. 10147 /// \param IsDefinition Whether it is a definition or just a declarartion. 10148 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10149 /// nullptr if no attribute should be added. 10150 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10151 bool IsDefinition) { 10152 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10153 return A; 10154 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10155 CodeSegStack.CurrentValue) 10156 return SectionAttr::CreateImplicit( 10157 getASTContext(), CodeSegStack.CurrentValue->getString(), 10158 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10159 SectionAttr::Declspec_allocate); 10160 return nullptr; 10161 } 10162 10163 /// Determines if we can perform a correct type check for \p D as a 10164 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10165 /// best-effort check. 10166 /// 10167 /// \param NewD The new declaration. 10168 /// \param OldD The old declaration. 10169 /// \param NewT The portion of the type of the new declaration to check. 10170 /// \param OldT The portion of the type of the old declaration to check. 10171 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10172 QualType NewT, QualType OldT) { 10173 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10174 return true; 10175 10176 // For dependently-typed local extern declarations and friends, we can't 10177 // perform a correct type check in general until instantiation: 10178 // 10179 // int f(); 10180 // template<typename T> void g() { T f(); } 10181 // 10182 // (valid if g() is only instantiated with T = int). 10183 if (NewT->isDependentType() && 10184 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10185 return false; 10186 10187 // Similarly, if the previous declaration was a dependent local extern 10188 // declaration, we don't really know its type yet. 10189 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10190 return false; 10191 10192 return true; 10193 } 10194 10195 /// Checks if the new declaration declared in dependent context must be 10196 /// put in the same redeclaration chain as the specified declaration. 10197 /// 10198 /// \param D Declaration that is checked. 10199 /// \param PrevDecl Previous declaration found with proper lookup method for the 10200 /// same declaration name. 10201 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10202 /// belongs to. 10203 /// 10204 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10205 if (!D->getLexicalDeclContext()->isDependentContext()) 10206 return true; 10207 10208 // Don't chain dependent friend function definitions until instantiation, to 10209 // permit cases like 10210 // 10211 // void func(); 10212 // template<typename T> class C1 { friend void func() {} }; 10213 // template<typename T> class C2 { friend void func() {} }; 10214 // 10215 // ... which is valid if only one of C1 and C2 is ever instantiated. 10216 // 10217 // FIXME: This need only apply to function definitions. For now, we proxy 10218 // this by checking for a file-scope function. We do not want this to apply 10219 // to friend declarations nominating member functions, because that gets in 10220 // the way of access checks. 10221 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10222 return false; 10223 10224 auto *VD = dyn_cast<ValueDecl>(D); 10225 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10226 return !VD || !PrevVD || 10227 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10228 PrevVD->getType()); 10229 } 10230 10231 /// Check the target attribute of the function for MultiVersion 10232 /// validity. 10233 /// 10234 /// Returns true if there was an error, false otherwise. 10235 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10236 const auto *TA = FD->getAttr<TargetAttr>(); 10237 assert(TA && "MultiVersion Candidate requires a target attribute"); 10238 ParsedTargetAttr ParseInfo = TA->parse(); 10239 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10240 enum ErrType { Feature = 0, Architecture = 1 }; 10241 10242 if (!ParseInfo.Architecture.empty() && 10243 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10244 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10245 << Architecture << ParseInfo.Architecture; 10246 return true; 10247 } 10248 10249 for (const auto &Feat : ParseInfo.Features) { 10250 auto BareFeat = StringRef{Feat}.substr(1); 10251 if (Feat[0] == '-') { 10252 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10253 << Feature << ("no-" + BareFeat).str(); 10254 return true; 10255 } 10256 10257 if (!TargetInfo.validateCpuSupports(BareFeat) || 10258 !TargetInfo.isValidFeatureName(BareFeat)) { 10259 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10260 << Feature << BareFeat; 10261 return true; 10262 } 10263 } 10264 return false; 10265 } 10266 10267 // Provide a white-list of attributes that are allowed to be combined with 10268 // multiversion functions. 10269 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10270 MultiVersionKind MVType) { 10271 // Note: this list/diagnosis must match the list in 10272 // checkMultiversionAttributesAllSame. 10273 switch (Kind) { 10274 default: 10275 return false; 10276 case attr::Used: 10277 return MVType == MultiVersionKind::Target; 10278 case attr::NonNull: 10279 case attr::NoThrow: 10280 return true; 10281 } 10282 } 10283 10284 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10285 const FunctionDecl *FD, 10286 const FunctionDecl *CausedFD, 10287 MultiVersionKind MVType) { 10288 const auto Diagnose = [FD, CausedFD, MVType](Sema &S, const Attr *A) { 10289 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10290 << static_cast<unsigned>(MVType) << A; 10291 if (CausedFD) 10292 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10293 return true; 10294 }; 10295 10296 for (const Attr *A : FD->attrs()) { 10297 switch (A->getKind()) { 10298 case attr::CPUDispatch: 10299 case attr::CPUSpecific: 10300 if (MVType != MultiVersionKind::CPUDispatch && 10301 MVType != MultiVersionKind::CPUSpecific) 10302 return Diagnose(S, A); 10303 break; 10304 case attr::Target: 10305 if (MVType != MultiVersionKind::Target) 10306 return Diagnose(S, A); 10307 break; 10308 case attr::TargetClones: 10309 if (MVType != MultiVersionKind::TargetClones) 10310 return Diagnose(S, A); 10311 break; 10312 default: 10313 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10314 return Diagnose(S, A); 10315 break; 10316 } 10317 } 10318 return false; 10319 } 10320 10321 bool Sema::areMultiversionVariantFunctionsCompatible( 10322 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10323 const PartialDiagnostic &NoProtoDiagID, 10324 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10325 const PartialDiagnosticAt &NoSupportDiagIDAt, 10326 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10327 bool ConstexprSupported, bool CLinkageMayDiffer) { 10328 enum DoesntSupport { 10329 FuncTemplates = 0, 10330 VirtFuncs = 1, 10331 DeducedReturn = 2, 10332 Constructors = 3, 10333 Destructors = 4, 10334 DeletedFuncs = 5, 10335 DefaultedFuncs = 6, 10336 ConstexprFuncs = 7, 10337 ConstevalFuncs = 8, 10338 Lambda = 9, 10339 }; 10340 enum Different { 10341 CallingConv = 0, 10342 ReturnType = 1, 10343 ConstexprSpec = 2, 10344 InlineSpec = 3, 10345 Linkage = 4, 10346 LanguageLinkage = 5, 10347 }; 10348 10349 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10350 !OldFD->getType()->getAs<FunctionProtoType>()) { 10351 Diag(OldFD->getLocation(), NoProtoDiagID); 10352 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10353 return true; 10354 } 10355 10356 if (NoProtoDiagID.getDiagID() != 0 && 10357 !NewFD->getType()->getAs<FunctionProtoType>()) 10358 return Diag(NewFD->getLocation(), NoProtoDiagID); 10359 10360 if (!TemplatesSupported && 10361 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10362 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10363 << FuncTemplates; 10364 10365 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10366 if (NewCXXFD->isVirtual()) 10367 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10368 << VirtFuncs; 10369 10370 if (isa<CXXConstructorDecl>(NewCXXFD)) 10371 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10372 << Constructors; 10373 10374 if (isa<CXXDestructorDecl>(NewCXXFD)) 10375 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10376 << Destructors; 10377 } 10378 10379 if (NewFD->isDeleted()) 10380 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10381 << DeletedFuncs; 10382 10383 if (NewFD->isDefaulted()) 10384 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10385 << DefaultedFuncs; 10386 10387 if (!ConstexprSupported && NewFD->isConstexpr()) 10388 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10389 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10390 10391 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10392 const auto *NewType = cast<FunctionType>(NewQType); 10393 QualType NewReturnType = NewType->getReturnType(); 10394 10395 if (NewReturnType->isUndeducedType()) 10396 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10397 << DeducedReturn; 10398 10399 // Ensure the return type is identical. 10400 if (OldFD) { 10401 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10402 const auto *OldType = cast<FunctionType>(OldQType); 10403 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10404 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10405 10406 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10407 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10408 10409 QualType OldReturnType = OldType->getReturnType(); 10410 10411 if (OldReturnType != NewReturnType) 10412 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10413 10414 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10415 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10416 10417 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10418 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10419 10420 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10421 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10422 10423 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10424 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10425 10426 if (CheckEquivalentExceptionSpec( 10427 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10428 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10429 return true; 10430 } 10431 return false; 10432 } 10433 10434 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10435 const FunctionDecl *NewFD, 10436 bool CausesMV, 10437 MultiVersionKind MVType) { 10438 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10439 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10440 if (OldFD) 10441 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10442 return true; 10443 } 10444 10445 bool IsCPUSpecificCPUDispatchMVType = 10446 MVType == MultiVersionKind::CPUDispatch || 10447 MVType == MultiVersionKind::CPUSpecific; 10448 10449 if (CausesMV && OldFD && 10450 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10451 return true; 10452 10453 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10454 return true; 10455 10456 // Only allow transition to MultiVersion if it hasn't been used. 10457 if (OldFD && CausesMV && OldFD->isUsed(false)) 10458 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10459 10460 return S.areMultiversionVariantFunctionsCompatible( 10461 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10462 PartialDiagnosticAt(NewFD->getLocation(), 10463 S.PDiag(diag::note_multiversioning_caused_here)), 10464 PartialDiagnosticAt(NewFD->getLocation(), 10465 S.PDiag(diag::err_multiversion_doesnt_support) 10466 << static_cast<unsigned>(MVType)), 10467 PartialDiagnosticAt(NewFD->getLocation(), 10468 S.PDiag(diag::err_multiversion_diff)), 10469 /*TemplatesSupported=*/false, 10470 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10471 /*CLinkageMayDiffer=*/false); 10472 } 10473 10474 /// Check the validity of a multiversion function declaration that is the 10475 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10476 /// 10477 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10478 /// 10479 /// Returns true if there was an error, false otherwise. 10480 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10481 MultiVersionKind MVType, 10482 const TargetAttr *TA) { 10483 assert(MVType != MultiVersionKind::None && 10484 "Function lacks multiversion attribute"); 10485 10486 // Target only causes MV if it is default, otherwise this is a normal 10487 // function. 10488 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10489 return false; 10490 10491 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10492 FD->setInvalidDecl(); 10493 return true; 10494 } 10495 10496 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10497 FD->setInvalidDecl(); 10498 return true; 10499 } 10500 10501 FD->setIsMultiVersion(); 10502 return false; 10503 } 10504 10505 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10506 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10507 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10508 return true; 10509 } 10510 10511 return false; 10512 } 10513 10514 static bool CheckTargetCausesMultiVersioning( 10515 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10516 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10517 LookupResult &Previous) { 10518 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10519 ParsedTargetAttr NewParsed = NewTA->parse(); 10520 // Sort order doesn't matter, it just needs to be consistent. 10521 llvm::sort(NewParsed.Features); 10522 10523 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10524 // to change, this is a simple redeclaration. 10525 if (!NewTA->isDefaultVersion() && 10526 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10527 return false; 10528 10529 // Otherwise, this decl causes MultiVersioning. 10530 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10531 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10532 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10533 NewFD->setInvalidDecl(); 10534 return true; 10535 } 10536 10537 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10538 MultiVersionKind::Target)) { 10539 NewFD->setInvalidDecl(); 10540 return true; 10541 } 10542 10543 if (CheckMultiVersionValue(S, NewFD)) { 10544 NewFD->setInvalidDecl(); 10545 return true; 10546 } 10547 10548 // If this is 'default', permit the forward declaration. 10549 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10550 Redeclaration = true; 10551 OldDecl = OldFD; 10552 OldFD->setIsMultiVersion(); 10553 NewFD->setIsMultiVersion(); 10554 return false; 10555 } 10556 10557 if (CheckMultiVersionValue(S, OldFD)) { 10558 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10559 NewFD->setInvalidDecl(); 10560 return true; 10561 } 10562 10563 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10564 10565 if (OldParsed == NewParsed) { 10566 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10567 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10568 NewFD->setInvalidDecl(); 10569 return true; 10570 } 10571 10572 for (const auto *FD : OldFD->redecls()) { 10573 const auto *CurTA = FD->getAttr<TargetAttr>(); 10574 // We allow forward declarations before ANY multiversioning attributes, but 10575 // nothing after the fact. 10576 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10577 (!CurTA || CurTA->isInherited())) { 10578 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10579 << 0; 10580 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10581 NewFD->setInvalidDecl(); 10582 return true; 10583 } 10584 } 10585 10586 OldFD->setIsMultiVersion(); 10587 NewFD->setIsMultiVersion(); 10588 Redeclaration = false; 10589 MergeTypeWithPrevious = false; 10590 OldDecl = nullptr; 10591 Previous.clear(); 10592 return false; 10593 } 10594 10595 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 10596 MultiVersionKind New) { 10597 if (Old == New || Old == MultiVersionKind::None || 10598 New == MultiVersionKind::None) 10599 return true; 10600 10601 return (Old == MultiVersionKind::CPUDispatch && 10602 New == MultiVersionKind::CPUSpecific) || 10603 (Old == MultiVersionKind::CPUSpecific && 10604 New == MultiVersionKind::CPUDispatch); 10605 } 10606 10607 /// Check the validity of a new function declaration being added to an existing 10608 /// multiversioned declaration collection. 10609 static bool CheckMultiVersionAdditionalDecl( 10610 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10611 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10612 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10613 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 10614 bool &MergeTypeWithPrevious, LookupResult &Previous) { 10615 10616 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10617 // Disallow mixing of multiversioning types. 10618 if (!MultiVersionTypesCompatible(OldMVType, NewMVType)) { 10619 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10620 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10621 NewFD->setInvalidDecl(); 10622 return true; 10623 } 10624 10625 ParsedTargetAttr NewParsed; 10626 if (NewTA) { 10627 NewParsed = NewTA->parse(); 10628 llvm::sort(NewParsed.Features); 10629 } 10630 10631 bool UseMemberUsingDeclRules = 10632 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10633 10634 // Next, check ALL non-overloads to see if this is a redeclaration of a 10635 // previous member of the MultiVersion set. 10636 for (NamedDecl *ND : Previous) { 10637 FunctionDecl *CurFD = ND->getAsFunction(); 10638 if (!CurFD) 10639 continue; 10640 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10641 continue; 10642 10643 switch (NewMVType) { 10644 case MultiVersionKind::None: 10645 assert(OldMVType == MultiVersionKind::TargetClones && 10646 "Only target_clones can be omitted in subsequent declarations"); 10647 break; 10648 case MultiVersionKind::Target: { 10649 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10650 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10651 NewFD->setIsMultiVersion(); 10652 Redeclaration = true; 10653 OldDecl = ND; 10654 return false; 10655 } 10656 10657 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10658 if (CurParsed == NewParsed) { 10659 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10660 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10661 NewFD->setInvalidDecl(); 10662 return true; 10663 } 10664 break; 10665 } 10666 case MultiVersionKind::TargetClones: { 10667 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 10668 Redeclaration = true; 10669 OldDecl = CurFD; 10670 MergeTypeWithPrevious = true; 10671 NewFD->setIsMultiVersion(); 10672 10673 if (CurClones && NewClones && 10674 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 10675 !std::equal(CurClones->featuresStrs_begin(), 10676 CurClones->featuresStrs_end(), 10677 NewClones->featuresStrs_begin()))) { 10678 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 10679 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10680 NewFD->setInvalidDecl(); 10681 return true; 10682 } 10683 10684 return false; 10685 } 10686 case MultiVersionKind::CPUSpecific: 10687 case MultiVersionKind::CPUDispatch: { 10688 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10689 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10690 // Handle CPUDispatch/CPUSpecific versions. 10691 // Only 1 CPUDispatch function is allowed, this will make it go through 10692 // the redeclaration errors. 10693 if (NewMVType == MultiVersionKind::CPUDispatch && 10694 CurFD->hasAttr<CPUDispatchAttr>()) { 10695 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10696 std::equal( 10697 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10698 NewCPUDisp->cpus_begin(), 10699 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10700 return Cur->getName() == New->getName(); 10701 })) { 10702 NewFD->setIsMultiVersion(); 10703 Redeclaration = true; 10704 OldDecl = ND; 10705 return false; 10706 } 10707 10708 // If the declarations don't match, this is an error condition. 10709 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10710 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10711 NewFD->setInvalidDecl(); 10712 return true; 10713 } 10714 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10715 10716 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10717 std::equal( 10718 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10719 NewCPUSpec->cpus_begin(), 10720 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10721 return Cur->getName() == New->getName(); 10722 })) { 10723 NewFD->setIsMultiVersion(); 10724 Redeclaration = true; 10725 OldDecl = ND; 10726 return false; 10727 } 10728 10729 // Only 1 version of CPUSpecific is allowed for each CPU. 10730 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10731 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10732 if (CurII == NewII) { 10733 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10734 << NewII; 10735 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10736 NewFD->setInvalidDecl(); 10737 return true; 10738 } 10739 } 10740 } 10741 } 10742 break; 10743 } 10744 } 10745 } 10746 10747 // Else, this is simply a non-redecl case. Checking the 'value' is only 10748 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10749 // handled in the attribute adding step. 10750 if (NewMVType == MultiVersionKind::Target && 10751 CheckMultiVersionValue(S, NewFD)) { 10752 NewFD->setInvalidDecl(); 10753 return true; 10754 } 10755 10756 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10757 !OldFD->isMultiVersion(), NewMVType)) { 10758 NewFD->setInvalidDecl(); 10759 return true; 10760 } 10761 10762 // Permit forward declarations in the case where these two are compatible. 10763 if (!OldFD->isMultiVersion()) { 10764 OldFD->setIsMultiVersion(); 10765 NewFD->setIsMultiVersion(); 10766 Redeclaration = true; 10767 OldDecl = OldFD; 10768 return false; 10769 } 10770 10771 NewFD->setIsMultiVersion(); 10772 Redeclaration = false; 10773 MergeTypeWithPrevious = false; 10774 OldDecl = nullptr; 10775 Previous.clear(); 10776 return false; 10777 } 10778 10779 /// Check the validity of a mulitversion function declaration. 10780 /// Also sets the multiversion'ness' of the function itself. 10781 /// 10782 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10783 /// 10784 /// Returns true if there was an error, false otherwise. 10785 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10786 bool &Redeclaration, NamedDecl *&OldDecl, 10787 bool &MergeTypeWithPrevious, 10788 LookupResult &Previous) { 10789 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10790 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10791 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10792 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 10793 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10794 10795 // Main isn't allowed to become a multiversion function, however it IS 10796 // permitted to have 'main' be marked with the 'target' optimization hint. 10797 if (NewFD->isMain()) { 10798 if (MVType != MultiVersionKind::None && 10799 !(MVType == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { 10800 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10801 NewFD->setInvalidDecl(); 10802 return true; 10803 } 10804 return false; 10805 } 10806 10807 if (!OldDecl || !OldDecl->getAsFunction() || 10808 OldDecl->getDeclContext()->getRedeclContext() != 10809 NewFD->getDeclContext()->getRedeclContext()) { 10810 // If there's no previous declaration, AND this isn't attempting to cause 10811 // multiversioning, this isn't an error condition. 10812 if (MVType == MultiVersionKind::None) 10813 return false; 10814 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10815 } 10816 10817 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10818 10819 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10820 return false; 10821 10822 // Multiversioned redeclarations aren't allowed to omit the attribute, except 10823 // for target_clones. 10824 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None && 10825 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { 10826 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10827 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10828 NewFD->setInvalidDecl(); 10829 return true; 10830 } 10831 10832 if (!OldFD->isMultiVersion()) { 10833 switch (MVType) { 10834 case MultiVersionKind::Target: 10835 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10836 Redeclaration, OldDecl, 10837 MergeTypeWithPrevious, Previous); 10838 case MultiVersionKind::TargetClones: 10839 if (OldFD->isUsed(false)) { 10840 NewFD->setInvalidDecl(); 10841 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10842 } 10843 OldFD->setIsMultiVersion(); 10844 break; 10845 case MultiVersionKind::CPUDispatch: 10846 case MultiVersionKind::CPUSpecific: 10847 case MultiVersionKind::None: 10848 break; 10849 } 10850 } 10851 // Handle the target potentially causes multiversioning case. 10852 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10853 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10854 Redeclaration, OldDecl, 10855 MergeTypeWithPrevious, Previous); 10856 10857 // At this point, we have a multiversion function decl (in OldFD) AND an 10858 // appropriate attribute in the current function decl. Resolve that these are 10859 // still compatible with previous declarations. 10860 return CheckMultiVersionAdditionalDecl( 10861 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, NewClones, 10862 Redeclaration, OldDecl, MergeTypeWithPrevious, Previous); 10863 } 10864 10865 /// Perform semantic checking of a new function declaration. 10866 /// 10867 /// Performs semantic analysis of the new function declaration 10868 /// NewFD. This routine performs all semantic checking that does not 10869 /// require the actual declarator involved in the declaration, and is 10870 /// used both for the declaration of functions as they are parsed 10871 /// (called via ActOnDeclarator) and for the declaration of functions 10872 /// that have been instantiated via C++ template instantiation (called 10873 /// via InstantiateDecl). 10874 /// 10875 /// \param IsMemberSpecialization whether this new function declaration is 10876 /// a member specialization (that replaces any definition provided by the 10877 /// previous declaration). 10878 /// 10879 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10880 /// 10881 /// \returns true if the function declaration is a redeclaration. 10882 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10883 LookupResult &Previous, 10884 bool IsMemberSpecialization) { 10885 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10886 "Variably modified return types are not handled here"); 10887 10888 // Determine whether the type of this function should be merged with 10889 // a previous visible declaration. This never happens for functions in C++, 10890 // and always happens in C if the previous declaration was visible. 10891 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10892 !Previous.isShadowed(); 10893 10894 bool Redeclaration = false; 10895 NamedDecl *OldDecl = nullptr; 10896 bool MayNeedOverloadableChecks = false; 10897 10898 // Merge or overload the declaration with an existing declaration of 10899 // the same name, if appropriate. 10900 if (!Previous.empty()) { 10901 // Determine whether NewFD is an overload of PrevDecl or 10902 // a declaration that requires merging. If it's an overload, 10903 // there's no more work to do here; we'll just add the new 10904 // function to the scope. 10905 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10906 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10907 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10908 Redeclaration = true; 10909 OldDecl = Candidate; 10910 } 10911 } else { 10912 MayNeedOverloadableChecks = true; 10913 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10914 /*NewIsUsingDecl*/ false)) { 10915 case Ovl_Match: 10916 Redeclaration = true; 10917 break; 10918 10919 case Ovl_NonFunction: 10920 Redeclaration = true; 10921 break; 10922 10923 case Ovl_Overload: 10924 Redeclaration = false; 10925 break; 10926 } 10927 } 10928 } 10929 10930 // Check for a previous extern "C" declaration with this name. 10931 if (!Redeclaration && 10932 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10933 if (!Previous.empty()) { 10934 // This is an extern "C" declaration with the same name as a previous 10935 // declaration, and thus redeclares that entity... 10936 Redeclaration = true; 10937 OldDecl = Previous.getFoundDecl(); 10938 MergeTypeWithPrevious = false; 10939 10940 // ... except in the presence of __attribute__((overloadable)). 10941 if (OldDecl->hasAttr<OverloadableAttr>() || 10942 NewFD->hasAttr<OverloadableAttr>()) { 10943 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10944 MayNeedOverloadableChecks = true; 10945 Redeclaration = false; 10946 OldDecl = nullptr; 10947 } 10948 } 10949 } 10950 } 10951 10952 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10953 MergeTypeWithPrevious, Previous)) 10954 return Redeclaration; 10955 10956 // PPC MMA non-pointer types are not allowed as function return types. 10957 if (Context.getTargetInfo().getTriple().isPPC64() && 10958 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10959 NewFD->setInvalidDecl(); 10960 } 10961 10962 // C++11 [dcl.constexpr]p8: 10963 // A constexpr specifier for a non-static member function that is not 10964 // a constructor declares that member function to be const. 10965 // 10966 // This needs to be delayed until we know whether this is an out-of-line 10967 // definition of a static member function. 10968 // 10969 // This rule is not present in C++1y, so we produce a backwards 10970 // compatibility warning whenever it happens in C++11. 10971 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10972 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10973 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10974 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10975 CXXMethodDecl *OldMD = nullptr; 10976 if (OldDecl) 10977 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10978 if (!OldMD || !OldMD->isStatic()) { 10979 const FunctionProtoType *FPT = 10980 MD->getType()->castAs<FunctionProtoType>(); 10981 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10982 EPI.TypeQuals.addConst(); 10983 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10984 FPT->getParamTypes(), EPI)); 10985 10986 // Warn that we did this, if we're not performing template instantiation. 10987 // In that case, we'll have warned already when the template was defined. 10988 if (!inTemplateInstantiation()) { 10989 SourceLocation AddConstLoc; 10990 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10991 .IgnoreParens().getAs<FunctionTypeLoc>()) 10992 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10993 10994 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10995 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10996 } 10997 } 10998 } 10999 11000 if (Redeclaration) { 11001 // NewFD and OldDecl represent declarations that need to be 11002 // merged. 11003 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 11004 NewFD->setInvalidDecl(); 11005 return Redeclaration; 11006 } 11007 11008 Previous.clear(); 11009 Previous.addDecl(OldDecl); 11010 11011 if (FunctionTemplateDecl *OldTemplateDecl = 11012 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11013 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11014 FunctionTemplateDecl *NewTemplateDecl 11015 = NewFD->getDescribedFunctionTemplate(); 11016 assert(NewTemplateDecl && "Template/non-template mismatch"); 11017 11018 // The call to MergeFunctionDecl above may have created some state in 11019 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11020 // can add it as a redeclaration. 11021 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11022 11023 NewFD->setPreviousDeclaration(OldFD); 11024 if (NewFD->isCXXClassMember()) { 11025 NewFD->setAccess(OldTemplateDecl->getAccess()); 11026 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11027 } 11028 11029 // If this is an explicit specialization of a member that is a function 11030 // template, mark it as a member specialization. 11031 if (IsMemberSpecialization && 11032 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11033 NewTemplateDecl->setMemberSpecialization(); 11034 assert(OldTemplateDecl->isMemberSpecialization()); 11035 // Explicit specializations of a member template do not inherit deleted 11036 // status from the parent member template that they are specializing. 11037 if (OldFD->isDeleted()) { 11038 // FIXME: This assert will not hold in the presence of modules. 11039 assert(OldFD->getCanonicalDecl() == OldFD); 11040 // FIXME: We need an update record for this AST mutation. 11041 OldFD->setDeletedAsWritten(false); 11042 } 11043 } 11044 11045 } else { 11046 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11047 auto *OldFD = cast<FunctionDecl>(OldDecl); 11048 // This needs to happen first so that 'inline' propagates. 11049 NewFD->setPreviousDeclaration(OldFD); 11050 if (NewFD->isCXXClassMember()) 11051 NewFD->setAccess(OldFD->getAccess()); 11052 } 11053 } 11054 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11055 !NewFD->getAttr<OverloadableAttr>()) { 11056 assert((Previous.empty() || 11057 llvm::any_of(Previous, 11058 [](const NamedDecl *ND) { 11059 return ND->hasAttr<OverloadableAttr>(); 11060 })) && 11061 "Non-redecls shouldn't happen without overloadable present"); 11062 11063 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11064 const auto *FD = dyn_cast<FunctionDecl>(ND); 11065 return FD && !FD->hasAttr<OverloadableAttr>(); 11066 }); 11067 11068 if (OtherUnmarkedIter != Previous.end()) { 11069 Diag(NewFD->getLocation(), 11070 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11071 Diag((*OtherUnmarkedIter)->getLocation(), 11072 diag::note_attribute_overloadable_prev_overload) 11073 << false; 11074 11075 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11076 } 11077 } 11078 11079 if (LangOpts.OpenMP) 11080 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11081 11082 // Semantic checking for this function declaration (in isolation). 11083 11084 if (getLangOpts().CPlusPlus) { 11085 // C++-specific checks. 11086 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11087 CheckConstructor(Constructor); 11088 } else if (CXXDestructorDecl *Destructor = 11089 dyn_cast<CXXDestructorDecl>(NewFD)) { 11090 CXXRecordDecl *Record = Destructor->getParent(); 11091 QualType ClassType = Context.getTypeDeclType(Record); 11092 11093 // FIXME: Shouldn't we be able to perform this check even when the class 11094 // type is dependent? Both gcc and edg can handle that. 11095 if (!ClassType->isDependentType()) { 11096 DeclarationName Name 11097 = Context.DeclarationNames.getCXXDestructorName( 11098 Context.getCanonicalType(ClassType)); 11099 if (NewFD->getDeclName() != Name) { 11100 Diag(NewFD->getLocation(), diag::err_destructor_name); 11101 NewFD->setInvalidDecl(); 11102 return Redeclaration; 11103 } 11104 } 11105 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11106 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11107 CheckDeductionGuideTemplate(TD); 11108 11109 // A deduction guide is not on the list of entities that can be 11110 // explicitly specialized. 11111 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11112 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11113 << /*explicit specialization*/ 1; 11114 } 11115 11116 // Find any virtual functions that this function overrides. 11117 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11118 if (!Method->isFunctionTemplateSpecialization() && 11119 !Method->getDescribedFunctionTemplate() && 11120 Method->isCanonicalDecl()) { 11121 AddOverriddenMethods(Method->getParent(), Method); 11122 } 11123 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11124 // C++2a [class.virtual]p6 11125 // A virtual method shall not have a requires-clause. 11126 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11127 diag::err_constrained_virtual_method); 11128 11129 if (Method->isStatic()) 11130 checkThisInStaticMemberFunctionType(Method); 11131 } 11132 11133 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11134 ActOnConversionDeclarator(Conversion); 11135 11136 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11137 if (NewFD->isOverloadedOperator() && 11138 CheckOverloadedOperatorDeclaration(NewFD)) { 11139 NewFD->setInvalidDecl(); 11140 return Redeclaration; 11141 } 11142 11143 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11144 if (NewFD->getLiteralIdentifier() && 11145 CheckLiteralOperatorDeclaration(NewFD)) { 11146 NewFD->setInvalidDecl(); 11147 return Redeclaration; 11148 } 11149 11150 // In C++, check default arguments now that we have merged decls. Unless 11151 // the lexical context is the class, because in this case this is done 11152 // during delayed parsing anyway. 11153 if (!CurContext->isRecord()) 11154 CheckCXXDefaultArguments(NewFD); 11155 11156 // If this function is declared as being extern "C", then check to see if 11157 // the function returns a UDT (class, struct, or union type) that is not C 11158 // compatible, and if it does, warn the user. 11159 // But, issue any diagnostic on the first declaration only. 11160 if (Previous.empty() && NewFD->isExternC()) { 11161 QualType R = NewFD->getReturnType(); 11162 if (R->isIncompleteType() && !R->isVoidType()) 11163 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11164 << NewFD << R; 11165 else if (!R.isPODType(Context) && !R->isVoidType() && 11166 !R->isObjCObjectPointerType()) 11167 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11168 } 11169 11170 // C++1z [dcl.fct]p6: 11171 // [...] whether the function has a non-throwing exception-specification 11172 // [is] part of the function type 11173 // 11174 // This results in an ABI break between C++14 and C++17 for functions whose 11175 // declared type includes an exception-specification in a parameter or 11176 // return type. (Exception specifications on the function itself are OK in 11177 // most cases, and exception specifications are not permitted in most other 11178 // contexts where they could make it into a mangling.) 11179 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11180 auto HasNoexcept = [&](QualType T) -> bool { 11181 // Strip off declarator chunks that could be between us and a function 11182 // type. We don't need to look far, exception specifications are very 11183 // restricted prior to C++17. 11184 if (auto *RT = T->getAs<ReferenceType>()) 11185 T = RT->getPointeeType(); 11186 else if (T->isAnyPointerType()) 11187 T = T->getPointeeType(); 11188 else if (auto *MPT = T->getAs<MemberPointerType>()) 11189 T = MPT->getPointeeType(); 11190 if (auto *FPT = T->getAs<FunctionProtoType>()) 11191 if (FPT->isNothrow()) 11192 return true; 11193 return false; 11194 }; 11195 11196 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11197 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11198 for (QualType T : FPT->param_types()) 11199 AnyNoexcept |= HasNoexcept(T); 11200 if (AnyNoexcept) 11201 Diag(NewFD->getLocation(), 11202 diag::warn_cxx17_compat_exception_spec_in_signature) 11203 << NewFD; 11204 } 11205 11206 if (!Redeclaration && LangOpts.CUDA) 11207 checkCUDATargetOverload(NewFD, Previous); 11208 } 11209 return Redeclaration; 11210 } 11211 11212 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11213 // C++11 [basic.start.main]p3: 11214 // A program that [...] declares main to be inline, static or 11215 // constexpr is ill-formed. 11216 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11217 // appear in a declaration of main. 11218 // static main is not an error under C99, but we should warn about it. 11219 // We accept _Noreturn main as an extension. 11220 if (FD->getStorageClass() == SC_Static) 11221 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11222 ? diag::err_static_main : diag::warn_static_main) 11223 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11224 if (FD->isInlineSpecified()) 11225 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11226 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11227 if (DS.isNoreturnSpecified()) { 11228 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11229 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11230 Diag(NoreturnLoc, diag::ext_noreturn_main); 11231 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11232 << FixItHint::CreateRemoval(NoreturnRange); 11233 } 11234 if (FD->isConstexpr()) { 11235 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11236 << FD->isConsteval() 11237 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11238 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11239 } 11240 11241 if (getLangOpts().OpenCL) { 11242 Diag(FD->getLocation(), diag::err_opencl_no_main) 11243 << FD->hasAttr<OpenCLKernelAttr>(); 11244 FD->setInvalidDecl(); 11245 return; 11246 } 11247 11248 QualType T = FD->getType(); 11249 assert(T->isFunctionType() && "function decl is not of function type"); 11250 const FunctionType* FT = T->castAs<FunctionType>(); 11251 11252 // Set default calling convention for main() 11253 if (FT->getCallConv() != CC_C) { 11254 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11255 FD->setType(QualType(FT, 0)); 11256 T = Context.getCanonicalType(FD->getType()); 11257 } 11258 11259 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11260 // In C with GNU extensions we allow main() to have non-integer return 11261 // type, but we should warn about the extension, and we disable the 11262 // implicit-return-zero rule. 11263 11264 // GCC in C mode accepts qualified 'int'. 11265 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11266 FD->setHasImplicitReturnZero(true); 11267 else { 11268 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11269 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11270 if (RTRange.isValid()) 11271 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11272 << FixItHint::CreateReplacement(RTRange, "int"); 11273 } 11274 } else { 11275 // In C and C++, main magically returns 0 if you fall off the end; 11276 // set the flag which tells us that. 11277 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11278 11279 // All the standards say that main() should return 'int'. 11280 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11281 FD->setHasImplicitReturnZero(true); 11282 else { 11283 // Otherwise, this is just a flat-out error. 11284 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11285 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11286 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11287 : FixItHint()); 11288 FD->setInvalidDecl(true); 11289 } 11290 } 11291 11292 // Treat protoless main() as nullary. 11293 if (isa<FunctionNoProtoType>(FT)) return; 11294 11295 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11296 unsigned nparams = FTP->getNumParams(); 11297 assert(FD->getNumParams() == nparams); 11298 11299 bool HasExtraParameters = (nparams > 3); 11300 11301 if (FTP->isVariadic()) { 11302 Diag(FD->getLocation(), diag::ext_variadic_main); 11303 // FIXME: if we had information about the location of the ellipsis, we 11304 // could add a FixIt hint to remove it as a parameter. 11305 } 11306 11307 // Darwin passes an undocumented fourth argument of type char**. If 11308 // other platforms start sprouting these, the logic below will start 11309 // getting shifty. 11310 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11311 HasExtraParameters = false; 11312 11313 if (HasExtraParameters) { 11314 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11315 FD->setInvalidDecl(true); 11316 nparams = 3; 11317 } 11318 11319 // FIXME: a lot of the following diagnostics would be improved 11320 // if we had some location information about types. 11321 11322 QualType CharPP = 11323 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11324 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11325 11326 for (unsigned i = 0; i < nparams; ++i) { 11327 QualType AT = FTP->getParamType(i); 11328 11329 bool mismatch = true; 11330 11331 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11332 mismatch = false; 11333 else if (Expected[i] == CharPP) { 11334 // As an extension, the following forms are okay: 11335 // char const ** 11336 // char const * const * 11337 // char * const * 11338 11339 QualifierCollector qs; 11340 const PointerType* PT; 11341 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11342 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11343 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11344 Context.CharTy)) { 11345 qs.removeConst(); 11346 mismatch = !qs.empty(); 11347 } 11348 } 11349 11350 if (mismatch) { 11351 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11352 // TODO: suggest replacing given type with expected type 11353 FD->setInvalidDecl(true); 11354 } 11355 } 11356 11357 if (nparams == 1 && !FD->isInvalidDecl()) { 11358 Diag(FD->getLocation(), diag::warn_main_one_arg); 11359 } 11360 11361 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11362 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11363 FD->setInvalidDecl(); 11364 } 11365 } 11366 11367 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11368 11369 // Default calling convention for main and wmain is __cdecl 11370 if (FD->getName() == "main" || FD->getName() == "wmain") 11371 return false; 11372 11373 // Default calling convention for MinGW is __cdecl 11374 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11375 if (T.isWindowsGNUEnvironment()) 11376 return false; 11377 11378 // Default calling convention for WinMain, wWinMain and DllMain 11379 // is __stdcall on 32 bit Windows 11380 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11381 return true; 11382 11383 return false; 11384 } 11385 11386 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11387 QualType T = FD->getType(); 11388 assert(T->isFunctionType() && "function decl is not of function type"); 11389 const FunctionType *FT = T->castAs<FunctionType>(); 11390 11391 // Set an implicit return of 'zero' if the function can return some integral, 11392 // enumeration, pointer or nullptr type. 11393 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11394 FT->getReturnType()->isAnyPointerType() || 11395 FT->getReturnType()->isNullPtrType()) 11396 // DllMain is exempt because a return value of zero means it failed. 11397 if (FD->getName() != "DllMain") 11398 FD->setHasImplicitReturnZero(true); 11399 11400 // Explicity specified calling conventions are applied to MSVC entry points 11401 if (!hasExplicitCallingConv(T)) { 11402 if (isDefaultStdCall(FD, *this)) { 11403 if (FT->getCallConv() != CC_X86StdCall) { 11404 FT = Context.adjustFunctionType( 11405 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11406 FD->setType(QualType(FT, 0)); 11407 } 11408 } else if (FT->getCallConv() != CC_C) { 11409 FT = Context.adjustFunctionType(FT, 11410 FT->getExtInfo().withCallingConv(CC_C)); 11411 FD->setType(QualType(FT, 0)); 11412 } 11413 } 11414 11415 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11416 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11417 FD->setInvalidDecl(); 11418 } 11419 } 11420 11421 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11422 // FIXME: Need strict checking. In C89, we need to check for 11423 // any assignment, increment, decrement, function-calls, or 11424 // commas outside of a sizeof. In C99, it's the same list, 11425 // except that the aforementioned are allowed in unevaluated 11426 // expressions. Everything else falls under the 11427 // "may accept other forms of constant expressions" exception. 11428 // 11429 // Regular C++ code will not end up here (exceptions: language extensions, 11430 // OpenCL C++ etc), so the constant expression rules there don't matter. 11431 if (Init->isValueDependent()) { 11432 assert(Init->containsErrors() && 11433 "Dependent code should only occur in error-recovery path."); 11434 return true; 11435 } 11436 const Expr *Culprit; 11437 if (Init->isConstantInitializer(Context, false, &Culprit)) 11438 return false; 11439 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11440 << Culprit->getSourceRange(); 11441 return true; 11442 } 11443 11444 namespace { 11445 // Visits an initialization expression to see if OrigDecl is evaluated in 11446 // its own initialization and throws a warning if it does. 11447 class SelfReferenceChecker 11448 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11449 Sema &S; 11450 Decl *OrigDecl; 11451 bool isRecordType; 11452 bool isPODType; 11453 bool isReferenceType; 11454 11455 bool isInitList; 11456 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11457 11458 public: 11459 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11460 11461 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11462 S(S), OrigDecl(OrigDecl) { 11463 isPODType = false; 11464 isRecordType = false; 11465 isReferenceType = false; 11466 isInitList = false; 11467 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11468 isPODType = VD->getType().isPODType(S.Context); 11469 isRecordType = VD->getType()->isRecordType(); 11470 isReferenceType = VD->getType()->isReferenceType(); 11471 } 11472 } 11473 11474 // For most expressions, just call the visitor. For initializer lists, 11475 // track the index of the field being initialized since fields are 11476 // initialized in order allowing use of previously initialized fields. 11477 void CheckExpr(Expr *E) { 11478 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11479 if (!InitList) { 11480 Visit(E); 11481 return; 11482 } 11483 11484 // Track and increment the index here. 11485 isInitList = true; 11486 InitFieldIndex.push_back(0); 11487 for (auto Child : InitList->children()) { 11488 CheckExpr(cast<Expr>(Child)); 11489 ++InitFieldIndex.back(); 11490 } 11491 InitFieldIndex.pop_back(); 11492 } 11493 11494 // Returns true if MemberExpr is checked and no further checking is needed. 11495 // Returns false if additional checking is required. 11496 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11497 llvm::SmallVector<FieldDecl*, 4> Fields; 11498 Expr *Base = E; 11499 bool ReferenceField = false; 11500 11501 // Get the field members used. 11502 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11503 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11504 if (!FD) 11505 return false; 11506 Fields.push_back(FD); 11507 if (FD->getType()->isReferenceType()) 11508 ReferenceField = true; 11509 Base = ME->getBase()->IgnoreParenImpCasts(); 11510 } 11511 11512 // Keep checking only if the base Decl is the same. 11513 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11514 if (!DRE || DRE->getDecl() != OrigDecl) 11515 return false; 11516 11517 // A reference field can be bound to an unininitialized field. 11518 if (CheckReference && !ReferenceField) 11519 return true; 11520 11521 // Convert FieldDecls to their index number. 11522 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11523 for (const FieldDecl *I : llvm::reverse(Fields)) 11524 UsedFieldIndex.push_back(I->getFieldIndex()); 11525 11526 // See if a warning is needed by checking the first difference in index 11527 // numbers. If field being used has index less than the field being 11528 // initialized, then the use is safe. 11529 for (auto UsedIter = UsedFieldIndex.begin(), 11530 UsedEnd = UsedFieldIndex.end(), 11531 OrigIter = InitFieldIndex.begin(), 11532 OrigEnd = InitFieldIndex.end(); 11533 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11534 if (*UsedIter < *OrigIter) 11535 return true; 11536 if (*UsedIter > *OrigIter) 11537 break; 11538 } 11539 11540 // TODO: Add a different warning which will print the field names. 11541 HandleDeclRefExpr(DRE); 11542 return true; 11543 } 11544 11545 // For most expressions, the cast is directly above the DeclRefExpr. 11546 // For conditional operators, the cast can be outside the conditional 11547 // operator if both expressions are DeclRefExpr's. 11548 void HandleValue(Expr *E) { 11549 E = E->IgnoreParens(); 11550 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11551 HandleDeclRefExpr(DRE); 11552 return; 11553 } 11554 11555 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11556 Visit(CO->getCond()); 11557 HandleValue(CO->getTrueExpr()); 11558 HandleValue(CO->getFalseExpr()); 11559 return; 11560 } 11561 11562 if (BinaryConditionalOperator *BCO = 11563 dyn_cast<BinaryConditionalOperator>(E)) { 11564 Visit(BCO->getCond()); 11565 HandleValue(BCO->getFalseExpr()); 11566 return; 11567 } 11568 11569 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11570 HandleValue(OVE->getSourceExpr()); 11571 return; 11572 } 11573 11574 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11575 if (BO->getOpcode() == BO_Comma) { 11576 Visit(BO->getLHS()); 11577 HandleValue(BO->getRHS()); 11578 return; 11579 } 11580 } 11581 11582 if (isa<MemberExpr>(E)) { 11583 if (isInitList) { 11584 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11585 false /*CheckReference*/)) 11586 return; 11587 } 11588 11589 Expr *Base = E->IgnoreParenImpCasts(); 11590 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11591 // Check for static member variables and don't warn on them. 11592 if (!isa<FieldDecl>(ME->getMemberDecl())) 11593 return; 11594 Base = ME->getBase()->IgnoreParenImpCasts(); 11595 } 11596 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11597 HandleDeclRefExpr(DRE); 11598 return; 11599 } 11600 11601 Visit(E); 11602 } 11603 11604 // Reference types not handled in HandleValue are handled here since all 11605 // uses of references are bad, not just r-value uses. 11606 void VisitDeclRefExpr(DeclRefExpr *E) { 11607 if (isReferenceType) 11608 HandleDeclRefExpr(E); 11609 } 11610 11611 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11612 if (E->getCastKind() == CK_LValueToRValue) { 11613 HandleValue(E->getSubExpr()); 11614 return; 11615 } 11616 11617 Inherited::VisitImplicitCastExpr(E); 11618 } 11619 11620 void VisitMemberExpr(MemberExpr *E) { 11621 if (isInitList) { 11622 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11623 return; 11624 } 11625 11626 // Don't warn on arrays since they can be treated as pointers. 11627 if (E->getType()->canDecayToPointerType()) return; 11628 11629 // Warn when a non-static method call is followed by non-static member 11630 // field accesses, which is followed by a DeclRefExpr. 11631 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11632 bool Warn = (MD && !MD->isStatic()); 11633 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11634 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11635 if (!isa<FieldDecl>(ME->getMemberDecl())) 11636 Warn = false; 11637 Base = ME->getBase()->IgnoreParenImpCasts(); 11638 } 11639 11640 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11641 if (Warn) 11642 HandleDeclRefExpr(DRE); 11643 return; 11644 } 11645 11646 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11647 // Visit that expression. 11648 Visit(Base); 11649 } 11650 11651 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11652 Expr *Callee = E->getCallee(); 11653 11654 if (isa<UnresolvedLookupExpr>(Callee)) 11655 return Inherited::VisitCXXOperatorCallExpr(E); 11656 11657 Visit(Callee); 11658 for (auto Arg: E->arguments()) 11659 HandleValue(Arg->IgnoreParenImpCasts()); 11660 } 11661 11662 void VisitUnaryOperator(UnaryOperator *E) { 11663 // For POD record types, addresses of its own members are well-defined. 11664 if (E->getOpcode() == UO_AddrOf && isRecordType && 11665 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11666 if (!isPODType) 11667 HandleValue(E->getSubExpr()); 11668 return; 11669 } 11670 11671 if (E->isIncrementDecrementOp()) { 11672 HandleValue(E->getSubExpr()); 11673 return; 11674 } 11675 11676 Inherited::VisitUnaryOperator(E); 11677 } 11678 11679 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11680 11681 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11682 if (E->getConstructor()->isCopyConstructor()) { 11683 Expr *ArgExpr = E->getArg(0); 11684 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11685 if (ILE->getNumInits() == 1) 11686 ArgExpr = ILE->getInit(0); 11687 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11688 if (ICE->getCastKind() == CK_NoOp) 11689 ArgExpr = ICE->getSubExpr(); 11690 HandleValue(ArgExpr); 11691 return; 11692 } 11693 Inherited::VisitCXXConstructExpr(E); 11694 } 11695 11696 void VisitCallExpr(CallExpr *E) { 11697 // Treat std::move as a use. 11698 if (E->isCallToStdMove()) { 11699 HandleValue(E->getArg(0)); 11700 return; 11701 } 11702 11703 Inherited::VisitCallExpr(E); 11704 } 11705 11706 void VisitBinaryOperator(BinaryOperator *E) { 11707 if (E->isCompoundAssignmentOp()) { 11708 HandleValue(E->getLHS()); 11709 Visit(E->getRHS()); 11710 return; 11711 } 11712 11713 Inherited::VisitBinaryOperator(E); 11714 } 11715 11716 // A custom visitor for BinaryConditionalOperator is needed because the 11717 // regular visitor would check the condition and true expression separately 11718 // but both point to the same place giving duplicate diagnostics. 11719 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11720 Visit(E->getCond()); 11721 Visit(E->getFalseExpr()); 11722 } 11723 11724 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11725 Decl* ReferenceDecl = DRE->getDecl(); 11726 if (OrigDecl != ReferenceDecl) return; 11727 unsigned diag; 11728 if (isReferenceType) { 11729 diag = diag::warn_uninit_self_reference_in_reference_init; 11730 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11731 diag = diag::warn_static_self_reference_in_init; 11732 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11733 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11734 DRE->getDecl()->getType()->isRecordType()) { 11735 diag = diag::warn_uninit_self_reference_in_init; 11736 } else { 11737 // Local variables will be handled by the CFG analysis. 11738 return; 11739 } 11740 11741 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11742 S.PDiag(diag) 11743 << DRE->getDecl() << OrigDecl->getLocation() 11744 << DRE->getSourceRange()); 11745 } 11746 }; 11747 11748 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11749 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11750 bool DirectInit) { 11751 // Parameters arguments are occassionially constructed with itself, 11752 // for instance, in recursive functions. Skip them. 11753 if (isa<ParmVarDecl>(OrigDecl)) 11754 return; 11755 11756 E = E->IgnoreParens(); 11757 11758 // Skip checking T a = a where T is not a record or reference type. 11759 // Doing so is a way to silence uninitialized warnings. 11760 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11761 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11762 if (ICE->getCastKind() == CK_LValueToRValue) 11763 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11764 if (DRE->getDecl() == OrigDecl) 11765 return; 11766 11767 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11768 } 11769 } // end anonymous namespace 11770 11771 namespace { 11772 // Simple wrapper to add the name of a variable or (if no variable is 11773 // available) a DeclarationName into a diagnostic. 11774 struct VarDeclOrName { 11775 VarDecl *VDecl; 11776 DeclarationName Name; 11777 11778 friend const Sema::SemaDiagnosticBuilder & 11779 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11780 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11781 } 11782 }; 11783 } // end anonymous namespace 11784 11785 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11786 DeclarationName Name, QualType Type, 11787 TypeSourceInfo *TSI, 11788 SourceRange Range, bool DirectInit, 11789 Expr *Init) { 11790 bool IsInitCapture = !VDecl; 11791 assert((!VDecl || !VDecl->isInitCapture()) && 11792 "init captures are expected to be deduced prior to initialization"); 11793 11794 VarDeclOrName VN{VDecl, Name}; 11795 11796 DeducedType *Deduced = Type->getContainedDeducedType(); 11797 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11798 11799 // C++11 [dcl.spec.auto]p3 11800 if (!Init) { 11801 assert(VDecl && "no init for init capture deduction?"); 11802 11803 // Except for class argument deduction, and then for an initializing 11804 // declaration only, i.e. no static at class scope or extern. 11805 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11806 VDecl->hasExternalStorage() || 11807 VDecl->isStaticDataMember()) { 11808 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11809 << VDecl->getDeclName() << Type; 11810 return QualType(); 11811 } 11812 } 11813 11814 ArrayRef<Expr*> DeduceInits; 11815 if (Init) 11816 DeduceInits = Init; 11817 11818 if (DirectInit) { 11819 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11820 DeduceInits = PL->exprs(); 11821 } 11822 11823 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11824 assert(VDecl && "non-auto type for init capture deduction?"); 11825 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11826 InitializationKind Kind = InitializationKind::CreateForInit( 11827 VDecl->getLocation(), DirectInit, Init); 11828 // FIXME: Initialization should not be taking a mutable list of inits. 11829 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11830 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11831 InitsCopy); 11832 } 11833 11834 if (DirectInit) { 11835 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11836 DeduceInits = IL->inits(); 11837 } 11838 11839 // Deduction only works if we have exactly one source expression. 11840 if (DeduceInits.empty()) { 11841 // It isn't possible to write this directly, but it is possible to 11842 // end up in this situation with "auto x(some_pack...);" 11843 Diag(Init->getBeginLoc(), IsInitCapture 11844 ? diag::err_init_capture_no_expression 11845 : diag::err_auto_var_init_no_expression) 11846 << VN << Type << Range; 11847 return QualType(); 11848 } 11849 11850 if (DeduceInits.size() > 1) { 11851 Diag(DeduceInits[1]->getBeginLoc(), 11852 IsInitCapture ? diag::err_init_capture_multiple_expressions 11853 : diag::err_auto_var_init_multiple_expressions) 11854 << VN << Type << Range; 11855 return QualType(); 11856 } 11857 11858 Expr *DeduceInit = DeduceInits[0]; 11859 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11860 Diag(Init->getBeginLoc(), IsInitCapture 11861 ? diag::err_init_capture_paren_braces 11862 : diag::err_auto_var_init_paren_braces) 11863 << isa<InitListExpr>(Init) << VN << Type << Range; 11864 return QualType(); 11865 } 11866 11867 // Expressions default to 'id' when we're in a debugger. 11868 bool DefaultedAnyToId = false; 11869 if (getLangOpts().DebuggerCastResultToId && 11870 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11871 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11872 if (Result.isInvalid()) { 11873 return QualType(); 11874 } 11875 Init = Result.get(); 11876 DefaultedAnyToId = true; 11877 } 11878 11879 // C++ [dcl.decomp]p1: 11880 // If the assignment-expression [...] has array type A and no ref-qualifier 11881 // is present, e has type cv A 11882 if (VDecl && isa<DecompositionDecl>(VDecl) && 11883 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11884 DeduceInit->getType()->isConstantArrayType()) 11885 return Context.getQualifiedType(DeduceInit->getType(), 11886 Type.getQualifiers()); 11887 11888 QualType DeducedType; 11889 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11890 if (!IsInitCapture) 11891 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11892 else if (isa<InitListExpr>(Init)) 11893 Diag(Range.getBegin(), 11894 diag::err_init_capture_deduction_failure_from_init_list) 11895 << VN 11896 << (DeduceInit->getType().isNull() ? TSI->getType() 11897 : DeduceInit->getType()) 11898 << DeduceInit->getSourceRange(); 11899 else 11900 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11901 << VN << TSI->getType() 11902 << (DeduceInit->getType().isNull() ? TSI->getType() 11903 : DeduceInit->getType()) 11904 << DeduceInit->getSourceRange(); 11905 } 11906 11907 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11908 // 'id' instead of a specific object type prevents most of our usual 11909 // checks. 11910 // We only want to warn outside of template instantiations, though: 11911 // inside a template, the 'id' could have come from a parameter. 11912 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11913 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11914 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11915 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11916 } 11917 11918 return DeducedType; 11919 } 11920 11921 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11922 Expr *Init) { 11923 assert(!Init || !Init->containsErrors()); 11924 QualType DeducedType = deduceVarTypeFromInitializer( 11925 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11926 VDecl->getSourceRange(), DirectInit, Init); 11927 if (DeducedType.isNull()) { 11928 VDecl->setInvalidDecl(); 11929 return true; 11930 } 11931 11932 VDecl->setType(DeducedType); 11933 assert(VDecl->isLinkageValid()); 11934 11935 // In ARC, infer lifetime. 11936 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11937 VDecl->setInvalidDecl(); 11938 11939 if (getLangOpts().OpenCL) 11940 deduceOpenCLAddressSpace(VDecl); 11941 11942 // If this is a redeclaration, check that the type we just deduced matches 11943 // the previously declared type. 11944 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11945 // We never need to merge the type, because we cannot form an incomplete 11946 // array of auto, nor deduce such a type. 11947 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11948 } 11949 11950 // Check the deduced type is valid for a variable declaration. 11951 CheckVariableDeclarationType(VDecl); 11952 return VDecl->isInvalidDecl(); 11953 } 11954 11955 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11956 SourceLocation Loc) { 11957 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11958 Init = EWC->getSubExpr(); 11959 11960 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11961 Init = CE->getSubExpr(); 11962 11963 QualType InitType = Init->getType(); 11964 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11965 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11966 "shouldn't be called if type doesn't have a non-trivial C struct"); 11967 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11968 for (auto I : ILE->inits()) { 11969 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11970 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11971 continue; 11972 SourceLocation SL = I->getExprLoc(); 11973 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11974 } 11975 return; 11976 } 11977 11978 if (isa<ImplicitValueInitExpr>(Init)) { 11979 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11980 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11981 NTCUK_Init); 11982 } else { 11983 // Assume all other explicit initializers involving copying some existing 11984 // object. 11985 // TODO: ignore any explicit initializers where we can guarantee 11986 // copy-elision. 11987 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11988 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11989 } 11990 } 11991 11992 namespace { 11993 11994 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11995 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11996 // in the source code or implicitly by the compiler if it is in a union 11997 // defined in a system header and has non-trivial ObjC ownership 11998 // qualifications. We don't want those fields to participate in determining 11999 // whether the containing union is non-trivial. 12000 return FD->hasAttr<UnavailableAttr>(); 12001 } 12002 12003 struct DiagNonTrivalCUnionDefaultInitializeVisitor 12004 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12005 void> { 12006 using Super = 12007 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12008 void>; 12009 12010 DiagNonTrivalCUnionDefaultInitializeVisitor( 12011 QualType OrigTy, SourceLocation OrigLoc, 12012 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12013 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12014 12015 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 12016 const FieldDecl *FD, bool InNonTrivialUnion) { 12017 if (const auto *AT = S.Context.getAsArrayType(QT)) 12018 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12019 InNonTrivialUnion); 12020 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 12021 } 12022 12023 void visitARCStrong(QualType QT, const FieldDecl *FD, 12024 bool InNonTrivialUnion) { 12025 if (InNonTrivialUnion) 12026 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12027 << 1 << 0 << QT << FD->getName(); 12028 } 12029 12030 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12031 if (InNonTrivialUnion) 12032 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12033 << 1 << 0 << QT << FD->getName(); 12034 } 12035 12036 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12037 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12038 if (RD->isUnion()) { 12039 if (OrigLoc.isValid()) { 12040 bool IsUnion = false; 12041 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12042 IsUnion = OrigRD->isUnion(); 12043 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12044 << 0 << OrigTy << IsUnion << UseContext; 12045 // Reset OrigLoc so that this diagnostic is emitted only once. 12046 OrigLoc = SourceLocation(); 12047 } 12048 InNonTrivialUnion = true; 12049 } 12050 12051 if (InNonTrivialUnion) 12052 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12053 << 0 << 0 << QT.getUnqualifiedType() << ""; 12054 12055 for (const FieldDecl *FD : RD->fields()) 12056 if (!shouldIgnoreForRecordTriviality(FD)) 12057 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12058 } 12059 12060 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12061 12062 // The non-trivial C union type or the struct/union type that contains a 12063 // non-trivial C union. 12064 QualType OrigTy; 12065 SourceLocation OrigLoc; 12066 Sema::NonTrivialCUnionContext UseContext; 12067 Sema &S; 12068 }; 12069 12070 struct DiagNonTrivalCUnionDestructedTypeVisitor 12071 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12072 using Super = 12073 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12074 12075 DiagNonTrivalCUnionDestructedTypeVisitor( 12076 QualType OrigTy, SourceLocation OrigLoc, 12077 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12078 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12079 12080 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12081 const FieldDecl *FD, bool InNonTrivialUnion) { 12082 if (const auto *AT = S.Context.getAsArrayType(QT)) 12083 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12084 InNonTrivialUnion); 12085 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12086 } 12087 12088 void visitARCStrong(QualType QT, const FieldDecl *FD, 12089 bool InNonTrivialUnion) { 12090 if (InNonTrivialUnion) 12091 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12092 << 1 << 1 << QT << FD->getName(); 12093 } 12094 12095 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12096 if (InNonTrivialUnion) 12097 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12098 << 1 << 1 << QT << FD->getName(); 12099 } 12100 12101 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12102 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12103 if (RD->isUnion()) { 12104 if (OrigLoc.isValid()) { 12105 bool IsUnion = false; 12106 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12107 IsUnion = OrigRD->isUnion(); 12108 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12109 << 1 << OrigTy << IsUnion << UseContext; 12110 // Reset OrigLoc so that this diagnostic is emitted only once. 12111 OrigLoc = SourceLocation(); 12112 } 12113 InNonTrivialUnion = true; 12114 } 12115 12116 if (InNonTrivialUnion) 12117 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12118 << 0 << 1 << QT.getUnqualifiedType() << ""; 12119 12120 for (const FieldDecl *FD : RD->fields()) 12121 if (!shouldIgnoreForRecordTriviality(FD)) 12122 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12123 } 12124 12125 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12126 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12127 bool InNonTrivialUnion) {} 12128 12129 // The non-trivial C union type or the struct/union type that contains a 12130 // non-trivial C union. 12131 QualType OrigTy; 12132 SourceLocation OrigLoc; 12133 Sema::NonTrivialCUnionContext UseContext; 12134 Sema &S; 12135 }; 12136 12137 struct DiagNonTrivalCUnionCopyVisitor 12138 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12139 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12140 12141 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12142 Sema::NonTrivialCUnionContext UseContext, 12143 Sema &S) 12144 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12145 12146 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12147 const FieldDecl *FD, bool InNonTrivialUnion) { 12148 if (const auto *AT = S.Context.getAsArrayType(QT)) 12149 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12150 InNonTrivialUnion); 12151 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12152 } 12153 12154 void visitARCStrong(QualType QT, const FieldDecl *FD, 12155 bool InNonTrivialUnion) { 12156 if (InNonTrivialUnion) 12157 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12158 << 1 << 2 << QT << FD->getName(); 12159 } 12160 12161 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12162 if (InNonTrivialUnion) 12163 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12164 << 1 << 2 << QT << FD->getName(); 12165 } 12166 12167 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12168 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12169 if (RD->isUnion()) { 12170 if (OrigLoc.isValid()) { 12171 bool IsUnion = false; 12172 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12173 IsUnion = OrigRD->isUnion(); 12174 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12175 << 2 << OrigTy << IsUnion << UseContext; 12176 // Reset OrigLoc so that this diagnostic is emitted only once. 12177 OrigLoc = SourceLocation(); 12178 } 12179 InNonTrivialUnion = true; 12180 } 12181 12182 if (InNonTrivialUnion) 12183 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12184 << 0 << 2 << QT.getUnqualifiedType() << ""; 12185 12186 for (const FieldDecl *FD : RD->fields()) 12187 if (!shouldIgnoreForRecordTriviality(FD)) 12188 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12189 } 12190 12191 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12192 const FieldDecl *FD, bool InNonTrivialUnion) {} 12193 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12194 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12195 bool InNonTrivialUnion) {} 12196 12197 // The non-trivial C union type or the struct/union type that contains a 12198 // non-trivial C union. 12199 QualType OrigTy; 12200 SourceLocation OrigLoc; 12201 Sema::NonTrivialCUnionContext UseContext; 12202 Sema &S; 12203 }; 12204 12205 } // namespace 12206 12207 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12208 NonTrivialCUnionContext UseContext, 12209 unsigned NonTrivialKind) { 12210 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12211 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12212 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12213 "shouldn't be called if type doesn't have a non-trivial C union"); 12214 12215 if ((NonTrivialKind & NTCUK_Init) && 12216 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12217 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12218 .visit(QT, nullptr, false); 12219 if ((NonTrivialKind & NTCUK_Destruct) && 12220 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12221 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12222 .visit(QT, nullptr, false); 12223 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12224 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12225 .visit(QT, nullptr, false); 12226 } 12227 12228 /// AddInitializerToDecl - Adds the initializer Init to the 12229 /// declaration dcl. If DirectInit is true, this is C++ direct 12230 /// initialization rather than copy initialization. 12231 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12232 // If there is no declaration, there was an error parsing it. Just ignore 12233 // the initializer. 12234 if (!RealDecl || RealDecl->isInvalidDecl()) { 12235 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12236 return; 12237 } 12238 12239 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12240 // Pure-specifiers are handled in ActOnPureSpecifier. 12241 Diag(Method->getLocation(), diag::err_member_function_initialization) 12242 << Method->getDeclName() << Init->getSourceRange(); 12243 Method->setInvalidDecl(); 12244 return; 12245 } 12246 12247 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12248 if (!VDecl) { 12249 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12250 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12251 RealDecl->setInvalidDecl(); 12252 return; 12253 } 12254 12255 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12256 if (VDecl->getType()->isUndeducedType()) { 12257 // Attempt typo correction early so that the type of the init expression can 12258 // be deduced based on the chosen correction if the original init contains a 12259 // TypoExpr. 12260 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12261 if (!Res.isUsable()) { 12262 // There are unresolved typos in Init, just drop them. 12263 // FIXME: improve the recovery strategy to preserve the Init. 12264 RealDecl->setInvalidDecl(); 12265 return; 12266 } 12267 if (Res.get()->containsErrors()) { 12268 // Invalidate the decl as we don't know the type for recovery-expr yet. 12269 RealDecl->setInvalidDecl(); 12270 VDecl->setInit(Res.get()); 12271 return; 12272 } 12273 Init = Res.get(); 12274 12275 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12276 return; 12277 } 12278 12279 // dllimport cannot be used on variable definitions. 12280 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12281 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12282 VDecl->setInvalidDecl(); 12283 return; 12284 } 12285 12286 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12287 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12288 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12289 VDecl->setInvalidDecl(); 12290 return; 12291 } 12292 12293 if (!VDecl->getType()->isDependentType()) { 12294 // A definition must end up with a complete type, which means it must be 12295 // complete with the restriction that an array type might be completed by 12296 // the initializer; note that later code assumes this restriction. 12297 QualType BaseDeclType = VDecl->getType(); 12298 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12299 BaseDeclType = Array->getElementType(); 12300 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12301 diag::err_typecheck_decl_incomplete_type)) { 12302 RealDecl->setInvalidDecl(); 12303 return; 12304 } 12305 12306 // The variable can not have an abstract class type. 12307 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12308 diag::err_abstract_type_in_decl, 12309 AbstractVariableType)) 12310 VDecl->setInvalidDecl(); 12311 } 12312 12313 // If adding the initializer will turn this declaration into a definition, 12314 // and we already have a definition for this variable, diagnose or otherwise 12315 // handle the situation. 12316 if (VarDecl *Def = VDecl->getDefinition()) 12317 if (Def != VDecl && 12318 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12319 !VDecl->isThisDeclarationADemotedDefinition() && 12320 checkVarDeclRedefinition(Def, VDecl)) 12321 return; 12322 12323 if (getLangOpts().CPlusPlus) { 12324 // C++ [class.static.data]p4 12325 // If a static data member is of const integral or const 12326 // enumeration type, its declaration in the class definition can 12327 // specify a constant-initializer which shall be an integral 12328 // constant expression (5.19). In that case, the member can appear 12329 // in integral constant expressions. The member shall still be 12330 // defined in a namespace scope if it is used in the program and the 12331 // namespace scope definition shall not contain an initializer. 12332 // 12333 // We already performed a redefinition check above, but for static 12334 // data members we also need to check whether there was an in-class 12335 // declaration with an initializer. 12336 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12337 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12338 << VDecl->getDeclName(); 12339 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12340 diag::note_previous_initializer) 12341 << 0; 12342 return; 12343 } 12344 12345 if (VDecl->hasLocalStorage()) 12346 setFunctionHasBranchProtectedScope(); 12347 12348 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12349 VDecl->setInvalidDecl(); 12350 return; 12351 } 12352 } 12353 12354 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12355 // a kernel function cannot be initialized." 12356 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12357 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12358 VDecl->setInvalidDecl(); 12359 return; 12360 } 12361 12362 // The LoaderUninitialized attribute acts as a definition (of undef). 12363 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12364 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12365 VDecl->setInvalidDecl(); 12366 return; 12367 } 12368 12369 // Get the decls type and save a reference for later, since 12370 // CheckInitializerTypes may change it. 12371 QualType DclT = VDecl->getType(), SavT = DclT; 12372 12373 // Expressions default to 'id' when we're in a debugger 12374 // and we are assigning it to a variable of Objective-C pointer type. 12375 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12376 Init->getType() == Context.UnknownAnyTy) { 12377 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12378 if (Result.isInvalid()) { 12379 VDecl->setInvalidDecl(); 12380 return; 12381 } 12382 Init = Result.get(); 12383 } 12384 12385 // Perform the initialization. 12386 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12387 if (!VDecl->isInvalidDecl()) { 12388 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12389 InitializationKind Kind = InitializationKind::CreateForInit( 12390 VDecl->getLocation(), DirectInit, Init); 12391 12392 MultiExprArg Args = Init; 12393 if (CXXDirectInit) 12394 Args = MultiExprArg(CXXDirectInit->getExprs(), 12395 CXXDirectInit->getNumExprs()); 12396 12397 // Try to correct any TypoExprs in the initialization arguments. 12398 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12399 ExprResult Res = CorrectDelayedTyposInExpr( 12400 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12401 [this, Entity, Kind](Expr *E) { 12402 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12403 return Init.Failed() ? ExprError() : E; 12404 }); 12405 if (Res.isInvalid()) { 12406 VDecl->setInvalidDecl(); 12407 } else if (Res.get() != Args[Idx]) { 12408 Args[Idx] = Res.get(); 12409 } 12410 } 12411 if (VDecl->isInvalidDecl()) 12412 return; 12413 12414 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12415 /*TopLevelOfInitList=*/false, 12416 /*TreatUnavailableAsInvalid=*/false); 12417 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12418 if (Result.isInvalid()) { 12419 // If the provided initializer fails to initialize the var decl, 12420 // we attach a recovery expr for better recovery. 12421 auto RecoveryExpr = 12422 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12423 if (RecoveryExpr.get()) 12424 VDecl->setInit(RecoveryExpr.get()); 12425 return; 12426 } 12427 12428 Init = Result.getAs<Expr>(); 12429 } 12430 12431 // Check for self-references within variable initializers. 12432 // Variables declared within a function/method body (except for references) 12433 // are handled by a dataflow analysis. 12434 // This is undefined behavior in C++, but valid in C. 12435 if (getLangOpts().CPlusPlus) 12436 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12437 VDecl->getType()->isReferenceType()) 12438 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12439 12440 // If the type changed, it means we had an incomplete type that was 12441 // completed by the initializer. For example: 12442 // int ary[] = { 1, 3, 5 }; 12443 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12444 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12445 VDecl->setType(DclT); 12446 12447 if (!VDecl->isInvalidDecl()) { 12448 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12449 12450 if (VDecl->hasAttr<BlocksAttr>()) 12451 checkRetainCycles(VDecl, Init); 12452 12453 // It is safe to assign a weak reference into a strong variable. 12454 // Although this code can still have problems: 12455 // id x = self.weakProp; 12456 // id y = self.weakProp; 12457 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12458 // paths through the function. This should be revisited if 12459 // -Wrepeated-use-of-weak is made flow-sensitive. 12460 if (FunctionScopeInfo *FSI = getCurFunction()) 12461 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12462 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12463 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12464 Init->getBeginLoc())) 12465 FSI->markSafeWeakUse(Init); 12466 } 12467 12468 // The initialization is usually a full-expression. 12469 // 12470 // FIXME: If this is a braced initialization of an aggregate, it is not 12471 // an expression, and each individual field initializer is a separate 12472 // full-expression. For instance, in: 12473 // 12474 // struct Temp { ~Temp(); }; 12475 // struct S { S(Temp); }; 12476 // struct T { S a, b; } t = { Temp(), Temp() } 12477 // 12478 // we should destroy the first Temp before constructing the second. 12479 ExprResult Result = 12480 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12481 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12482 if (Result.isInvalid()) { 12483 VDecl->setInvalidDecl(); 12484 return; 12485 } 12486 Init = Result.get(); 12487 12488 // Attach the initializer to the decl. 12489 VDecl->setInit(Init); 12490 12491 if (VDecl->isLocalVarDecl()) { 12492 // Don't check the initializer if the declaration is malformed. 12493 if (VDecl->isInvalidDecl()) { 12494 // do nothing 12495 12496 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12497 // This is true even in C++ for OpenCL. 12498 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12499 CheckForConstantInitializer(Init, DclT); 12500 12501 // Otherwise, C++ does not restrict the initializer. 12502 } else if (getLangOpts().CPlusPlus) { 12503 // do nothing 12504 12505 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12506 // static storage duration shall be constant expressions or string literals. 12507 } else if (VDecl->getStorageClass() == SC_Static) { 12508 CheckForConstantInitializer(Init, DclT); 12509 12510 // C89 is stricter than C99 for aggregate initializers. 12511 // C89 6.5.7p3: All the expressions [...] in an initializer list 12512 // for an object that has aggregate or union type shall be 12513 // constant expressions. 12514 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12515 isa<InitListExpr>(Init)) { 12516 const Expr *Culprit; 12517 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12518 Diag(Culprit->getExprLoc(), 12519 diag::ext_aggregate_init_not_constant) 12520 << Culprit->getSourceRange(); 12521 } 12522 } 12523 12524 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12525 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12526 if (VDecl->hasLocalStorage()) 12527 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12528 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12529 VDecl->getLexicalDeclContext()->isRecord()) { 12530 // This is an in-class initialization for a static data member, e.g., 12531 // 12532 // struct S { 12533 // static const int value = 17; 12534 // }; 12535 12536 // C++ [class.mem]p4: 12537 // A member-declarator can contain a constant-initializer only 12538 // if it declares a static member (9.4) of const integral or 12539 // const enumeration type, see 9.4.2. 12540 // 12541 // C++11 [class.static.data]p3: 12542 // If a non-volatile non-inline const static data member is of integral 12543 // or enumeration type, its declaration in the class definition can 12544 // specify a brace-or-equal-initializer in which every initializer-clause 12545 // that is an assignment-expression is a constant expression. A static 12546 // data member of literal type can be declared in the class definition 12547 // with the constexpr specifier; if so, its declaration shall specify a 12548 // brace-or-equal-initializer in which every initializer-clause that is 12549 // an assignment-expression is a constant expression. 12550 12551 // Do nothing on dependent types. 12552 if (DclT->isDependentType()) { 12553 12554 // Allow any 'static constexpr' members, whether or not they are of literal 12555 // type. We separately check that every constexpr variable is of literal 12556 // type. 12557 } else if (VDecl->isConstexpr()) { 12558 12559 // Require constness. 12560 } else if (!DclT.isConstQualified()) { 12561 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12562 << Init->getSourceRange(); 12563 VDecl->setInvalidDecl(); 12564 12565 // We allow integer constant expressions in all cases. 12566 } else if (DclT->isIntegralOrEnumerationType()) { 12567 // Check whether the expression is a constant expression. 12568 SourceLocation Loc; 12569 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12570 // In C++11, a non-constexpr const static data member with an 12571 // in-class initializer cannot be volatile. 12572 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12573 else if (Init->isValueDependent()) 12574 ; // Nothing to check. 12575 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12576 ; // Ok, it's an ICE! 12577 else if (Init->getType()->isScopedEnumeralType() && 12578 Init->isCXX11ConstantExpr(Context)) 12579 ; // Ok, it is a scoped-enum constant expression. 12580 else if (Init->isEvaluatable(Context)) { 12581 // If we can constant fold the initializer through heroics, accept it, 12582 // but report this as a use of an extension for -pedantic. 12583 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12584 << Init->getSourceRange(); 12585 } else { 12586 // Otherwise, this is some crazy unknown case. Report the issue at the 12587 // location provided by the isIntegerConstantExpr failed check. 12588 Diag(Loc, diag::err_in_class_initializer_non_constant) 12589 << Init->getSourceRange(); 12590 VDecl->setInvalidDecl(); 12591 } 12592 12593 // We allow foldable floating-point constants as an extension. 12594 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12595 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12596 // it anyway and provide a fixit to add the 'constexpr'. 12597 if (getLangOpts().CPlusPlus11) { 12598 Diag(VDecl->getLocation(), 12599 diag::ext_in_class_initializer_float_type_cxx11) 12600 << DclT << Init->getSourceRange(); 12601 Diag(VDecl->getBeginLoc(), 12602 diag::note_in_class_initializer_float_type_cxx11) 12603 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12604 } else { 12605 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12606 << DclT << Init->getSourceRange(); 12607 12608 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12609 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12610 << Init->getSourceRange(); 12611 VDecl->setInvalidDecl(); 12612 } 12613 } 12614 12615 // Suggest adding 'constexpr' in C++11 for literal types. 12616 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12617 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12618 << DclT << Init->getSourceRange() 12619 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12620 VDecl->setConstexpr(true); 12621 12622 } else { 12623 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12624 << DclT << Init->getSourceRange(); 12625 VDecl->setInvalidDecl(); 12626 } 12627 } else if (VDecl->isFileVarDecl()) { 12628 // In C, extern is typically used to avoid tentative definitions when 12629 // declaring variables in headers, but adding an intializer makes it a 12630 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12631 // In C++, extern is often used to give implictly static const variables 12632 // external linkage, so don't warn in that case. If selectany is present, 12633 // this might be header code intended for C and C++ inclusion, so apply the 12634 // C++ rules. 12635 if (VDecl->getStorageClass() == SC_Extern && 12636 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12637 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12638 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12639 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12640 Diag(VDecl->getLocation(), diag::warn_extern_init); 12641 12642 // In Microsoft C++ mode, a const variable defined in namespace scope has 12643 // external linkage by default if the variable is declared with 12644 // __declspec(dllexport). 12645 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12646 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12647 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12648 VDecl->setStorageClass(SC_Extern); 12649 12650 // C99 6.7.8p4. All file scoped initializers need to be constant. 12651 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12652 CheckForConstantInitializer(Init, DclT); 12653 } 12654 12655 QualType InitType = Init->getType(); 12656 if (!InitType.isNull() && 12657 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12658 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12659 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12660 12661 // We will represent direct-initialization similarly to copy-initialization: 12662 // int x(1); -as-> int x = 1; 12663 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12664 // 12665 // Clients that want to distinguish between the two forms, can check for 12666 // direct initializer using VarDecl::getInitStyle(). 12667 // A major benefit is that clients that don't particularly care about which 12668 // exactly form was it (like the CodeGen) can handle both cases without 12669 // special case code. 12670 12671 // C++ 8.5p11: 12672 // The form of initialization (using parentheses or '=') is generally 12673 // insignificant, but does matter when the entity being initialized has a 12674 // class type. 12675 if (CXXDirectInit) { 12676 assert(DirectInit && "Call-style initializer must be direct init."); 12677 VDecl->setInitStyle(VarDecl::CallInit); 12678 } else if (DirectInit) { 12679 // This must be list-initialization. No other way is direct-initialization. 12680 VDecl->setInitStyle(VarDecl::ListInit); 12681 } 12682 12683 if (LangOpts.OpenMP && 12684 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 12685 VDecl->isFileVarDecl()) 12686 DeclsToCheckForDeferredDiags.insert(VDecl); 12687 CheckCompleteVariableDeclaration(VDecl); 12688 } 12689 12690 /// ActOnInitializerError - Given that there was an error parsing an 12691 /// initializer for the given declaration, try to at least re-establish 12692 /// invariants such as whether a variable's type is either dependent or 12693 /// complete. 12694 void Sema::ActOnInitializerError(Decl *D) { 12695 // Our main concern here is re-establishing invariants like "a 12696 // variable's type is either dependent or complete". 12697 if (!D || D->isInvalidDecl()) return; 12698 12699 VarDecl *VD = dyn_cast<VarDecl>(D); 12700 if (!VD) return; 12701 12702 // Bindings are not usable if we can't make sense of the initializer. 12703 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12704 for (auto *BD : DD->bindings()) 12705 BD->setInvalidDecl(); 12706 12707 // Auto types are meaningless if we can't make sense of the initializer. 12708 if (VD->getType()->isUndeducedType()) { 12709 D->setInvalidDecl(); 12710 return; 12711 } 12712 12713 QualType Ty = VD->getType(); 12714 if (Ty->isDependentType()) return; 12715 12716 // Require a complete type. 12717 if (RequireCompleteType(VD->getLocation(), 12718 Context.getBaseElementType(Ty), 12719 diag::err_typecheck_decl_incomplete_type)) { 12720 VD->setInvalidDecl(); 12721 return; 12722 } 12723 12724 // Require a non-abstract type. 12725 if (RequireNonAbstractType(VD->getLocation(), Ty, 12726 diag::err_abstract_type_in_decl, 12727 AbstractVariableType)) { 12728 VD->setInvalidDecl(); 12729 return; 12730 } 12731 12732 // Don't bother complaining about constructors or destructors, 12733 // though. 12734 } 12735 12736 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12737 // If there is no declaration, there was an error parsing it. Just ignore it. 12738 if (!RealDecl) 12739 return; 12740 12741 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12742 QualType Type = Var->getType(); 12743 12744 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12745 if (isa<DecompositionDecl>(RealDecl)) { 12746 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12747 Var->setInvalidDecl(); 12748 return; 12749 } 12750 12751 if (Type->isUndeducedType() && 12752 DeduceVariableDeclarationType(Var, false, nullptr)) 12753 return; 12754 12755 // C++11 [class.static.data]p3: A static data member can be declared with 12756 // the constexpr specifier; if so, its declaration shall specify 12757 // a brace-or-equal-initializer. 12758 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12759 // the definition of a variable [...] or the declaration of a static data 12760 // member. 12761 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12762 !Var->isThisDeclarationADemotedDefinition()) { 12763 if (Var->isStaticDataMember()) { 12764 // C++1z removes the relevant rule; the in-class declaration is always 12765 // a definition there. 12766 if (!getLangOpts().CPlusPlus17 && 12767 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12768 Diag(Var->getLocation(), 12769 diag::err_constexpr_static_mem_var_requires_init) 12770 << Var; 12771 Var->setInvalidDecl(); 12772 return; 12773 } 12774 } else { 12775 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12776 Var->setInvalidDecl(); 12777 return; 12778 } 12779 } 12780 12781 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12782 // be initialized. 12783 if (!Var->isInvalidDecl() && 12784 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12785 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12786 bool HasConstExprDefaultConstructor = false; 12787 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12788 for (auto *Ctor : RD->ctors()) { 12789 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12790 Ctor->getMethodQualifiers().getAddressSpace() == 12791 LangAS::opencl_constant) { 12792 HasConstExprDefaultConstructor = true; 12793 } 12794 } 12795 } 12796 if (!HasConstExprDefaultConstructor) { 12797 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12798 Var->setInvalidDecl(); 12799 return; 12800 } 12801 } 12802 12803 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12804 if (Var->getStorageClass() == SC_Extern) { 12805 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12806 << Var; 12807 Var->setInvalidDecl(); 12808 return; 12809 } 12810 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12811 diag::err_typecheck_decl_incomplete_type)) { 12812 Var->setInvalidDecl(); 12813 return; 12814 } 12815 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12816 if (!RD->hasTrivialDefaultConstructor()) { 12817 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12818 Var->setInvalidDecl(); 12819 return; 12820 } 12821 } 12822 // The declaration is unitialized, no need for further checks. 12823 return; 12824 } 12825 12826 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12827 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12828 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12829 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12830 NTCUC_DefaultInitializedObject, NTCUK_Init); 12831 12832 12833 switch (DefKind) { 12834 case VarDecl::Definition: 12835 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12836 break; 12837 12838 // We have an out-of-line definition of a static data member 12839 // that has an in-class initializer, so we type-check this like 12840 // a declaration. 12841 // 12842 LLVM_FALLTHROUGH; 12843 12844 case VarDecl::DeclarationOnly: 12845 // It's only a declaration. 12846 12847 // Block scope. C99 6.7p7: If an identifier for an object is 12848 // declared with no linkage (C99 6.2.2p6), the type for the 12849 // object shall be complete. 12850 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12851 !Var->hasLinkage() && !Var->isInvalidDecl() && 12852 RequireCompleteType(Var->getLocation(), Type, 12853 diag::err_typecheck_decl_incomplete_type)) 12854 Var->setInvalidDecl(); 12855 12856 // Make sure that the type is not abstract. 12857 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12858 RequireNonAbstractType(Var->getLocation(), Type, 12859 diag::err_abstract_type_in_decl, 12860 AbstractVariableType)) 12861 Var->setInvalidDecl(); 12862 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12863 Var->getStorageClass() == SC_PrivateExtern) { 12864 Diag(Var->getLocation(), diag::warn_private_extern); 12865 Diag(Var->getLocation(), diag::note_private_extern); 12866 } 12867 12868 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12869 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12870 ExternalDeclarations.push_back(Var); 12871 12872 return; 12873 12874 case VarDecl::TentativeDefinition: 12875 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12876 // object that has file scope without an initializer, and without a 12877 // storage-class specifier or with the storage-class specifier "static", 12878 // constitutes a tentative definition. Note: A tentative definition with 12879 // external linkage is valid (C99 6.2.2p5). 12880 if (!Var->isInvalidDecl()) { 12881 if (const IncompleteArrayType *ArrayT 12882 = Context.getAsIncompleteArrayType(Type)) { 12883 if (RequireCompleteSizedType( 12884 Var->getLocation(), ArrayT->getElementType(), 12885 diag::err_array_incomplete_or_sizeless_type)) 12886 Var->setInvalidDecl(); 12887 } else if (Var->getStorageClass() == SC_Static) { 12888 // C99 6.9.2p3: If the declaration of an identifier for an object is 12889 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12890 // declared type shall not be an incomplete type. 12891 // NOTE: code such as the following 12892 // static struct s; 12893 // struct s { int a; }; 12894 // is accepted by gcc. Hence here we issue a warning instead of 12895 // an error and we do not invalidate the static declaration. 12896 // NOTE: to avoid multiple warnings, only check the first declaration. 12897 if (Var->isFirstDecl()) 12898 RequireCompleteType(Var->getLocation(), Type, 12899 diag::ext_typecheck_decl_incomplete_type); 12900 } 12901 } 12902 12903 // Record the tentative definition; we're done. 12904 if (!Var->isInvalidDecl()) 12905 TentativeDefinitions.push_back(Var); 12906 return; 12907 } 12908 12909 // Provide a specific diagnostic for uninitialized variable 12910 // definitions with incomplete array type. 12911 if (Type->isIncompleteArrayType()) { 12912 Diag(Var->getLocation(), 12913 diag::err_typecheck_incomplete_array_needs_initializer); 12914 Var->setInvalidDecl(); 12915 return; 12916 } 12917 12918 // Provide a specific diagnostic for uninitialized variable 12919 // definitions with reference type. 12920 if (Type->isReferenceType()) { 12921 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12922 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12923 Var->setInvalidDecl(); 12924 return; 12925 } 12926 12927 // Do not attempt to type-check the default initializer for a 12928 // variable with dependent type. 12929 if (Type->isDependentType()) 12930 return; 12931 12932 if (Var->isInvalidDecl()) 12933 return; 12934 12935 if (!Var->hasAttr<AliasAttr>()) { 12936 if (RequireCompleteType(Var->getLocation(), 12937 Context.getBaseElementType(Type), 12938 diag::err_typecheck_decl_incomplete_type)) { 12939 Var->setInvalidDecl(); 12940 return; 12941 } 12942 } else { 12943 return; 12944 } 12945 12946 // The variable can not have an abstract class type. 12947 if (RequireNonAbstractType(Var->getLocation(), Type, 12948 diag::err_abstract_type_in_decl, 12949 AbstractVariableType)) { 12950 Var->setInvalidDecl(); 12951 return; 12952 } 12953 12954 // Check for jumps past the implicit initializer. C++0x 12955 // clarifies that this applies to a "variable with automatic 12956 // storage duration", not a "local variable". 12957 // C++11 [stmt.dcl]p3 12958 // A program that jumps from a point where a variable with automatic 12959 // storage duration is not in scope to a point where it is in scope is 12960 // ill-formed unless the variable has scalar type, class type with a 12961 // trivial default constructor and a trivial destructor, a cv-qualified 12962 // version of one of these types, or an array of one of the preceding 12963 // types and is declared without an initializer. 12964 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12965 if (const RecordType *Record 12966 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12967 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12968 // Mark the function (if we're in one) for further checking even if the 12969 // looser rules of C++11 do not require such checks, so that we can 12970 // diagnose incompatibilities with C++98. 12971 if (!CXXRecord->isPOD()) 12972 setFunctionHasBranchProtectedScope(); 12973 } 12974 } 12975 // In OpenCL, we can't initialize objects in the __local address space, 12976 // even implicitly, so don't synthesize an implicit initializer. 12977 if (getLangOpts().OpenCL && 12978 Var->getType().getAddressSpace() == LangAS::opencl_local) 12979 return; 12980 // C++03 [dcl.init]p9: 12981 // If no initializer is specified for an object, and the 12982 // object is of (possibly cv-qualified) non-POD class type (or 12983 // array thereof), the object shall be default-initialized; if 12984 // the object is of const-qualified type, the underlying class 12985 // type shall have a user-declared default 12986 // constructor. Otherwise, if no initializer is specified for 12987 // a non- static object, the object and its subobjects, if 12988 // any, have an indeterminate initial value); if the object 12989 // or any of its subobjects are of const-qualified type, the 12990 // program is ill-formed. 12991 // C++0x [dcl.init]p11: 12992 // If no initializer is specified for an object, the object is 12993 // default-initialized; [...]. 12994 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12995 InitializationKind Kind 12996 = InitializationKind::CreateDefault(Var->getLocation()); 12997 12998 InitializationSequence InitSeq(*this, Entity, Kind, None); 12999 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 13000 13001 if (Init.get()) { 13002 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 13003 // This is important for template substitution. 13004 Var->setInitStyle(VarDecl::CallInit); 13005 } else if (Init.isInvalid()) { 13006 // If default-init fails, attach a recovery-expr initializer to track 13007 // that initialization was attempted and failed. 13008 auto RecoveryExpr = 13009 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 13010 if (RecoveryExpr.get()) 13011 Var->setInit(RecoveryExpr.get()); 13012 } 13013 13014 CheckCompleteVariableDeclaration(Var); 13015 } 13016 } 13017 13018 void Sema::ActOnCXXForRangeDecl(Decl *D) { 13019 // If there is no declaration, there was an error parsing it. Ignore it. 13020 if (!D) 13021 return; 13022 13023 VarDecl *VD = dyn_cast<VarDecl>(D); 13024 if (!VD) { 13025 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 13026 D->setInvalidDecl(); 13027 return; 13028 } 13029 13030 VD->setCXXForRangeDecl(true); 13031 13032 // for-range-declaration cannot be given a storage class specifier. 13033 int Error = -1; 13034 switch (VD->getStorageClass()) { 13035 case SC_None: 13036 break; 13037 case SC_Extern: 13038 Error = 0; 13039 break; 13040 case SC_Static: 13041 Error = 1; 13042 break; 13043 case SC_PrivateExtern: 13044 Error = 2; 13045 break; 13046 case SC_Auto: 13047 Error = 3; 13048 break; 13049 case SC_Register: 13050 Error = 4; 13051 break; 13052 } 13053 13054 // for-range-declaration cannot be given a storage class specifier con't. 13055 switch (VD->getTSCSpec()) { 13056 case TSCS_thread_local: 13057 Error = 6; 13058 break; 13059 case TSCS___thread: 13060 case TSCS__Thread_local: 13061 case TSCS_unspecified: 13062 break; 13063 } 13064 13065 if (Error != -1) { 13066 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 13067 << VD << Error; 13068 D->setInvalidDecl(); 13069 } 13070 } 13071 13072 StmtResult 13073 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13074 IdentifierInfo *Ident, 13075 ParsedAttributes &Attrs, 13076 SourceLocation AttrEnd) { 13077 // C++1y [stmt.iter]p1: 13078 // A range-based for statement of the form 13079 // for ( for-range-identifier : for-range-initializer ) statement 13080 // is equivalent to 13081 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13082 DeclSpec DS(Attrs.getPool().getFactory()); 13083 13084 const char *PrevSpec; 13085 unsigned DiagID; 13086 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13087 getPrintingPolicy()); 13088 13089 Declarator D(DS, DeclaratorContext::ForInit); 13090 D.SetIdentifier(Ident, IdentLoc); 13091 D.takeAttributes(Attrs, AttrEnd); 13092 13093 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13094 IdentLoc); 13095 Decl *Var = ActOnDeclarator(S, D); 13096 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13097 FinalizeDeclaration(Var); 13098 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13099 AttrEnd.isValid() ? AttrEnd : IdentLoc); 13100 } 13101 13102 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13103 if (var->isInvalidDecl()) return; 13104 13105 MaybeAddCUDAConstantAttr(var); 13106 13107 if (getLangOpts().OpenCL) { 13108 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13109 // initialiser 13110 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13111 !var->hasInit()) { 13112 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13113 << 1 /*Init*/; 13114 var->setInvalidDecl(); 13115 return; 13116 } 13117 } 13118 13119 // In Objective-C, don't allow jumps past the implicit initialization of a 13120 // local retaining variable. 13121 if (getLangOpts().ObjC && 13122 var->hasLocalStorage()) { 13123 switch (var->getType().getObjCLifetime()) { 13124 case Qualifiers::OCL_None: 13125 case Qualifiers::OCL_ExplicitNone: 13126 case Qualifiers::OCL_Autoreleasing: 13127 break; 13128 13129 case Qualifiers::OCL_Weak: 13130 case Qualifiers::OCL_Strong: 13131 setFunctionHasBranchProtectedScope(); 13132 break; 13133 } 13134 } 13135 13136 if (var->hasLocalStorage() && 13137 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13138 setFunctionHasBranchProtectedScope(); 13139 13140 // Warn about externally-visible variables being defined without a 13141 // prior declaration. We only want to do this for global 13142 // declarations, but we also specifically need to avoid doing it for 13143 // class members because the linkage of an anonymous class can 13144 // change if it's later given a typedef name. 13145 if (var->isThisDeclarationADefinition() && 13146 var->getDeclContext()->getRedeclContext()->isFileContext() && 13147 var->isExternallyVisible() && var->hasLinkage() && 13148 !var->isInline() && !var->getDescribedVarTemplate() && 13149 !isa<VarTemplatePartialSpecializationDecl>(var) && 13150 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13151 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13152 var->getLocation())) { 13153 // Find a previous declaration that's not a definition. 13154 VarDecl *prev = var->getPreviousDecl(); 13155 while (prev && prev->isThisDeclarationADefinition()) 13156 prev = prev->getPreviousDecl(); 13157 13158 if (!prev) { 13159 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13160 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13161 << /* variable */ 0; 13162 } 13163 } 13164 13165 // Cache the result of checking for constant initialization. 13166 Optional<bool> CacheHasConstInit; 13167 const Expr *CacheCulprit = nullptr; 13168 auto checkConstInit = [&]() mutable { 13169 if (!CacheHasConstInit) 13170 CacheHasConstInit = var->getInit()->isConstantInitializer( 13171 Context, var->getType()->isReferenceType(), &CacheCulprit); 13172 return *CacheHasConstInit; 13173 }; 13174 13175 if (var->getTLSKind() == VarDecl::TLS_Static) { 13176 if (var->getType().isDestructedType()) { 13177 // GNU C++98 edits for __thread, [basic.start.term]p3: 13178 // The type of an object with thread storage duration shall not 13179 // have a non-trivial destructor. 13180 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13181 if (getLangOpts().CPlusPlus11) 13182 Diag(var->getLocation(), diag::note_use_thread_local); 13183 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13184 if (!checkConstInit()) { 13185 // GNU C++98 edits for __thread, [basic.start.init]p4: 13186 // An object of thread storage duration shall not require dynamic 13187 // initialization. 13188 // FIXME: Need strict checking here. 13189 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13190 << CacheCulprit->getSourceRange(); 13191 if (getLangOpts().CPlusPlus11) 13192 Diag(var->getLocation(), diag::note_use_thread_local); 13193 } 13194 } 13195 } 13196 13197 13198 if (!var->getType()->isStructureType() && var->hasInit() && 13199 isa<InitListExpr>(var->getInit())) { 13200 const auto *ILE = cast<InitListExpr>(var->getInit()); 13201 unsigned NumInits = ILE->getNumInits(); 13202 if (NumInits > 2) 13203 for (unsigned I = 0; I < NumInits; ++I) { 13204 const auto *Init = ILE->getInit(I); 13205 if (!Init) 13206 break; 13207 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13208 if (!SL) 13209 break; 13210 13211 unsigned NumConcat = SL->getNumConcatenated(); 13212 // Diagnose missing comma in string array initialization. 13213 // Do not warn when all the elements in the initializer are concatenated 13214 // together. Do not warn for macros too. 13215 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13216 bool OnlyOneMissingComma = true; 13217 for (unsigned J = I + 1; J < NumInits; ++J) { 13218 const auto *Init = ILE->getInit(J); 13219 if (!Init) 13220 break; 13221 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13222 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13223 OnlyOneMissingComma = false; 13224 break; 13225 } 13226 } 13227 13228 if (OnlyOneMissingComma) { 13229 SmallVector<FixItHint, 1> Hints; 13230 for (unsigned i = 0; i < NumConcat - 1; ++i) 13231 Hints.push_back(FixItHint::CreateInsertion( 13232 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13233 13234 Diag(SL->getStrTokenLoc(1), 13235 diag::warn_concatenated_literal_array_init) 13236 << Hints; 13237 Diag(SL->getBeginLoc(), 13238 diag::note_concatenated_string_literal_silence); 13239 } 13240 // In any case, stop now. 13241 break; 13242 } 13243 } 13244 } 13245 13246 13247 QualType type = var->getType(); 13248 13249 if (var->hasAttr<BlocksAttr>()) 13250 getCurFunction()->addByrefBlockVar(var); 13251 13252 Expr *Init = var->getInit(); 13253 bool GlobalStorage = var->hasGlobalStorage(); 13254 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13255 QualType baseType = Context.getBaseElementType(type); 13256 bool HasConstInit = true; 13257 13258 // Check whether the initializer is sufficiently constant. 13259 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13260 !Init->isValueDependent() && 13261 (GlobalStorage || var->isConstexpr() || 13262 var->mightBeUsableInConstantExpressions(Context))) { 13263 // If this variable might have a constant initializer or might be usable in 13264 // constant expressions, check whether or not it actually is now. We can't 13265 // do this lazily, because the result might depend on things that change 13266 // later, such as which constexpr functions happen to be defined. 13267 SmallVector<PartialDiagnosticAt, 8> Notes; 13268 if (!getLangOpts().CPlusPlus11) { 13269 // Prior to C++11, in contexts where a constant initializer is required, 13270 // the set of valid constant initializers is described by syntactic rules 13271 // in [expr.const]p2-6. 13272 // FIXME: Stricter checking for these rules would be useful for constinit / 13273 // -Wglobal-constructors. 13274 HasConstInit = checkConstInit(); 13275 13276 // Compute and cache the constant value, and remember that we have a 13277 // constant initializer. 13278 if (HasConstInit) { 13279 (void)var->checkForConstantInitialization(Notes); 13280 Notes.clear(); 13281 } else if (CacheCulprit) { 13282 Notes.emplace_back(CacheCulprit->getExprLoc(), 13283 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13284 Notes.back().second << CacheCulprit->getSourceRange(); 13285 } 13286 } else { 13287 // Evaluate the initializer to see if it's a constant initializer. 13288 HasConstInit = var->checkForConstantInitialization(Notes); 13289 } 13290 13291 if (HasConstInit) { 13292 // FIXME: Consider replacing the initializer with a ConstantExpr. 13293 } else if (var->isConstexpr()) { 13294 SourceLocation DiagLoc = var->getLocation(); 13295 // If the note doesn't add any useful information other than a source 13296 // location, fold it into the primary diagnostic. 13297 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13298 diag::note_invalid_subexpr_in_const_expr) { 13299 DiagLoc = Notes[0].first; 13300 Notes.clear(); 13301 } 13302 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13303 << var << Init->getSourceRange(); 13304 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13305 Diag(Notes[I].first, Notes[I].second); 13306 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13307 auto *Attr = var->getAttr<ConstInitAttr>(); 13308 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13309 << Init->getSourceRange(); 13310 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13311 << Attr->getRange() << Attr->isConstinit(); 13312 for (auto &it : Notes) 13313 Diag(it.first, it.second); 13314 } else if (IsGlobal && 13315 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13316 var->getLocation())) { 13317 // Warn about globals which don't have a constant initializer. Don't 13318 // warn about globals with a non-trivial destructor because we already 13319 // warned about them. 13320 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13321 if (!(RD && !RD->hasTrivialDestructor())) { 13322 // checkConstInit() here permits trivial default initialization even in 13323 // C++11 onwards, where such an initializer is not a constant initializer 13324 // but nonetheless doesn't require a global constructor. 13325 if (!checkConstInit()) 13326 Diag(var->getLocation(), diag::warn_global_constructor) 13327 << Init->getSourceRange(); 13328 } 13329 } 13330 } 13331 13332 // Apply section attributes and pragmas to global variables. 13333 if (GlobalStorage && var->isThisDeclarationADefinition() && 13334 !inTemplateInstantiation()) { 13335 PragmaStack<StringLiteral *> *Stack = nullptr; 13336 int SectionFlags = ASTContext::PSF_Read; 13337 if (var->getType().isConstQualified()) { 13338 if (HasConstInit) 13339 Stack = &ConstSegStack; 13340 else { 13341 Stack = &BSSSegStack; 13342 SectionFlags |= ASTContext::PSF_Write; 13343 } 13344 } else if (var->hasInit() && HasConstInit) { 13345 Stack = &DataSegStack; 13346 SectionFlags |= ASTContext::PSF_Write; 13347 } else { 13348 Stack = &BSSSegStack; 13349 SectionFlags |= ASTContext::PSF_Write; 13350 } 13351 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13352 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13353 SectionFlags |= ASTContext::PSF_Implicit; 13354 UnifySection(SA->getName(), SectionFlags, var); 13355 } else if (Stack->CurrentValue) { 13356 SectionFlags |= ASTContext::PSF_Implicit; 13357 auto SectionName = Stack->CurrentValue->getString(); 13358 var->addAttr(SectionAttr::CreateImplicit( 13359 Context, SectionName, Stack->CurrentPragmaLocation, 13360 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13361 if (UnifySection(SectionName, SectionFlags, var)) 13362 var->dropAttr<SectionAttr>(); 13363 } 13364 13365 // Apply the init_seg attribute if this has an initializer. If the 13366 // initializer turns out to not be dynamic, we'll end up ignoring this 13367 // attribute. 13368 if (CurInitSeg && var->getInit()) 13369 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13370 CurInitSegLoc, 13371 AttributeCommonInfo::AS_Pragma)); 13372 } 13373 13374 // All the following checks are C++ only. 13375 if (!getLangOpts().CPlusPlus) { 13376 // If this variable must be emitted, add it as an initializer for the 13377 // current module. 13378 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13379 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13380 return; 13381 } 13382 13383 // Require the destructor. 13384 if (!type->isDependentType()) 13385 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13386 FinalizeVarWithDestructor(var, recordType); 13387 13388 // If this variable must be emitted, add it as an initializer for the current 13389 // module. 13390 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13391 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13392 13393 // Build the bindings if this is a structured binding declaration. 13394 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13395 CheckCompleteDecompositionDeclaration(DD); 13396 } 13397 13398 /// Check if VD needs to be dllexport/dllimport due to being in a 13399 /// dllexport/import function. 13400 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13401 assert(VD->isStaticLocal()); 13402 13403 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13404 13405 // Find outermost function when VD is in lambda function. 13406 while (FD && !getDLLAttr(FD) && 13407 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13408 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13409 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13410 } 13411 13412 if (!FD) 13413 return; 13414 13415 // Static locals inherit dll attributes from their function. 13416 if (Attr *A = getDLLAttr(FD)) { 13417 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13418 NewAttr->setInherited(true); 13419 VD->addAttr(NewAttr); 13420 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13421 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13422 NewAttr->setInherited(true); 13423 VD->addAttr(NewAttr); 13424 13425 // Export this function to enforce exporting this static variable even 13426 // if it is not used in this compilation unit. 13427 if (!FD->hasAttr<DLLExportAttr>()) 13428 FD->addAttr(NewAttr); 13429 13430 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13431 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13432 NewAttr->setInherited(true); 13433 VD->addAttr(NewAttr); 13434 } 13435 } 13436 13437 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13438 /// any semantic actions necessary after any initializer has been attached. 13439 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13440 // Note that we are no longer parsing the initializer for this declaration. 13441 ParsingInitForAutoVars.erase(ThisDecl); 13442 13443 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13444 if (!VD) 13445 return; 13446 13447 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13448 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13449 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13450 if (PragmaClangBSSSection.Valid) 13451 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13452 Context, PragmaClangBSSSection.SectionName, 13453 PragmaClangBSSSection.PragmaLocation, 13454 AttributeCommonInfo::AS_Pragma)); 13455 if (PragmaClangDataSection.Valid) 13456 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13457 Context, PragmaClangDataSection.SectionName, 13458 PragmaClangDataSection.PragmaLocation, 13459 AttributeCommonInfo::AS_Pragma)); 13460 if (PragmaClangRodataSection.Valid) 13461 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13462 Context, PragmaClangRodataSection.SectionName, 13463 PragmaClangRodataSection.PragmaLocation, 13464 AttributeCommonInfo::AS_Pragma)); 13465 if (PragmaClangRelroSection.Valid) 13466 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13467 Context, PragmaClangRelroSection.SectionName, 13468 PragmaClangRelroSection.PragmaLocation, 13469 AttributeCommonInfo::AS_Pragma)); 13470 } 13471 13472 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13473 for (auto *BD : DD->bindings()) { 13474 FinalizeDeclaration(BD); 13475 } 13476 } 13477 13478 checkAttributesAfterMerging(*this, *VD); 13479 13480 // Perform TLS alignment check here after attributes attached to the variable 13481 // which may affect the alignment have been processed. Only perform the check 13482 // if the target has a maximum TLS alignment (zero means no constraints). 13483 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13484 // Protect the check so that it's not performed on dependent types and 13485 // dependent alignments (we can't determine the alignment in that case). 13486 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13487 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13488 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13489 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13490 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13491 << (unsigned)MaxAlignChars.getQuantity(); 13492 } 13493 } 13494 } 13495 13496 if (VD->isStaticLocal()) 13497 CheckStaticLocalForDllExport(VD); 13498 13499 // Perform check for initializers of device-side global variables. 13500 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13501 // 7.5). We must also apply the same checks to all __shared__ 13502 // variables whether they are local or not. CUDA also allows 13503 // constant initializers for __constant__ and __device__ variables. 13504 if (getLangOpts().CUDA) 13505 checkAllowedCUDAInitializer(VD); 13506 13507 // Grab the dllimport or dllexport attribute off of the VarDecl. 13508 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13509 13510 // Imported static data members cannot be defined out-of-line. 13511 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13512 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13513 VD->isThisDeclarationADefinition()) { 13514 // We allow definitions of dllimport class template static data members 13515 // with a warning. 13516 CXXRecordDecl *Context = 13517 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13518 bool IsClassTemplateMember = 13519 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13520 Context->getDescribedClassTemplate(); 13521 13522 Diag(VD->getLocation(), 13523 IsClassTemplateMember 13524 ? diag::warn_attribute_dllimport_static_field_definition 13525 : diag::err_attribute_dllimport_static_field_definition); 13526 Diag(IA->getLocation(), diag::note_attribute); 13527 if (!IsClassTemplateMember) 13528 VD->setInvalidDecl(); 13529 } 13530 } 13531 13532 // dllimport/dllexport variables cannot be thread local, their TLS index 13533 // isn't exported with the variable. 13534 if (DLLAttr && VD->getTLSKind()) { 13535 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13536 if (F && getDLLAttr(F)) { 13537 assert(VD->isStaticLocal()); 13538 // But if this is a static local in a dlimport/dllexport function, the 13539 // function will never be inlined, which means the var would never be 13540 // imported, so having it marked import/export is safe. 13541 } else { 13542 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13543 << DLLAttr; 13544 VD->setInvalidDecl(); 13545 } 13546 } 13547 13548 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13549 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13550 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13551 << Attr; 13552 VD->dropAttr<UsedAttr>(); 13553 } 13554 } 13555 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13556 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13557 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13558 << Attr; 13559 VD->dropAttr<RetainAttr>(); 13560 } 13561 } 13562 13563 const DeclContext *DC = VD->getDeclContext(); 13564 // If there's a #pragma GCC visibility in scope, and this isn't a class 13565 // member, set the visibility of this variable. 13566 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13567 AddPushedVisibilityAttribute(VD); 13568 13569 // FIXME: Warn on unused var template partial specializations. 13570 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13571 MarkUnusedFileScopedDecl(VD); 13572 13573 // Now we have parsed the initializer and can update the table of magic 13574 // tag values. 13575 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13576 !VD->getType()->isIntegralOrEnumerationType()) 13577 return; 13578 13579 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13580 const Expr *MagicValueExpr = VD->getInit(); 13581 if (!MagicValueExpr) { 13582 continue; 13583 } 13584 Optional<llvm::APSInt> MagicValueInt; 13585 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13586 Diag(I->getRange().getBegin(), 13587 diag::err_type_tag_for_datatype_not_ice) 13588 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13589 continue; 13590 } 13591 if (MagicValueInt->getActiveBits() > 64) { 13592 Diag(I->getRange().getBegin(), 13593 diag::err_type_tag_for_datatype_too_large) 13594 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13595 continue; 13596 } 13597 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13598 RegisterTypeTagForDatatype(I->getArgumentKind(), 13599 MagicValue, 13600 I->getMatchingCType(), 13601 I->getLayoutCompatible(), 13602 I->getMustBeNull()); 13603 } 13604 } 13605 13606 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13607 auto *VD = dyn_cast<VarDecl>(DD); 13608 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13609 } 13610 13611 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13612 ArrayRef<Decl *> Group) { 13613 SmallVector<Decl*, 8> Decls; 13614 13615 if (DS.isTypeSpecOwned()) 13616 Decls.push_back(DS.getRepAsDecl()); 13617 13618 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13619 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13620 bool DiagnosedMultipleDecomps = false; 13621 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13622 bool DiagnosedNonDeducedAuto = false; 13623 13624 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13625 if (Decl *D = Group[i]) { 13626 // For declarators, there are some additional syntactic-ish checks we need 13627 // to perform. 13628 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13629 if (!FirstDeclaratorInGroup) 13630 FirstDeclaratorInGroup = DD; 13631 if (!FirstDecompDeclaratorInGroup) 13632 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13633 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13634 !hasDeducedAuto(DD)) 13635 FirstNonDeducedAutoInGroup = DD; 13636 13637 if (FirstDeclaratorInGroup != DD) { 13638 // A decomposition declaration cannot be combined with any other 13639 // declaration in the same group. 13640 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13641 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13642 diag::err_decomp_decl_not_alone) 13643 << FirstDeclaratorInGroup->getSourceRange() 13644 << DD->getSourceRange(); 13645 DiagnosedMultipleDecomps = true; 13646 } 13647 13648 // A declarator that uses 'auto' in any way other than to declare a 13649 // variable with a deduced type cannot be combined with any other 13650 // declarator in the same group. 13651 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13652 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13653 diag::err_auto_non_deduced_not_alone) 13654 << FirstNonDeducedAutoInGroup->getType() 13655 ->hasAutoForTrailingReturnType() 13656 << FirstDeclaratorInGroup->getSourceRange() 13657 << DD->getSourceRange(); 13658 DiagnosedNonDeducedAuto = true; 13659 } 13660 } 13661 } 13662 13663 Decls.push_back(D); 13664 } 13665 } 13666 13667 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13668 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13669 handleTagNumbering(Tag, S); 13670 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13671 getLangOpts().CPlusPlus) 13672 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13673 } 13674 } 13675 13676 return BuildDeclaratorGroup(Decls); 13677 } 13678 13679 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13680 /// group, performing any necessary semantic checking. 13681 Sema::DeclGroupPtrTy 13682 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13683 // C++14 [dcl.spec.auto]p7: (DR1347) 13684 // If the type that replaces the placeholder type is not the same in each 13685 // deduction, the program is ill-formed. 13686 if (Group.size() > 1) { 13687 QualType Deduced; 13688 VarDecl *DeducedDecl = nullptr; 13689 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13690 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13691 if (!D || D->isInvalidDecl()) 13692 break; 13693 DeducedType *DT = D->getType()->getContainedDeducedType(); 13694 if (!DT || DT->getDeducedType().isNull()) 13695 continue; 13696 if (Deduced.isNull()) { 13697 Deduced = DT->getDeducedType(); 13698 DeducedDecl = D; 13699 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13700 auto *AT = dyn_cast<AutoType>(DT); 13701 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13702 diag::err_auto_different_deductions) 13703 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13704 << DeducedDecl->getDeclName() << DT->getDeducedType() 13705 << D->getDeclName(); 13706 if (DeducedDecl->hasInit()) 13707 Dia << DeducedDecl->getInit()->getSourceRange(); 13708 if (D->getInit()) 13709 Dia << D->getInit()->getSourceRange(); 13710 D->setInvalidDecl(); 13711 break; 13712 } 13713 } 13714 } 13715 13716 ActOnDocumentableDecls(Group); 13717 13718 return DeclGroupPtrTy::make( 13719 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13720 } 13721 13722 void Sema::ActOnDocumentableDecl(Decl *D) { 13723 ActOnDocumentableDecls(D); 13724 } 13725 13726 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13727 // Don't parse the comment if Doxygen diagnostics are ignored. 13728 if (Group.empty() || !Group[0]) 13729 return; 13730 13731 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13732 Group[0]->getLocation()) && 13733 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13734 Group[0]->getLocation())) 13735 return; 13736 13737 if (Group.size() >= 2) { 13738 // This is a decl group. Normally it will contain only declarations 13739 // produced from declarator list. But in case we have any definitions or 13740 // additional declaration references: 13741 // 'typedef struct S {} S;' 13742 // 'typedef struct S *S;' 13743 // 'struct S *pS;' 13744 // FinalizeDeclaratorGroup adds these as separate declarations. 13745 Decl *MaybeTagDecl = Group[0]; 13746 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13747 Group = Group.slice(1); 13748 } 13749 } 13750 13751 // FIMXE: We assume every Decl in the group is in the same file. 13752 // This is false when preprocessor constructs the group from decls in 13753 // different files (e. g. macros or #include). 13754 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13755 } 13756 13757 /// Common checks for a parameter-declaration that should apply to both function 13758 /// parameters and non-type template parameters. 13759 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13760 // Check that there are no default arguments inside the type of this 13761 // parameter. 13762 if (getLangOpts().CPlusPlus) 13763 CheckExtraCXXDefaultArguments(D); 13764 13765 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13766 if (D.getCXXScopeSpec().isSet()) { 13767 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13768 << D.getCXXScopeSpec().getRange(); 13769 } 13770 13771 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13772 // simple identifier except [...irrelevant cases...]. 13773 switch (D.getName().getKind()) { 13774 case UnqualifiedIdKind::IK_Identifier: 13775 break; 13776 13777 case UnqualifiedIdKind::IK_OperatorFunctionId: 13778 case UnqualifiedIdKind::IK_ConversionFunctionId: 13779 case UnqualifiedIdKind::IK_LiteralOperatorId: 13780 case UnqualifiedIdKind::IK_ConstructorName: 13781 case UnqualifiedIdKind::IK_DestructorName: 13782 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13783 case UnqualifiedIdKind::IK_DeductionGuideName: 13784 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13785 << GetNameForDeclarator(D).getName(); 13786 break; 13787 13788 case UnqualifiedIdKind::IK_TemplateId: 13789 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13790 // GetNameForDeclarator would not produce a useful name in this case. 13791 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13792 break; 13793 } 13794 } 13795 13796 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13797 /// to introduce parameters into function prototype scope. 13798 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13799 const DeclSpec &DS = D.getDeclSpec(); 13800 13801 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13802 13803 // C++03 [dcl.stc]p2 also permits 'auto'. 13804 StorageClass SC = SC_None; 13805 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13806 SC = SC_Register; 13807 // In C++11, the 'register' storage class specifier is deprecated. 13808 // In C++17, it is not allowed, but we tolerate it as an extension. 13809 if (getLangOpts().CPlusPlus11) { 13810 Diag(DS.getStorageClassSpecLoc(), 13811 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13812 : diag::warn_deprecated_register) 13813 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13814 } 13815 } else if (getLangOpts().CPlusPlus && 13816 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13817 SC = SC_Auto; 13818 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13819 Diag(DS.getStorageClassSpecLoc(), 13820 diag::err_invalid_storage_class_in_func_decl); 13821 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13822 } 13823 13824 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13825 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13826 << DeclSpec::getSpecifierName(TSCS); 13827 if (DS.isInlineSpecified()) 13828 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13829 << getLangOpts().CPlusPlus17; 13830 if (DS.hasConstexprSpecifier()) 13831 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13832 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13833 13834 DiagnoseFunctionSpecifiers(DS); 13835 13836 CheckFunctionOrTemplateParamDeclarator(S, D); 13837 13838 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13839 QualType parmDeclType = TInfo->getType(); 13840 13841 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13842 IdentifierInfo *II = D.getIdentifier(); 13843 if (II) { 13844 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13845 ForVisibleRedeclaration); 13846 LookupName(R, S); 13847 if (R.isSingleResult()) { 13848 NamedDecl *PrevDecl = R.getFoundDecl(); 13849 if (PrevDecl->isTemplateParameter()) { 13850 // Maybe we will complain about the shadowed template parameter. 13851 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13852 // Just pretend that we didn't see the previous declaration. 13853 PrevDecl = nullptr; 13854 } else if (S->isDeclScope(PrevDecl)) { 13855 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13856 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13857 13858 // Recover by removing the name 13859 II = nullptr; 13860 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13861 D.setInvalidType(true); 13862 } 13863 } 13864 } 13865 13866 // Temporarily put parameter variables in the translation unit, not 13867 // the enclosing context. This prevents them from accidentally 13868 // looking like class members in C++. 13869 ParmVarDecl *New = 13870 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13871 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13872 13873 if (D.isInvalidType()) 13874 New->setInvalidDecl(); 13875 13876 assert(S->isFunctionPrototypeScope()); 13877 assert(S->getFunctionPrototypeDepth() >= 1); 13878 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13879 S->getNextFunctionPrototypeIndex()); 13880 13881 // Add the parameter declaration into this scope. 13882 S->AddDecl(New); 13883 if (II) 13884 IdResolver.AddDecl(New); 13885 13886 ProcessDeclAttributes(S, New, D); 13887 13888 if (D.getDeclSpec().isModulePrivateSpecified()) 13889 Diag(New->getLocation(), diag::err_module_private_local) 13890 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13891 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13892 13893 if (New->hasAttr<BlocksAttr>()) { 13894 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13895 } 13896 13897 if (getLangOpts().OpenCL) 13898 deduceOpenCLAddressSpace(New); 13899 13900 return New; 13901 } 13902 13903 /// Synthesizes a variable for a parameter arising from a 13904 /// typedef. 13905 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13906 SourceLocation Loc, 13907 QualType T) { 13908 /* FIXME: setting StartLoc == Loc. 13909 Would it be worth to modify callers so as to provide proper source 13910 location for the unnamed parameters, embedding the parameter's type? */ 13911 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13912 T, Context.getTrivialTypeSourceInfo(T, Loc), 13913 SC_None, nullptr); 13914 Param->setImplicit(); 13915 return Param; 13916 } 13917 13918 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13919 // Don't diagnose unused-parameter errors in template instantiations; we 13920 // will already have done so in the template itself. 13921 if (inTemplateInstantiation()) 13922 return; 13923 13924 for (const ParmVarDecl *Parameter : Parameters) { 13925 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13926 !Parameter->hasAttr<UnusedAttr>()) { 13927 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13928 << Parameter->getDeclName(); 13929 } 13930 } 13931 } 13932 13933 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13934 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13935 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13936 return; 13937 13938 // Warn if the return value is pass-by-value and larger than the specified 13939 // threshold. 13940 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13941 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13942 if (Size > LangOpts.NumLargeByValueCopy) 13943 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13944 } 13945 13946 // Warn if any parameter is pass-by-value and larger than the specified 13947 // threshold. 13948 for (const ParmVarDecl *Parameter : Parameters) { 13949 QualType T = Parameter->getType(); 13950 if (T->isDependentType() || !T.isPODType(Context)) 13951 continue; 13952 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13953 if (Size > LangOpts.NumLargeByValueCopy) 13954 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13955 << Parameter << Size; 13956 } 13957 } 13958 13959 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13960 SourceLocation NameLoc, IdentifierInfo *Name, 13961 QualType T, TypeSourceInfo *TSInfo, 13962 StorageClass SC) { 13963 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13964 if (getLangOpts().ObjCAutoRefCount && 13965 T.getObjCLifetime() == Qualifiers::OCL_None && 13966 T->isObjCLifetimeType()) { 13967 13968 Qualifiers::ObjCLifetime lifetime; 13969 13970 // Special cases for arrays: 13971 // - if it's const, use __unsafe_unretained 13972 // - otherwise, it's an error 13973 if (T->isArrayType()) { 13974 if (!T.isConstQualified()) { 13975 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13976 DelayedDiagnostics.add( 13977 sema::DelayedDiagnostic::makeForbiddenType( 13978 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13979 else 13980 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13981 << TSInfo->getTypeLoc().getSourceRange(); 13982 } 13983 lifetime = Qualifiers::OCL_ExplicitNone; 13984 } else { 13985 lifetime = T->getObjCARCImplicitLifetime(); 13986 } 13987 T = Context.getLifetimeQualifiedType(T, lifetime); 13988 } 13989 13990 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13991 Context.getAdjustedParameterType(T), 13992 TSInfo, SC, nullptr); 13993 13994 // Make a note if we created a new pack in the scope of a lambda, so that 13995 // we know that references to that pack must also be expanded within the 13996 // lambda scope. 13997 if (New->isParameterPack()) 13998 if (auto *LSI = getEnclosingLambda()) 13999 LSI->LocalPacks.push_back(New); 14000 14001 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 14002 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14003 checkNonTrivialCUnion(New->getType(), New->getLocation(), 14004 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 14005 14006 // Parameters can not be abstract class types. 14007 // For record types, this is done by the AbstractClassUsageDiagnoser once 14008 // the class has been completely parsed. 14009 if (!CurContext->isRecord() && 14010 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 14011 AbstractParamType)) 14012 New->setInvalidDecl(); 14013 14014 // Parameter declarators cannot be interface types. All ObjC objects are 14015 // passed by reference. 14016 if (T->isObjCObjectType()) { 14017 SourceLocation TypeEndLoc = 14018 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 14019 Diag(NameLoc, 14020 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 14021 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 14022 T = Context.getObjCObjectPointerType(T); 14023 New->setType(T); 14024 } 14025 14026 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 14027 // duration shall not be qualified by an address-space qualifier." 14028 // Since all parameters have automatic store duration, they can not have 14029 // an address space. 14030 if (T.getAddressSpace() != LangAS::Default && 14031 // OpenCL allows function arguments declared to be an array of a type 14032 // to be qualified with an address space. 14033 !(getLangOpts().OpenCL && 14034 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 14035 Diag(NameLoc, diag::err_arg_with_address_space); 14036 New->setInvalidDecl(); 14037 } 14038 14039 // PPC MMA non-pointer types are not allowed as function argument types. 14040 if (Context.getTargetInfo().getTriple().isPPC64() && 14041 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 14042 New->setInvalidDecl(); 14043 } 14044 14045 return New; 14046 } 14047 14048 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 14049 SourceLocation LocAfterDecls) { 14050 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 14051 14052 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 14053 // for a K&R function. 14054 if (!FTI.hasPrototype) { 14055 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 14056 --i; 14057 if (FTI.Params[i].Param == nullptr) { 14058 SmallString<256> Code; 14059 llvm::raw_svector_ostream(Code) 14060 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 14061 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 14062 << FTI.Params[i].Ident 14063 << FixItHint::CreateInsertion(LocAfterDecls, Code); 14064 14065 // Implicitly declare the argument as type 'int' for lack of a better 14066 // type. 14067 AttributeFactory attrs; 14068 DeclSpec DS(attrs); 14069 const char* PrevSpec; // unused 14070 unsigned DiagID; // unused 14071 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14072 DiagID, Context.getPrintingPolicy()); 14073 // Use the identifier location for the type source range. 14074 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14075 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14076 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14077 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14078 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14079 } 14080 } 14081 } 14082 } 14083 14084 Decl * 14085 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14086 MultiTemplateParamsArg TemplateParameterLists, 14087 SkipBodyInfo *SkipBody) { 14088 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14089 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14090 Scope *ParentScope = FnBodyScope->getParent(); 14091 14092 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14093 // we define a non-templated function definition, we will create a declaration 14094 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14095 // The base function declaration will have the equivalent of an `omp declare 14096 // variant` annotation which specifies the mangled definition as a 14097 // specialization function under the OpenMP context defined as part of the 14098 // `omp begin declare variant`. 14099 SmallVector<FunctionDecl *, 4> Bases; 14100 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14101 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14102 ParentScope, D, TemplateParameterLists, Bases); 14103 14104 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14105 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14106 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14107 14108 if (!Bases.empty()) 14109 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14110 14111 return Dcl; 14112 } 14113 14114 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14115 Consumer.HandleInlineFunctionDefinition(D); 14116 } 14117 14118 static bool 14119 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14120 const FunctionDecl *&PossiblePrototype) { 14121 // Don't warn about invalid declarations. 14122 if (FD->isInvalidDecl()) 14123 return false; 14124 14125 // Or declarations that aren't global. 14126 if (!FD->isGlobal()) 14127 return false; 14128 14129 // Don't warn about C++ member functions. 14130 if (isa<CXXMethodDecl>(FD)) 14131 return false; 14132 14133 // Don't warn about 'main'. 14134 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14135 if (IdentifierInfo *II = FD->getIdentifier()) 14136 if (II->isStr("main") || II->isStr("efi_main")) 14137 return false; 14138 14139 // Don't warn about inline functions. 14140 if (FD->isInlined()) 14141 return false; 14142 14143 // Don't warn about function templates. 14144 if (FD->getDescribedFunctionTemplate()) 14145 return false; 14146 14147 // Don't warn about function template specializations. 14148 if (FD->isFunctionTemplateSpecialization()) 14149 return false; 14150 14151 // Don't warn for OpenCL kernels. 14152 if (FD->hasAttr<OpenCLKernelAttr>()) 14153 return false; 14154 14155 // Don't warn on explicitly deleted functions. 14156 if (FD->isDeleted()) 14157 return false; 14158 14159 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14160 Prev; Prev = Prev->getPreviousDecl()) { 14161 // Ignore any declarations that occur in function or method 14162 // scope, because they aren't visible from the header. 14163 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14164 continue; 14165 14166 PossiblePrototype = Prev; 14167 return Prev->getType()->isFunctionNoProtoType(); 14168 } 14169 14170 return true; 14171 } 14172 14173 void 14174 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14175 const FunctionDecl *EffectiveDefinition, 14176 SkipBodyInfo *SkipBody) { 14177 const FunctionDecl *Definition = EffectiveDefinition; 14178 if (!Definition && 14179 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14180 return; 14181 14182 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14183 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14184 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14185 // A merged copy of the same function, instantiated as a member of 14186 // the same class, is OK. 14187 if (declaresSameEntity(OrigFD, OrigDef) && 14188 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14189 cast<Decl>(FD->getLexicalDeclContext()))) 14190 return; 14191 } 14192 } 14193 } 14194 14195 if (canRedefineFunction(Definition, getLangOpts())) 14196 return; 14197 14198 // Don't emit an error when this is redefinition of a typo-corrected 14199 // definition. 14200 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14201 return; 14202 14203 // If we don't have a visible definition of the function, and it's inline or 14204 // a template, skip the new definition. 14205 if (SkipBody && !hasVisibleDefinition(Definition) && 14206 (Definition->getFormalLinkage() == InternalLinkage || 14207 Definition->isInlined() || 14208 Definition->getDescribedFunctionTemplate() || 14209 Definition->getNumTemplateParameterLists())) { 14210 SkipBody->ShouldSkip = true; 14211 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14212 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14213 makeMergedDefinitionVisible(TD); 14214 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14215 return; 14216 } 14217 14218 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14219 Definition->getStorageClass() == SC_Extern) 14220 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14221 << FD << getLangOpts().CPlusPlus; 14222 else 14223 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14224 14225 Diag(Definition->getLocation(), diag::note_previous_definition); 14226 FD->setInvalidDecl(); 14227 } 14228 14229 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14230 Sema &S) { 14231 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14232 14233 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14234 LSI->CallOperator = CallOperator; 14235 LSI->Lambda = LambdaClass; 14236 LSI->ReturnType = CallOperator->getReturnType(); 14237 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14238 14239 if (LCD == LCD_None) 14240 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14241 else if (LCD == LCD_ByCopy) 14242 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14243 else if (LCD == LCD_ByRef) 14244 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14245 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14246 14247 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14248 LSI->Mutable = !CallOperator->isConst(); 14249 14250 // Add the captures to the LSI so they can be noted as already 14251 // captured within tryCaptureVar. 14252 auto I = LambdaClass->field_begin(); 14253 for (const auto &C : LambdaClass->captures()) { 14254 if (C.capturesVariable()) { 14255 VarDecl *VD = C.getCapturedVar(); 14256 if (VD->isInitCapture()) 14257 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14258 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14259 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14260 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14261 /*EllipsisLoc*/C.isPackExpansion() 14262 ? C.getEllipsisLoc() : SourceLocation(), 14263 I->getType(), /*Invalid*/false); 14264 14265 } else if (C.capturesThis()) { 14266 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14267 C.getCaptureKind() == LCK_StarThis); 14268 } else { 14269 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14270 I->getType()); 14271 } 14272 ++I; 14273 } 14274 } 14275 14276 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14277 SkipBodyInfo *SkipBody) { 14278 if (!D) { 14279 // Parsing the function declaration failed in some way. Push on a fake scope 14280 // anyway so we can try to parse the function body. 14281 PushFunctionScope(); 14282 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14283 return D; 14284 } 14285 14286 FunctionDecl *FD = nullptr; 14287 14288 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14289 FD = FunTmpl->getTemplatedDecl(); 14290 else 14291 FD = cast<FunctionDecl>(D); 14292 14293 // Do not push if it is a lambda because one is already pushed when building 14294 // the lambda in ActOnStartOfLambdaDefinition(). 14295 if (!isLambdaCallOperator(FD)) 14296 PushExpressionEvaluationContext( 14297 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14298 : ExprEvalContexts.back().Context); 14299 14300 // Check for defining attributes before the check for redefinition. 14301 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14302 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14303 FD->dropAttr<AliasAttr>(); 14304 FD->setInvalidDecl(); 14305 } 14306 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14307 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14308 FD->dropAttr<IFuncAttr>(); 14309 FD->setInvalidDecl(); 14310 } 14311 14312 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14313 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14314 Ctor->isDefaultConstructor() && 14315 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14316 // If this is an MS ABI dllexport default constructor, instantiate any 14317 // default arguments. 14318 InstantiateDefaultCtorDefaultArgs(Ctor); 14319 } 14320 } 14321 14322 // See if this is a redefinition. If 'will have body' (or similar) is already 14323 // set, then these checks were already performed when it was set. 14324 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14325 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14326 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14327 14328 // If we're skipping the body, we're done. Don't enter the scope. 14329 if (SkipBody && SkipBody->ShouldSkip) 14330 return D; 14331 } 14332 14333 // Mark this function as "will have a body eventually". This lets users to 14334 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14335 // this function. 14336 FD->setWillHaveBody(); 14337 14338 // If we are instantiating a generic lambda call operator, push 14339 // a LambdaScopeInfo onto the function stack. But use the information 14340 // that's already been calculated (ActOnLambdaExpr) to prime the current 14341 // LambdaScopeInfo. 14342 // When the template operator is being specialized, the LambdaScopeInfo, 14343 // has to be properly restored so that tryCaptureVariable doesn't try 14344 // and capture any new variables. In addition when calculating potential 14345 // captures during transformation of nested lambdas, it is necessary to 14346 // have the LSI properly restored. 14347 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14348 assert(inTemplateInstantiation() && 14349 "There should be an active template instantiation on the stack " 14350 "when instantiating a generic lambda!"); 14351 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14352 } else { 14353 // Enter a new function scope 14354 PushFunctionScope(); 14355 } 14356 14357 // Builtin functions cannot be defined. 14358 if (unsigned BuiltinID = FD->getBuiltinID()) { 14359 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14360 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14361 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14362 FD->setInvalidDecl(); 14363 } 14364 } 14365 14366 // The return type of a function definition must be complete 14367 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14368 QualType ResultType = FD->getReturnType(); 14369 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14370 !FD->isInvalidDecl() && 14371 RequireCompleteType(FD->getLocation(), ResultType, 14372 diag::err_func_def_incomplete_result)) 14373 FD->setInvalidDecl(); 14374 14375 if (FnBodyScope) 14376 PushDeclContext(FnBodyScope, FD); 14377 14378 // Check the validity of our function parameters 14379 CheckParmsForFunctionDef(FD->parameters(), 14380 /*CheckParameterNames=*/true); 14381 14382 // Add non-parameter declarations already in the function to the current 14383 // scope. 14384 if (FnBodyScope) { 14385 for (Decl *NPD : FD->decls()) { 14386 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14387 if (!NonParmDecl) 14388 continue; 14389 assert(!isa<ParmVarDecl>(NonParmDecl) && 14390 "parameters should not be in newly created FD yet"); 14391 14392 // If the decl has a name, make it accessible in the current scope. 14393 if (NonParmDecl->getDeclName()) 14394 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14395 14396 // Similarly, dive into enums and fish their constants out, making them 14397 // accessible in this scope. 14398 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14399 for (auto *EI : ED->enumerators()) 14400 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14401 } 14402 } 14403 } 14404 14405 // Introduce our parameters into the function scope 14406 for (auto Param : FD->parameters()) { 14407 Param->setOwningFunction(FD); 14408 14409 // If this has an identifier, add it to the scope stack. 14410 if (Param->getIdentifier() && FnBodyScope) { 14411 CheckShadow(FnBodyScope, Param); 14412 14413 PushOnScopeChains(Param, FnBodyScope); 14414 } 14415 } 14416 14417 // Ensure that the function's exception specification is instantiated. 14418 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14419 ResolveExceptionSpec(D->getLocation(), FPT); 14420 14421 // dllimport cannot be applied to non-inline function definitions. 14422 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14423 !FD->isTemplateInstantiation()) { 14424 assert(!FD->hasAttr<DLLExportAttr>()); 14425 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14426 FD->setInvalidDecl(); 14427 return D; 14428 } 14429 // We want to attach documentation to original Decl (which might be 14430 // a function template). 14431 ActOnDocumentableDecl(D); 14432 if (getCurLexicalContext()->isObjCContainer() && 14433 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14434 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14435 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14436 14437 return D; 14438 } 14439 14440 /// Given the set of return statements within a function body, 14441 /// compute the variables that are subject to the named return value 14442 /// optimization. 14443 /// 14444 /// Each of the variables that is subject to the named return value 14445 /// optimization will be marked as NRVO variables in the AST, and any 14446 /// return statement that has a marked NRVO variable as its NRVO candidate can 14447 /// use the named return value optimization. 14448 /// 14449 /// This function applies a very simplistic algorithm for NRVO: if every return 14450 /// statement in the scope of a variable has the same NRVO candidate, that 14451 /// candidate is an NRVO variable. 14452 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14453 ReturnStmt **Returns = Scope->Returns.data(); 14454 14455 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14456 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14457 if (!NRVOCandidate->isNRVOVariable()) 14458 Returns[I]->setNRVOCandidate(nullptr); 14459 } 14460 } 14461 } 14462 14463 bool Sema::canDelayFunctionBody(const Declarator &D) { 14464 // We can't delay parsing the body of a constexpr function template (yet). 14465 if (D.getDeclSpec().hasConstexprSpecifier()) 14466 return false; 14467 14468 // We can't delay parsing the body of a function template with a deduced 14469 // return type (yet). 14470 if (D.getDeclSpec().hasAutoTypeSpec()) { 14471 // If the placeholder introduces a non-deduced trailing return type, 14472 // we can still delay parsing it. 14473 if (D.getNumTypeObjects()) { 14474 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14475 if (Outer.Kind == DeclaratorChunk::Function && 14476 Outer.Fun.hasTrailingReturnType()) { 14477 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14478 return Ty.isNull() || !Ty->isUndeducedType(); 14479 } 14480 } 14481 return false; 14482 } 14483 14484 return true; 14485 } 14486 14487 bool Sema::canSkipFunctionBody(Decl *D) { 14488 // We cannot skip the body of a function (or function template) which is 14489 // constexpr, since we may need to evaluate its body in order to parse the 14490 // rest of the file. 14491 // We cannot skip the body of a function with an undeduced return type, 14492 // because any callers of that function need to know the type. 14493 if (const FunctionDecl *FD = D->getAsFunction()) { 14494 if (FD->isConstexpr()) 14495 return false; 14496 // We can't simply call Type::isUndeducedType here, because inside template 14497 // auto can be deduced to a dependent type, which is not considered 14498 // "undeduced". 14499 if (FD->getReturnType()->getContainedDeducedType()) 14500 return false; 14501 } 14502 return Consumer.shouldSkipFunctionBody(D); 14503 } 14504 14505 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14506 if (!Decl) 14507 return nullptr; 14508 if (FunctionDecl *FD = Decl->getAsFunction()) 14509 FD->setHasSkippedBody(); 14510 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14511 MD->setHasSkippedBody(); 14512 return Decl; 14513 } 14514 14515 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14516 return ActOnFinishFunctionBody(D, BodyArg, false); 14517 } 14518 14519 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14520 /// body. 14521 class ExitFunctionBodyRAII { 14522 public: 14523 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14524 ~ExitFunctionBodyRAII() { 14525 if (!IsLambda) 14526 S.PopExpressionEvaluationContext(); 14527 } 14528 14529 private: 14530 Sema &S; 14531 bool IsLambda = false; 14532 }; 14533 14534 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14535 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14536 14537 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14538 if (EscapeInfo.count(BD)) 14539 return EscapeInfo[BD]; 14540 14541 bool R = false; 14542 const BlockDecl *CurBD = BD; 14543 14544 do { 14545 R = !CurBD->doesNotEscape(); 14546 if (R) 14547 break; 14548 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14549 } while (CurBD); 14550 14551 return EscapeInfo[BD] = R; 14552 }; 14553 14554 // If the location where 'self' is implicitly retained is inside a escaping 14555 // block, emit a diagnostic. 14556 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14557 S.ImplicitlyRetainedSelfLocs) 14558 if (IsOrNestedInEscapingBlock(P.second)) 14559 S.Diag(P.first, diag::warn_implicitly_retains_self) 14560 << FixItHint::CreateInsertion(P.first, "self->"); 14561 } 14562 14563 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14564 bool IsInstantiation) { 14565 FunctionScopeInfo *FSI = getCurFunction(); 14566 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14567 14568 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14569 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14570 14571 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14572 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14573 14574 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14575 CheckCompletedCoroutineBody(FD, Body); 14576 14577 { 14578 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14579 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14580 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14581 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14582 14583 if (FD) { 14584 FD->setBody(Body); 14585 FD->setWillHaveBody(false); 14586 14587 if (getLangOpts().CPlusPlus14) { 14588 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14589 FD->getReturnType()->isUndeducedType()) { 14590 // If the function has a deduced result type but contains no 'return' 14591 // statements, the result type as written must be exactly 'auto', and 14592 // the deduced result type is 'void'. 14593 if (!FD->getReturnType()->getAs<AutoType>()) { 14594 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14595 << FD->getReturnType(); 14596 FD->setInvalidDecl(); 14597 } else { 14598 // Substitute 'void' for the 'auto' in the type. 14599 TypeLoc ResultType = getReturnTypeLoc(FD); 14600 Context.adjustDeducedFunctionResultType( 14601 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14602 } 14603 } 14604 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14605 // In C++11, we don't use 'auto' deduction rules for lambda call 14606 // operators because we don't support return type deduction. 14607 auto *LSI = getCurLambda(); 14608 if (LSI->HasImplicitReturnType) { 14609 deduceClosureReturnType(*LSI); 14610 14611 // C++11 [expr.prim.lambda]p4: 14612 // [...] if there are no return statements in the compound-statement 14613 // [the deduced type is] the type void 14614 QualType RetType = 14615 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14616 14617 // Update the return type to the deduced type. 14618 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14619 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14620 Proto->getExtProtoInfo())); 14621 } 14622 } 14623 14624 // If the function implicitly returns zero (like 'main') or is naked, 14625 // don't complain about missing return statements. 14626 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14627 WP.disableCheckFallThrough(); 14628 14629 // MSVC permits the use of pure specifier (=0) on function definition, 14630 // defined at class scope, warn about this non-standard construct. 14631 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14632 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14633 14634 if (!FD->isInvalidDecl()) { 14635 // Don't diagnose unused parameters of defaulted or deleted functions. 14636 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14637 DiagnoseUnusedParameters(FD->parameters()); 14638 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14639 FD->getReturnType(), FD); 14640 14641 // If this is a structor, we need a vtable. 14642 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14643 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14644 else if (CXXDestructorDecl *Destructor = 14645 dyn_cast<CXXDestructorDecl>(FD)) 14646 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14647 14648 // Try to apply the named return value optimization. We have to check 14649 // if we can do this here because lambdas keep return statements around 14650 // to deduce an implicit return type. 14651 if (FD->getReturnType()->isRecordType() && 14652 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14653 computeNRVO(Body, FSI); 14654 } 14655 14656 // GNU warning -Wmissing-prototypes: 14657 // Warn if a global function is defined without a previous 14658 // prototype declaration. This warning is issued even if the 14659 // definition itself provides a prototype. The aim is to detect 14660 // global functions that fail to be declared in header files. 14661 const FunctionDecl *PossiblePrototype = nullptr; 14662 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14663 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14664 14665 if (PossiblePrototype) { 14666 // We found a declaration that is not a prototype, 14667 // but that could be a zero-parameter prototype 14668 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14669 TypeLoc TL = TI->getTypeLoc(); 14670 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14671 Diag(PossiblePrototype->getLocation(), 14672 diag::note_declaration_not_a_prototype) 14673 << (FD->getNumParams() != 0) 14674 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 14675 FTL.getRParenLoc(), "void") 14676 : FixItHint{}); 14677 } 14678 } else { 14679 // Returns true if the token beginning at this Loc is `const`. 14680 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14681 const LangOptions &LangOpts) { 14682 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14683 if (LocInfo.first.isInvalid()) 14684 return false; 14685 14686 bool Invalid = false; 14687 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14688 if (Invalid) 14689 return false; 14690 14691 if (LocInfo.second > Buffer.size()) 14692 return false; 14693 14694 const char *LexStart = Buffer.data() + LocInfo.second; 14695 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14696 14697 return StartTok.consume_front("const") && 14698 (StartTok.empty() || isWhitespace(StartTok[0]) || 14699 StartTok.startswith("/*") || StartTok.startswith("//")); 14700 }; 14701 14702 auto findBeginLoc = [&]() { 14703 // If the return type has `const` qualifier, we want to insert 14704 // `static` before `const` (and not before the typename). 14705 if ((FD->getReturnType()->isAnyPointerType() && 14706 FD->getReturnType()->getPointeeType().isConstQualified()) || 14707 FD->getReturnType().isConstQualified()) { 14708 // But only do this if we can determine where the `const` is. 14709 14710 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14711 getLangOpts())) 14712 14713 return FD->getBeginLoc(); 14714 } 14715 return FD->getTypeSpecStartLoc(); 14716 }; 14717 Diag(FD->getTypeSpecStartLoc(), 14718 diag::note_static_for_internal_linkage) 14719 << /* function */ 1 14720 << (FD->getStorageClass() == SC_None 14721 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14722 : FixItHint{}); 14723 } 14724 14725 // GNU warning -Wstrict-prototypes 14726 // Warn if K&R function is defined without a previous declaration. 14727 // This warning is issued only if the definition itself does not 14728 // provide a prototype. Only K&R definitions do not provide a 14729 // prototype. 14730 if (!FD->hasWrittenPrototype()) { 14731 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14732 TypeLoc TL = TI->getTypeLoc(); 14733 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14734 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14735 } 14736 } 14737 14738 // Warn on CPUDispatch with an actual body. 14739 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14740 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14741 if (!CmpndBody->body_empty()) 14742 Diag(CmpndBody->body_front()->getBeginLoc(), 14743 diag::warn_dispatch_body_ignored); 14744 14745 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14746 const CXXMethodDecl *KeyFunction; 14747 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14748 MD->isVirtual() && 14749 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14750 MD == KeyFunction->getCanonicalDecl()) { 14751 // Update the key-function state if necessary for this ABI. 14752 if (FD->isInlined() && 14753 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14754 Context.setNonKeyFunction(MD); 14755 14756 // If the newly-chosen key function is already defined, then we 14757 // need to mark the vtable as used retroactively. 14758 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14759 const FunctionDecl *Definition; 14760 if (KeyFunction && KeyFunction->isDefined(Definition)) 14761 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14762 } else { 14763 // We just defined they key function; mark the vtable as used. 14764 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14765 } 14766 } 14767 } 14768 14769 assert( 14770 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14771 "Function parsing confused"); 14772 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14773 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14774 MD->setBody(Body); 14775 if (!MD->isInvalidDecl()) { 14776 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14777 MD->getReturnType(), MD); 14778 14779 if (Body) 14780 computeNRVO(Body, FSI); 14781 } 14782 if (FSI->ObjCShouldCallSuper) { 14783 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14784 << MD->getSelector().getAsString(); 14785 FSI->ObjCShouldCallSuper = false; 14786 } 14787 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14788 const ObjCMethodDecl *InitMethod = nullptr; 14789 bool isDesignated = 14790 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14791 assert(isDesignated && InitMethod); 14792 (void)isDesignated; 14793 14794 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14795 auto IFace = MD->getClassInterface(); 14796 if (!IFace) 14797 return false; 14798 auto SuperD = IFace->getSuperClass(); 14799 if (!SuperD) 14800 return false; 14801 return SuperD->getIdentifier() == 14802 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14803 }; 14804 // Don't issue this warning for unavailable inits or direct subclasses 14805 // of NSObject. 14806 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14807 Diag(MD->getLocation(), 14808 diag::warn_objc_designated_init_missing_super_call); 14809 Diag(InitMethod->getLocation(), 14810 diag::note_objc_designated_init_marked_here); 14811 } 14812 FSI->ObjCWarnForNoDesignatedInitChain = false; 14813 } 14814 if (FSI->ObjCWarnForNoInitDelegation) { 14815 // Don't issue this warning for unavaialable inits. 14816 if (!MD->isUnavailable()) 14817 Diag(MD->getLocation(), 14818 diag::warn_objc_secondary_init_missing_init_call); 14819 FSI->ObjCWarnForNoInitDelegation = false; 14820 } 14821 14822 diagnoseImplicitlyRetainedSelf(*this); 14823 } else { 14824 // Parsing the function declaration failed in some way. Pop the fake scope 14825 // we pushed on. 14826 PopFunctionScopeInfo(ActivePolicy, dcl); 14827 return nullptr; 14828 } 14829 14830 if (Body && FSI->HasPotentialAvailabilityViolations) 14831 DiagnoseUnguardedAvailabilityViolations(dcl); 14832 14833 assert(!FSI->ObjCShouldCallSuper && 14834 "This should only be set for ObjC methods, which should have been " 14835 "handled in the block above."); 14836 14837 // Verify and clean out per-function state. 14838 if (Body && (!FD || !FD->isDefaulted())) { 14839 // C++ constructors that have function-try-blocks can't have return 14840 // statements in the handlers of that block. (C++ [except.handle]p14) 14841 // Verify this. 14842 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14843 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14844 14845 // Verify that gotos and switch cases don't jump into scopes illegally. 14846 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 14847 DiagnoseInvalidJumps(Body); 14848 14849 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14850 if (!Destructor->getParent()->isDependentType()) 14851 CheckDestructor(Destructor); 14852 14853 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14854 Destructor->getParent()); 14855 } 14856 14857 // If any errors have occurred, clear out any temporaries that may have 14858 // been leftover. This ensures that these temporaries won't be picked up 14859 // for deletion in some later function. 14860 if (hasUncompilableErrorOccurred() || 14861 getDiagnostics().getSuppressAllDiagnostics()) { 14862 DiscardCleanupsInEvaluationContext(); 14863 } 14864 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 14865 // Since the body is valid, issue any analysis-based warnings that are 14866 // enabled. 14867 ActivePolicy = &WP; 14868 } 14869 14870 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14871 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14872 FD->setInvalidDecl(); 14873 14874 if (FD && FD->hasAttr<NakedAttr>()) { 14875 for (const Stmt *S : Body->children()) { 14876 // Allow local register variables without initializer as they don't 14877 // require prologue. 14878 bool RegisterVariables = false; 14879 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14880 for (const auto *Decl : DS->decls()) { 14881 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14882 RegisterVariables = 14883 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14884 if (!RegisterVariables) 14885 break; 14886 } 14887 } 14888 } 14889 if (RegisterVariables) 14890 continue; 14891 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14892 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14893 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14894 FD->setInvalidDecl(); 14895 break; 14896 } 14897 } 14898 } 14899 14900 assert(ExprCleanupObjects.size() == 14901 ExprEvalContexts.back().NumCleanupObjects && 14902 "Leftover temporaries in function"); 14903 assert(!Cleanup.exprNeedsCleanups() && 14904 "Unaccounted cleanups in function"); 14905 assert(MaybeODRUseExprs.empty() && 14906 "Leftover expressions for odr-use checking"); 14907 } 14908 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 14909 // the declaration context below. Otherwise, we're unable to transform 14910 // 'this' expressions when transforming immediate context functions. 14911 14912 if (!IsInstantiation) 14913 PopDeclContext(); 14914 14915 PopFunctionScopeInfo(ActivePolicy, dcl); 14916 // If any errors have occurred, clear out any temporaries that may have 14917 // been leftover. This ensures that these temporaries won't be picked up for 14918 // deletion in some later function. 14919 if (hasUncompilableErrorOccurred()) { 14920 DiscardCleanupsInEvaluationContext(); 14921 } 14922 14923 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 14924 !LangOpts.OMPTargetTriples.empty())) || 14925 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14926 auto ES = getEmissionStatus(FD); 14927 if (ES == Sema::FunctionEmissionStatus::Emitted || 14928 ES == Sema::FunctionEmissionStatus::Unknown) 14929 DeclsToCheckForDeferredDiags.insert(FD); 14930 } 14931 14932 if (FD && !FD->isDeleted()) 14933 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 14934 14935 return dcl; 14936 } 14937 14938 /// When we finish delayed parsing of an attribute, we must attach it to the 14939 /// relevant Decl. 14940 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14941 ParsedAttributes &Attrs) { 14942 // Always attach attributes to the underlying decl. 14943 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14944 D = TD->getTemplatedDecl(); 14945 ProcessDeclAttributeList(S, D, Attrs); 14946 14947 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14948 if (Method->isStatic()) 14949 checkThisInStaticMemberFunctionAttributes(Method); 14950 } 14951 14952 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14953 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14954 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14955 IdentifierInfo &II, Scope *S) { 14956 // Find the scope in which the identifier is injected and the corresponding 14957 // DeclContext. 14958 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14959 // In that case, we inject the declaration into the translation unit scope 14960 // instead. 14961 Scope *BlockScope = S; 14962 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14963 BlockScope = BlockScope->getParent(); 14964 14965 Scope *ContextScope = BlockScope; 14966 while (!ContextScope->getEntity()) 14967 ContextScope = ContextScope->getParent(); 14968 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14969 14970 // Before we produce a declaration for an implicitly defined 14971 // function, see whether there was a locally-scoped declaration of 14972 // this name as a function or variable. If so, use that 14973 // (non-visible) declaration, and complain about it. 14974 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14975 if (ExternCPrev) { 14976 // We still need to inject the function into the enclosing block scope so 14977 // that later (non-call) uses can see it. 14978 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14979 14980 // C89 footnote 38: 14981 // If in fact it is not defined as having type "function returning int", 14982 // the behavior is undefined. 14983 if (!isa<FunctionDecl>(ExternCPrev) || 14984 !Context.typesAreCompatible( 14985 cast<FunctionDecl>(ExternCPrev)->getType(), 14986 Context.getFunctionNoProtoType(Context.IntTy))) { 14987 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14988 << ExternCPrev << !getLangOpts().C99; 14989 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14990 return ExternCPrev; 14991 } 14992 } 14993 14994 // Extension in C99. Legal in C90, but warn about it. 14995 unsigned diag_id; 14996 if (II.getName().startswith("__builtin_")) 14997 diag_id = diag::warn_builtin_unknown; 14998 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14999 else if (getLangOpts().OpenCL) 15000 diag_id = diag::err_opencl_implicit_function_decl; 15001 else if (getLangOpts().C99) 15002 diag_id = diag::ext_implicit_function_decl; 15003 else 15004 diag_id = diag::warn_implicit_function_decl; 15005 Diag(Loc, diag_id) << &II; 15006 15007 // If we found a prior declaration of this function, don't bother building 15008 // another one. We've already pushed that one into scope, so there's nothing 15009 // more to do. 15010 if (ExternCPrev) 15011 return ExternCPrev; 15012 15013 // Because typo correction is expensive, only do it if the implicit 15014 // function declaration is going to be treated as an error. 15015 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 15016 TypoCorrection Corrected; 15017 DeclFilterCCC<FunctionDecl> CCC{}; 15018 if (S && (Corrected = 15019 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 15020 S, nullptr, CCC, CTK_NonError))) 15021 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 15022 /*ErrorRecovery*/false); 15023 } 15024 15025 // Set a Declarator for the implicit definition: int foo(); 15026 const char *Dummy; 15027 AttributeFactory attrFactory; 15028 DeclSpec DS(attrFactory); 15029 unsigned DiagID; 15030 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 15031 Context.getPrintingPolicy()); 15032 (void)Error; // Silence warning. 15033 assert(!Error && "Error setting up implicit decl!"); 15034 SourceLocation NoLoc; 15035 Declarator D(DS, DeclaratorContext::Block); 15036 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 15037 /*IsAmbiguous=*/false, 15038 /*LParenLoc=*/NoLoc, 15039 /*Params=*/nullptr, 15040 /*NumParams=*/0, 15041 /*EllipsisLoc=*/NoLoc, 15042 /*RParenLoc=*/NoLoc, 15043 /*RefQualifierIsLvalueRef=*/true, 15044 /*RefQualifierLoc=*/NoLoc, 15045 /*MutableLoc=*/NoLoc, EST_None, 15046 /*ESpecRange=*/SourceRange(), 15047 /*Exceptions=*/nullptr, 15048 /*ExceptionRanges=*/nullptr, 15049 /*NumExceptions=*/0, 15050 /*NoexceptExpr=*/nullptr, 15051 /*ExceptionSpecTokens=*/nullptr, 15052 /*DeclsInPrototype=*/None, Loc, 15053 Loc, D), 15054 std::move(DS.getAttributes()), SourceLocation()); 15055 D.SetIdentifier(&II, Loc); 15056 15057 // Insert this function into the enclosing block scope. 15058 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 15059 FD->setImplicit(); 15060 15061 AddKnownFunctionAttributes(FD); 15062 15063 return FD; 15064 } 15065 15066 /// If this function is a C++ replaceable global allocation function 15067 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15068 /// adds any function attributes that we know a priori based on the standard. 15069 /// 15070 /// We need to check for duplicate attributes both here and where user-written 15071 /// attributes are applied to declarations. 15072 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15073 FunctionDecl *FD) { 15074 if (FD->isInvalidDecl()) 15075 return; 15076 15077 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15078 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15079 return; 15080 15081 Optional<unsigned> AlignmentParam; 15082 bool IsNothrow = false; 15083 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15084 return; 15085 15086 // C++2a [basic.stc.dynamic.allocation]p4: 15087 // An allocation function that has a non-throwing exception specification 15088 // indicates failure by returning a null pointer value. Any other allocation 15089 // function never returns a null pointer value and indicates failure only by 15090 // throwing an exception [...] 15091 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15092 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15093 15094 // C++2a [basic.stc.dynamic.allocation]p2: 15095 // An allocation function attempts to allocate the requested amount of 15096 // storage. [...] If the request succeeds, the value returned by a 15097 // replaceable allocation function is a [...] pointer value p0 different 15098 // from any previously returned value p1 [...] 15099 // 15100 // However, this particular information is being added in codegen, 15101 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15102 15103 // C++2a [basic.stc.dynamic.allocation]p2: 15104 // An allocation function attempts to allocate the requested amount of 15105 // storage. If it is successful, it returns the address of the start of a 15106 // block of storage whose length in bytes is at least as large as the 15107 // requested size. 15108 if (!FD->hasAttr<AllocSizeAttr>()) { 15109 FD->addAttr(AllocSizeAttr::CreateImplicit( 15110 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15111 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15112 } 15113 15114 // C++2a [basic.stc.dynamic.allocation]p3: 15115 // For an allocation function [...], the pointer returned on a successful 15116 // call shall represent the address of storage that is aligned as follows: 15117 // (3.1) If the allocation function takes an argument of type 15118 // std::align_val_t, the storage will have the alignment 15119 // specified by the value of this argument. 15120 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15121 FD->addAttr(AllocAlignAttr::CreateImplicit( 15122 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15123 } 15124 15125 // FIXME: 15126 // C++2a [basic.stc.dynamic.allocation]p3: 15127 // For an allocation function [...], the pointer returned on a successful 15128 // call shall represent the address of storage that is aligned as follows: 15129 // (3.2) Otherwise, if the allocation function is named operator new[], 15130 // the storage is aligned for any object that does not have 15131 // new-extended alignment ([basic.align]) and is no larger than the 15132 // requested size. 15133 // (3.3) Otherwise, the storage is aligned for any object that does not 15134 // have new-extended alignment and is of the requested size. 15135 } 15136 15137 /// Adds any function attributes that we know a priori based on 15138 /// the declaration of this function. 15139 /// 15140 /// These attributes can apply both to implicitly-declared builtins 15141 /// (like __builtin___printf_chk) or to library-declared functions 15142 /// like NSLog or printf. 15143 /// 15144 /// We need to check for duplicate attributes both here and where user-written 15145 /// attributes are applied to declarations. 15146 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15147 if (FD->isInvalidDecl()) 15148 return; 15149 15150 // If this is a built-in function, map its builtin attributes to 15151 // actual attributes. 15152 if (unsigned BuiltinID = FD->getBuiltinID()) { 15153 // Handle printf-formatting attributes. 15154 unsigned FormatIdx; 15155 bool HasVAListArg; 15156 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15157 if (!FD->hasAttr<FormatAttr>()) { 15158 const char *fmt = "printf"; 15159 unsigned int NumParams = FD->getNumParams(); 15160 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15161 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15162 fmt = "NSString"; 15163 FD->addAttr(FormatAttr::CreateImplicit(Context, 15164 &Context.Idents.get(fmt), 15165 FormatIdx+1, 15166 HasVAListArg ? 0 : FormatIdx+2, 15167 FD->getLocation())); 15168 } 15169 } 15170 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15171 HasVAListArg)) { 15172 if (!FD->hasAttr<FormatAttr>()) 15173 FD->addAttr(FormatAttr::CreateImplicit(Context, 15174 &Context.Idents.get("scanf"), 15175 FormatIdx+1, 15176 HasVAListArg ? 0 : FormatIdx+2, 15177 FD->getLocation())); 15178 } 15179 15180 // Handle automatically recognized callbacks. 15181 SmallVector<int, 4> Encoding; 15182 if (!FD->hasAttr<CallbackAttr>() && 15183 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15184 FD->addAttr(CallbackAttr::CreateImplicit( 15185 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15186 15187 // Mark const if we don't care about errno and that is the only thing 15188 // preventing the function from being const. This allows IRgen to use LLVM 15189 // intrinsics for such functions. 15190 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15191 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15192 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15193 15194 // We make "fma" on some platforms const because we know it does not set 15195 // errno in those environments even though it could set errno based on the 15196 // C standard. 15197 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15198 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 15199 !FD->hasAttr<ConstAttr>()) { 15200 switch (BuiltinID) { 15201 case Builtin::BI__builtin_fma: 15202 case Builtin::BI__builtin_fmaf: 15203 case Builtin::BI__builtin_fmal: 15204 case Builtin::BIfma: 15205 case Builtin::BIfmaf: 15206 case Builtin::BIfmal: 15207 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15208 break; 15209 default: 15210 break; 15211 } 15212 } 15213 15214 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15215 !FD->hasAttr<ReturnsTwiceAttr>()) 15216 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15217 FD->getLocation())); 15218 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15219 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15220 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15221 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15222 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15223 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15224 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15225 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15226 // Add the appropriate attribute, depending on the CUDA compilation mode 15227 // and which target the builtin belongs to. For example, during host 15228 // compilation, aux builtins are __device__, while the rest are __host__. 15229 if (getLangOpts().CUDAIsDevice != 15230 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15231 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15232 else 15233 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15234 } 15235 15236 // Add known guaranteed alignment for allocation functions. 15237 switch (BuiltinID) { 15238 case Builtin::BIaligned_alloc: 15239 if (!FD->hasAttr<AllocAlignAttr>()) 15240 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15241 FD->getLocation())); 15242 LLVM_FALLTHROUGH; 15243 case Builtin::BIcalloc: 15244 case Builtin::BImalloc: 15245 case Builtin::BImemalign: 15246 case Builtin::BIrealloc: 15247 case Builtin::BIstrdup: 15248 case Builtin::BIstrndup: { 15249 if (!FD->hasAttr<AssumeAlignedAttr>()) { 15250 unsigned NewAlign = Context.getTargetInfo().getNewAlign() / 15251 Context.getTargetInfo().getCharWidth(); 15252 IntegerLiteral *Alignment = IntegerLiteral::Create( 15253 Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy), 15254 Context.UnsignedIntTy, FD->getLocation()); 15255 FD->addAttr(AssumeAlignedAttr::CreateImplicit( 15256 Context, Alignment, /*Offset=*/nullptr, FD->getLocation())); 15257 } 15258 break; 15259 } 15260 default: 15261 break; 15262 } 15263 } 15264 15265 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15266 15267 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15268 // throw, add an implicit nothrow attribute to any extern "C" function we come 15269 // across. 15270 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15271 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15272 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15273 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15274 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15275 } 15276 15277 IdentifierInfo *Name = FD->getIdentifier(); 15278 if (!Name) 15279 return; 15280 if ((!getLangOpts().CPlusPlus && 15281 FD->getDeclContext()->isTranslationUnit()) || 15282 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15283 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15284 LinkageSpecDecl::lang_c)) { 15285 // Okay: this could be a libc/libm/Objective-C function we know 15286 // about. 15287 } else 15288 return; 15289 15290 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15291 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15292 // target-specific builtins, perhaps? 15293 if (!FD->hasAttr<FormatAttr>()) 15294 FD->addAttr(FormatAttr::CreateImplicit(Context, 15295 &Context.Idents.get("printf"), 2, 15296 Name->isStr("vasprintf") ? 0 : 3, 15297 FD->getLocation())); 15298 } 15299 15300 if (Name->isStr("__CFStringMakeConstantString")) { 15301 // We already have a __builtin___CFStringMakeConstantString, 15302 // but builds that use -fno-constant-cfstrings don't go through that. 15303 if (!FD->hasAttr<FormatArgAttr>()) 15304 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15305 FD->getLocation())); 15306 } 15307 } 15308 15309 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15310 TypeSourceInfo *TInfo) { 15311 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15312 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15313 15314 if (!TInfo) { 15315 assert(D.isInvalidType() && "no declarator info for valid type"); 15316 TInfo = Context.getTrivialTypeSourceInfo(T); 15317 } 15318 15319 // Scope manipulation handled by caller. 15320 TypedefDecl *NewTD = 15321 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15322 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15323 15324 // Bail out immediately if we have an invalid declaration. 15325 if (D.isInvalidType()) { 15326 NewTD->setInvalidDecl(); 15327 return NewTD; 15328 } 15329 15330 if (D.getDeclSpec().isModulePrivateSpecified()) { 15331 if (CurContext->isFunctionOrMethod()) 15332 Diag(NewTD->getLocation(), diag::err_module_private_local) 15333 << 2 << NewTD 15334 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15335 << FixItHint::CreateRemoval( 15336 D.getDeclSpec().getModulePrivateSpecLoc()); 15337 else 15338 NewTD->setModulePrivate(); 15339 } 15340 15341 // C++ [dcl.typedef]p8: 15342 // If the typedef declaration defines an unnamed class (or 15343 // enum), the first typedef-name declared by the declaration 15344 // to be that class type (or enum type) is used to denote the 15345 // class type (or enum type) for linkage purposes only. 15346 // We need to check whether the type was declared in the declaration. 15347 switch (D.getDeclSpec().getTypeSpecType()) { 15348 case TST_enum: 15349 case TST_struct: 15350 case TST_interface: 15351 case TST_union: 15352 case TST_class: { 15353 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15354 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15355 break; 15356 } 15357 15358 default: 15359 break; 15360 } 15361 15362 return NewTD; 15363 } 15364 15365 /// Check that this is a valid underlying type for an enum declaration. 15366 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15367 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15368 QualType T = TI->getType(); 15369 15370 if (T->isDependentType()) 15371 return false; 15372 15373 // This doesn't use 'isIntegralType' despite the error message mentioning 15374 // integral type because isIntegralType would also allow enum types in C. 15375 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15376 if (BT->isInteger()) 15377 return false; 15378 15379 if (T->isBitIntType()) 15380 return false; 15381 15382 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15383 } 15384 15385 /// Check whether this is a valid redeclaration of a previous enumeration. 15386 /// \return true if the redeclaration was invalid. 15387 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15388 QualType EnumUnderlyingTy, bool IsFixed, 15389 const EnumDecl *Prev) { 15390 if (IsScoped != Prev->isScoped()) { 15391 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15392 << Prev->isScoped(); 15393 Diag(Prev->getLocation(), diag::note_previous_declaration); 15394 return true; 15395 } 15396 15397 if (IsFixed && Prev->isFixed()) { 15398 if (!EnumUnderlyingTy->isDependentType() && 15399 !Prev->getIntegerType()->isDependentType() && 15400 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15401 Prev->getIntegerType())) { 15402 // TODO: Highlight the underlying type of the redeclaration. 15403 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15404 << EnumUnderlyingTy << Prev->getIntegerType(); 15405 Diag(Prev->getLocation(), diag::note_previous_declaration) 15406 << Prev->getIntegerTypeRange(); 15407 return true; 15408 } 15409 } else if (IsFixed != Prev->isFixed()) { 15410 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15411 << Prev->isFixed(); 15412 Diag(Prev->getLocation(), diag::note_previous_declaration); 15413 return true; 15414 } 15415 15416 return false; 15417 } 15418 15419 /// Get diagnostic %select index for tag kind for 15420 /// redeclaration diagnostic message. 15421 /// WARNING: Indexes apply to particular diagnostics only! 15422 /// 15423 /// \returns diagnostic %select index. 15424 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15425 switch (Tag) { 15426 case TTK_Struct: return 0; 15427 case TTK_Interface: return 1; 15428 case TTK_Class: return 2; 15429 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15430 } 15431 } 15432 15433 /// Determine if tag kind is a class-key compatible with 15434 /// class for redeclaration (class, struct, or __interface). 15435 /// 15436 /// \returns true iff the tag kind is compatible. 15437 static bool isClassCompatTagKind(TagTypeKind Tag) 15438 { 15439 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15440 } 15441 15442 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15443 TagTypeKind TTK) { 15444 if (isa<TypedefDecl>(PrevDecl)) 15445 return NTK_Typedef; 15446 else if (isa<TypeAliasDecl>(PrevDecl)) 15447 return NTK_TypeAlias; 15448 else if (isa<ClassTemplateDecl>(PrevDecl)) 15449 return NTK_Template; 15450 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15451 return NTK_TypeAliasTemplate; 15452 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15453 return NTK_TemplateTemplateArgument; 15454 switch (TTK) { 15455 case TTK_Struct: 15456 case TTK_Interface: 15457 case TTK_Class: 15458 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15459 case TTK_Union: 15460 return NTK_NonUnion; 15461 case TTK_Enum: 15462 return NTK_NonEnum; 15463 } 15464 llvm_unreachable("invalid TTK"); 15465 } 15466 15467 /// Determine whether a tag with a given kind is acceptable 15468 /// as a redeclaration of the given tag declaration. 15469 /// 15470 /// \returns true if the new tag kind is acceptable, false otherwise. 15471 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15472 TagTypeKind NewTag, bool isDefinition, 15473 SourceLocation NewTagLoc, 15474 const IdentifierInfo *Name) { 15475 // C++ [dcl.type.elab]p3: 15476 // The class-key or enum keyword present in the 15477 // elaborated-type-specifier shall agree in kind with the 15478 // declaration to which the name in the elaborated-type-specifier 15479 // refers. This rule also applies to the form of 15480 // elaborated-type-specifier that declares a class-name or 15481 // friend class since it can be construed as referring to the 15482 // definition of the class. Thus, in any 15483 // elaborated-type-specifier, the enum keyword shall be used to 15484 // refer to an enumeration (7.2), the union class-key shall be 15485 // used to refer to a union (clause 9), and either the class or 15486 // struct class-key shall be used to refer to a class (clause 9) 15487 // declared using the class or struct class-key. 15488 TagTypeKind OldTag = Previous->getTagKind(); 15489 if (OldTag != NewTag && 15490 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15491 return false; 15492 15493 // Tags are compatible, but we might still want to warn on mismatched tags. 15494 // Non-class tags can't be mismatched at this point. 15495 if (!isClassCompatTagKind(NewTag)) 15496 return true; 15497 15498 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15499 // by our warning analysis. We don't want to warn about mismatches with (eg) 15500 // declarations in system headers that are designed to be specialized, but if 15501 // a user asks us to warn, we should warn if their code contains mismatched 15502 // declarations. 15503 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15504 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15505 Loc); 15506 }; 15507 if (IsIgnoredLoc(NewTagLoc)) 15508 return true; 15509 15510 auto IsIgnored = [&](const TagDecl *Tag) { 15511 return IsIgnoredLoc(Tag->getLocation()); 15512 }; 15513 while (IsIgnored(Previous)) { 15514 Previous = Previous->getPreviousDecl(); 15515 if (!Previous) 15516 return true; 15517 OldTag = Previous->getTagKind(); 15518 } 15519 15520 bool isTemplate = false; 15521 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15522 isTemplate = Record->getDescribedClassTemplate(); 15523 15524 if (inTemplateInstantiation()) { 15525 if (OldTag != NewTag) { 15526 // In a template instantiation, do not offer fix-its for tag mismatches 15527 // since they usually mess up the template instead of fixing the problem. 15528 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15529 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15530 << getRedeclDiagFromTagKind(OldTag); 15531 // FIXME: Note previous location? 15532 } 15533 return true; 15534 } 15535 15536 if (isDefinition) { 15537 // On definitions, check all previous tags and issue a fix-it for each 15538 // one that doesn't match the current tag. 15539 if (Previous->getDefinition()) { 15540 // Don't suggest fix-its for redefinitions. 15541 return true; 15542 } 15543 15544 bool previousMismatch = false; 15545 for (const TagDecl *I : Previous->redecls()) { 15546 if (I->getTagKind() != NewTag) { 15547 // Ignore previous declarations for which the warning was disabled. 15548 if (IsIgnored(I)) 15549 continue; 15550 15551 if (!previousMismatch) { 15552 previousMismatch = true; 15553 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15554 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15555 << getRedeclDiagFromTagKind(I->getTagKind()); 15556 } 15557 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15558 << getRedeclDiagFromTagKind(NewTag) 15559 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15560 TypeWithKeyword::getTagTypeKindName(NewTag)); 15561 } 15562 } 15563 return true; 15564 } 15565 15566 // Identify the prevailing tag kind: this is the kind of the definition (if 15567 // there is a non-ignored definition), or otherwise the kind of the prior 15568 // (non-ignored) declaration. 15569 const TagDecl *PrevDef = Previous->getDefinition(); 15570 if (PrevDef && IsIgnored(PrevDef)) 15571 PrevDef = nullptr; 15572 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15573 if (Redecl->getTagKind() != NewTag) { 15574 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15575 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15576 << getRedeclDiagFromTagKind(OldTag); 15577 Diag(Redecl->getLocation(), diag::note_previous_use); 15578 15579 // If there is a previous definition, suggest a fix-it. 15580 if (PrevDef) { 15581 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15582 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15583 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15584 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15585 } 15586 } 15587 15588 return true; 15589 } 15590 15591 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15592 /// from an outer enclosing namespace or file scope inside a friend declaration. 15593 /// This should provide the commented out code in the following snippet: 15594 /// namespace N { 15595 /// struct X; 15596 /// namespace M { 15597 /// struct Y { friend struct /*N::*/ X; }; 15598 /// } 15599 /// } 15600 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15601 SourceLocation NameLoc) { 15602 // While the decl is in a namespace, do repeated lookup of that name and see 15603 // if we get the same namespace back. If we do not, continue until 15604 // translation unit scope, at which point we have a fully qualified NNS. 15605 SmallVector<IdentifierInfo *, 4> Namespaces; 15606 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15607 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15608 // This tag should be declared in a namespace, which can only be enclosed by 15609 // other namespaces. Bail if there's an anonymous namespace in the chain. 15610 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15611 if (!Namespace || Namespace->isAnonymousNamespace()) 15612 return FixItHint(); 15613 IdentifierInfo *II = Namespace->getIdentifier(); 15614 Namespaces.push_back(II); 15615 NamedDecl *Lookup = SemaRef.LookupSingleName( 15616 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15617 if (Lookup == Namespace) 15618 break; 15619 } 15620 15621 // Once we have all the namespaces, reverse them to go outermost first, and 15622 // build an NNS. 15623 SmallString<64> Insertion; 15624 llvm::raw_svector_ostream OS(Insertion); 15625 if (DC->isTranslationUnit()) 15626 OS << "::"; 15627 std::reverse(Namespaces.begin(), Namespaces.end()); 15628 for (auto *II : Namespaces) 15629 OS << II->getName() << "::"; 15630 return FixItHint::CreateInsertion(NameLoc, Insertion); 15631 } 15632 15633 /// Determine whether a tag originally declared in context \p OldDC can 15634 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15635 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15636 /// using-declaration). 15637 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15638 DeclContext *NewDC) { 15639 OldDC = OldDC->getRedeclContext(); 15640 NewDC = NewDC->getRedeclContext(); 15641 15642 if (OldDC->Equals(NewDC)) 15643 return true; 15644 15645 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15646 // encloses the other). 15647 if (S.getLangOpts().MSVCCompat && 15648 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15649 return true; 15650 15651 return false; 15652 } 15653 15654 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15655 /// former case, Name will be non-null. In the later case, Name will be null. 15656 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15657 /// reference/declaration/definition of a tag. 15658 /// 15659 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15660 /// trailing-type-specifier) other than one in an alias-declaration. 15661 /// 15662 /// \param SkipBody If non-null, will be set to indicate if the caller should 15663 /// skip the definition of this tag and treat it as if it were a declaration. 15664 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15665 SourceLocation KWLoc, CXXScopeSpec &SS, 15666 IdentifierInfo *Name, SourceLocation NameLoc, 15667 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15668 SourceLocation ModulePrivateLoc, 15669 MultiTemplateParamsArg TemplateParameterLists, 15670 bool &OwnedDecl, bool &IsDependent, 15671 SourceLocation ScopedEnumKWLoc, 15672 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15673 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15674 SkipBodyInfo *SkipBody) { 15675 // If this is not a definition, it must have a name. 15676 IdentifierInfo *OrigName = Name; 15677 assert((Name != nullptr || TUK == TUK_Definition) && 15678 "Nameless record must be a definition!"); 15679 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15680 15681 OwnedDecl = false; 15682 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15683 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15684 15685 // FIXME: Check member specializations more carefully. 15686 bool isMemberSpecialization = false; 15687 bool Invalid = false; 15688 15689 // We only need to do this matching if we have template parameters 15690 // or a scope specifier, which also conveniently avoids this work 15691 // for non-C++ cases. 15692 if (TemplateParameterLists.size() > 0 || 15693 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15694 if (TemplateParameterList *TemplateParams = 15695 MatchTemplateParametersToScopeSpecifier( 15696 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15697 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15698 if (Kind == TTK_Enum) { 15699 Diag(KWLoc, diag::err_enum_template); 15700 return nullptr; 15701 } 15702 15703 if (TemplateParams->size() > 0) { 15704 // This is a declaration or definition of a class template (which may 15705 // be a member of another template). 15706 15707 if (Invalid) 15708 return nullptr; 15709 15710 OwnedDecl = false; 15711 DeclResult Result = CheckClassTemplate( 15712 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15713 AS, ModulePrivateLoc, 15714 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15715 TemplateParameterLists.data(), SkipBody); 15716 return Result.get(); 15717 } else { 15718 // The "template<>" header is extraneous. 15719 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15720 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15721 isMemberSpecialization = true; 15722 } 15723 } 15724 15725 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15726 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15727 return nullptr; 15728 } 15729 15730 // Figure out the underlying type if this a enum declaration. We need to do 15731 // this early, because it's needed to detect if this is an incompatible 15732 // redeclaration. 15733 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15734 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15735 15736 if (Kind == TTK_Enum) { 15737 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15738 // No underlying type explicitly specified, or we failed to parse the 15739 // type, default to int. 15740 EnumUnderlying = Context.IntTy.getTypePtr(); 15741 } else if (UnderlyingType.get()) { 15742 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15743 // integral type; any cv-qualification is ignored. 15744 TypeSourceInfo *TI = nullptr; 15745 GetTypeFromParser(UnderlyingType.get(), &TI); 15746 EnumUnderlying = TI; 15747 15748 if (CheckEnumUnderlyingType(TI)) 15749 // Recover by falling back to int. 15750 EnumUnderlying = Context.IntTy.getTypePtr(); 15751 15752 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15753 UPPC_FixedUnderlyingType)) 15754 EnumUnderlying = Context.IntTy.getTypePtr(); 15755 15756 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15757 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15758 // of 'int'. However, if this is an unfixed forward declaration, don't set 15759 // the underlying type unless the user enables -fms-compatibility. This 15760 // makes unfixed forward declared enums incomplete and is more conforming. 15761 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15762 EnumUnderlying = Context.IntTy.getTypePtr(); 15763 } 15764 } 15765 15766 DeclContext *SearchDC = CurContext; 15767 DeclContext *DC = CurContext; 15768 bool isStdBadAlloc = false; 15769 bool isStdAlignValT = false; 15770 15771 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15772 if (TUK == TUK_Friend || TUK == TUK_Reference) 15773 Redecl = NotForRedeclaration; 15774 15775 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15776 /// implemented asks for structural equivalence checking, the returned decl 15777 /// here is passed back to the parser, allowing the tag body to be parsed. 15778 auto createTagFromNewDecl = [&]() -> TagDecl * { 15779 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15780 // If there is an identifier, use the location of the identifier as the 15781 // location of the decl, otherwise use the location of the struct/union 15782 // keyword. 15783 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15784 TagDecl *New = nullptr; 15785 15786 if (Kind == TTK_Enum) { 15787 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15788 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15789 // If this is an undefined enum, bail. 15790 if (TUK != TUK_Definition && !Invalid) 15791 return nullptr; 15792 if (EnumUnderlying) { 15793 EnumDecl *ED = cast<EnumDecl>(New); 15794 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15795 ED->setIntegerTypeSourceInfo(TI); 15796 else 15797 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15798 ED->setPromotionType(ED->getIntegerType()); 15799 } 15800 } else { // struct/union 15801 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15802 nullptr); 15803 } 15804 15805 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15806 // Add alignment attributes if necessary; these attributes are checked 15807 // when the ASTContext lays out the structure. 15808 // 15809 // It is important for implementing the correct semantics that this 15810 // happen here (in ActOnTag). The #pragma pack stack is 15811 // maintained as a result of parser callbacks which can occur at 15812 // many points during the parsing of a struct declaration (because 15813 // the #pragma tokens are effectively skipped over during the 15814 // parsing of the struct). 15815 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15816 AddAlignmentAttributesForRecord(RD); 15817 AddMsStructLayoutForRecord(RD); 15818 } 15819 } 15820 New->setLexicalDeclContext(CurContext); 15821 return New; 15822 }; 15823 15824 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15825 if (Name && SS.isNotEmpty()) { 15826 // We have a nested-name tag ('struct foo::bar'). 15827 15828 // Check for invalid 'foo::'. 15829 if (SS.isInvalid()) { 15830 Name = nullptr; 15831 goto CreateNewDecl; 15832 } 15833 15834 // If this is a friend or a reference to a class in a dependent 15835 // context, don't try to make a decl for it. 15836 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15837 DC = computeDeclContext(SS, false); 15838 if (!DC) { 15839 IsDependent = true; 15840 return nullptr; 15841 } 15842 } else { 15843 DC = computeDeclContext(SS, true); 15844 if (!DC) { 15845 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15846 << SS.getRange(); 15847 return nullptr; 15848 } 15849 } 15850 15851 if (RequireCompleteDeclContext(SS, DC)) 15852 return nullptr; 15853 15854 SearchDC = DC; 15855 // Look-up name inside 'foo::'. 15856 LookupQualifiedName(Previous, DC); 15857 15858 if (Previous.isAmbiguous()) 15859 return nullptr; 15860 15861 if (Previous.empty()) { 15862 // Name lookup did not find anything. However, if the 15863 // nested-name-specifier refers to the current instantiation, 15864 // and that current instantiation has any dependent base 15865 // classes, we might find something at instantiation time: treat 15866 // this as a dependent elaborated-type-specifier. 15867 // But this only makes any sense for reference-like lookups. 15868 if (Previous.wasNotFoundInCurrentInstantiation() && 15869 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15870 IsDependent = true; 15871 return nullptr; 15872 } 15873 15874 // A tag 'foo::bar' must already exist. 15875 Diag(NameLoc, diag::err_not_tag_in_scope) 15876 << Kind << Name << DC << SS.getRange(); 15877 Name = nullptr; 15878 Invalid = true; 15879 goto CreateNewDecl; 15880 } 15881 } else if (Name) { 15882 // C++14 [class.mem]p14: 15883 // If T is the name of a class, then each of the following shall have a 15884 // name different from T: 15885 // -- every member of class T that is itself a type 15886 if (TUK != TUK_Reference && TUK != TUK_Friend && 15887 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15888 return nullptr; 15889 15890 // If this is a named struct, check to see if there was a previous forward 15891 // declaration or definition. 15892 // FIXME: We're looking into outer scopes here, even when we 15893 // shouldn't be. Doing so can result in ambiguities that we 15894 // shouldn't be diagnosing. 15895 LookupName(Previous, S); 15896 15897 // When declaring or defining a tag, ignore ambiguities introduced 15898 // by types using'ed into this scope. 15899 if (Previous.isAmbiguous() && 15900 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15901 LookupResult::Filter F = Previous.makeFilter(); 15902 while (F.hasNext()) { 15903 NamedDecl *ND = F.next(); 15904 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15905 SearchDC->getRedeclContext())) 15906 F.erase(); 15907 } 15908 F.done(); 15909 } 15910 15911 // C++11 [namespace.memdef]p3: 15912 // If the name in a friend declaration is neither qualified nor 15913 // a template-id and the declaration is a function or an 15914 // elaborated-type-specifier, the lookup to determine whether 15915 // the entity has been previously declared shall not consider 15916 // any scopes outside the innermost enclosing namespace. 15917 // 15918 // MSVC doesn't implement the above rule for types, so a friend tag 15919 // declaration may be a redeclaration of a type declared in an enclosing 15920 // scope. They do implement this rule for friend functions. 15921 // 15922 // Does it matter that this should be by scope instead of by 15923 // semantic context? 15924 if (!Previous.empty() && TUK == TUK_Friend) { 15925 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15926 LookupResult::Filter F = Previous.makeFilter(); 15927 bool FriendSawTagOutsideEnclosingNamespace = false; 15928 while (F.hasNext()) { 15929 NamedDecl *ND = F.next(); 15930 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15931 if (DC->isFileContext() && 15932 !EnclosingNS->Encloses(ND->getDeclContext())) { 15933 if (getLangOpts().MSVCCompat) 15934 FriendSawTagOutsideEnclosingNamespace = true; 15935 else 15936 F.erase(); 15937 } 15938 } 15939 F.done(); 15940 15941 // Diagnose this MSVC extension in the easy case where lookup would have 15942 // unambiguously found something outside the enclosing namespace. 15943 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15944 NamedDecl *ND = Previous.getFoundDecl(); 15945 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15946 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15947 } 15948 } 15949 15950 // Note: there used to be some attempt at recovery here. 15951 if (Previous.isAmbiguous()) 15952 return nullptr; 15953 15954 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15955 // FIXME: This makes sure that we ignore the contexts associated 15956 // with C structs, unions, and enums when looking for a matching 15957 // tag declaration or definition. See the similar lookup tweak 15958 // in Sema::LookupName; is there a better way to deal with this? 15959 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15960 SearchDC = SearchDC->getParent(); 15961 } 15962 } 15963 15964 if (Previous.isSingleResult() && 15965 Previous.getFoundDecl()->isTemplateParameter()) { 15966 // Maybe we will complain about the shadowed template parameter. 15967 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15968 // Just pretend that we didn't see the previous declaration. 15969 Previous.clear(); 15970 } 15971 15972 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15973 DC->Equals(getStdNamespace())) { 15974 if (Name->isStr("bad_alloc")) { 15975 // This is a declaration of or a reference to "std::bad_alloc". 15976 isStdBadAlloc = true; 15977 15978 // If std::bad_alloc has been implicitly declared (but made invisible to 15979 // name lookup), fill in this implicit declaration as the previous 15980 // declaration, so that the declarations get chained appropriately. 15981 if (Previous.empty() && StdBadAlloc) 15982 Previous.addDecl(getStdBadAlloc()); 15983 } else if (Name->isStr("align_val_t")) { 15984 isStdAlignValT = true; 15985 if (Previous.empty() && StdAlignValT) 15986 Previous.addDecl(getStdAlignValT()); 15987 } 15988 } 15989 15990 // If we didn't find a previous declaration, and this is a reference 15991 // (or friend reference), move to the correct scope. In C++, we 15992 // also need to do a redeclaration lookup there, just in case 15993 // there's a shadow friend decl. 15994 if (Name && Previous.empty() && 15995 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15996 if (Invalid) goto CreateNewDecl; 15997 assert(SS.isEmpty()); 15998 15999 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 16000 // C++ [basic.scope.pdecl]p5: 16001 // -- for an elaborated-type-specifier of the form 16002 // 16003 // class-key identifier 16004 // 16005 // if the elaborated-type-specifier is used in the 16006 // decl-specifier-seq or parameter-declaration-clause of a 16007 // function defined in namespace scope, the identifier is 16008 // declared as a class-name in the namespace that contains 16009 // the declaration; otherwise, except as a friend 16010 // declaration, the identifier is declared in the smallest 16011 // non-class, non-function-prototype scope that contains the 16012 // declaration. 16013 // 16014 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 16015 // C structs and unions. 16016 // 16017 // It is an error in C++ to declare (rather than define) an enum 16018 // type, including via an elaborated type specifier. We'll 16019 // diagnose that later; for now, declare the enum in the same 16020 // scope as we would have picked for any other tag type. 16021 // 16022 // GNU C also supports this behavior as part of its incomplete 16023 // enum types extension, while GNU C++ does not. 16024 // 16025 // Find the context where we'll be declaring the tag. 16026 // FIXME: We would like to maintain the current DeclContext as the 16027 // lexical context, 16028 SearchDC = getTagInjectionContext(SearchDC); 16029 16030 // Find the scope where we'll be declaring the tag. 16031 S = getTagInjectionScope(S, getLangOpts()); 16032 } else { 16033 assert(TUK == TUK_Friend); 16034 // C++ [namespace.memdef]p3: 16035 // If a friend declaration in a non-local class first declares a 16036 // class or function, the friend class or function is a member of 16037 // the innermost enclosing namespace. 16038 SearchDC = SearchDC->getEnclosingNamespaceContext(); 16039 } 16040 16041 // In C++, we need to do a redeclaration lookup to properly 16042 // diagnose some problems. 16043 // FIXME: redeclaration lookup is also used (with and without C++) to find a 16044 // hidden declaration so that we don't get ambiguity errors when using a 16045 // type declared by an elaborated-type-specifier. In C that is not correct 16046 // and we should instead merge compatible types found by lookup. 16047 if (getLangOpts().CPlusPlus) { 16048 // FIXME: This can perform qualified lookups into function contexts, 16049 // which are meaningless. 16050 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16051 LookupQualifiedName(Previous, SearchDC); 16052 } else { 16053 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16054 LookupName(Previous, S); 16055 } 16056 } 16057 16058 // If we have a known previous declaration to use, then use it. 16059 if (Previous.empty() && SkipBody && SkipBody->Previous) 16060 Previous.addDecl(SkipBody->Previous); 16061 16062 if (!Previous.empty()) { 16063 NamedDecl *PrevDecl = Previous.getFoundDecl(); 16064 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 16065 16066 // It's okay to have a tag decl in the same scope as a typedef 16067 // which hides a tag decl in the same scope. Finding this 16068 // with a redeclaration lookup can only actually happen in C++. 16069 // 16070 // This is also okay for elaborated-type-specifiers, which is 16071 // technically forbidden by the current standard but which is 16072 // okay according to the likely resolution of an open issue; 16073 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16074 if (getLangOpts().CPlusPlus) { 16075 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16076 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16077 TagDecl *Tag = TT->getDecl(); 16078 if (Tag->getDeclName() == Name && 16079 Tag->getDeclContext()->getRedeclContext() 16080 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16081 PrevDecl = Tag; 16082 Previous.clear(); 16083 Previous.addDecl(Tag); 16084 Previous.resolveKind(); 16085 } 16086 } 16087 } 16088 } 16089 16090 // If this is a redeclaration of a using shadow declaration, it must 16091 // declare a tag in the same context. In MSVC mode, we allow a 16092 // redefinition if either context is within the other. 16093 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16094 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16095 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16096 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16097 !(OldTag && isAcceptableTagRedeclContext( 16098 *this, OldTag->getDeclContext(), SearchDC))) { 16099 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16100 Diag(Shadow->getTargetDecl()->getLocation(), 16101 diag::note_using_decl_target); 16102 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16103 << 0; 16104 // Recover by ignoring the old declaration. 16105 Previous.clear(); 16106 goto CreateNewDecl; 16107 } 16108 } 16109 16110 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16111 // If this is a use of a previous tag, or if the tag is already declared 16112 // in the same scope (so that the definition/declaration completes or 16113 // rementions the tag), reuse the decl. 16114 if (TUK == TUK_Reference || TUK == TUK_Friend || 16115 isDeclInScope(DirectPrevDecl, SearchDC, S, 16116 SS.isNotEmpty() || isMemberSpecialization)) { 16117 // Make sure that this wasn't declared as an enum and now used as a 16118 // struct or something similar. 16119 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16120 TUK == TUK_Definition, KWLoc, 16121 Name)) { 16122 bool SafeToContinue 16123 = (PrevTagDecl->getTagKind() != TTK_Enum && 16124 Kind != TTK_Enum); 16125 if (SafeToContinue) 16126 Diag(KWLoc, diag::err_use_with_wrong_tag) 16127 << Name 16128 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16129 PrevTagDecl->getKindName()); 16130 else 16131 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16132 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16133 16134 if (SafeToContinue) 16135 Kind = PrevTagDecl->getTagKind(); 16136 else { 16137 // Recover by making this an anonymous redefinition. 16138 Name = nullptr; 16139 Previous.clear(); 16140 Invalid = true; 16141 } 16142 } 16143 16144 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16145 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16146 if (TUK == TUK_Reference || TUK == TUK_Friend) 16147 return PrevTagDecl; 16148 16149 QualType EnumUnderlyingTy; 16150 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16151 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16152 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16153 EnumUnderlyingTy = QualType(T, 0); 16154 16155 // All conflicts with previous declarations are recovered by 16156 // returning the previous declaration, unless this is a definition, 16157 // in which case we want the caller to bail out. 16158 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16159 ScopedEnum, EnumUnderlyingTy, 16160 IsFixed, PrevEnum)) 16161 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16162 } 16163 16164 // C++11 [class.mem]p1: 16165 // A member shall not be declared twice in the member-specification, 16166 // except that a nested class or member class template can be declared 16167 // and then later defined. 16168 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16169 S->isDeclScope(PrevDecl)) { 16170 Diag(NameLoc, diag::ext_member_redeclared); 16171 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16172 } 16173 16174 if (!Invalid) { 16175 // If this is a use, just return the declaration we found, unless 16176 // we have attributes. 16177 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16178 if (!Attrs.empty()) { 16179 // FIXME: Diagnose these attributes. For now, we create a new 16180 // declaration to hold them. 16181 } else if (TUK == TUK_Reference && 16182 (PrevTagDecl->getFriendObjectKind() == 16183 Decl::FOK_Undeclared || 16184 PrevDecl->getOwningModule() != getCurrentModule()) && 16185 SS.isEmpty()) { 16186 // This declaration is a reference to an existing entity, but 16187 // has different visibility from that entity: it either makes 16188 // a friend visible or it makes a type visible in a new module. 16189 // In either case, create a new declaration. We only do this if 16190 // the declaration would have meant the same thing if no prior 16191 // declaration were found, that is, if it was found in the same 16192 // scope where we would have injected a declaration. 16193 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16194 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16195 return PrevTagDecl; 16196 // This is in the injected scope, create a new declaration in 16197 // that scope. 16198 S = getTagInjectionScope(S, getLangOpts()); 16199 } else { 16200 return PrevTagDecl; 16201 } 16202 } 16203 16204 // Diagnose attempts to redefine a tag. 16205 if (TUK == TUK_Definition) { 16206 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16207 // If we're defining a specialization and the previous definition 16208 // is from an implicit instantiation, don't emit an error 16209 // here; we'll catch this in the general case below. 16210 bool IsExplicitSpecializationAfterInstantiation = false; 16211 if (isMemberSpecialization) { 16212 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16213 IsExplicitSpecializationAfterInstantiation = 16214 RD->getTemplateSpecializationKind() != 16215 TSK_ExplicitSpecialization; 16216 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16217 IsExplicitSpecializationAfterInstantiation = 16218 ED->getTemplateSpecializationKind() != 16219 TSK_ExplicitSpecialization; 16220 } 16221 16222 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16223 // not keep more that one definition around (merge them). However, 16224 // ensure the decl passes the structural compatibility check in 16225 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16226 NamedDecl *Hidden = nullptr; 16227 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16228 // There is a definition of this tag, but it is not visible. We 16229 // explicitly make use of C++'s one definition rule here, and 16230 // assume that this definition is identical to the hidden one 16231 // we already have. Make the existing definition visible and 16232 // use it in place of this one. 16233 if (!getLangOpts().CPlusPlus) { 16234 // Postpone making the old definition visible until after we 16235 // complete parsing the new one and do the structural 16236 // comparison. 16237 SkipBody->CheckSameAsPrevious = true; 16238 SkipBody->New = createTagFromNewDecl(); 16239 SkipBody->Previous = Def; 16240 return Def; 16241 } else { 16242 SkipBody->ShouldSkip = true; 16243 SkipBody->Previous = Def; 16244 makeMergedDefinitionVisible(Hidden); 16245 // Carry on and handle it like a normal definition. We'll 16246 // skip starting the definitiion later. 16247 } 16248 } else if (!IsExplicitSpecializationAfterInstantiation) { 16249 // A redeclaration in function prototype scope in C isn't 16250 // visible elsewhere, so merely issue a warning. 16251 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16252 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16253 else 16254 Diag(NameLoc, diag::err_redefinition) << Name; 16255 notePreviousDefinition(Def, 16256 NameLoc.isValid() ? NameLoc : KWLoc); 16257 // If this is a redefinition, recover by making this 16258 // struct be anonymous, which will make any later 16259 // references get the previous definition. 16260 Name = nullptr; 16261 Previous.clear(); 16262 Invalid = true; 16263 } 16264 } else { 16265 // If the type is currently being defined, complain 16266 // about a nested redefinition. 16267 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16268 if (TD->isBeingDefined()) { 16269 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16270 Diag(PrevTagDecl->getLocation(), 16271 diag::note_previous_definition); 16272 Name = nullptr; 16273 Previous.clear(); 16274 Invalid = true; 16275 } 16276 } 16277 16278 // Okay, this is definition of a previously declared or referenced 16279 // tag. We're going to create a new Decl for it. 16280 } 16281 16282 // Okay, we're going to make a redeclaration. If this is some kind 16283 // of reference, make sure we build the redeclaration in the same DC 16284 // as the original, and ignore the current access specifier. 16285 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16286 SearchDC = PrevTagDecl->getDeclContext(); 16287 AS = AS_none; 16288 } 16289 } 16290 // If we get here we have (another) forward declaration or we 16291 // have a definition. Just create a new decl. 16292 16293 } else { 16294 // If we get here, this is a definition of a new tag type in a nested 16295 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16296 // new decl/type. We set PrevDecl to NULL so that the entities 16297 // have distinct types. 16298 Previous.clear(); 16299 } 16300 // If we get here, we're going to create a new Decl. If PrevDecl 16301 // is non-NULL, it's a definition of the tag declared by 16302 // PrevDecl. If it's NULL, we have a new definition. 16303 16304 // Otherwise, PrevDecl is not a tag, but was found with tag 16305 // lookup. This is only actually possible in C++, where a few 16306 // things like templates still live in the tag namespace. 16307 } else { 16308 // Use a better diagnostic if an elaborated-type-specifier 16309 // found the wrong kind of type on the first 16310 // (non-redeclaration) lookup. 16311 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16312 !Previous.isForRedeclaration()) { 16313 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16314 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16315 << Kind; 16316 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16317 Invalid = true; 16318 16319 // Otherwise, only diagnose if the declaration is in scope. 16320 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16321 SS.isNotEmpty() || isMemberSpecialization)) { 16322 // do nothing 16323 16324 // Diagnose implicit declarations introduced by elaborated types. 16325 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16326 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16327 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16328 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16329 Invalid = true; 16330 16331 // Otherwise it's a declaration. Call out a particularly common 16332 // case here. 16333 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16334 unsigned Kind = 0; 16335 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16336 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16337 << Name << Kind << TND->getUnderlyingType(); 16338 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16339 Invalid = true; 16340 16341 // Otherwise, diagnose. 16342 } else { 16343 // The tag name clashes with something else in the target scope, 16344 // issue an error and recover by making this tag be anonymous. 16345 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16346 notePreviousDefinition(PrevDecl, NameLoc); 16347 Name = nullptr; 16348 Invalid = true; 16349 } 16350 16351 // The existing declaration isn't relevant to us; we're in a 16352 // new scope, so clear out the previous declaration. 16353 Previous.clear(); 16354 } 16355 } 16356 16357 CreateNewDecl: 16358 16359 TagDecl *PrevDecl = nullptr; 16360 if (Previous.isSingleResult()) 16361 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16362 16363 // If there is an identifier, use the location of the identifier as the 16364 // location of the decl, otherwise use the location of the struct/union 16365 // keyword. 16366 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16367 16368 // Otherwise, create a new declaration. If there is a previous 16369 // declaration of the same entity, the two will be linked via 16370 // PrevDecl. 16371 TagDecl *New; 16372 16373 if (Kind == TTK_Enum) { 16374 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16375 // enum X { A, B, C } D; D should chain to X. 16376 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16377 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16378 ScopedEnumUsesClassTag, IsFixed); 16379 16380 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16381 StdAlignValT = cast<EnumDecl>(New); 16382 16383 // If this is an undefined enum, warn. 16384 if (TUK != TUK_Definition && !Invalid) { 16385 TagDecl *Def; 16386 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16387 // C++0x: 7.2p2: opaque-enum-declaration. 16388 // Conflicts are diagnosed above. Do nothing. 16389 } 16390 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16391 Diag(Loc, diag::ext_forward_ref_enum_def) 16392 << New; 16393 Diag(Def->getLocation(), diag::note_previous_definition); 16394 } else { 16395 unsigned DiagID = diag::ext_forward_ref_enum; 16396 if (getLangOpts().MSVCCompat) 16397 DiagID = diag::ext_ms_forward_ref_enum; 16398 else if (getLangOpts().CPlusPlus) 16399 DiagID = diag::err_forward_ref_enum; 16400 Diag(Loc, DiagID); 16401 } 16402 } 16403 16404 if (EnumUnderlying) { 16405 EnumDecl *ED = cast<EnumDecl>(New); 16406 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16407 ED->setIntegerTypeSourceInfo(TI); 16408 else 16409 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16410 ED->setPromotionType(ED->getIntegerType()); 16411 assert(ED->isComplete() && "enum with type should be complete"); 16412 } 16413 } else { 16414 // struct/union/class 16415 16416 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16417 // struct X { int A; } D; D should chain to X. 16418 if (getLangOpts().CPlusPlus) { 16419 // FIXME: Look for a way to use RecordDecl for simple structs. 16420 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16421 cast_or_null<CXXRecordDecl>(PrevDecl)); 16422 16423 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16424 StdBadAlloc = cast<CXXRecordDecl>(New); 16425 } else 16426 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16427 cast_or_null<RecordDecl>(PrevDecl)); 16428 } 16429 16430 // C++11 [dcl.type]p3: 16431 // A type-specifier-seq shall not define a class or enumeration [...]. 16432 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16433 TUK == TUK_Definition) { 16434 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16435 << Context.getTagDeclType(New); 16436 Invalid = true; 16437 } 16438 16439 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16440 DC->getDeclKind() == Decl::Enum) { 16441 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16442 << Context.getTagDeclType(New); 16443 Invalid = true; 16444 } 16445 16446 // Maybe add qualifier info. 16447 if (SS.isNotEmpty()) { 16448 if (SS.isSet()) { 16449 // If this is either a declaration or a definition, check the 16450 // nested-name-specifier against the current context. 16451 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16452 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16453 isMemberSpecialization)) 16454 Invalid = true; 16455 16456 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16457 if (TemplateParameterLists.size() > 0) { 16458 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16459 } 16460 } 16461 else 16462 Invalid = true; 16463 } 16464 16465 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16466 // Add alignment attributes if necessary; these attributes are checked when 16467 // the ASTContext lays out the structure. 16468 // 16469 // It is important for implementing the correct semantics that this 16470 // happen here (in ActOnTag). The #pragma pack stack is 16471 // maintained as a result of parser callbacks which can occur at 16472 // many points during the parsing of a struct declaration (because 16473 // the #pragma tokens are effectively skipped over during the 16474 // parsing of the struct). 16475 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16476 AddAlignmentAttributesForRecord(RD); 16477 AddMsStructLayoutForRecord(RD); 16478 } 16479 } 16480 16481 if (ModulePrivateLoc.isValid()) { 16482 if (isMemberSpecialization) 16483 Diag(New->getLocation(), diag::err_module_private_specialization) 16484 << 2 16485 << FixItHint::CreateRemoval(ModulePrivateLoc); 16486 // __module_private__ does not apply to local classes. However, we only 16487 // diagnose this as an error when the declaration specifiers are 16488 // freestanding. Here, we just ignore the __module_private__. 16489 else if (!SearchDC->isFunctionOrMethod()) 16490 New->setModulePrivate(); 16491 } 16492 16493 // If this is a specialization of a member class (of a class template), 16494 // check the specialization. 16495 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16496 Invalid = true; 16497 16498 // If we're declaring or defining a tag in function prototype scope in C, 16499 // note that this type can only be used within the function and add it to 16500 // the list of decls to inject into the function definition scope. 16501 if ((Name || Kind == TTK_Enum) && 16502 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16503 if (getLangOpts().CPlusPlus) { 16504 // C++ [dcl.fct]p6: 16505 // Types shall not be defined in return or parameter types. 16506 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16507 Diag(Loc, diag::err_type_defined_in_param_type) 16508 << Name; 16509 Invalid = true; 16510 } 16511 } else if (!PrevDecl) { 16512 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16513 } 16514 } 16515 16516 if (Invalid) 16517 New->setInvalidDecl(); 16518 16519 // Set the lexical context. If the tag has a C++ scope specifier, the 16520 // lexical context will be different from the semantic context. 16521 New->setLexicalDeclContext(CurContext); 16522 16523 // Mark this as a friend decl if applicable. 16524 // In Microsoft mode, a friend declaration also acts as a forward 16525 // declaration so we always pass true to setObjectOfFriendDecl to make 16526 // the tag name visible. 16527 if (TUK == TUK_Friend) 16528 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16529 16530 // Set the access specifier. 16531 if (!Invalid && SearchDC->isRecord()) 16532 SetMemberAccessSpecifier(New, PrevDecl, AS); 16533 16534 if (PrevDecl) 16535 CheckRedeclarationModuleOwnership(New, PrevDecl); 16536 16537 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16538 New->startDefinition(); 16539 16540 ProcessDeclAttributeList(S, New, Attrs); 16541 AddPragmaAttributes(S, New); 16542 16543 // If this has an identifier, add it to the scope stack. 16544 if (TUK == TUK_Friend) { 16545 // We might be replacing an existing declaration in the lookup tables; 16546 // if so, borrow its access specifier. 16547 if (PrevDecl) 16548 New->setAccess(PrevDecl->getAccess()); 16549 16550 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16551 DC->makeDeclVisibleInContext(New); 16552 if (Name) // can be null along some error paths 16553 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16554 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16555 } else if (Name) { 16556 S = getNonFieldDeclScope(S); 16557 PushOnScopeChains(New, S, true); 16558 } else { 16559 CurContext->addDecl(New); 16560 } 16561 16562 // If this is the C FILE type, notify the AST context. 16563 if (IdentifierInfo *II = New->getIdentifier()) 16564 if (!New->isInvalidDecl() && 16565 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16566 II->isStr("FILE")) 16567 Context.setFILEDecl(New); 16568 16569 if (PrevDecl) 16570 mergeDeclAttributes(New, PrevDecl); 16571 16572 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16573 inferGslOwnerPointerAttribute(CXXRD); 16574 16575 // If there's a #pragma GCC visibility in scope, set the visibility of this 16576 // record. 16577 AddPushedVisibilityAttribute(New); 16578 16579 if (isMemberSpecialization && !New->isInvalidDecl()) 16580 CompleteMemberSpecialization(New, Previous); 16581 16582 OwnedDecl = true; 16583 // In C++, don't return an invalid declaration. We can't recover well from 16584 // the cases where we make the type anonymous. 16585 if (Invalid && getLangOpts().CPlusPlus) { 16586 if (New->isBeingDefined()) 16587 if (auto RD = dyn_cast<RecordDecl>(New)) 16588 RD->completeDefinition(); 16589 return nullptr; 16590 } else if (SkipBody && SkipBody->ShouldSkip) { 16591 return SkipBody->Previous; 16592 } else { 16593 return New; 16594 } 16595 } 16596 16597 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16598 AdjustDeclIfTemplate(TagD); 16599 TagDecl *Tag = cast<TagDecl>(TagD); 16600 16601 // Enter the tag context. 16602 PushDeclContext(S, Tag); 16603 16604 ActOnDocumentableDecl(TagD); 16605 16606 // If there's a #pragma GCC visibility in scope, set the visibility of this 16607 // record. 16608 AddPushedVisibilityAttribute(Tag); 16609 } 16610 16611 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16612 SkipBodyInfo &SkipBody) { 16613 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16614 return false; 16615 16616 // Make the previous decl visible. 16617 makeMergedDefinitionVisible(SkipBody.Previous); 16618 return true; 16619 } 16620 16621 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16622 assert(isa<ObjCContainerDecl>(IDecl) && 16623 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16624 DeclContext *OCD = cast<DeclContext>(IDecl); 16625 assert(OCD->getLexicalParent() == CurContext && 16626 "The next DeclContext should be lexically contained in the current one."); 16627 CurContext = OCD; 16628 return IDecl; 16629 } 16630 16631 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16632 SourceLocation FinalLoc, 16633 bool IsFinalSpelledSealed, 16634 bool IsAbstract, 16635 SourceLocation LBraceLoc) { 16636 AdjustDeclIfTemplate(TagD); 16637 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16638 16639 FieldCollector->StartClass(); 16640 16641 if (!Record->getIdentifier()) 16642 return; 16643 16644 if (IsAbstract) 16645 Record->markAbstract(); 16646 16647 if (FinalLoc.isValid()) { 16648 Record->addAttr(FinalAttr::Create( 16649 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16650 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16651 } 16652 // C++ [class]p2: 16653 // [...] The class-name is also inserted into the scope of the 16654 // class itself; this is known as the injected-class-name. For 16655 // purposes of access checking, the injected-class-name is treated 16656 // as if it were a public member name. 16657 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16658 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16659 Record->getLocation(), Record->getIdentifier(), 16660 /*PrevDecl=*/nullptr, 16661 /*DelayTypeCreation=*/true); 16662 Context.getTypeDeclType(InjectedClassName, Record); 16663 InjectedClassName->setImplicit(); 16664 InjectedClassName->setAccess(AS_public); 16665 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16666 InjectedClassName->setDescribedClassTemplate(Template); 16667 PushOnScopeChains(InjectedClassName, S); 16668 assert(InjectedClassName->isInjectedClassName() && 16669 "Broken injected-class-name"); 16670 } 16671 16672 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16673 SourceRange BraceRange) { 16674 AdjustDeclIfTemplate(TagD); 16675 TagDecl *Tag = cast<TagDecl>(TagD); 16676 Tag->setBraceRange(BraceRange); 16677 16678 // Make sure we "complete" the definition even it is invalid. 16679 if (Tag->isBeingDefined()) { 16680 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16681 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16682 RD->completeDefinition(); 16683 } 16684 16685 if (isa<CXXRecordDecl>(Tag)) { 16686 FieldCollector->FinishClass(); 16687 } 16688 16689 // Exit this scope of this tag's definition. 16690 PopDeclContext(); 16691 16692 if (getCurLexicalContext()->isObjCContainer() && 16693 Tag->getDeclContext()->isFileContext()) 16694 Tag->setTopLevelDeclInObjCContainer(); 16695 16696 // Notify the consumer that we've defined a tag. 16697 if (!Tag->isInvalidDecl()) 16698 Consumer.HandleTagDeclDefinition(Tag); 16699 16700 // Clangs implementation of #pragma align(packed) differs in bitfield layout 16701 // from XLs and instead matches the XL #pragma pack(1) behavior. 16702 if (Context.getTargetInfo().getTriple().isOSAIX() && 16703 AlignPackStack.hasValue()) { 16704 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 16705 // Only diagnose #pragma align(packed). 16706 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 16707 return; 16708 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 16709 if (!RD) 16710 return; 16711 // Only warn if there is at least 1 bitfield member. 16712 if (llvm::any_of(RD->fields(), 16713 [](const FieldDecl *FD) { return FD->isBitField(); })) 16714 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 16715 } 16716 } 16717 16718 void Sema::ActOnObjCContainerFinishDefinition() { 16719 // Exit this scope of this interface definition. 16720 PopDeclContext(); 16721 } 16722 16723 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16724 assert(DC == CurContext && "Mismatch of container contexts"); 16725 OriginalLexicalContext = DC; 16726 ActOnObjCContainerFinishDefinition(); 16727 } 16728 16729 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16730 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16731 OriginalLexicalContext = nullptr; 16732 } 16733 16734 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16735 AdjustDeclIfTemplate(TagD); 16736 TagDecl *Tag = cast<TagDecl>(TagD); 16737 Tag->setInvalidDecl(); 16738 16739 // Make sure we "complete" the definition even it is invalid. 16740 if (Tag->isBeingDefined()) { 16741 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16742 RD->completeDefinition(); 16743 } 16744 16745 // We're undoing ActOnTagStartDefinition here, not 16746 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16747 // the FieldCollector. 16748 16749 PopDeclContext(); 16750 } 16751 16752 // Note that FieldName may be null for anonymous bitfields. 16753 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16754 IdentifierInfo *FieldName, 16755 QualType FieldTy, bool IsMsStruct, 16756 Expr *BitWidth, bool *ZeroWidth) { 16757 assert(BitWidth); 16758 if (BitWidth->containsErrors()) 16759 return ExprError(); 16760 16761 // Default to true; that shouldn't confuse checks for emptiness 16762 if (ZeroWidth) 16763 *ZeroWidth = true; 16764 16765 // C99 6.7.2.1p4 - verify the field type. 16766 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16767 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16768 // Handle incomplete and sizeless types with a specific error. 16769 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16770 diag::err_field_incomplete_or_sizeless)) 16771 return ExprError(); 16772 if (FieldName) 16773 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16774 << FieldName << FieldTy << BitWidth->getSourceRange(); 16775 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16776 << FieldTy << BitWidth->getSourceRange(); 16777 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16778 UPPC_BitFieldWidth)) 16779 return ExprError(); 16780 16781 // If the bit-width is type- or value-dependent, don't try to check 16782 // it now. 16783 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16784 return BitWidth; 16785 16786 llvm::APSInt Value; 16787 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16788 if (ICE.isInvalid()) 16789 return ICE; 16790 BitWidth = ICE.get(); 16791 16792 if (Value != 0 && ZeroWidth) 16793 *ZeroWidth = false; 16794 16795 // Zero-width bitfield is ok for anonymous field. 16796 if (Value == 0 && FieldName) 16797 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16798 16799 if (Value.isSigned() && Value.isNegative()) { 16800 if (FieldName) 16801 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16802 << FieldName << toString(Value, 10); 16803 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16804 << toString(Value, 10); 16805 } 16806 16807 // The size of the bit-field must not exceed our maximum permitted object 16808 // size. 16809 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16810 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16811 << !FieldName << FieldName << toString(Value, 10); 16812 } 16813 16814 if (!FieldTy->isDependentType()) { 16815 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16816 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16817 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16818 16819 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16820 // ABI. 16821 bool CStdConstraintViolation = 16822 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16823 bool MSBitfieldViolation = 16824 Value.ugt(TypeStorageSize) && 16825 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16826 if (CStdConstraintViolation || MSBitfieldViolation) { 16827 unsigned DiagWidth = 16828 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16829 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16830 << (bool)FieldName << FieldName << toString(Value, 10) 16831 << !CStdConstraintViolation << DiagWidth; 16832 } 16833 16834 // Warn on types where the user might conceivably expect to get all 16835 // specified bits as value bits: that's all integral types other than 16836 // 'bool'. 16837 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16838 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16839 << FieldName << toString(Value, 10) 16840 << (unsigned)TypeWidth; 16841 } 16842 } 16843 16844 return BitWidth; 16845 } 16846 16847 /// ActOnField - Each field of a C struct/union is passed into this in order 16848 /// to create a FieldDecl object for it. 16849 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16850 Declarator &D, Expr *BitfieldWidth) { 16851 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16852 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16853 /*InitStyle=*/ICIS_NoInit, AS_public); 16854 return Res; 16855 } 16856 16857 /// HandleField - Analyze a field of a C struct or a C++ data member. 16858 /// 16859 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16860 SourceLocation DeclStart, 16861 Declarator &D, Expr *BitWidth, 16862 InClassInitStyle InitStyle, 16863 AccessSpecifier AS) { 16864 if (D.isDecompositionDeclarator()) { 16865 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16866 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16867 << Decomp.getSourceRange(); 16868 return nullptr; 16869 } 16870 16871 IdentifierInfo *II = D.getIdentifier(); 16872 SourceLocation Loc = DeclStart; 16873 if (II) Loc = D.getIdentifierLoc(); 16874 16875 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16876 QualType T = TInfo->getType(); 16877 if (getLangOpts().CPlusPlus) { 16878 CheckExtraCXXDefaultArguments(D); 16879 16880 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16881 UPPC_DataMemberType)) { 16882 D.setInvalidType(); 16883 T = Context.IntTy; 16884 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16885 } 16886 } 16887 16888 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16889 16890 if (D.getDeclSpec().isInlineSpecified()) 16891 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16892 << getLangOpts().CPlusPlus17; 16893 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16894 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16895 diag::err_invalid_thread) 16896 << DeclSpec::getSpecifierName(TSCS); 16897 16898 // Check to see if this name was declared as a member previously 16899 NamedDecl *PrevDecl = nullptr; 16900 LookupResult Previous(*this, II, Loc, LookupMemberName, 16901 ForVisibleRedeclaration); 16902 LookupName(Previous, S); 16903 switch (Previous.getResultKind()) { 16904 case LookupResult::Found: 16905 case LookupResult::FoundUnresolvedValue: 16906 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16907 break; 16908 16909 case LookupResult::FoundOverloaded: 16910 PrevDecl = Previous.getRepresentativeDecl(); 16911 break; 16912 16913 case LookupResult::NotFound: 16914 case LookupResult::NotFoundInCurrentInstantiation: 16915 case LookupResult::Ambiguous: 16916 break; 16917 } 16918 Previous.suppressDiagnostics(); 16919 16920 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16921 // Maybe we will complain about the shadowed template parameter. 16922 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16923 // Just pretend that we didn't see the previous declaration. 16924 PrevDecl = nullptr; 16925 } 16926 16927 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16928 PrevDecl = nullptr; 16929 16930 bool Mutable 16931 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16932 SourceLocation TSSL = D.getBeginLoc(); 16933 FieldDecl *NewFD 16934 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16935 TSSL, AS, PrevDecl, &D); 16936 16937 if (NewFD->isInvalidDecl()) 16938 Record->setInvalidDecl(); 16939 16940 if (D.getDeclSpec().isModulePrivateSpecified()) 16941 NewFD->setModulePrivate(); 16942 16943 if (NewFD->isInvalidDecl() && PrevDecl) { 16944 // Don't introduce NewFD into scope; there's already something 16945 // with the same name in the same scope. 16946 } else if (II) { 16947 PushOnScopeChains(NewFD, S); 16948 } else 16949 Record->addDecl(NewFD); 16950 16951 return NewFD; 16952 } 16953 16954 /// Build a new FieldDecl and check its well-formedness. 16955 /// 16956 /// This routine builds a new FieldDecl given the fields name, type, 16957 /// record, etc. \p PrevDecl should refer to any previous declaration 16958 /// with the same name and in the same scope as the field to be 16959 /// created. 16960 /// 16961 /// \returns a new FieldDecl. 16962 /// 16963 /// \todo The Declarator argument is a hack. It will be removed once 16964 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16965 TypeSourceInfo *TInfo, 16966 RecordDecl *Record, SourceLocation Loc, 16967 bool Mutable, Expr *BitWidth, 16968 InClassInitStyle InitStyle, 16969 SourceLocation TSSL, 16970 AccessSpecifier AS, NamedDecl *PrevDecl, 16971 Declarator *D) { 16972 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16973 bool InvalidDecl = false; 16974 if (D) InvalidDecl = D->isInvalidType(); 16975 16976 // If we receive a broken type, recover by assuming 'int' and 16977 // marking this declaration as invalid. 16978 if (T.isNull() || T->containsErrors()) { 16979 InvalidDecl = true; 16980 T = Context.IntTy; 16981 } 16982 16983 QualType EltTy = Context.getBaseElementType(T); 16984 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16985 if (RequireCompleteSizedType(Loc, EltTy, 16986 diag::err_field_incomplete_or_sizeless)) { 16987 // Fields of incomplete type force their record to be invalid. 16988 Record->setInvalidDecl(); 16989 InvalidDecl = true; 16990 } else { 16991 NamedDecl *Def; 16992 EltTy->isIncompleteType(&Def); 16993 if (Def && Def->isInvalidDecl()) { 16994 Record->setInvalidDecl(); 16995 InvalidDecl = true; 16996 } 16997 } 16998 } 16999 17000 // TR 18037 does not allow fields to be declared with address space 17001 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 17002 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 17003 Diag(Loc, diag::err_field_with_address_space); 17004 Record->setInvalidDecl(); 17005 InvalidDecl = true; 17006 } 17007 17008 if (LangOpts.OpenCL) { 17009 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 17010 // used as structure or union field: image, sampler, event or block types. 17011 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 17012 T->isBlockPointerType()) { 17013 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 17014 Record->setInvalidDecl(); 17015 InvalidDecl = true; 17016 } 17017 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 17018 // is enabled. 17019 if (BitWidth && !getOpenCLOptions().isAvailableOption( 17020 "__cl_clang_bitfields", LangOpts)) { 17021 Diag(Loc, diag::err_opencl_bitfields); 17022 InvalidDecl = true; 17023 } 17024 } 17025 17026 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 17027 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 17028 T.hasQualifiers()) { 17029 InvalidDecl = true; 17030 Diag(Loc, diag::err_anon_bitfield_qualifiers); 17031 } 17032 17033 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17034 // than a variably modified type. 17035 if (!InvalidDecl && T->isVariablyModifiedType()) { 17036 if (!tryToFixVariablyModifiedVarType( 17037 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 17038 InvalidDecl = true; 17039 } 17040 17041 // Fields can not have abstract class types 17042 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 17043 diag::err_abstract_type_in_decl, 17044 AbstractFieldType)) 17045 InvalidDecl = true; 17046 17047 bool ZeroWidth = false; 17048 if (InvalidDecl) 17049 BitWidth = nullptr; 17050 // If this is declared as a bit-field, check the bit-field. 17051 if (BitWidth) { 17052 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 17053 &ZeroWidth).get(); 17054 if (!BitWidth) { 17055 InvalidDecl = true; 17056 BitWidth = nullptr; 17057 ZeroWidth = false; 17058 } 17059 } 17060 17061 // Check that 'mutable' is consistent with the type of the declaration. 17062 if (!InvalidDecl && Mutable) { 17063 unsigned DiagID = 0; 17064 if (T->isReferenceType()) 17065 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 17066 : diag::err_mutable_reference; 17067 else if (T.isConstQualified()) 17068 DiagID = diag::err_mutable_const; 17069 17070 if (DiagID) { 17071 SourceLocation ErrLoc = Loc; 17072 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17073 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17074 Diag(ErrLoc, DiagID); 17075 if (DiagID != diag::ext_mutable_reference) { 17076 Mutable = false; 17077 InvalidDecl = true; 17078 } 17079 } 17080 } 17081 17082 // C++11 [class.union]p8 (DR1460): 17083 // At most one variant member of a union may have a 17084 // brace-or-equal-initializer. 17085 if (InitStyle != ICIS_NoInit) 17086 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17087 17088 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17089 BitWidth, Mutable, InitStyle); 17090 if (InvalidDecl) 17091 NewFD->setInvalidDecl(); 17092 17093 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17094 Diag(Loc, diag::err_duplicate_member) << II; 17095 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17096 NewFD->setInvalidDecl(); 17097 } 17098 17099 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17100 if (Record->isUnion()) { 17101 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17102 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17103 if (RDecl->getDefinition()) { 17104 // C++ [class.union]p1: An object of a class with a non-trivial 17105 // constructor, a non-trivial copy constructor, a non-trivial 17106 // destructor, or a non-trivial copy assignment operator 17107 // cannot be a member of a union, nor can an array of such 17108 // objects. 17109 if (CheckNontrivialField(NewFD)) 17110 NewFD->setInvalidDecl(); 17111 } 17112 } 17113 17114 // C++ [class.union]p1: If a union contains a member of reference type, 17115 // the program is ill-formed, except when compiling with MSVC extensions 17116 // enabled. 17117 if (EltTy->isReferenceType()) { 17118 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17119 diag::ext_union_member_of_reference_type : 17120 diag::err_union_member_of_reference_type) 17121 << NewFD->getDeclName() << EltTy; 17122 if (!getLangOpts().MicrosoftExt) 17123 NewFD->setInvalidDecl(); 17124 } 17125 } 17126 } 17127 17128 // FIXME: We need to pass in the attributes given an AST 17129 // representation, not a parser representation. 17130 if (D) { 17131 // FIXME: The current scope is almost... but not entirely... correct here. 17132 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17133 17134 if (NewFD->hasAttrs()) 17135 CheckAlignasUnderalignment(NewFD); 17136 } 17137 17138 // In auto-retain/release, infer strong retension for fields of 17139 // retainable type. 17140 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17141 NewFD->setInvalidDecl(); 17142 17143 if (T.isObjCGCWeak()) 17144 Diag(Loc, diag::warn_attribute_weak_on_field); 17145 17146 // PPC MMA non-pointer types are not allowed as field types. 17147 if (Context.getTargetInfo().getTriple().isPPC64() && 17148 CheckPPCMMAType(T, NewFD->getLocation())) 17149 NewFD->setInvalidDecl(); 17150 17151 NewFD->setAccess(AS); 17152 return NewFD; 17153 } 17154 17155 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17156 assert(FD); 17157 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17158 17159 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17160 return false; 17161 17162 QualType EltTy = Context.getBaseElementType(FD->getType()); 17163 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17164 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17165 if (RDecl->getDefinition()) { 17166 // We check for copy constructors before constructors 17167 // because otherwise we'll never get complaints about 17168 // copy constructors. 17169 17170 CXXSpecialMember member = CXXInvalid; 17171 // We're required to check for any non-trivial constructors. Since the 17172 // implicit default constructor is suppressed if there are any 17173 // user-declared constructors, we just need to check that there is a 17174 // trivial default constructor and a trivial copy constructor. (We don't 17175 // worry about move constructors here, since this is a C++98 check.) 17176 if (RDecl->hasNonTrivialCopyConstructor()) 17177 member = CXXCopyConstructor; 17178 else if (!RDecl->hasTrivialDefaultConstructor()) 17179 member = CXXDefaultConstructor; 17180 else if (RDecl->hasNonTrivialCopyAssignment()) 17181 member = CXXCopyAssignment; 17182 else if (RDecl->hasNonTrivialDestructor()) 17183 member = CXXDestructor; 17184 17185 if (member != CXXInvalid) { 17186 if (!getLangOpts().CPlusPlus11 && 17187 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17188 // Objective-C++ ARC: it is an error to have a non-trivial field of 17189 // a union. However, system headers in Objective-C programs 17190 // occasionally have Objective-C lifetime objects within unions, 17191 // and rather than cause the program to fail, we make those 17192 // members unavailable. 17193 SourceLocation Loc = FD->getLocation(); 17194 if (getSourceManager().isInSystemHeader(Loc)) { 17195 if (!FD->hasAttr<UnavailableAttr>()) 17196 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17197 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17198 return false; 17199 } 17200 } 17201 17202 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17203 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17204 diag::err_illegal_union_or_anon_struct_member) 17205 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17206 DiagnoseNontrivial(RDecl, member); 17207 return !getLangOpts().CPlusPlus11; 17208 } 17209 } 17210 } 17211 17212 return false; 17213 } 17214 17215 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17216 /// AST enum value. 17217 static ObjCIvarDecl::AccessControl 17218 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17219 switch (ivarVisibility) { 17220 default: llvm_unreachable("Unknown visitibility kind"); 17221 case tok::objc_private: return ObjCIvarDecl::Private; 17222 case tok::objc_public: return ObjCIvarDecl::Public; 17223 case tok::objc_protected: return ObjCIvarDecl::Protected; 17224 case tok::objc_package: return ObjCIvarDecl::Package; 17225 } 17226 } 17227 17228 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17229 /// in order to create an IvarDecl object for it. 17230 Decl *Sema::ActOnIvar(Scope *S, 17231 SourceLocation DeclStart, 17232 Declarator &D, Expr *BitfieldWidth, 17233 tok::ObjCKeywordKind Visibility) { 17234 17235 IdentifierInfo *II = D.getIdentifier(); 17236 Expr *BitWidth = (Expr*)BitfieldWidth; 17237 SourceLocation Loc = DeclStart; 17238 if (II) Loc = D.getIdentifierLoc(); 17239 17240 // FIXME: Unnamed fields can be handled in various different ways, for 17241 // example, unnamed unions inject all members into the struct namespace! 17242 17243 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17244 QualType T = TInfo->getType(); 17245 17246 if (BitWidth) { 17247 // 6.7.2.1p3, 6.7.2.1p4 17248 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17249 if (!BitWidth) 17250 D.setInvalidType(); 17251 } else { 17252 // Not a bitfield. 17253 17254 // validate II. 17255 17256 } 17257 if (T->isReferenceType()) { 17258 Diag(Loc, diag::err_ivar_reference_type); 17259 D.setInvalidType(); 17260 } 17261 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17262 // than a variably modified type. 17263 else if (T->isVariablyModifiedType()) { 17264 if (!tryToFixVariablyModifiedVarType( 17265 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17266 D.setInvalidType(); 17267 } 17268 17269 // Get the visibility (access control) for this ivar. 17270 ObjCIvarDecl::AccessControl ac = 17271 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17272 : ObjCIvarDecl::None; 17273 // Must set ivar's DeclContext to its enclosing interface. 17274 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17275 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17276 return nullptr; 17277 ObjCContainerDecl *EnclosingContext; 17278 if (ObjCImplementationDecl *IMPDecl = 17279 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17280 if (LangOpts.ObjCRuntime.isFragile()) { 17281 // Case of ivar declared in an implementation. Context is that of its class. 17282 EnclosingContext = IMPDecl->getClassInterface(); 17283 assert(EnclosingContext && "Implementation has no class interface!"); 17284 } 17285 else 17286 EnclosingContext = EnclosingDecl; 17287 } else { 17288 if (ObjCCategoryDecl *CDecl = 17289 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17290 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17291 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17292 return nullptr; 17293 } 17294 } 17295 EnclosingContext = EnclosingDecl; 17296 } 17297 17298 // Construct the decl. 17299 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17300 DeclStart, Loc, II, T, 17301 TInfo, ac, (Expr *)BitfieldWidth); 17302 17303 if (II) { 17304 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17305 ForVisibleRedeclaration); 17306 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17307 && !isa<TagDecl>(PrevDecl)) { 17308 Diag(Loc, diag::err_duplicate_member) << II; 17309 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17310 NewID->setInvalidDecl(); 17311 } 17312 } 17313 17314 // Process attributes attached to the ivar. 17315 ProcessDeclAttributes(S, NewID, D); 17316 17317 if (D.isInvalidType()) 17318 NewID->setInvalidDecl(); 17319 17320 // In ARC, infer 'retaining' for ivars of retainable type. 17321 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17322 NewID->setInvalidDecl(); 17323 17324 if (D.getDeclSpec().isModulePrivateSpecified()) 17325 NewID->setModulePrivate(); 17326 17327 if (II) { 17328 // FIXME: When interfaces are DeclContexts, we'll need to add 17329 // these to the interface. 17330 S->AddDecl(NewID); 17331 IdResolver.AddDecl(NewID); 17332 } 17333 17334 if (LangOpts.ObjCRuntime.isNonFragile() && 17335 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17336 Diag(Loc, diag::warn_ivars_in_interface); 17337 17338 return NewID; 17339 } 17340 17341 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17342 /// class and class extensions. For every class \@interface and class 17343 /// extension \@interface, if the last ivar is a bitfield of any type, 17344 /// then add an implicit `char :0` ivar to the end of that interface. 17345 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17346 SmallVectorImpl<Decl *> &AllIvarDecls) { 17347 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17348 return; 17349 17350 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17351 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17352 17353 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17354 return; 17355 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17356 if (!ID) { 17357 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17358 if (!CD->IsClassExtension()) 17359 return; 17360 } 17361 // No need to add this to end of @implementation. 17362 else 17363 return; 17364 } 17365 // All conditions are met. Add a new bitfield to the tail end of ivars. 17366 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17367 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17368 17369 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17370 DeclLoc, DeclLoc, nullptr, 17371 Context.CharTy, 17372 Context.getTrivialTypeSourceInfo(Context.CharTy, 17373 DeclLoc), 17374 ObjCIvarDecl::Private, BW, 17375 true); 17376 AllIvarDecls.push_back(Ivar); 17377 } 17378 17379 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17380 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17381 SourceLocation RBrac, 17382 const ParsedAttributesView &Attrs) { 17383 assert(EnclosingDecl && "missing record or interface decl"); 17384 17385 // If this is an Objective-C @implementation or category and we have 17386 // new fields here we should reset the layout of the interface since 17387 // it will now change. 17388 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17389 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17390 switch (DC->getKind()) { 17391 default: break; 17392 case Decl::ObjCCategory: 17393 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17394 break; 17395 case Decl::ObjCImplementation: 17396 Context. 17397 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17398 break; 17399 } 17400 } 17401 17402 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17403 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17404 17405 // Start counting up the number of named members; make sure to include 17406 // members of anonymous structs and unions in the total. 17407 unsigned NumNamedMembers = 0; 17408 if (Record) { 17409 for (const auto *I : Record->decls()) { 17410 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17411 if (IFD->getDeclName()) 17412 ++NumNamedMembers; 17413 } 17414 } 17415 17416 // Verify that all the fields are okay. 17417 SmallVector<FieldDecl*, 32> RecFields; 17418 17419 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17420 i != end; ++i) { 17421 FieldDecl *FD = cast<FieldDecl>(*i); 17422 17423 // Get the type for the field. 17424 const Type *FDTy = FD->getType().getTypePtr(); 17425 17426 if (!FD->isAnonymousStructOrUnion()) { 17427 // Remember all fields written by the user. 17428 RecFields.push_back(FD); 17429 } 17430 17431 // If the field is already invalid for some reason, don't emit more 17432 // diagnostics about it. 17433 if (FD->isInvalidDecl()) { 17434 EnclosingDecl->setInvalidDecl(); 17435 continue; 17436 } 17437 17438 // C99 6.7.2.1p2: 17439 // A structure or union shall not contain a member with 17440 // incomplete or function type (hence, a structure shall not 17441 // contain an instance of itself, but may contain a pointer to 17442 // an instance of itself), except that the last member of a 17443 // structure with more than one named member may have incomplete 17444 // array type; such a structure (and any union containing, 17445 // possibly recursively, a member that is such a structure) 17446 // shall not be a member of a structure or an element of an 17447 // array. 17448 bool IsLastField = (i + 1 == Fields.end()); 17449 if (FDTy->isFunctionType()) { 17450 // Field declared as a function. 17451 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17452 << FD->getDeclName(); 17453 FD->setInvalidDecl(); 17454 EnclosingDecl->setInvalidDecl(); 17455 continue; 17456 } else if (FDTy->isIncompleteArrayType() && 17457 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17458 if (Record) { 17459 // Flexible array member. 17460 // Microsoft and g++ is more permissive regarding flexible array. 17461 // It will accept flexible array in union and also 17462 // as the sole element of a struct/class. 17463 unsigned DiagID = 0; 17464 if (!Record->isUnion() && !IsLastField) { 17465 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17466 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17467 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17468 FD->setInvalidDecl(); 17469 EnclosingDecl->setInvalidDecl(); 17470 continue; 17471 } else if (Record->isUnion()) 17472 DiagID = getLangOpts().MicrosoftExt 17473 ? diag::ext_flexible_array_union_ms 17474 : getLangOpts().CPlusPlus 17475 ? diag::ext_flexible_array_union_gnu 17476 : diag::err_flexible_array_union; 17477 else if (NumNamedMembers < 1) 17478 DiagID = getLangOpts().MicrosoftExt 17479 ? diag::ext_flexible_array_empty_aggregate_ms 17480 : getLangOpts().CPlusPlus 17481 ? diag::ext_flexible_array_empty_aggregate_gnu 17482 : diag::err_flexible_array_empty_aggregate; 17483 17484 if (DiagID) 17485 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17486 << Record->getTagKind(); 17487 // While the layout of types that contain virtual bases is not specified 17488 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17489 // virtual bases after the derived members. This would make a flexible 17490 // array member declared at the end of an object not adjacent to the end 17491 // of the type. 17492 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17493 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17494 << FD->getDeclName() << Record->getTagKind(); 17495 if (!getLangOpts().C99) 17496 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17497 << FD->getDeclName() << Record->getTagKind(); 17498 17499 // If the element type has a non-trivial destructor, we would not 17500 // implicitly destroy the elements, so disallow it for now. 17501 // 17502 // FIXME: GCC allows this. We should probably either implicitly delete 17503 // the destructor of the containing class, or just allow this. 17504 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17505 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17506 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17507 << FD->getDeclName() << FD->getType(); 17508 FD->setInvalidDecl(); 17509 EnclosingDecl->setInvalidDecl(); 17510 continue; 17511 } 17512 // Okay, we have a legal flexible array member at the end of the struct. 17513 Record->setHasFlexibleArrayMember(true); 17514 } else { 17515 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17516 // unless they are followed by another ivar. That check is done 17517 // elsewhere, after synthesized ivars are known. 17518 } 17519 } else if (!FDTy->isDependentType() && 17520 RequireCompleteSizedType( 17521 FD->getLocation(), FD->getType(), 17522 diag::err_field_incomplete_or_sizeless)) { 17523 // Incomplete type 17524 FD->setInvalidDecl(); 17525 EnclosingDecl->setInvalidDecl(); 17526 continue; 17527 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17528 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17529 // A type which contains a flexible array member is considered to be a 17530 // flexible array member. 17531 Record->setHasFlexibleArrayMember(true); 17532 if (!Record->isUnion()) { 17533 // If this is a struct/class and this is not the last element, reject 17534 // it. Note that GCC supports variable sized arrays in the middle of 17535 // structures. 17536 if (!IsLastField) 17537 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17538 << FD->getDeclName() << FD->getType(); 17539 else { 17540 // We support flexible arrays at the end of structs in 17541 // other structs as an extension. 17542 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17543 << FD->getDeclName(); 17544 } 17545 } 17546 } 17547 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17548 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17549 diag::err_abstract_type_in_decl, 17550 AbstractIvarType)) { 17551 // Ivars can not have abstract class types 17552 FD->setInvalidDecl(); 17553 } 17554 if (Record && FDTTy->getDecl()->hasObjectMember()) 17555 Record->setHasObjectMember(true); 17556 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17557 Record->setHasVolatileMember(true); 17558 } else if (FDTy->isObjCObjectType()) { 17559 /// A field cannot be an Objective-c object 17560 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17561 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17562 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17563 FD->setType(T); 17564 } else if (Record && Record->isUnion() && 17565 FD->getType().hasNonTrivialObjCLifetime() && 17566 getSourceManager().isInSystemHeader(FD->getLocation()) && 17567 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17568 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17569 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17570 // For backward compatibility, fields of C unions declared in system 17571 // headers that have non-trivial ObjC ownership qualifications are marked 17572 // as unavailable unless the qualifier is explicit and __strong. This can 17573 // break ABI compatibility between programs compiled with ARC and MRR, but 17574 // is a better option than rejecting programs using those unions under 17575 // ARC. 17576 FD->addAttr(UnavailableAttr::CreateImplicit( 17577 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17578 FD->getLocation())); 17579 } else if (getLangOpts().ObjC && 17580 getLangOpts().getGC() != LangOptions::NonGC && Record && 17581 !Record->hasObjectMember()) { 17582 if (FD->getType()->isObjCObjectPointerType() || 17583 FD->getType().isObjCGCStrong()) 17584 Record->setHasObjectMember(true); 17585 else if (Context.getAsArrayType(FD->getType())) { 17586 QualType BaseType = Context.getBaseElementType(FD->getType()); 17587 if (BaseType->isRecordType() && 17588 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17589 Record->setHasObjectMember(true); 17590 else if (BaseType->isObjCObjectPointerType() || 17591 BaseType.isObjCGCStrong()) 17592 Record->setHasObjectMember(true); 17593 } 17594 } 17595 17596 if (Record && !getLangOpts().CPlusPlus && 17597 !shouldIgnoreForRecordTriviality(FD)) { 17598 QualType FT = FD->getType(); 17599 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17600 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17601 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17602 Record->isUnion()) 17603 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17604 } 17605 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17606 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17607 Record->setNonTrivialToPrimitiveCopy(true); 17608 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17609 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17610 } 17611 if (FT.isDestructedType()) { 17612 Record->setNonTrivialToPrimitiveDestroy(true); 17613 Record->setParamDestroyedInCallee(true); 17614 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17615 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17616 } 17617 17618 if (const auto *RT = FT->getAs<RecordType>()) { 17619 if (RT->getDecl()->getArgPassingRestrictions() == 17620 RecordDecl::APK_CanNeverPassInRegs) 17621 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17622 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17623 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17624 } 17625 17626 if (Record && FD->getType().isVolatileQualified()) 17627 Record->setHasVolatileMember(true); 17628 // Keep track of the number of named members. 17629 if (FD->getIdentifier()) 17630 ++NumNamedMembers; 17631 } 17632 17633 // Okay, we successfully defined 'Record'. 17634 if (Record) { 17635 bool Completed = false; 17636 if (CXXRecord) { 17637 if (!CXXRecord->isInvalidDecl()) { 17638 // Set access bits correctly on the directly-declared conversions. 17639 for (CXXRecordDecl::conversion_iterator 17640 I = CXXRecord->conversion_begin(), 17641 E = CXXRecord->conversion_end(); I != E; ++I) 17642 I.setAccess((*I)->getAccess()); 17643 } 17644 17645 // Add any implicitly-declared members to this class. 17646 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17647 17648 if (!CXXRecord->isDependentType()) { 17649 if (!CXXRecord->isInvalidDecl()) { 17650 // If we have virtual base classes, we may end up finding multiple 17651 // final overriders for a given virtual function. Check for this 17652 // problem now. 17653 if (CXXRecord->getNumVBases()) { 17654 CXXFinalOverriderMap FinalOverriders; 17655 CXXRecord->getFinalOverriders(FinalOverriders); 17656 17657 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17658 MEnd = FinalOverriders.end(); 17659 M != MEnd; ++M) { 17660 for (OverridingMethods::iterator SO = M->second.begin(), 17661 SOEnd = M->second.end(); 17662 SO != SOEnd; ++SO) { 17663 assert(SO->second.size() > 0 && 17664 "Virtual function without overriding functions?"); 17665 if (SO->second.size() == 1) 17666 continue; 17667 17668 // C++ [class.virtual]p2: 17669 // In a derived class, if a virtual member function of a base 17670 // class subobject has more than one final overrider the 17671 // program is ill-formed. 17672 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17673 << (const NamedDecl *)M->first << Record; 17674 Diag(M->first->getLocation(), 17675 diag::note_overridden_virtual_function); 17676 for (OverridingMethods::overriding_iterator 17677 OM = SO->second.begin(), 17678 OMEnd = SO->second.end(); 17679 OM != OMEnd; ++OM) 17680 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17681 << (const NamedDecl *)M->first << OM->Method->getParent(); 17682 17683 Record->setInvalidDecl(); 17684 } 17685 } 17686 CXXRecord->completeDefinition(&FinalOverriders); 17687 Completed = true; 17688 } 17689 } 17690 } 17691 } 17692 17693 if (!Completed) 17694 Record->completeDefinition(); 17695 17696 // Handle attributes before checking the layout. 17697 ProcessDeclAttributeList(S, Record, Attrs); 17698 17699 // We may have deferred checking for a deleted destructor. Check now. 17700 if (CXXRecord) { 17701 auto *Dtor = CXXRecord->getDestructor(); 17702 if (Dtor && Dtor->isImplicit() && 17703 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17704 CXXRecord->setImplicitDestructorIsDeleted(); 17705 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17706 } 17707 } 17708 17709 if (Record->hasAttrs()) { 17710 CheckAlignasUnderalignment(Record); 17711 17712 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17713 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17714 IA->getRange(), IA->getBestCase(), 17715 IA->getInheritanceModel()); 17716 } 17717 17718 // Check if the structure/union declaration is a type that can have zero 17719 // size in C. For C this is a language extension, for C++ it may cause 17720 // compatibility problems. 17721 bool CheckForZeroSize; 17722 if (!getLangOpts().CPlusPlus) { 17723 CheckForZeroSize = true; 17724 } else { 17725 // For C++ filter out types that cannot be referenced in C code. 17726 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17727 CheckForZeroSize = 17728 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17729 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17730 CXXRecord->isCLike(); 17731 } 17732 if (CheckForZeroSize) { 17733 bool ZeroSize = true; 17734 bool IsEmpty = true; 17735 unsigned NonBitFields = 0; 17736 for (RecordDecl::field_iterator I = Record->field_begin(), 17737 E = Record->field_end(); 17738 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17739 IsEmpty = false; 17740 if (I->isUnnamedBitfield()) { 17741 if (!I->isZeroLengthBitField(Context)) 17742 ZeroSize = false; 17743 } else { 17744 ++NonBitFields; 17745 QualType FieldType = I->getType(); 17746 if (FieldType->isIncompleteType() || 17747 !Context.getTypeSizeInChars(FieldType).isZero()) 17748 ZeroSize = false; 17749 } 17750 } 17751 17752 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17753 // allowed in C++, but warn if its declaration is inside 17754 // extern "C" block. 17755 if (ZeroSize) { 17756 Diag(RecLoc, getLangOpts().CPlusPlus ? 17757 diag::warn_zero_size_struct_union_in_extern_c : 17758 diag::warn_zero_size_struct_union_compat) 17759 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17760 } 17761 17762 // Structs without named members are extension in C (C99 6.7.2.1p7), 17763 // but are accepted by GCC. 17764 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17765 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17766 diag::ext_no_named_members_in_struct_union) 17767 << Record->isUnion(); 17768 } 17769 } 17770 } else { 17771 ObjCIvarDecl **ClsFields = 17772 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17773 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17774 ID->setEndOfDefinitionLoc(RBrac); 17775 // Add ivar's to class's DeclContext. 17776 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17777 ClsFields[i]->setLexicalDeclContext(ID); 17778 ID->addDecl(ClsFields[i]); 17779 } 17780 // Must enforce the rule that ivars in the base classes may not be 17781 // duplicates. 17782 if (ID->getSuperClass()) 17783 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17784 } else if (ObjCImplementationDecl *IMPDecl = 17785 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17786 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17787 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17788 // Ivar declared in @implementation never belongs to the implementation. 17789 // Only it is in implementation's lexical context. 17790 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17791 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17792 IMPDecl->setIvarLBraceLoc(LBrac); 17793 IMPDecl->setIvarRBraceLoc(RBrac); 17794 } else if (ObjCCategoryDecl *CDecl = 17795 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17796 // case of ivars in class extension; all other cases have been 17797 // reported as errors elsewhere. 17798 // FIXME. Class extension does not have a LocEnd field. 17799 // CDecl->setLocEnd(RBrac); 17800 // Add ivar's to class extension's DeclContext. 17801 // Diagnose redeclaration of private ivars. 17802 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17803 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17804 if (IDecl) { 17805 if (const ObjCIvarDecl *ClsIvar = 17806 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17807 Diag(ClsFields[i]->getLocation(), 17808 diag::err_duplicate_ivar_declaration); 17809 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17810 continue; 17811 } 17812 for (const auto *Ext : IDecl->known_extensions()) { 17813 if (const ObjCIvarDecl *ClsExtIvar 17814 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17815 Diag(ClsFields[i]->getLocation(), 17816 diag::err_duplicate_ivar_declaration); 17817 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17818 continue; 17819 } 17820 } 17821 } 17822 ClsFields[i]->setLexicalDeclContext(CDecl); 17823 CDecl->addDecl(ClsFields[i]); 17824 } 17825 CDecl->setIvarLBraceLoc(LBrac); 17826 CDecl->setIvarRBraceLoc(RBrac); 17827 } 17828 } 17829 } 17830 17831 /// Determine whether the given integral value is representable within 17832 /// the given type T. 17833 static bool isRepresentableIntegerValue(ASTContext &Context, 17834 llvm::APSInt &Value, 17835 QualType T) { 17836 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17837 "Integral type required!"); 17838 unsigned BitWidth = Context.getIntWidth(T); 17839 17840 if (Value.isUnsigned() || Value.isNonNegative()) { 17841 if (T->isSignedIntegerOrEnumerationType()) 17842 --BitWidth; 17843 return Value.getActiveBits() <= BitWidth; 17844 } 17845 return Value.getMinSignedBits() <= BitWidth; 17846 } 17847 17848 // Given an integral type, return the next larger integral type 17849 // (or a NULL type of no such type exists). 17850 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17851 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17852 // enum checking below. 17853 assert((T->isIntegralType(Context) || 17854 T->isEnumeralType()) && "Integral type required!"); 17855 const unsigned NumTypes = 4; 17856 QualType SignedIntegralTypes[NumTypes] = { 17857 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17858 }; 17859 QualType UnsignedIntegralTypes[NumTypes] = { 17860 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17861 Context.UnsignedLongLongTy 17862 }; 17863 17864 unsigned BitWidth = Context.getTypeSize(T); 17865 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17866 : UnsignedIntegralTypes; 17867 for (unsigned I = 0; I != NumTypes; ++I) 17868 if (Context.getTypeSize(Types[I]) > BitWidth) 17869 return Types[I]; 17870 17871 return QualType(); 17872 } 17873 17874 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17875 EnumConstantDecl *LastEnumConst, 17876 SourceLocation IdLoc, 17877 IdentifierInfo *Id, 17878 Expr *Val) { 17879 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17880 llvm::APSInt EnumVal(IntWidth); 17881 QualType EltTy; 17882 17883 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17884 Val = nullptr; 17885 17886 if (Val) 17887 Val = DefaultLvalueConversion(Val).get(); 17888 17889 if (Val) { 17890 if (Enum->isDependentType() || Val->isTypeDependent() || 17891 Val->containsErrors()) 17892 EltTy = Context.DependentTy; 17893 else { 17894 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17895 // underlying type, but do allow it in all other contexts. 17896 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17897 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17898 // constant-expression in the enumerator-definition shall be a converted 17899 // constant expression of the underlying type. 17900 EltTy = Enum->getIntegerType(); 17901 ExprResult Converted = 17902 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17903 CCEK_Enumerator); 17904 if (Converted.isInvalid()) 17905 Val = nullptr; 17906 else 17907 Val = Converted.get(); 17908 } else if (!Val->isValueDependent() && 17909 !(Val = 17910 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17911 .get())) { 17912 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17913 } else { 17914 if (Enum->isComplete()) { 17915 EltTy = Enum->getIntegerType(); 17916 17917 // In Obj-C and Microsoft mode, require the enumeration value to be 17918 // representable in the underlying type of the enumeration. In C++11, 17919 // we perform a non-narrowing conversion as part of converted constant 17920 // expression checking. 17921 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17922 if (Context.getTargetInfo() 17923 .getTriple() 17924 .isWindowsMSVCEnvironment()) { 17925 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17926 } else { 17927 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17928 } 17929 } 17930 17931 // Cast to the underlying type. 17932 Val = ImpCastExprToType(Val, EltTy, 17933 EltTy->isBooleanType() ? CK_IntegralToBoolean 17934 : CK_IntegralCast) 17935 .get(); 17936 } else if (getLangOpts().CPlusPlus) { 17937 // C++11 [dcl.enum]p5: 17938 // If the underlying type is not fixed, the type of each enumerator 17939 // is the type of its initializing value: 17940 // - If an initializer is specified for an enumerator, the 17941 // initializing value has the same type as the expression. 17942 EltTy = Val->getType(); 17943 } else { 17944 // C99 6.7.2.2p2: 17945 // The expression that defines the value of an enumeration constant 17946 // shall be an integer constant expression that has a value 17947 // representable as an int. 17948 17949 // Complain if the value is not representable in an int. 17950 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17951 Diag(IdLoc, diag::ext_enum_value_not_int) 17952 << toString(EnumVal, 10) << Val->getSourceRange() 17953 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17954 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17955 // Force the type of the expression to 'int'. 17956 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17957 } 17958 EltTy = Val->getType(); 17959 } 17960 } 17961 } 17962 } 17963 17964 if (!Val) { 17965 if (Enum->isDependentType()) 17966 EltTy = Context.DependentTy; 17967 else if (!LastEnumConst) { 17968 // C++0x [dcl.enum]p5: 17969 // If the underlying type is not fixed, the type of each enumerator 17970 // is the type of its initializing value: 17971 // - If no initializer is specified for the first enumerator, the 17972 // initializing value has an unspecified integral type. 17973 // 17974 // GCC uses 'int' for its unspecified integral type, as does 17975 // C99 6.7.2.2p3. 17976 if (Enum->isFixed()) { 17977 EltTy = Enum->getIntegerType(); 17978 } 17979 else { 17980 EltTy = Context.IntTy; 17981 } 17982 } else { 17983 // Assign the last value + 1. 17984 EnumVal = LastEnumConst->getInitVal(); 17985 ++EnumVal; 17986 EltTy = LastEnumConst->getType(); 17987 17988 // Check for overflow on increment. 17989 if (EnumVal < LastEnumConst->getInitVal()) { 17990 // C++0x [dcl.enum]p5: 17991 // If the underlying type is not fixed, the type of each enumerator 17992 // is the type of its initializing value: 17993 // 17994 // - Otherwise the type of the initializing value is the same as 17995 // the type of the initializing value of the preceding enumerator 17996 // unless the incremented value is not representable in that type, 17997 // in which case the type is an unspecified integral type 17998 // sufficient to contain the incremented value. If no such type 17999 // exists, the program is ill-formed. 18000 QualType T = getNextLargerIntegralType(Context, EltTy); 18001 if (T.isNull() || Enum->isFixed()) { 18002 // There is no integral type larger enough to represent this 18003 // value. Complain, then allow the value to wrap around. 18004 EnumVal = LastEnumConst->getInitVal(); 18005 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 18006 ++EnumVal; 18007 if (Enum->isFixed()) 18008 // When the underlying type is fixed, this is ill-formed. 18009 Diag(IdLoc, diag::err_enumerator_wrapped) 18010 << toString(EnumVal, 10) 18011 << EltTy; 18012 else 18013 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 18014 << toString(EnumVal, 10); 18015 } else { 18016 EltTy = T; 18017 } 18018 18019 // Retrieve the last enumerator's value, extent that type to the 18020 // type that is supposed to be large enough to represent the incremented 18021 // value, then increment. 18022 EnumVal = LastEnumConst->getInitVal(); 18023 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18024 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 18025 ++EnumVal; 18026 18027 // If we're not in C++, diagnose the overflow of enumerator values, 18028 // which in C99 means that the enumerator value is not representable in 18029 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 18030 // permits enumerator values that are representable in some larger 18031 // integral type. 18032 if (!getLangOpts().CPlusPlus && !T.isNull()) 18033 Diag(IdLoc, diag::warn_enum_value_overflow); 18034 } else if (!getLangOpts().CPlusPlus && 18035 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18036 // Enforce C99 6.7.2.2p2 even when we compute the next value. 18037 Diag(IdLoc, diag::ext_enum_value_not_int) 18038 << toString(EnumVal, 10) << 1; 18039 } 18040 } 18041 } 18042 18043 if (!EltTy->isDependentType()) { 18044 // Make the enumerator value match the signedness and size of the 18045 // enumerator's type. 18046 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 18047 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18048 } 18049 18050 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 18051 Val, EnumVal); 18052 } 18053 18054 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 18055 SourceLocation IILoc) { 18056 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 18057 !getLangOpts().CPlusPlus) 18058 return SkipBodyInfo(); 18059 18060 // We have an anonymous enum definition. Look up the first enumerator to 18061 // determine if we should merge the definition with an existing one and 18062 // skip the body. 18063 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 18064 forRedeclarationInCurContext()); 18065 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 18066 if (!PrevECD) 18067 return SkipBodyInfo(); 18068 18069 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18070 NamedDecl *Hidden; 18071 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18072 SkipBodyInfo Skip; 18073 Skip.Previous = Hidden; 18074 return Skip; 18075 } 18076 18077 return SkipBodyInfo(); 18078 } 18079 18080 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18081 SourceLocation IdLoc, IdentifierInfo *Id, 18082 const ParsedAttributesView &Attrs, 18083 SourceLocation EqualLoc, Expr *Val) { 18084 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18085 EnumConstantDecl *LastEnumConst = 18086 cast_or_null<EnumConstantDecl>(lastEnumConst); 18087 18088 // The scope passed in may not be a decl scope. Zip up the scope tree until 18089 // we find one that is. 18090 S = getNonFieldDeclScope(S); 18091 18092 // Verify that there isn't already something declared with this name in this 18093 // scope. 18094 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18095 LookupName(R, S); 18096 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18097 18098 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18099 // Maybe we will complain about the shadowed template parameter. 18100 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18101 // Just pretend that we didn't see the previous declaration. 18102 PrevDecl = nullptr; 18103 } 18104 18105 // C++ [class.mem]p15: 18106 // If T is the name of a class, then each of the following shall have a name 18107 // different from T: 18108 // - every enumerator of every member of class T that is an unscoped 18109 // enumerated type 18110 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18111 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18112 DeclarationNameInfo(Id, IdLoc)); 18113 18114 EnumConstantDecl *New = 18115 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18116 if (!New) 18117 return nullptr; 18118 18119 if (PrevDecl) { 18120 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18121 // Check for other kinds of shadowing not already handled. 18122 CheckShadow(New, PrevDecl, R); 18123 } 18124 18125 // When in C++, we may get a TagDecl with the same name; in this case the 18126 // enum constant will 'hide' the tag. 18127 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18128 "Received TagDecl when not in C++!"); 18129 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18130 if (isa<EnumConstantDecl>(PrevDecl)) 18131 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18132 else 18133 Diag(IdLoc, diag::err_redefinition) << Id; 18134 notePreviousDefinition(PrevDecl, IdLoc); 18135 return nullptr; 18136 } 18137 } 18138 18139 // Process attributes. 18140 ProcessDeclAttributeList(S, New, Attrs); 18141 AddPragmaAttributes(S, New); 18142 18143 // Register this decl in the current scope stack. 18144 New->setAccess(TheEnumDecl->getAccess()); 18145 PushOnScopeChains(New, S); 18146 18147 ActOnDocumentableDecl(New); 18148 18149 return New; 18150 } 18151 18152 // Returns true when the enum initial expression does not trigger the 18153 // duplicate enum warning. A few common cases are exempted as follows: 18154 // Element2 = Element1 18155 // Element2 = Element1 + 1 18156 // Element2 = Element1 - 1 18157 // Where Element2 and Element1 are from the same enum. 18158 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18159 Expr *InitExpr = ECD->getInitExpr(); 18160 if (!InitExpr) 18161 return true; 18162 InitExpr = InitExpr->IgnoreImpCasts(); 18163 18164 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18165 if (!BO->isAdditiveOp()) 18166 return true; 18167 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18168 if (!IL) 18169 return true; 18170 if (IL->getValue() != 1) 18171 return true; 18172 18173 InitExpr = BO->getLHS(); 18174 } 18175 18176 // This checks if the elements are from the same enum. 18177 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18178 if (!DRE) 18179 return true; 18180 18181 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18182 if (!EnumConstant) 18183 return true; 18184 18185 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18186 Enum) 18187 return true; 18188 18189 return false; 18190 } 18191 18192 // Emits a warning when an element is implicitly set a value that 18193 // a previous element has already been set to. 18194 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18195 EnumDecl *Enum, QualType EnumType) { 18196 // Avoid anonymous enums 18197 if (!Enum->getIdentifier()) 18198 return; 18199 18200 // Only check for small enums. 18201 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18202 return; 18203 18204 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18205 return; 18206 18207 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18208 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18209 18210 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18211 18212 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18213 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18214 18215 // Use int64_t as a key to avoid needing special handling for map keys. 18216 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18217 llvm::APSInt Val = D->getInitVal(); 18218 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18219 }; 18220 18221 DuplicatesVector DupVector; 18222 ValueToVectorMap EnumMap; 18223 18224 // Populate the EnumMap with all values represented by enum constants without 18225 // an initializer. 18226 for (auto *Element : Elements) { 18227 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18228 18229 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18230 // this constant. Skip this enum since it may be ill-formed. 18231 if (!ECD) { 18232 return; 18233 } 18234 18235 // Constants with initalizers are handled in the next loop. 18236 if (ECD->getInitExpr()) 18237 continue; 18238 18239 // Duplicate values are handled in the next loop. 18240 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18241 } 18242 18243 if (EnumMap.size() == 0) 18244 return; 18245 18246 // Create vectors for any values that has duplicates. 18247 for (auto *Element : Elements) { 18248 // The last loop returned if any constant was null. 18249 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18250 if (!ValidDuplicateEnum(ECD, Enum)) 18251 continue; 18252 18253 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18254 if (Iter == EnumMap.end()) 18255 continue; 18256 18257 DeclOrVector& Entry = Iter->second; 18258 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18259 // Ensure constants are different. 18260 if (D == ECD) 18261 continue; 18262 18263 // Create new vector and push values onto it. 18264 auto Vec = std::make_unique<ECDVector>(); 18265 Vec->push_back(D); 18266 Vec->push_back(ECD); 18267 18268 // Update entry to point to the duplicates vector. 18269 Entry = Vec.get(); 18270 18271 // Store the vector somewhere we can consult later for quick emission of 18272 // diagnostics. 18273 DupVector.emplace_back(std::move(Vec)); 18274 continue; 18275 } 18276 18277 ECDVector *Vec = Entry.get<ECDVector*>(); 18278 // Make sure constants are not added more than once. 18279 if (*Vec->begin() == ECD) 18280 continue; 18281 18282 Vec->push_back(ECD); 18283 } 18284 18285 // Emit diagnostics. 18286 for (const auto &Vec : DupVector) { 18287 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18288 18289 // Emit warning for one enum constant. 18290 auto *FirstECD = Vec->front(); 18291 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18292 << FirstECD << toString(FirstECD->getInitVal(), 10) 18293 << FirstECD->getSourceRange(); 18294 18295 // Emit one note for each of the remaining enum constants with 18296 // the same value. 18297 for (auto *ECD : llvm::drop_begin(*Vec)) 18298 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18299 << ECD << toString(ECD->getInitVal(), 10) 18300 << ECD->getSourceRange(); 18301 } 18302 } 18303 18304 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18305 bool AllowMask) const { 18306 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18307 assert(ED->isCompleteDefinition() && "expected enum definition"); 18308 18309 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18310 llvm::APInt &FlagBits = R.first->second; 18311 18312 if (R.second) { 18313 for (auto *E : ED->enumerators()) { 18314 const auto &EVal = E->getInitVal(); 18315 // Only single-bit enumerators introduce new flag values. 18316 if (EVal.isPowerOf2()) 18317 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18318 } 18319 } 18320 18321 // A value is in a flag enum if either its bits are a subset of the enum's 18322 // flag bits (the first condition) or we are allowing masks and the same is 18323 // true of its complement (the second condition). When masks are allowed, we 18324 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18325 // 18326 // While it's true that any value could be used as a mask, the assumption is 18327 // that a mask will have all of the insignificant bits set. Anything else is 18328 // likely a logic error. 18329 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18330 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18331 } 18332 18333 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18334 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18335 const ParsedAttributesView &Attrs) { 18336 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18337 QualType EnumType = Context.getTypeDeclType(Enum); 18338 18339 ProcessDeclAttributeList(S, Enum, Attrs); 18340 18341 if (Enum->isDependentType()) { 18342 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18343 EnumConstantDecl *ECD = 18344 cast_or_null<EnumConstantDecl>(Elements[i]); 18345 if (!ECD) continue; 18346 18347 ECD->setType(EnumType); 18348 } 18349 18350 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18351 return; 18352 } 18353 18354 // TODO: If the result value doesn't fit in an int, it must be a long or long 18355 // long value. ISO C does not support this, but GCC does as an extension, 18356 // emit a warning. 18357 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18358 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18359 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18360 18361 // Verify that all the values are okay, compute the size of the values, and 18362 // reverse the list. 18363 unsigned NumNegativeBits = 0; 18364 unsigned NumPositiveBits = 0; 18365 18366 // Keep track of whether all elements have type int. 18367 bool AllElementsInt = true; 18368 18369 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18370 EnumConstantDecl *ECD = 18371 cast_or_null<EnumConstantDecl>(Elements[i]); 18372 if (!ECD) continue; // Already issued a diagnostic. 18373 18374 const llvm::APSInt &InitVal = ECD->getInitVal(); 18375 18376 // Keep track of the size of positive and negative values. 18377 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18378 NumPositiveBits = std::max(NumPositiveBits, 18379 (unsigned)InitVal.getActiveBits()); 18380 else 18381 NumNegativeBits = std::max(NumNegativeBits, 18382 (unsigned)InitVal.getMinSignedBits()); 18383 18384 // Keep track of whether every enum element has type int (very common). 18385 if (AllElementsInt) 18386 AllElementsInt = ECD->getType() == Context.IntTy; 18387 } 18388 18389 // Figure out the type that should be used for this enum. 18390 QualType BestType; 18391 unsigned BestWidth; 18392 18393 // C++0x N3000 [conv.prom]p3: 18394 // An rvalue of an unscoped enumeration type whose underlying 18395 // type is not fixed can be converted to an rvalue of the first 18396 // of the following types that can represent all the values of 18397 // the enumeration: int, unsigned int, long int, unsigned long 18398 // int, long long int, or unsigned long long int. 18399 // C99 6.4.4.3p2: 18400 // An identifier declared as an enumeration constant has type int. 18401 // The C99 rule is modified by a gcc extension 18402 QualType BestPromotionType; 18403 18404 bool Packed = Enum->hasAttr<PackedAttr>(); 18405 // -fshort-enums is the equivalent to specifying the packed attribute on all 18406 // enum definitions. 18407 if (LangOpts.ShortEnums) 18408 Packed = true; 18409 18410 // If the enum already has a type because it is fixed or dictated by the 18411 // target, promote that type instead of analyzing the enumerators. 18412 if (Enum->isComplete()) { 18413 BestType = Enum->getIntegerType(); 18414 if (BestType->isPromotableIntegerType()) 18415 BestPromotionType = Context.getPromotedIntegerType(BestType); 18416 else 18417 BestPromotionType = BestType; 18418 18419 BestWidth = Context.getIntWidth(BestType); 18420 } 18421 else if (NumNegativeBits) { 18422 // If there is a negative value, figure out the smallest integer type (of 18423 // int/long/longlong) that fits. 18424 // If it's packed, check also if it fits a char or a short. 18425 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18426 BestType = Context.SignedCharTy; 18427 BestWidth = CharWidth; 18428 } else if (Packed && NumNegativeBits <= ShortWidth && 18429 NumPositiveBits < ShortWidth) { 18430 BestType = Context.ShortTy; 18431 BestWidth = ShortWidth; 18432 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18433 BestType = Context.IntTy; 18434 BestWidth = IntWidth; 18435 } else { 18436 BestWidth = Context.getTargetInfo().getLongWidth(); 18437 18438 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18439 BestType = Context.LongTy; 18440 } else { 18441 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18442 18443 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18444 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18445 BestType = Context.LongLongTy; 18446 } 18447 } 18448 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18449 } else { 18450 // If there is no negative value, figure out the smallest type that fits 18451 // all of the enumerator values. 18452 // If it's packed, check also if it fits a char or a short. 18453 if (Packed && NumPositiveBits <= CharWidth) { 18454 BestType = Context.UnsignedCharTy; 18455 BestPromotionType = Context.IntTy; 18456 BestWidth = CharWidth; 18457 } else if (Packed && NumPositiveBits <= ShortWidth) { 18458 BestType = Context.UnsignedShortTy; 18459 BestPromotionType = Context.IntTy; 18460 BestWidth = ShortWidth; 18461 } else if (NumPositiveBits <= IntWidth) { 18462 BestType = Context.UnsignedIntTy; 18463 BestWidth = IntWidth; 18464 BestPromotionType 18465 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18466 ? Context.UnsignedIntTy : Context.IntTy; 18467 } else if (NumPositiveBits <= 18468 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18469 BestType = Context.UnsignedLongTy; 18470 BestPromotionType 18471 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18472 ? Context.UnsignedLongTy : Context.LongTy; 18473 } else { 18474 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18475 assert(NumPositiveBits <= BestWidth && 18476 "How could an initializer get larger than ULL?"); 18477 BestType = Context.UnsignedLongLongTy; 18478 BestPromotionType 18479 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18480 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18481 } 18482 } 18483 18484 // Loop over all of the enumerator constants, changing their types to match 18485 // the type of the enum if needed. 18486 for (auto *D : Elements) { 18487 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18488 if (!ECD) continue; // Already issued a diagnostic. 18489 18490 // Standard C says the enumerators have int type, but we allow, as an 18491 // extension, the enumerators to be larger than int size. If each 18492 // enumerator value fits in an int, type it as an int, otherwise type it the 18493 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18494 // that X has type 'int', not 'unsigned'. 18495 18496 // Determine whether the value fits into an int. 18497 llvm::APSInt InitVal = ECD->getInitVal(); 18498 18499 // If it fits into an integer type, force it. Otherwise force it to match 18500 // the enum decl type. 18501 QualType NewTy; 18502 unsigned NewWidth; 18503 bool NewSign; 18504 if (!getLangOpts().CPlusPlus && 18505 !Enum->isFixed() && 18506 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18507 NewTy = Context.IntTy; 18508 NewWidth = IntWidth; 18509 NewSign = true; 18510 } else if (ECD->getType() == BestType) { 18511 // Already the right type! 18512 if (getLangOpts().CPlusPlus) 18513 // C++ [dcl.enum]p4: Following the closing brace of an 18514 // enum-specifier, each enumerator has the type of its 18515 // enumeration. 18516 ECD->setType(EnumType); 18517 continue; 18518 } else { 18519 NewTy = BestType; 18520 NewWidth = BestWidth; 18521 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18522 } 18523 18524 // Adjust the APSInt value. 18525 InitVal = InitVal.extOrTrunc(NewWidth); 18526 InitVal.setIsSigned(NewSign); 18527 ECD->setInitVal(InitVal); 18528 18529 // Adjust the Expr initializer and type. 18530 if (ECD->getInitExpr() && 18531 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18532 ECD->setInitExpr(ImplicitCastExpr::Create( 18533 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18534 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18535 if (getLangOpts().CPlusPlus) 18536 // C++ [dcl.enum]p4: Following the closing brace of an 18537 // enum-specifier, each enumerator has the type of its 18538 // enumeration. 18539 ECD->setType(EnumType); 18540 else 18541 ECD->setType(NewTy); 18542 } 18543 18544 Enum->completeDefinition(BestType, BestPromotionType, 18545 NumPositiveBits, NumNegativeBits); 18546 18547 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18548 18549 if (Enum->isClosedFlag()) { 18550 for (Decl *D : Elements) { 18551 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18552 if (!ECD) continue; // Already issued a diagnostic. 18553 18554 llvm::APSInt InitVal = ECD->getInitVal(); 18555 if (InitVal != 0 && !InitVal.isPowerOf2() && 18556 !IsValueInFlagEnum(Enum, InitVal, true)) 18557 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18558 << ECD << Enum; 18559 } 18560 } 18561 18562 // Now that the enum type is defined, ensure it's not been underaligned. 18563 if (Enum->hasAttrs()) 18564 CheckAlignasUnderalignment(Enum); 18565 } 18566 18567 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18568 SourceLocation StartLoc, 18569 SourceLocation EndLoc) { 18570 StringLiteral *AsmString = cast<StringLiteral>(expr); 18571 18572 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18573 AsmString, StartLoc, 18574 EndLoc); 18575 CurContext->addDecl(New); 18576 return New; 18577 } 18578 18579 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18580 IdentifierInfo* AliasName, 18581 SourceLocation PragmaLoc, 18582 SourceLocation NameLoc, 18583 SourceLocation AliasNameLoc) { 18584 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18585 LookupOrdinaryName); 18586 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18587 AttributeCommonInfo::AS_Pragma); 18588 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18589 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18590 18591 // If a declaration that: 18592 // 1) declares a function or a variable 18593 // 2) has external linkage 18594 // already exists, add a label attribute to it. 18595 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18596 if (isDeclExternC(PrevDecl)) 18597 PrevDecl->addAttr(Attr); 18598 else 18599 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18600 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18601 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18602 } else 18603 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18604 } 18605 18606 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18607 SourceLocation PragmaLoc, 18608 SourceLocation NameLoc) { 18609 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18610 18611 if (PrevDecl) { 18612 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18613 } else { 18614 (void)WeakUndeclaredIdentifiers.insert( 18615 std::pair<IdentifierInfo*,WeakInfo> 18616 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18617 } 18618 } 18619 18620 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18621 IdentifierInfo* AliasName, 18622 SourceLocation PragmaLoc, 18623 SourceLocation NameLoc, 18624 SourceLocation AliasNameLoc) { 18625 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18626 LookupOrdinaryName); 18627 WeakInfo W = WeakInfo(Name, NameLoc); 18628 18629 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18630 if (!PrevDecl->hasAttr<AliasAttr>()) 18631 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18632 DeclApplyPragmaWeak(TUScope, ND, W); 18633 } else { 18634 (void)WeakUndeclaredIdentifiers.insert( 18635 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18636 } 18637 } 18638 18639 Decl *Sema::getObjCDeclContext() const { 18640 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18641 } 18642 18643 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18644 bool Final) { 18645 assert(FD && "Expected non-null FunctionDecl"); 18646 18647 // SYCL functions can be template, so we check if they have appropriate 18648 // attribute prior to checking if it is a template. 18649 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18650 return FunctionEmissionStatus::Emitted; 18651 18652 // Templates are emitted when they're instantiated. 18653 if (FD->isDependentContext()) 18654 return FunctionEmissionStatus::TemplateDiscarded; 18655 18656 // Check whether this function is an externally visible definition. 18657 auto IsEmittedForExternalSymbol = [this, FD]() { 18658 // We have to check the GVA linkage of the function's *definition* -- if we 18659 // only have a declaration, we don't know whether or not the function will 18660 // be emitted, because (say) the definition could include "inline". 18661 FunctionDecl *Def = FD->getDefinition(); 18662 18663 return Def && !isDiscardableGVALinkage( 18664 getASTContext().GetGVALinkageForFunction(Def)); 18665 }; 18666 18667 if (LangOpts.OpenMPIsDevice) { 18668 // In OpenMP device mode we will not emit host only functions, or functions 18669 // we don't need due to their linkage. 18670 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18671 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18672 // DevTy may be changed later by 18673 // #pragma omp declare target to(*) device_type(*). 18674 // Therefore DevTy having no value does not imply host. The emission status 18675 // will be checked again at the end of compilation unit with Final = true. 18676 if (DevTy.hasValue()) 18677 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18678 return FunctionEmissionStatus::OMPDiscarded; 18679 // If we have an explicit value for the device type, or we are in a target 18680 // declare context, we need to emit all extern and used symbols. 18681 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18682 if (IsEmittedForExternalSymbol()) 18683 return FunctionEmissionStatus::Emitted; 18684 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18685 // we'll omit it. 18686 if (Final) 18687 return FunctionEmissionStatus::OMPDiscarded; 18688 } else if (LangOpts.OpenMP > 45) { 18689 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18690 // function. In 5.0, no_host was introduced which might cause a function to 18691 // be ommitted. 18692 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18693 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18694 if (DevTy.hasValue()) 18695 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18696 return FunctionEmissionStatus::OMPDiscarded; 18697 } 18698 18699 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18700 return FunctionEmissionStatus::Emitted; 18701 18702 if (LangOpts.CUDA) { 18703 // When compiling for device, host functions are never emitted. Similarly, 18704 // when compiling for host, device and global functions are never emitted. 18705 // (Technically, we do emit a host-side stub for global functions, but this 18706 // doesn't count for our purposes here.) 18707 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18708 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18709 return FunctionEmissionStatus::CUDADiscarded; 18710 if (!LangOpts.CUDAIsDevice && 18711 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18712 return FunctionEmissionStatus::CUDADiscarded; 18713 18714 if (IsEmittedForExternalSymbol()) 18715 return FunctionEmissionStatus::Emitted; 18716 } 18717 18718 // Otherwise, the function is known-emitted if it's in our set of 18719 // known-emitted functions. 18720 return FunctionEmissionStatus::Unknown; 18721 } 18722 18723 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18724 // Host-side references to a __global__ function refer to the stub, so the 18725 // function itself is never emitted and therefore should not be marked. 18726 // If we have host fn calls kernel fn calls host+device, the HD function 18727 // does not get instantiated on the host. We model this by omitting at the 18728 // call to the kernel from the callgraph. This ensures that, when compiling 18729 // for host, only HD functions actually called from the host get marked as 18730 // known-emitted. 18731 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18732 IdentifyCUDATarget(Callee) == CFT_Global; 18733 } 18734