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 // [module.interface]p7: 1590 // A declaration is attached to a module as follows: 1591 // - If the declaration is a non-dependent friend declaration that nominates a 1592 // function with a declarator-id that is a qualified-id or template-id or that 1593 // nominates a class other than with an elaborated-type-specifier with neither 1594 // a nested-name-specifier nor a simple-template-id, it is attached to the 1595 // module to which the friend is attached ([basic.link]). 1596 if (New->getFriendObjectKind() && 1597 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1598 New->setLocalOwningModule(Old->getOwningModule()); 1599 makeMergedDefinitionVisible(New); 1600 return false; 1601 } 1602 1603 Module *NewM = New->getOwningModule(); 1604 Module *OldM = Old->getOwningModule(); 1605 1606 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1607 NewM = NewM->Parent; 1608 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1609 OldM = OldM->Parent; 1610 1611 if (NewM == OldM) 1612 return false; 1613 1614 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1615 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1616 if (NewIsModuleInterface || OldIsModuleInterface) { 1617 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1618 // if a declaration of D [...] appears in the purview of a module, all 1619 // other such declarations shall appear in the purview of the same module 1620 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1621 << New 1622 << NewIsModuleInterface 1623 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1624 << OldIsModuleInterface 1625 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1626 Diag(Old->getLocation(), diag::note_previous_declaration); 1627 New->setInvalidDecl(); 1628 return true; 1629 } 1630 1631 return false; 1632 } 1633 1634 // [module.interface]p6: 1635 // A redeclaration of an entity X is implicitly exported if X was introduced by 1636 // an exported declaration; otherwise it shall not be exported. 1637 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { 1638 // [module.interface]p1: 1639 // An export-declaration shall inhabit a namespace scope. 1640 // 1641 // So it is meaningless to talk about redeclaration which is not at namespace 1642 // scope. 1643 if (!New->getLexicalDeclContext() 1644 ->getNonTransparentContext() 1645 ->isFileContext() || 1646 !Old->getLexicalDeclContext() 1647 ->getNonTransparentContext() 1648 ->isFileContext()) 1649 return false; 1650 1651 bool IsNewExported = New->isInExportDeclContext(); 1652 bool IsOldExported = Old->isInExportDeclContext(); 1653 1654 // It should be irrevelant if both of them are not exported. 1655 if (!IsNewExported && !IsOldExported) 1656 return false; 1657 1658 if (IsOldExported) 1659 return false; 1660 1661 assert(IsNewExported); 1662 1663 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New; 1664 Diag(Old->getLocation(), diag::note_previous_declaration); 1665 return true; 1666 } 1667 1668 // A wrapper function for checking the semantic restrictions of 1669 // a redeclaration within a module. 1670 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1671 if (CheckRedeclarationModuleOwnership(New, Old)) 1672 return true; 1673 1674 if (CheckRedeclarationExported(New, Old)) 1675 return true; 1676 1677 return false; 1678 } 1679 1680 static bool isUsingDecl(NamedDecl *D) { 1681 return isa<UsingShadowDecl>(D) || 1682 isa<UnresolvedUsingTypenameDecl>(D) || 1683 isa<UnresolvedUsingValueDecl>(D); 1684 } 1685 1686 /// Removes using shadow declarations from the lookup results. 1687 static void RemoveUsingDecls(LookupResult &R) { 1688 LookupResult::Filter F = R.makeFilter(); 1689 while (F.hasNext()) 1690 if (isUsingDecl(F.next())) 1691 F.erase(); 1692 1693 F.done(); 1694 } 1695 1696 /// Check for this common pattern: 1697 /// @code 1698 /// class S { 1699 /// S(const S&); // DO NOT IMPLEMENT 1700 /// void operator=(const S&); // DO NOT IMPLEMENT 1701 /// }; 1702 /// @endcode 1703 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1704 // FIXME: Should check for private access too but access is set after we get 1705 // the decl here. 1706 if (D->doesThisDeclarationHaveABody()) 1707 return false; 1708 1709 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1710 return CD->isCopyConstructor(); 1711 return D->isCopyAssignmentOperator(); 1712 } 1713 1714 // We need this to handle 1715 // 1716 // typedef struct { 1717 // void *foo() { return 0; } 1718 // } A; 1719 // 1720 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1721 // for example. If 'A', foo will have external linkage. If we have '*A', 1722 // foo will have no linkage. Since we can't know until we get to the end 1723 // of the typedef, this function finds out if D might have non-external linkage. 1724 // Callers should verify at the end of the TU if it D has external linkage or 1725 // not. 1726 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1727 const DeclContext *DC = D->getDeclContext(); 1728 while (!DC->isTranslationUnit()) { 1729 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1730 if (!RD->hasNameForLinkage()) 1731 return true; 1732 } 1733 DC = DC->getParent(); 1734 } 1735 1736 return !D->isExternallyVisible(); 1737 } 1738 1739 // FIXME: This needs to be refactored; some other isInMainFile users want 1740 // these semantics. 1741 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1742 if (S.TUKind != TU_Complete) 1743 return false; 1744 return S.SourceMgr.isInMainFile(Loc); 1745 } 1746 1747 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1748 assert(D); 1749 1750 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1751 return false; 1752 1753 // Ignore all entities declared within templates, and out-of-line definitions 1754 // of members of class templates. 1755 if (D->getDeclContext()->isDependentContext() || 1756 D->getLexicalDeclContext()->isDependentContext()) 1757 return false; 1758 1759 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1760 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1761 return false; 1762 // A non-out-of-line declaration of a member specialization was implicitly 1763 // instantiated; it's the out-of-line declaration that we're interested in. 1764 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1765 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1766 return false; 1767 1768 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1769 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1770 return false; 1771 } else { 1772 // 'static inline' functions are defined in headers; don't warn. 1773 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1774 return false; 1775 } 1776 1777 if (FD->doesThisDeclarationHaveABody() && 1778 Context.DeclMustBeEmitted(FD)) 1779 return false; 1780 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1781 // Constants and utility variables are defined in headers with internal 1782 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1783 // like "inline".) 1784 if (!isMainFileLoc(*this, VD->getLocation())) 1785 return false; 1786 1787 if (Context.DeclMustBeEmitted(VD)) 1788 return false; 1789 1790 if (VD->isStaticDataMember() && 1791 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1792 return false; 1793 if (VD->isStaticDataMember() && 1794 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1795 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1796 return false; 1797 1798 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1799 return false; 1800 } else { 1801 return false; 1802 } 1803 1804 // Only warn for unused decls internal to the translation unit. 1805 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1806 // for inline functions defined in the main source file, for instance. 1807 return mightHaveNonExternalLinkage(D); 1808 } 1809 1810 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1811 if (!D) 1812 return; 1813 1814 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1815 const FunctionDecl *First = FD->getFirstDecl(); 1816 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1817 return; // First should already be in the vector. 1818 } 1819 1820 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1821 const VarDecl *First = VD->getFirstDecl(); 1822 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1823 return; // First should already be in the vector. 1824 } 1825 1826 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1827 UnusedFileScopedDecls.push_back(D); 1828 } 1829 1830 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1831 if (D->isInvalidDecl()) 1832 return false; 1833 1834 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1835 // For a decomposition declaration, warn if none of the bindings are 1836 // referenced, instead of if the variable itself is referenced (which 1837 // it is, by the bindings' expressions). 1838 for (auto *BD : DD->bindings()) 1839 if (BD->isReferenced()) 1840 return false; 1841 } else if (!D->getDeclName()) { 1842 return false; 1843 } else if (D->isReferenced() || D->isUsed()) { 1844 return false; 1845 } 1846 1847 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1848 return false; 1849 1850 if (isa<LabelDecl>(D)) 1851 return true; 1852 1853 // Except for labels, we only care about unused decls that are local to 1854 // functions. 1855 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1856 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1857 // For dependent types, the diagnostic is deferred. 1858 WithinFunction = 1859 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1860 if (!WithinFunction) 1861 return false; 1862 1863 if (isa<TypedefNameDecl>(D)) 1864 return true; 1865 1866 // White-list anything that isn't a local variable. 1867 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1868 return false; 1869 1870 // Types of valid local variables should be complete, so this should succeed. 1871 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1872 1873 // White-list anything with an __attribute__((unused)) type. 1874 const auto *Ty = VD->getType().getTypePtr(); 1875 1876 // Only look at the outermost level of typedef. 1877 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1878 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1879 return false; 1880 } 1881 1882 // If we failed to complete the type for some reason, or if the type is 1883 // dependent, don't diagnose the variable. 1884 if (Ty->isIncompleteType() || Ty->isDependentType()) 1885 return false; 1886 1887 // Look at the element type to ensure that the warning behaviour is 1888 // consistent for both scalars and arrays. 1889 Ty = Ty->getBaseElementTypeUnsafe(); 1890 1891 if (const TagType *TT = Ty->getAs<TagType>()) { 1892 const TagDecl *Tag = TT->getDecl(); 1893 if (Tag->hasAttr<UnusedAttr>()) 1894 return false; 1895 1896 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1897 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1898 return false; 1899 1900 if (const Expr *Init = VD->getInit()) { 1901 if (const ExprWithCleanups *Cleanups = 1902 dyn_cast<ExprWithCleanups>(Init)) 1903 Init = Cleanups->getSubExpr(); 1904 const CXXConstructExpr *Construct = 1905 dyn_cast<CXXConstructExpr>(Init); 1906 if (Construct && !Construct->isElidable()) { 1907 CXXConstructorDecl *CD = Construct->getConstructor(); 1908 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1909 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1910 return false; 1911 } 1912 1913 // Suppress the warning if we don't know how this is constructed, and 1914 // it could possibly be non-trivial constructor. 1915 if (Init->isTypeDependent()) 1916 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1917 if (!Ctor->isTrivial()) 1918 return false; 1919 } 1920 } 1921 } 1922 1923 // TODO: __attribute__((unused)) templates? 1924 } 1925 1926 return true; 1927 } 1928 1929 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1930 FixItHint &Hint) { 1931 if (isa<LabelDecl>(D)) { 1932 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1933 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1934 true); 1935 if (AfterColon.isInvalid()) 1936 return; 1937 Hint = FixItHint::CreateRemoval( 1938 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1939 } 1940 } 1941 1942 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1943 if (D->getTypeForDecl()->isDependentType()) 1944 return; 1945 1946 for (auto *TmpD : D->decls()) { 1947 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1948 DiagnoseUnusedDecl(T); 1949 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1950 DiagnoseUnusedNestedTypedefs(R); 1951 } 1952 } 1953 1954 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1955 /// unless they are marked attr(unused). 1956 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1957 if (!ShouldDiagnoseUnusedDecl(D)) 1958 return; 1959 1960 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1961 // typedefs can be referenced later on, so the diagnostics are emitted 1962 // at end-of-translation-unit. 1963 UnusedLocalTypedefNameCandidates.insert(TD); 1964 return; 1965 } 1966 1967 FixItHint Hint; 1968 GenerateFixForUnusedDecl(D, Context, Hint); 1969 1970 unsigned DiagID; 1971 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1972 DiagID = diag::warn_unused_exception_param; 1973 else if (isa<LabelDecl>(D)) 1974 DiagID = diag::warn_unused_label; 1975 else 1976 DiagID = diag::warn_unused_variable; 1977 1978 Diag(D->getLocation(), DiagID) << D << Hint; 1979 } 1980 1981 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 1982 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 1983 // it's not really unused. 1984 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 1985 VD->hasAttr<CleanupAttr>()) 1986 return; 1987 1988 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 1989 1990 if (Ty->isReferenceType() || Ty->isDependentType()) 1991 return; 1992 1993 if (const TagType *TT = Ty->getAs<TagType>()) { 1994 const TagDecl *Tag = TT->getDecl(); 1995 if (Tag->hasAttr<UnusedAttr>()) 1996 return; 1997 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 1998 // mimic gcc's behavior. 1999 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 2000 if (!RD->hasAttr<WarnUnusedAttr>()) 2001 return; 2002 } 2003 } 2004 2005 // Don't warn about __block Objective-C pointer variables, as they might 2006 // be assigned in the block but not used elsewhere for the purpose of lifetime 2007 // extension. 2008 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 2009 return; 2010 2011 auto iter = RefsMinusAssignments.find(VD); 2012 if (iter == RefsMinusAssignments.end()) 2013 return; 2014 2015 assert(iter->getSecond() >= 0 && 2016 "Found a negative number of references to a VarDecl"); 2017 if (iter->getSecond() != 0) 2018 return; 2019 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2020 : diag::warn_unused_but_set_variable; 2021 Diag(VD->getLocation(), DiagID) << VD; 2022 } 2023 2024 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 2025 // Verify that we have no forward references left. If so, there was a goto 2026 // or address of a label taken, but no definition of it. Label fwd 2027 // definitions are indicated with a null substmt which is also not a resolved 2028 // MS inline assembly label name. 2029 bool Diagnose = false; 2030 if (L->isMSAsmLabel()) 2031 Diagnose = !L->isResolvedMSAsmLabel(); 2032 else 2033 Diagnose = L->getStmt() == nullptr; 2034 if (Diagnose) 2035 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 2036 } 2037 2038 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2039 S->mergeNRVOIntoParent(); 2040 2041 if (S->decl_empty()) return; 2042 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2043 "Scope shouldn't contain decls!"); 2044 2045 for (auto *TmpD : S->decls()) { 2046 assert(TmpD && "This decl didn't get pushed??"); 2047 2048 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2049 NamedDecl *D = cast<NamedDecl>(TmpD); 2050 2051 // Diagnose unused variables in this scope. 2052 if (!S->hasUnrecoverableErrorOccurred()) { 2053 DiagnoseUnusedDecl(D); 2054 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2055 DiagnoseUnusedNestedTypedefs(RD); 2056 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2057 DiagnoseUnusedButSetDecl(VD); 2058 RefsMinusAssignments.erase(VD); 2059 } 2060 } 2061 2062 if (!D->getDeclName()) continue; 2063 2064 // If this was a forward reference to a label, verify it was defined. 2065 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2066 CheckPoppedLabel(LD, *this); 2067 2068 // Remove this name from our lexical scope, and warn on it if we haven't 2069 // already. 2070 IdResolver.RemoveDecl(D); 2071 auto ShadowI = ShadowingDecls.find(D); 2072 if (ShadowI != ShadowingDecls.end()) { 2073 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2074 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2075 << D << FD << FD->getParent(); 2076 Diag(FD->getLocation(), diag::note_previous_declaration); 2077 } 2078 ShadowingDecls.erase(ShadowI); 2079 } 2080 } 2081 } 2082 2083 /// Look for an Objective-C class in the translation unit. 2084 /// 2085 /// \param Id The name of the Objective-C class we're looking for. If 2086 /// typo-correction fixes this name, the Id will be updated 2087 /// to the fixed name. 2088 /// 2089 /// \param IdLoc The location of the name in the translation unit. 2090 /// 2091 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2092 /// if there is no class with the given name. 2093 /// 2094 /// \returns The declaration of the named Objective-C class, or NULL if the 2095 /// class could not be found. 2096 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2097 SourceLocation IdLoc, 2098 bool DoTypoCorrection) { 2099 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2100 // creation from this context. 2101 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2102 2103 if (!IDecl && DoTypoCorrection) { 2104 // Perform typo correction at the given location, but only if we 2105 // find an Objective-C class name. 2106 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2107 if (TypoCorrection C = 2108 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2109 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2110 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2111 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2112 Id = IDecl->getIdentifier(); 2113 } 2114 } 2115 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2116 // This routine must always return a class definition, if any. 2117 if (Def && Def->getDefinition()) 2118 Def = Def->getDefinition(); 2119 return Def; 2120 } 2121 2122 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2123 /// from S, where a non-field would be declared. This routine copes 2124 /// with the difference between C and C++ scoping rules in structs and 2125 /// unions. For example, the following code is well-formed in C but 2126 /// ill-formed in C++: 2127 /// @code 2128 /// struct S6 { 2129 /// enum { BAR } e; 2130 /// }; 2131 /// 2132 /// void test_S6() { 2133 /// struct S6 a; 2134 /// a.e = BAR; 2135 /// } 2136 /// @endcode 2137 /// For the declaration of BAR, this routine will return a different 2138 /// scope. The scope S will be the scope of the unnamed enumeration 2139 /// within S6. In C++, this routine will return the scope associated 2140 /// with S6, because the enumeration's scope is a transparent 2141 /// context but structures can contain non-field names. In C, this 2142 /// routine will return the translation unit scope, since the 2143 /// enumeration's scope is a transparent context and structures cannot 2144 /// contain non-field names. 2145 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2146 while (((S->getFlags() & Scope::DeclScope) == 0) || 2147 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2148 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2149 S = S->getParent(); 2150 return S; 2151 } 2152 2153 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2154 ASTContext::GetBuiltinTypeError Error) { 2155 switch (Error) { 2156 case ASTContext::GE_None: 2157 return ""; 2158 case ASTContext::GE_Missing_type: 2159 return BuiltinInfo.getHeaderName(ID); 2160 case ASTContext::GE_Missing_stdio: 2161 return "stdio.h"; 2162 case ASTContext::GE_Missing_setjmp: 2163 return "setjmp.h"; 2164 case ASTContext::GE_Missing_ucontext: 2165 return "ucontext.h"; 2166 } 2167 llvm_unreachable("unhandled error kind"); 2168 } 2169 2170 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2171 unsigned ID, SourceLocation Loc) { 2172 DeclContext *Parent = Context.getTranslationUnitDecl(); 2173 2174 if (getLangOpts().CPlusPlus) { 2175 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2176 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2177 CLinkageDecl->setImplicit(); 2178 Parent->addDecl(CLinkageDecl); 2179 Parent = CLinkageDecl; 2180 } 2181 2182 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2183 /*TInfo=*/nullptr, SC_Extern, 2184 getCurFPFeatures().isFPConstrained(), 2185 false, Type->isFunctionProtoType()); 2186 New->setImplicit(); 2187 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2188 2189 // Create Decl objects for each parameter, adding them to the 2190 // FunctionDecl. 2191 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2192 SmallVector<ParmVarDecl *, 16> Params; 2193 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2194 ParmVarDecl *parm = ParmVarDecl::Create( 2195 Context, New, SourceLocation(), SourceLocation(), nullptr, 2196 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2197 parm->setScopeInfo(0, i); 2198 Params.push_back(parm); 2199 } 2200 New->setParams(Params); 2201 } 2202 2203 AddKnownFunctionAttributes(New); 2204 return New; 2205 } 2206 2207 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2208 /// file scope. lazily create a decl for it. ForRedeclaration is true 2209 /// if we're creating this built-in in anticipation of redeclaring the 2210 /// built-in. 2211 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2212 Scope *S, bool ForRedeclaration, 2213 SourceLocation Loc) { 2214 LookupNecessaryTypesForBuiltin(S, ID); 2215 2216 ASTContext::GetBuiltinTypeError Error; 2217 QualType R = Context.GetBuiltinType(ID, Error); 2218 if (Error) { 2219 if (!ForRedeclaration) 2220 return nullptr; 2221 2222 // If we have a builtin without an associated type we should not emit a 2223 // warning when we were not able to find a type for it. 2224 if (Error == ASTContext::GE_Missing_type || 2225 Context.BuiltinInfo.allowTypeMismatch(ID)) 2226 return nullptr; 2227 2228 // If we could not find a type for setjmp it is because the jmp_buf type was 2229 // not defined prior to the setjmp declaration. 2230 if (Error == ASTContext::GE_Missing_setjmp) { 2231 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2232 << Context.BuiltinInfo.getName(ID); 2233 return nullptr; 2234 } 2235 2236 // Generally, we emit a warning that the declaration requires the 2237 // appropriate header. 2238 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2239 << getHeaderName(Context.BuiltinInfo, ID, Error) 2240 << Context.BuiltinInfo.getName(ID); 2241 return nullptr; 2242 } 2243 2244 if (!ForRedeclaration && 2245 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2246 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2247 Diag(Loc, diag::ext_implicit_lib_function_decl) 2248 << Context.BuiltinInfo.getName(ID) << R; 2249 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2250 Diag(Loc, diag::note_include_header_or_declare) 2251 << Header << Context.BuiltinInfo.getName(ID); 2252 } 2253 2254 if (R.isNull()) 2255 return nullptr; 2256 2257 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2258 RegisterLocallyScopedExternCDecl(New, S); 2259 2260 // TUScope is the translation-unit scope to insert this function into. 2261 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2262 // relate Scopes to DeclContexts, and probably eliminate CurContext 2263 // entirely, but we're not there yet. 2264 DeclContext *SavedContext = CurContext; 2265 CurContext = New->getDeclContext(); 2266 PushOnScopeChains(New, TUScope); 2267 CurContext = SavedContext; 2268 return New; 2269 } 2270 2271 /// Typedef declarations don't have linkage, but they still denote the same 2272 /// entity if their types are the same. 2273 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2274 /// isSameEntity. 2275 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2276 TypedefNameDecl *Decl, 2277 LookupResult &Previous) { 2278 // This is only interesting when modules are enabled. 2279 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2280 return; 2281 2282 // Empty sets are uninteresting. 2283 if (Previous.empty()) 2284 return; 2285 2286 LookupResult::Filter Filter = Previous.makeFilter(); 2287 while (Filter.hasNext()) { 2288 NamedDecl *Old = Filter.next(); 2289 2290 // Non-hidden declarations are never ignored. 2291 if (S.isVisible(Old)) 2292 continue; 2293 2294 // Declarations of the same entity are not ignored, even if they have 2295 // different linkages. 2296 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2297 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2298 Decl->getUnderlyingType())) 2299 continue; 2300 2301 // If both declarations give a tag declaration a typedef name for linkage 2302 // purposes, then they declare the same entity. 2303 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2304 Decl->getAnonDeclWithTypedefName()) 2305 continue; 2306 } 2307 2308 Filter.erase(); 2309 } 2310 2311 Filter.done(); 2312 } 2313 2314 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2315 QualType OldType; 2316 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2317 OldType = OldTypedef->getUnderlyingType(); 2318 else 2319 OldType = Context.getTypeDeclType(Old); 2320 QualType NewType = New->getUnderlyingType(); 2321 2322 if (NewType->isVariablyModifiedType()) { 2323 // Must not redefine a typedef with a variably-modified type. 2324 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2325 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2326 << Kind << NewType; 2327 if (Old->getLocation().isValid()) 2328 notePreviousDefinition(Old, New->getLocation()); 2329 New->setInvalidDecl(); 2330 return true; 2331 } 2332 2333 if (OldType != NewType && 2334 !OldType->isDependentType() && 2335 !NewType->isDependentType() && 2336 !Context.hasSameType(OldType, NewType)) { 2337 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2338 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2339 << Kind << NewType << OldType; 2340 if (Old->getLocation().isValid()) 2341 notePreviousDefinition(Old, New->getLocation()); 2342 New->setInvalidDecl(); 2343 return true; 2344 } 2345 return false; 2346 } 2347 2348 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2349 /// same name and scope as a previous declaration 'Old'. Figure out 2350 /// how to resolve this situation, merging decls or emitting 2351 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2352 /// 2353 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2354 LookupResult &OldDecls) { 2355 // If the new decl is known invalid already, don't bother doing any 2356 // merging checks. 2357 if (New->isInvalidDecl()) return; 2358 2359 // Allow multiple definitions for ObjC built-in typedefs. 2360 // FIXME: Verify the underlying types are equivalent! 2361 if (getLangOpts().ObjC) { 2362 const IdentifierInfo *TypeID = New->getIdentifier(); 2363 switch (TypeID->getLength()) { 2364 default: break; 2365 case 2: 2366 { 2367 if (!TypeID->isStr("id")) 2368 break; 2369 QualType T = New->getUnderlyingType(); 2370 if (!T->isPointerType()) 2371 break; 2372 if (!T->isVoidPointerType()) { 2373 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2374 if (!PT->isStructureType()) 2375 break; 2376 } 2377 Context.setObjCIdRedefinitionType(T); 2378 // Install the built-in type for 'id', ignoring the current definition. 2379 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2380 return; 2381 } 2382 case 5: 2383 if (!TypeID->isStr("Class")) 2384 break; 2385 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2386 // Install the built-in type for 'Class', ignoring the current definition. 2387 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2388 return; 2389 case 3: 2390 if (!TypeID->isStr("SEL")) 2391 break; 2392 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2393 // Install the built-in type for 'SEL', ignoring the current definition. 2394 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2395 return; 2396 } 2397 // Fall through - the typedef name was not a builtin type. 2398 } 2399 2400 // Verify the old decl was also a type. 2401 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2402 if (!Old) { 2403 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2404 << New->getDeclName(); 2405 2406 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2407 if (OldD->getLocation().isValid()) 2408 notePreviousDefinition(OldD, New->getLocation()); 2409 2410 return New->setInvalidDecl(); 2411 } 2412 2413 // If the old declaration is invalid, just give up here. 2414 if (Old->isInvalidDecl()) 2415 return New->setInvalidDecl(); 2416 2417 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2418 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2419 auto *NewTag = New->getAnonDeclWithTypedefName(); 2420 NamedDecl *Hidden = nullptr; 2421 if (OldTag && NewTag && 2422 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2423 !hasVisibleDefinition(OldTag, &Hidden)) { 2424 // There is a definition of this tag, but it is not visible. Use it 2425 // instead of our tag. 2426 New->setTypeForDecl(OldTD->getTypeForDecl()); 2427 if (OldTD->isModed()) 2428 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2429 OldTD->getUnderlyingType()); 2430 else 2431 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2432 2433 // Make the old tag definition visible. 2434 makeMergedDefinitionVisible(Hidden); 2435 2436 // If this was an unscoped enumeration, yank all of its enumerators 2437 // out of the scope. 2438 if (isa<EnumDecl>(NewTag)) { 2439 Scope *EnumScope = getNonFieldDeclScope(S); 2440 for (auto *D : NewTag->decls()) { 2441 auto *ED = cast<EnumConstantDecl>(D); 2442 assert(EnumScope->isDeclScope(ED)); 2443 EnumScope->RemoveDecl(ED); 2444 IdResolver.RemoveDecl(ED); 2445 ED->getLexicalDeclContext()->removeDecl(ED); 2446 } 2447 } 2448 } 2449 } 2450 2451 // If the typedef types are not identical, reject them in all languages and 2452 // with any extensions enabled. 2453 if (isIncompatibleTypedef(Old, New)) 2454 return; 2455 2456 // The types match. Link up the redeclaration chain and merge attributes if 2457 // the old declaration was a typedef. 2458 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2459 New->setPreviousDecl(Typedef); 2460 mergeDeclAttributes(New, Old); 2461 } 2462 2463 if (getLangOpts().MicrosoftExt) 2464 return; 2465 2466 if (getLangOpts().CPlusPlus) { 2467 // C++ [dcl.typedef]p2: 2468 // In a given non-class scope, a typedef specifier can be used to 2469 // redefine the name of any type declared in that scope to refer 2470 // to the type to which it already refers. 2471 if (!isa<CXXRecordDecl>(CurContext)) 2472 return; 2473 2474 // C++0x [dcl.typedef]p4: 2475 // In a given class scope, a typedef specifier can be used to redefine 2476 // any class-name declared in that scope that is not also a typedef-name 2477 // to refer to the type to which it already refers. 2478 // 2479 // This wording came in via DR424, which was a correction to the 2480 // wording in DR56, which accidentally banned code like: 2481 // 2482 // struct S { 2483 // typedef struct A { } A; 2484 // }; 2485 // 2486 // in the C++03 standard. We implement the C++0x semantics, which 2487 // allow the above but disallow 2488 // 2489 // struct S { 2490 // typedef int I; 2491 // typedef int I; 2492 // }; 2493 // 2494 // since that was the intent of DR56. 2495 if (!isa<TypedefNameDecl>(Old)) 2496 return; 2497 2498 Diag(New->getLocation(), diag::err_redefinition) 2499 << New->getDeclName(); 2500 notePreviousDefinition(Old, New->getLocation()); 2501 return New->setInvalidDecl(); 2502 } 2503 2504 // Modules always permit redefinition of typedefs, as does C11. 2505 if (getLangOpts().Modules || getLangOpts().C11) 2506 return; 2507 2508 // If we have a redefinition of a typedef in C, emit a warning. This warning 2509 // is normally mapped to an error, but can be controlled with 2510 // -Wtypedef-redefinition. If either the original or the redefinition is 2511 // in a system header, don't emit this for compatibility with GCC. 2512 if (getDiagnostics().getSuppressSystemWarnings() && 2513 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2514 (Old->isImplicit() || 2515 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2516 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2517 return; 2518 2519 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2520 << New->getDeclName(); 2521 notePreviousDefinition(Old, New->getLocation()); 2522 } 2523 2524 /// DeclhasAttr - returns true if decl Declaration already has the target 2525 /// attribute. 2526 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2527 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2528 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2529 for (const auto *i : D->attrs()) 2530 if (i->getKind() == A->getKind()) { 2531 if (Ann) { 2532 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2533 return true; 2534 continue; 2535 } 2536 // FIXME: Don't hardcode this check 2537 if (OA && isa<OwnershipAttr>(i)) 2538 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2539 return true; 2540 } 2541 2542 return false; 2543 } 2544 2545 static bool isAttributeTargetADefinition(Decl *D) { 2546 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2547 return VD->isThisDeclarationADefinition(); 2548 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2549 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2550 return true; 2551 } 2552 2553 /// Merge alignment attributes from \p Old to \p New, taking into account the 2554 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2555 /// 2556 /// \return \c true if any attributes were added to \p New. 2557 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2558 // Look for alignas attributes on Old, and pick out whichever attribute 2559 // specifies the strictest alignment requirement. 2560 AlignedAttr *OldAlignasAttr = nullptr; 2561 AlignedAttr *OldStrictestAlignAttr = nullptr; 2562 unsigned OldAlign = 0; 2563 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2564 // FIXME: We have no way of representing inherited dependent alignments 2565 // in a case like: 2566 // template<int A, int B> struct alignas(A) X; 2567 // template<int A, int B> struct alignas(B) X {}; 2568 // For now, we just ignore any alignas attributes which are not on the 2569 // definition in such a case. 2570 if (I->isAlignmentDependent()) 2571 return false; 2572 2573 if (I->isAlignas()) 2574 OldAlignasAttr = I; 2575 2576 unsigned Align = I->getAlignment(S.Context); 2577 if (Align > OldAlign) { 2578 OldAlign = Align; 2579 OldStrictestAlignAttr = I; 2580 } 2581 } 2582 2583 // Look for alignas attributes on New. 2584 AlignedAttr *NewAlignasAttr = nullptr; 2585 unsigned NewAlign = 0; 2586 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2587 if (I->isAlignmentDependent()) 2588 return false; 2589 2590 if (I->isAlignas()) 2591 NewAlignasAttr = I; 2592 2593 unsigned Align = I->getAlignment(S.Context); 2594 if (Align > NewAlign) 2595 NewAlign = Align; 2596 } 2597 2598 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2599 // Both declarations have 'alignas' attributes. We require them to match. 2600 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2601 // fall short. (If two declarations both have alignas, they must both match 2602 // every definition, and so must match each other if there is a definition.) 2603 2604 // If either declaration only contains 'alignas(0)' specifiers, then it 2605 // specifies the natural alignment for the type. 2606 if (OldAlign == 0 || NewAlign == 0) { 2607 QualType Ty; 2608 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2609 Ty = VD->getType(); 2610 else 2611 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2612 2613 if (OldAlign == 0) 2614 OldAlign = S.Context.getTypeAlign(Ty); 2615 if (NewAlign == 0) 2616 NewAlign = S.Context.getTypeAlign(Ty); 2617 } 2618 2619 if (OldAlign != NewAlign) { 2620 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2621 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2622 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2623 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2624 } 2625 } 2626 2627 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2628 // C++11 [dcl.align]p6: 2629 // if any declaration of an entity has an alignment-specifier, 2630 // every defining declaration of that entity shall specify an 2631 // equivalent alignment. 2632 // C11 6.7.5/7: 2633 // If the definition of an object does not have an alignment 2634 // specifier, any other declaration of that object shall also 2635 // have no alignment specifier. 2636 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2637 << OldAlignasAttr; 2638 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2639 << OldAlignasAttr; 2640 } 2641 2642 bool AnyAdded = false; 2643 2644 // Ensure we have an attribute representing the strictest alignment. 2645 if (OldAlign > NewAlign) { 2646 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2647 Clone->setInherited(true); 2648 New->addAttr(Clone); 2649 AnyAdded = true; 2650 } 2651 2652 // Ensure we have an alignas attribute if the old declaration had one. 2653 if (OldAlignasAttr && !NewAlignasAttr && 2654 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2655 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2656 Clone->setInherited(true); 2657 New->addAttr(Clone); 2658 AnyAdded = true; 2659 } 2660 2661 return AnyAdded; 2662 } 2663 2664 #define WANT_DECL_MERGE_LOGIC 2665 #include "clang/Sema/AttrParsedAttrImpl.inc" 2666 #undef WANT_DECL_MERGE_LOGIC 2667 2668 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2669 const InheritableAttr *Attr, 2670 Sema::AvailabilityMergeKind AMK) { 2671 // Diagnose any mutual exclusions between the attribute that we want to add 2672 // and attributes that already exist on the declaration. 2673 if (!DiagnoseMutualExclusions(S, D, Attr)) 2674 return false; 2675 2676 // This function copies an attribute Attr from a previous declaration to the 2677 // new declaration D if the new declaration doesn't itself have that attribute 2678 // yet or if that attribute allows duplicates. 2679 // If you're adding a new attribute that requires logic different from 2680 // "use explicit attribute on decl if present, else use attribute from 2681 // previous decl", for example if the attribute needs to be consistent 2682 // between redeclarations, you need to call a custom merge function here. 2683 InheritableAttr *NewAttr = nullptr; 2684 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2685 NewAttr = S.mergeAvailabilityAttr( 2686 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2687 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2688 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2689 AA->getPriority()); 2690 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2691 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2692 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2693 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2694 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2695 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2696 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2697 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2698 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2699 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2700 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2701 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2702 FA->getFirstArg()); 2703 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2704 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2705 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2706 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2707 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2708 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2709 IA->getInheritanceModel()); 2710 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2711 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2712 &S.Context.Idents.get(AA->getSpelling())); 2713 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2714 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2715 isa<CUDAGlobalAttr>(Attr))) { 2716 // CUDA target attributes are part of function signature for 2717 // overloading purposes and must not be merged. 2718 return false; 2719 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2720 NewAttr = S.mergeMinSizeAttr(D, *MA); 2721 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2722 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2723 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2724 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2725 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2726 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2727 else if (isa<AlignedAttr>(Attr)) 2728 // AlignedAttrs are handled separately, because we need to handle all 2729 // such attributes on a declaration at the same time. 2730 NewAttr = nullptr; 2731 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2732 (AMK == Sema::AMK_Override || 2733 AMK == Sema::AMK_ProtocolImplementation || 2734 AMK == Sema::AMK_OptionalProtocolImplementation)) 2735 NewAttr = nullptr; 2736 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2737 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2738 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2739 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2740 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2741 NewAttr = S.mergeImportNameAttr(D, *INA); 2742 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2743 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2744 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2745 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2746 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2747 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2748 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2749 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2750 2751 if (NewAttr) { 2752 NewAttr->setInherited(true); 2753 D->addAttr(NewAttr); 2754 if (isa<MSInheritanceAttr>(NewAttr)) 2755 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2756 return true; 2757 } 2758 2759 return false; 2760 } 2761 2762 static const NamedDecl *getDefinition(const Decl *D) { 2763 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2764 return TD->getDefinition(); 2765 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2766 const VarDecl *Def = VD->getDefinition(); 2767 if (Def) 2768 return Def; 2769 return VD->getActingDefinition(); 2770 } 2771 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2772 const FunctionDecl *Def = nullptr; 2773 if (FD->isDefined(Def, true)) 2774 return Def; 2775 } 2776 return nullptr; 2777 } 2778 2779 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2780 for (const auto *Attribute : D->attrs()) 2781 if (Attribute->getKind() == Kind) 2782 return true; 2783 return false; 2784 } 2785 2786 /// checkNewAttributesAfterDef - If we already have a definition, check that 2787 /// there are no new attributes in this declaration. 2788 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2789 if (!New->hasAttrs()) 2790 return; 2791 2792 const NamedDecl *Def = getDefinition(Old); 2793 if (!Def || Def == New) 2794 return; 2795 2796 AttrVec &NewAttributes = New->getAttrs(); 2797 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2798 const Attr *NewAttribute = NewAttributes[I]; 2799 2800 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2801 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2802 Sema::SkipBodyInfo SkipBody; 2803 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2804 2805 // If we're skipping this definition, drop the "alias" attribute. 2806 if (SkipBody.ShouldSkip) { 2807 NewAttributes.erase(NewAttributes.begin() + I); 2808 --E; 2809 continue; 2810 } 2811 } else { 2812 VarDecl *VD = cast<VarDecl>(New); 2813 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2814 VarDecl::TentativeDefinition 2815 ? diag::err_alias_after_tentative 2816 : diag::err_redefinition; 2817 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2818 if (Diag == diag::err_redefinition) 2819 S.notePreviousDefinition(Def, VD->getLocation()); 2820 else 2821 S.Diag(Def->getLocation(), diag::note_previous_definition); 2822 VD->setInvalidDecl(); 2823 } 2824 ++I; 2825 continue; 2826 } 2827 2828 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2829 // Tentative definitions are only interesting for the alias check above. 2830 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2831 ++I; 2832 continue; 2833 } 2834 } 2835 2836 if (hasAttribute(Def, NewAttribute->getKind())) { 2837 ++I; 2838 continue; // regular attr merging will take care of validating this. 2839 } 2840 2841 if (isa<C11NoReturnAttr>(NewAttribute)) { 2842 // C's _Noreturn is allowed to be added to a function after it is defined. 2843 ++I; 2844 continue; 2845 } else if (isa<UuidAttr>(NewAttribute)) { 2846 // msvc will allow a subsequent definition to add an uuid to a class 2847 ++I; 2848 continue; 2849 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2850 if (AA->isAlignas()) { 2851 // C++11 [dcl.align]p6: 2852 // if any declaration of an entity has an alignment-specifier, 2853 // every defining declaration of that entity shall specify an 2854 // equivalent alignment. 2855 // C11 6.7.5/7: 2856 // If the definition of an object does not have an alignment 2857 // specifier, any other declaration of that object shall also 2858 // have no alignment specifier. 2859 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2860 << AA; 2861 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2862 << AA; 2863 NewAttributes.erase(NewAttributes.begin() + I); 2864 --E; 2865 continue; 2866 } 2867 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2868 // If there is a C definition followed by a redeclaration with this 2869 // attribute then there are two different definitions. In C++, prefer the 2870 // standard diagnostics. 2871 if (!S.getLangOpts().CPlusPlus) { 2872 S.Diag(NewAttribute->getLocation(), 2873 diag::err_loader_uninitialized_redeclaration); 2874 S.Diag(Def->getLocation(), diag::note_previous_definition); 2875 NewAttributes.erase(NewAttributes.begin() + I); 2876 --E; 2877 continue; 2878 } 2879 } else if (isa<SelectAnyAttr>(NewAttribute) && 2880 cast<VarDecl>(New)->isInline() && 2881 !cast<VarDecl>(New)->isInlineSpecified()) { 2882 // Don't warn about applying selectany to implicitly inline variables. 2883 // Older compilers and language modes would require the use of selectany 2884 // to make such variables inline, and it would have no effect if we 2885 // honored it. 2886 ++I; 2887 continue; 2888 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2889 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2890 // declarations after defintions. 2891 ++I; 2892 continue; 2893 } 2894 2895 S.Diag(NewAttribute->getLocation(), 2896 diag::warn_attribute_precede_definition); 2897 S.Diag(Def->getLocation(), diag::note_previous_definition); 2898 NewAttributes.erase(NewAttributes.begin() + I); 2899 --E; 2900 } 2901 } 2902 2903 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2904 const ConstInitAttr *CIAttr, 2905 bool AttrBeforeInit) { 2906 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2907 2908 // Figure out a good way to write this specifier on the old declaration. 2909 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2910 // enough of the attribute list spelling information to extract that without 2911 // heroics. 2912 std::string SuitableSpelling; 2913 if (S.getLangOpts().CPlusPlus20) 2914 SuitableSpelling = std::string( 2915 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2916 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2917 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2918 InsertLoc, {tok::l_square, tok::l_square, 2919 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2920 S.PP.getIdentifierInfo("require_constant_initialization"), 2921 tok::r_square, tok::r_square})); 2922 if (SuitableSpelling.empty()) 2923 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2924 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2925 S.PP.getIdentifierInfo("require_constant_initialization"), 2926 tok::r_paren, tok::r_paren})); 2927 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2928 SuitableSpelling = "constinit"; 2929 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2930 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2931 if (SuitableSpelling.empty()) 2932 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2933 SuitableSpelling += " "; 2934 2935 if (AttrBeforeInit) { 2936 // extern constinit int a; 2937 // int a = 0; // error (missing 'constinit'), accepted as extension 2938 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2939 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2940 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2941 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2942 } else { 2943 // int a = 0; 2944 // constinit extern int a; // error (missing 'constinit') 2945 S.Diag(CIAttr->getLocation(), 2946 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2947 : diag::warn_require_const_init_added_too_late) 2948 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2949 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2950 << CIAttr->isConstinit() 2951 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2952 } 2953 } 2954 2955 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2956 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2957 AvailabilityMergeKind AMK) { 2958 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2959 UsedAttr *NewAttr = OldAttr->clone(Context); 2960 NewAttr->setInherited(true); 2961 New->addAttr(NewAttr); 2962 } 2963 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2964 RetainAttr *NewAttr = OldAttr->clone(Context); 2965 NewAttr->setInherited(true); 2966 New->addAttr(NewAttr); 2967 } 2968 2969 if (!Old->hasAttrs() && !New->hasAttrs()) 2970 return; 2971 2972 // [dcl.constinit]p1: 2973 // If the [constinit] specifier is applied to any declaration of a 2974 // variable, it shall be applied to the initializing declaration. 2975 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2976 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2977 if (bool(OldConstInit) != bool(NewConstInit)) { 2978 const auto *OldVD = cast<VarDecl>(Old); 2979 auto *NewVD = cast<VarDecl>(New); 2980 2981 // Find the initializing declaration. Note that we might not have linked 2982 // the new declaration into the redeclaration chain yet. 2983 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2984 if (!InitDecl && 2985 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2986 InitDecl = NewVD; 2987 2988 if (InitDecl == NewVD) { 2989 // This is the initializing declaration. If it would inherit 'constinit', 2990 // that's ill-formed. (Note that we do not apply this to the attribute 2991 // form). 2992 if (OldConstInit && OldConstInit->isConstinit()) 2993 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2994 /*AttrBeforeInit=*/true); 2995 } else if (NewConstInit) { 2996 // This is the first time we've been told that this declaration should 2997 // have a constant initializer. If we already saw the initializing 2998 // declaration, this is too late. 2999 if (InitDecl && InitDecl != NewVD) { 3000 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3001 /*AttrBeforeInit=*/false); 3002 NewVD->dropAttr<ConstInitAttr>(); 3003 } 3004 } 3005 } 3006 3007 // Attributes declared post-definition are currently ignored. 3008 checkNewAttributesAfterDef(*this, New, Old); 3009 3010 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3011 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3012 if (!OldA->isEquivalent(NewA)) { 3013 // This redeclaration changes __asm__ label. 3014 Diag(New->getLocation(), diag::err_different_asm_label); 3015 Diag(OldA->getLocation(), diag::note_previous_declaration); 3016 } 3017 } else if (Old->isUsed()) { 3018 // This redeclaration adds an __asm__ label to a declaration that has 3019 // already been ODR-used. 3020 Diag(New->getLocation(), diag::err_late_asm_label_name) 3021 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3022 } 3023 } 3024 3025 // Re-declaration cannot add abi_tag's. 3026 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3027 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3028 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3029 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3030 Diag(NewAbiTagAttr->getLocation(), 3031 diag::err_new_abi_tag_on_redeclaration) 3032 << NewTag; 3033 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3034 } 3035 } 3036 } else { 3037 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3038 Diag(Old->getLocation(), diag::note_previous_declaration); 3039 } 3040 } 3041 3042 // This redeclaration adds a section attribute. 3043 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3044 if (auto *VD = dyn_cast<VarDecl>(New)) { 3045 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3046 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3047 Diag(Old->getLocation(), diag::note_previous_declaration); 3048 } 3049 } 3050 } 3051 3052 // Redeclaration adds code-seg attribute. 3053 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3054 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3055 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3056 Diag(New->getLocation(), diag::warn_mismatched_section) 3057 << 0 /*codeseg*/; 3058 Diag(Old->getLocation(), diag::note_previous_declaration); 3059 } 3060 3061 if (!Old->hasAttrs()) 3062 return; 3063 3064 bool foundAny = New->hasAttrs(); 3065 3066 // Ensure that any moving of objects within the allocated map is done before 3067 // we process them. 3068 if (!foundAny) New->setAttrs(AttrVec()); 3069 3070 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3071 // Ignore deprecated/unavailable/availability attributes if requested. 3072 AvailabilityMergeKind LocalAMK = AMK_None; 3073 if (isa<DeprecatedAttr>(I) || 3074 isa<UnavailableAttr>(I) || 3075 isa<AvailabilityAttr>(I)) { 3076 switch (AMK) { 3077 case AMK_None: 3078 continue; 3079 3080 case AMK_Redeclaration: 3081 case AMK_Override: 3082 case AMK_ProtocolImplementation: 3083 case AMK_OptionalProtocolImplementation: 3084 LocalAMK = AMK; 3085 break; 3086 } 3087 } 3088 3089 // Already handled. 3090 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3091 continue; 3092 3093 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3094 foundAny = true; 3095 } 3096 3097 if (mergeAlignedAttrs(*this, New, Old)) 3098 foundAny = true; 3099 3100 if (!foundAny) New->dropAttrs(); 3101 } 3102 3103 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3104 /// to the new one. 3105 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3106 const ParmVarDecl *oldDecl, 3107 Sema &S) { 3108 // C++11 [dcl.attr.depend]p2: 3109 // The first declaration of a function shall specify the 3110 // carries_dependency attribute for its declarator-id if any declaration 3111 // of the function specifies the carries_dependency attribute. 3112 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3113 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3114 S.Diag(CDA->getLocation(), 3115 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3116 // Find the first declaration of the parameter. 3117 // FIXME: Should we build redeclaration chains for function parameters? 3118 const FunctionDecl *FirstFD = 3119 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3120 const ParmVarDecl *FirstVD = 3121 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3122 S.Diag(FirstVD->getLocation(), 3123 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3124 } 3125 3126 if (!oldDecl->hasAttrs()) 3127 return; 3128 3129 bool foundAny = newDecl->hasAttrs(); 3130 3131 // Ensure that any moving of objects within the allocated map is 3132 // done before we process them. 3133 if (!foundAny) newDecl->setAttrs(AttrVec()); 3134 3135 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3136 if (!DeclHasAttr(newDecl, I)) { 3137 InheritableAttr *newAttr = 3138 cast<InheritableParamAttr>(I->clone(S.Context)); 3139 newAttr->setInherited(true); 3140 newDecl->addAttr(newAttr); 3141 foundAny = true; 3142 } 3143 } 3144 3145 if (!foundAny) newDecl->dropAttrs(); 3146 } 3147 3148 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3149 const ParmVarDecl *OldParam, 3150 Sema &S) { 3151 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3152 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3153 if (*Oldnullability != *Newnullability) { 3154 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3155 << DiagNullabilityKind( 3156 *Newnullability, 3157 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3158 != 0)) 3159 << DiagNullabilityKind( 3160 *Oldnullability, 3161 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3162 != 0)); 3163 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3164 } 3165 } else { 3166 QualType NewT = NewParam->getType(); 3167 NewT = S.Context.getAttributedType( 3168 AttributedType::getNullabilityAttrKind(*Oldnullability), 3169 NewT, NewT); 3170 NewParam->setType(NewT); 3171 } 3172 } 3173 } 3174 3175 namespace { 3176 3177 /// Used in MergeFunctionDecl to keep track of function parameters in 3178 /// C. 3179 struct GNUCompatibleParamWarning { 3180 ParmVarDecl *OldParm; 3181 ParmVarDecl *NewParm; 3182 QualType PromotedType; 3183 }; 3184 3185 } // end anonymous namespace 3186 3187 // Determine whether the previous declaration was a definition, implicit 3188 // declaration, or a declaration. 3189 template <typename T> 3190 static std::pair<diag::kind, SourceLocation> 3191 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3192 diag::kind PrevDiag; 3193 SourceLocation OldLocation = Old->getLocation(); 3194 if (Old->isThisDeclarationADefinition()) 3195 PrevDiag = diag::note_previous_definition; 3196 else if (Old->isImplicit()) { 3197 PrevDiag = diag::note_previous_implicit_declaration; 3198 if (OldLocation.isInvalid()) 3199 OldLocation = New->getLocation(); 3200 } else 3201 PrevDiag = diag::note_previous_declaration; 3202 return std::make_pair(PrevDiag, OldLocation); 3203 } 3204 3205 /// canRedefineFunction - checks if a function can be redefined. Currently, 3206 /// only extern inline functions can be redefined, and even then only in 3207 /// GNU89 mode. 3208 static bool canRedefineFunction(const FunctionDecl *FD, 3209 const LangOptions& LangOpts) { 3210 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3211 !LangOpts.CPlusPlus && 3212 FD->isInlineSpecified() && 3213 FD->getStorageClass() == SC_Extern); 3214 } 3215 3216 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3217 const AttributedType *AT = T->getAs<AttributedType>(); 3218 while (AT && !AT->isCallingConv()) 3219 AT = AT->getModifiedType()->getAs<AttributedType>(); 3220 return AT; 3221 } 3222 3223 template <typename T> 3224 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3225 const DeclContext *DC = Old->getDeclContext(); 3226 if (DC->isRecord()) 3227 return false; 3228 3229 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3230 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3231 return true; 3232 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3233 return true; 3234 return false; 3235 } 3236 3237 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3238 static bool isExternC(VarTemplateDecl *) { return false; } 3239 static bool isExternC(FunctionTemplateDecl *) { return false; } 3240 3241 /// Check whether a redeclaration of an entity introduced by a 3242 /// using-declaration is valid, given that we know it's not an overload 3243 /// (nor a hidden tag declaration). 3244 template<typename ExpectedDecl> 3245 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3246 ExpectedDecl *New) { 3247 // C++11 [basic.scope.declarative]p4: 3248 // Given a set of declarations in a single declarative region, each of 3249 // which specifies the same unqualified name, 3250 // -- they shall all refer to the same entity, or all refer to functions 3251 // and function templates; or 3252 // -- exactly one declaration shall declare a class name or enumeration 3253 // name that is not a typedef name and the other declarations shall all 3254 // refer to the same variable or enumerator, or all refer to functions 3255 // and function templates; in this case the class name or enumeration 3256 // name is hidden (3.3.10). 3257 3258 // C++11 [namespace.udecl]p14: 3259 // If a function declaration in namespace scope or block scope has the 3260 // same name and the same parameter-type-list as a function introduced 3261 // by a using-declaration, and the declarations do not declare the same 3262 // function, the program is ill-formed. 3263 3264 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3265 if (Old && 3266 !Old->getDeclContext()->getRedeclContext()->Equals( 3267 New->getDeclContext()->getRedeclContext()) && 3268 !(isExternC(Old) && isExternC(New))) 3269 Old = nullptr; 3270 3271 if (!Old) { 3272 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3273 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3274 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3275 return true; 3276 } 3277 return false; 3278 } 3279 3280 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3281 const FunctionDecl *B) { 3282 assert(A->getNumParams() == B->getNumParams()); 3283 3284 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3285 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3286 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3287 if (AttrA == AttrB) 3288 return true; 3289 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3290 AttrA->isDynamic() == AttrB->isDynamic(); 3291 }; 3292 3293 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3294 } 3295 3296 /// If necessary, adjust the semantic declaration context for a qualified 3297 /// declaration to name the correct inline namespace within the qualifier. 3298 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3299 DeclaratorDecl *OldD) { 3300 // The only case where we need to update the DeclContext is when 3301 // redeclaration lookup for a qualified name finds a declaration 3302 // in an inline namespace within the context named by the qualifier: 3303 // 3304 // inline namespace N { int f(); } 3305 // int ::f(); // Sema DC needs adjusting from :: to N::. 3306 // 3307 // For unqualified declarations, the semantic context *can* change 3308 // along the redeclaration chain (for local extern declarations, 3309 // extern "C" declarations, and friend declarations in particular). 3310 if (!NewD->getQualifier()) 3311 return; 3312 3313 // NewD is probably already in the right context. 3314 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3315 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3316 if (NamedDC->Equals(SemaDC)) 3317 return; 3318 3319 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3320 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3321 "unexpected context for redeclaration"); 3322 3323 auto *LexDC = NewD->getLexicalDeclContext(); 3324 auto FixSemaDC = [=](NamedDecl *D) { 3325 if (!D) 3326 return; 3327 D->setDeclContext(SemaDC); 3328 D->setLexicalDeclContext(LexDC); 3329 }; 3330 3331 FixSemaDC(NewD); 3332 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3333 FixSemaDC(FD->getDescribedFunctionTemplate()); 3334 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3335 FixSemaDC(VD->getDescribedVarTemplate()); 3336 } 3337 3338 /// MergeFunctionDecl - We just parsed a function 'New' from 3339 /// declarator D which has the same name and scope as a previous 3340 /// declaration 'Old'. Figure out how to resolve this situation, 3341 /// merging decls or emitting diagnostics as appropriate. 3342 /// 3343 /// In C++, New and Old must be declarations that are not 3344 /// overloaded. Use IsOverload to determine whether New and Old are 3345 /// overloaded, and to select the Old declaration that New should be 3346 /// merged with. 3347 /// 3348 /// Returns true if there was an error, false otherwise. 3349 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3350 Scope *S, bool MergeTypeWithOld) { 3351 // Verify the old decl was also a function. 3352 FunctionDecl *Old = OldD->getAsFunction(); 3353 if (!Old) { 3354 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3355 if (New->getFriendObjectKind()) { 3356 Diag(New->getLocation(), diag::err_using_decl_friend); 3357 Diag(Shadow->getTargetDecl()->getLocation(), 3358 diag::note_using_decl_target); 3359 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3360 << 0; 3361 return true; 3362 } 3363 3364 // Check whether the two declarations might declare the same function or 3365 // function template. 3366 if (FunctionTemplateDecl *NewTemplate = 3367 New->getDescribedFunctionTemplate()) { 3368 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3369 NewTemplate)) 3370 return true; 3371 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3372 ->getAsFunction(); 3373 } else { 3374 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3375 return true; 3376 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3377 } 3378 } else { 3379 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3380 << New->getDeclName(); 3381 notePreviousDefinition(OldD, New->getLocation()); 3382 return true; 3383 } 3384 } 3385 3386 // If the old declaration was found in an inline namespace and the new 3387 // declaration was qualified, update the DeclContext to match. 3388 adjustDeclContextForDeclaratorDecl(New, Old); 3389 3390 // If the old declaration is invalid, just give up here. 3391 if (Old->isInvalidDecl()) 3392 return true; 3393 3394 // Disallow redeclaration of some builtins. 3395 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3396 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3397 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3398 << Old << Old->getType(); 3399 return true; 3400 } 3401 3402 diag::kind PrevDiag; 3403 SourceLocation OldLocation; 3404 std::tie(PrevDiag, OldLocation) = 3405 getNoteDiagForInvalidRedeclaration(Old, New); 3406 3407 // Don't complain about this if we're in GNU89 mode and the old function 3408 // is an extern inline function. 3409 // Don't complain about specializations. They are not supposed to have 3410 // storage classes. 3411 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3412 New->getStorageClass() == SC_Static && 3413 Old->hasExternalFormalLinkage() && 3414 !New->getTemplateSpecializationInfo() && 3415 !canRedefineFunction(Old, getLangOpts())) { 3416 if (getLangOpts().MicrosoftExt) { 3417 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3418 Diag(OldLocation, PrevDiag); 3419 } else { 3420 Diag(New->getLocation(), diag::err_static_non_static) << New; 3421 Diag(OldLocation, PrevDiag); 3422 return true; 3423 } 3424 } 3425 3426 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3427 if (!Old->hasAttr<InternalLinkageAttr>()) { 3428 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3429 << ILA; 3430 Diag(Old->getLocation(), diag::note_previous_declaration); 3431 New->dropAttr<InternalLinkageAttr>(); 3432 } 3433 3434 if (auto *EA = New->getAttr<ErrorAttr>()) { 3435 if (!Old->hasAttr<ErrorAttr>()) { 3436 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3437 Diag(Old->getLocation(), diag::note_previous_declaration); 3438 New->dropAttr<ErrorAttr>(); 3439 } 3440 } 3441 3442 if (CheckRedeclarationInModule(New, Old)) 3443 return true; 3444 3445 if (!getLangOpts().CPlusPlus) { 3446 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3447 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3448 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3449 << New << OldOvl; 3450 3451 // Try our best to find a decl that actually has the overloadable 3452 // attribute for the note. In most cases (e.g. programs with only one 3453 // broken declaration/definition), this won't matter. 3454 // 3455 // FIXME: We could do this if we juggled some extra state in 3456 // OverloadableAttr, rather than just removing it. 3457 const Decl *DiagOld = Old; 3458 if (OldOvl) { 3459 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3460 const auto *A = D->getAttr<OverloadableAttr>(); 3461 return A && !A->isImplicit(); 3462 }); 3463 // If we've implicitly added *all* of the overloadable attrs to this 3464 // chain, emitting a "previous redecl" note is pointless. 3465 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3466 } 3467 3468 if (DiagOld) 3469 Diag(DiagOld->getLocation(), 3470 diag::note_attribute_overloadable_prev_overload) 3471 << OldOvl; 3472 3473 if (OldOvl) 3474 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3475 else 3476 New->dropAttr<OverloadableAttr>(); 3477 } 3478 } 3479 3480 // If a function is first declared with a calling convention, but is later 3481 // declared or defined without one, all following decls assume the calling 3482 // convention of the first. 3483 // 3484 // It's OK if a function is first declared without a calling convention, 3485 // but is later declared or defined with the default calling convention. 3486 // 3487 // To test if either decl has an explicit calling convention, we look for 3488 // AttributedType sugar nodes on the type as written. If they are missing or 3489 // were canonicalized away, we assume the calling convention was implicit. 3490 // 3491 // Note also that we DO NOT return at this point, because we still have 3492 // other tests to run. 3493 QualType OldQType = Context.getCanonicalType(Old->getType()); 3494 QualType NewQType = Context.getCanonicalType(New->getType()); 3495 const FunctionType *OldType = cast<FunctionType>(OldQType); 3496 const FunctionType *NewType = cast<FunctionType>(NewQType); 3497 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3498 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3499 bool RequiresAdjustment = false; 3500 3501 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3502 FunctionDecl *First = Old->getFirstDecl(); 3503 const FunctionType *FT = 3504 First->getType().getCanonicalType()->castAs<FunctionType>(); 3505 FunctionType::ExtInfo FI = FT->getExtInfo(); 3506 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3507 if (!NewCCExplicit) { 3508 // Inherit the CC from the previous declaration if it was specified 3509 // there but not here. 3510 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3511 RequiresAdjustment = true; 3512 } else if (Old->getBuiltinID()) { 3513 // Builtin attribute isn't propagated to the new one yet at this point, 3514 // so we check if the old one is a builtin. 3515 3516 // Calling Conventions on a Builtin aren't really useful and setting a 3517 // default calling convention and cdecl'ing some builtin redeclarations is 3518 // common, so warn and ignore the calling convention on the redeclaration. 3519 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3520 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3521 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3522 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3523 RequiresAdjustment = true; 3524 } else { 3525 // Calling conventions aren't compatible, so complain. 3526 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3527 Diag(New->getLocation(), diag::err_cconv_change) 3528 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3529 << !FirstCCExplicit 3530 << (!FirstCCExplicit ? "" : 3531 FunctionType::getNameForCallConv(FI.getCC())); 3532 3533 // Put the note on the first decl, since it is the one that matters. 3534 Diag(First->getLocation(), diag::note_previous_declaration); 3535 return true; 3536 } 3537 } 3538 3539 // FIXME: diagnose the other way around? 3540 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3541 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3542 RequiresAdjustment = true; 3543 } 3544 3545 // Merge regparm attribute. 3546 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3547 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3548 if (NewTypeInfo.getHasRegParm()) { 3549 Diag(New->getLocation(), diag::err_regparm_mismatch) 3550 << NewType->getRegParmType() 3551 << OldType->getRegParmType(); 3552 Diag(OldLocation, diag::note_previous_declaration); 3553 return true; 3554 } 3555 3556 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3557 RequiresAdjustment = true; 3558 } 3559 3560 // Merge ns_returns_retained attribute. 3561 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3562 if (NewTypeInfo.getProducesResult()) { 3563 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3564 << "'ns_returns_retained'"; 3565 Diag(OldLocation, diag::note_previous_declaration); 3566 return true; 3567 } 3568 3569 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3570 RequiresAdjustment = true; 3571 } 3572 3573 if (OldTypeInfo.getNoCallerSavedRegs() != 3574 NewTypeInfo.getNoCallerSavedRegs()) { 3575 if (NewTypeInfo.getNoCallerSavedRegs()) { 3576 AnyX86NoCallerSavedRegistersAttr *Attr = 3577 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3578 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3579 Diag(OldLocation, diag::note_previous_declaration); 3580 return true; 3581 } 3582 3583 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3584 RequiresAdjustment = true; 3585 } 3586 3587 if (RequiresAdjustment) { 3588 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3589 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3590 New->setType(QualType(AdjustedType, 0)); 3591 NewQType = Context.getCanonicalType(New->getType()); 3592 } 3593 3594 // If this redeclaration makes the function inline, we may need to add it to 3595 // UndefinedButUsed. 3596 if (!Old->isInlined() && New->isInlined() && 3597 !New->hasAttr<GNUInlineAttr>() && 3598 !getLangOpts().GNUInline && 3599 Old->isUsed(false) && 3600 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3601 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3602 SourceLocation())); 3603 3604 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3605 // about it. 3606 if (New->hasAttr<GNUInlineAttr>() && 3607 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3608 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3609 } 3610 3611 // If pass_object_size params don't match up perfectly, this isn't a valid 3612 // redeclaration. 3613 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3614 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3615 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3616 << New->getDeclName(); 3617 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3618 return true; 3619 } 3620 3621 if (getLangOpts().CPlusPlus) { 3622 // C++1z [over.load]p2 3623 // Certain function declarations cannot be overloaded: 3624 // -- Function declarations that differ only in the return type, 3625 // the exception specification, or both cannot be overloaded. 3626 3627 // Check the exception specifications match. This may recompute the type of 3628 // both Old and New if it resolved exception specifications, so grab the 3629 // types again after this. Because this updates the type, we do this before 3630 // any of the other checks below, which may update the "de facto" NewQType 3631 // but do not necessarily update the type of New. 3632 if (CheckEquivalentExceptionSpec(Old, New)) 3633 return true; 3634 OldQType = Context.getCanonicalType(Old->getType()); 3635 NewQType = Context.getCanonicalType(New->getType()); 3636 3637 // Go back to the type source info to compare the declared return types, 3638 // per C++1y [dcl.type.auto]p13: 3639 // Redeclarations or specializations of a function or function template 3640 // with a declared return type that uses a placeholder type shall also 3641 // use that placeholder, not a deduced type. 3642 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3643 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3644 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3645 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3646 OldDeclaredReturnType)) { 3647 QualType ResQT; 3648 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3649 OldDeclaredReturnType->isObjCObjectPointerType()) 3650 // FIXME: This does the wrong thing for a deduced return type. 3651 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3652 if (ResQT.isNull()) { 3653 if (New->isCXXClassMember() && New->isOutOfLine()) 3654 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3655 << New << New->getReturnTypeSourceRange(); 3656 else 3657 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3658 << New->getReturnTypeSourceRange(); 3659 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3660 << Old->getReturnTypeSourceRange(); 3661 return true; 3662 } 3663 else 3664 NewQType = ResQT; 3665 } 3666 3667 QualType OldReturnType = OldType->getReturnType(); 3668 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3669 if (OldReturnType != NewReturnType) { 3670 // If this function has a deduced return type and has already been 3671 // defined, copy the deduced value from the old declaration. 3672 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3673 if (OldAT && OldAT->isDeduced()) { 3674 QualType DT = OldAT->getDeducedType(); 3675 if (DT.isNull()) { 3676 New->setType(SubstAutoTypeDependent(New->getType())); 3677 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3678 } else { 3679 New->setType(SubstAutoType(New->getType(), DT)); 3680 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3681 } 3682 } 3683 } 3684 3685 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3686 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3687 if (OldMethod && NewMethod) { 3688 // Preserve triviality. 3689 NewMethod->setTrivial(OldMethod->isTrivial()); 3690 3691 // MSVC allows explicit template specialization at class scope: 3692 // 2 CXXMethodDecls referring to the same function will be injected. 3693 // We don't want a redeclaration error. 3694 bool IsClassScopeExplicitSpecialization = 3695 OldMethod->isFunctionTemplateSpecialization() && 3696 NewMethod->isFunctionTemplateSpecialization(); 3697 bool isFriend = NewMethod->getFriendObjectKind(); 3698 3699 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3700 !IsClassScopeExplicitSpecialization) { 3701 // -- Member function declarations with the same name and the 3702 // same parameter types cannot be overloaded if any of them 3703 // is a static member function declaration. 3704 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3705 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3706 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3707 return true; 3708 } 3709 3710 // C++ [class.mem]p1: 3711 // [...] A member shall not be declared twice in the 3712 // member-specification, except that a nested class or member 3713 // class template can be declared and then later defined. 3714 if (!inTemplateInstantiation()) { 3715 unsigned NewDiag; 3716 if (isa<CXXConstructorDecl>(OldMethod)) 3717 NewDiag = diag::err_constructor_redeclared; 3718 else if (isa<CXXDestructorDecl>(NewMethod)) 3719 NewDiag = diag::err_destructor_redeclared; 3720 else if (isa<CXXConversionDecl>(NewMethod)) 3721 NewDiag = diag::err_conv_function_redeclared; 3722 else 3723 NewDiag = diag::err_member_redeclared; 3724 3725 Diag(New->getLocation(), NewDiag); 3726 } else { 3727 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3728 << New << New->getType(); 3729 } 3730 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3731 return true; 3732 3733 // Complain if this is an explicit declaration of a special 3734 // member that was initially declared implicitly. 3735 // 3736 // As an exception, it's okay to befriend such methods in order 3737 // to permit the implicit constructor/destructor/operator calls. 3738 } else if (OldMethod->isImplicit()) { 3739 if (isFriend) { 3740 NewMethod->setImplicit(); 3741 } else { 3742 Diag(NewMethod->getLocation(), 3743 diag::err_definition_of_implicitly_declared_member) 3744 << New << getSpecialMember(OldMethod); 3745 return true; 3746 } 3747 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3748 Diag(NewMethod->getLocation(), 3749 diag::err_definition_of_explicitly_defaulted_member) 3750 << getSpecialMember(OldMethod); 3751 return true; 3752 } 3753 } 3754 3755 // C++11 [dcl.attr.noreturn]p1: 3756 // The first declaration of a function shall specify the noreturn 3757 // attribute if any declaration of that function specifies the noreturn 3758 // attribute. 3759 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3760 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3761 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3762 << NRA; 3763 Diag(Old->getLocation(), diag::note_previous_declaration); 3764 } 3765 3766 // C++11 [dcl.attr.depend]p2: 3767 // The first declaration of a function shall specify the 3768 // carries_dependency attribute for its declarator-id if any declaration 3769 // of the function specifies the carries_dependency attribute. 3770 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3771 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3772 Diag(CDA->getLocation(), 3773 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3774 Diag(Old->getFirstDecl()->getLocation(), 3775 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3776 } 3777 3778 // (C++98 8.3.5p3): 3779 // All declarations for a function shall agree exactly in both the 3780 // return type and the parameter-type-list. 3781 // We also want to respect all the extended bits except noreturn. 3782 3783 // noreturn should now match unless the old type info didn't have it. 3784 QualType OldQTypeForComparison = OldQType; 3785 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3786 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3787 const FunctionType *OldTypeForComparison 3788 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3789 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3790 assert(OldQTypeForComparison.isCanonical()); 3791 } 3792 3793 if (haveIncompatibleLanguageLinkages(Old, New)) { 3794 // As a special case, retain the language linkage from previous 3795 // declarations of a friend function as an extension. 3796 // 3797 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3798 // and is useful because there's otherwise no way to specify language 3799 // linkage within class scope. 3800 // 3801 // Check cautiously as the friend object kind isn't yet complete. 3802 if (New->getFriendObjectKind() != Decl::FOK_None) { 3803 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3804 Diag(OldLocation, PrevDiag); 3805 } else { 3806 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3807 Diag(OldLocation, PrevDiag); 3808 return true; 3809 } 3810 } 3811 3812 // If the function types are compatible, merge the declarations. Ignore the 3813 // exception specifier because it was already checked above in 3814 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3815 // about incompatible types under -fms-compatibility. 3816 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3817 NewQType)) 3818 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3819 3820 // If the types are imprecise (due to dependent constructs in friends or 3821 // local extern declarations), it's OK if they differ. We'll check again 3822 // during instantiation. 3823 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3824 return false; 3825 3826 // Fall through for conflicting redeclarations and redefinitions. 3827 } 3828 3829 // C: Function types need to be compatible, not identical. This handles 3830 // duplicate function decls like "void f(int); void f(enum X);" properly. 3831 if (!getLangOpts().CPlusPlus && 3832 Context.typesAreCompatible(OldQType, NewQType)) { 3833 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3834 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3835 const FunctionProtoType *OldProto = nullptr; 3836 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3837 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3838 // The old declaration provided a function prototype, but the 3839 // new declaration does not. Merge in the prototype. 3840 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3841 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3842 NewQType = 3843 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3844 OldProto->getExtProtoInfo()); 3845 New->setType(NewQType); 3846 New->setHasInheritedPrototype(); 3847 3848 // Synthesize parameters with the same types. 3849 SmallVector<ParmVarDecl*, 16> Params; 3850 for (const auto &ParamType : OldProto->param_types()) { 3851 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3852 SourceLocation(), nullptr, 3853 ParamType, /*TInfo=*/nullptr, 3854 SC_None, nullptr); 3855 Param->setScopeInfo(0, Params.size()); 3856 Param->setImplicit(); 3857 Params.push_back(Param); 3858 } 3859 3860 New->setParams(Params); 3861 } 3862 3863 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3864 } 3865 3866 // Check if the function types are compatible when pointer size address 3867 // spaces are ignored. 3868 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3869 return false; 3870 3871 // GNU C permits a K&R definition to follow a prototype declaration 3872 // if the declared types of the parameters in the K&R definition 3873 // match the types in the prototype declaration, even when the 3874 // promoted types of the parameters from the K&R definition differ 3875 // from the types in the prototype. GCC then keeps the types from 3876 // the prototype. 3877 // 3878 // If a variadic prototype is followed by a non-variadic K&R definition, 3879 // the K&R definition becomes variadic. This is sort of an edge case, but 3880 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3881 // C99 6.9.1p8. 3882 if (!getLangOpts().CPlusPlus && 3883 Old->hasPrototype() && !New->hasPrototype() && 3884 New->getType()->getAs<FunctionProtoType>() && 3885 Old->getNumParams() == New->getNumParams()) { 3886 SmallVector<QualType, 16> ArgTypes; 3887 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3888 const FunctionProtoType *OldProto 3889 = Old->getType()->getAs<FunctionProtoType>(); 3890 const FunctionProtoType *NewProto 3891 = New->getType()->getAs<FunctionProtoType>(); 3892 3893 // Determine whether this is the GNU C extension. 3894 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3895 NewProto->getReturnType()); 3896 bool LooseCompatible = !MergedReturn.isNull(); 3897 for (unsigned Idx = 0, End = Old->getNumParams(); 3898 LooseCompatible && Idx != End; ++Idx) { 3899 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3900 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3901 if (Context.typesAreCompatible(OldParm->getType(), 3902 NewProto->getParamType(Idx))) { 3903 ArgTypes.push_back(NewParm->getType()); 3904 } else if (Context.typesAreCompatible(OldParm->getType(), 3905 NewParm->getType(), 3906 /*CompareUnqualified=*/true)) { 3907 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3908 NewProto->getParamType(Idx) }; 3909 Warnings.push_back(Warn); 3910 ArgTypes.push_back(NewParm->getType()); 3911 } else 3912 LooseCompatible = false; 3913 } 3914 3915 if (LooseCompatible) { 3916 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3917 Diag(Warnings[Warn].NewParm->getLocation(), 3918 diag::ext_param_promoted_not_compatible_with_prototype) 3919 << Warnings[Warn].PromotedType 3920 << Warnings[Warn].OldParm->getType(); 3921 if (Warnings[Warn].OldParm->getLocation().isValid()) 3922 Diag(Warnings[Warn].OldParm->getLocation(), 3923 diag::note_previous_declaration); 3924 } 3925 3926 if (MergeTypeWithOld) 3927 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3928 OldProto->getExtProtoInfo())); 3929 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3930 } 3931 3932 // Fall through to diagnose conflicting types. 3933 } 3934 3935 // A function that has already been declared has been redeclared or 3936 // defined with a different type; show an appropriate diagnostic. 3937 3938 // If the previous declaration was an implicitly-generated builtin 3939 // declaration, then at the very least we should use a specialized note. 3940 unsigned BuiltinID; 3941 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3942 // If it's actually a library-defined builtin function like 'malloc' 3943 // or 'printf', just warn about the incompatible redeclaration. 3944 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3945 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3946 Diag(OldLocation, diag::note_previous_builtin_declaration) 3947 << Old << Old->getType(); 3948 return false; 3949 } 3950 3951 PrevDiag = diag::note_previous_builtin_declaration; 3952 } 3953 3954 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3955 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3956 return true; 3957 } 3958 3959 /// Completes the merge of two function declarations that are 3960 /// known to be compatible. 3961 /// 3962 /// This routine handles the merging of attributes and other 3963 /// properties of function declarations from the old declaration to 3964 /// the new declaration, once we know that New is in fact a 3965 /// redeclaration of Old. 3966 /// 3967 /// \returns false 3968 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3969 Scope *S, bool MergeTypeWithOld) { 3970 // Merge the attributes 3971 mergeDeclAttributes(New, Old); 3972 3973 // Merge "pure" flag. 3974 if (Old->isPure()) 3975 New->setPure(); 3976 3977 // Merge "used" flag. 3978 if (Old->getMostRecentDecl()->isUsed(false)) 3979 New->setIsUsed(); 3980 3981 // Merge attributes from the parameters. These can mismatch with K&R 3982 // declarations. 3983 if (New->getNumParams() == Old->getNumParams()) 3984 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3985 ParmVarDecl *NewParam = New->getParamDecl(i); 3986 ParmVarDecl *OldParam = Old->getParamDecl(i); 3987 mergeParamDeclAttributes(NewParam, OldParam, *this); 3988 mergeParamDeclTypes(NewParam, OldParam, *this); 3989 } 3990 3991 if (getLangOpts().CPlusPlus) 3992 return MergeCXXFunctionDecl(New, Old, S); 3993 3994 // Merge the function types so the we get the composite types for the return 3995 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3996 // was visible. 3997 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3998 if (!Merged.isNull() && MergeTypeWithOld) 3999 New->setType(Merged); 4000 4001 return false; 4002 } 4003 4004 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4005 ObjCMethodDecl *oldMethod) { 4006 // Merge the attributes, including deprecated/unavailable 4007 AvailabilityMergeKind MergeKind = 4008 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4009 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4010 : AMK_ProtocolImplementation) 4011 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4012 : AMK_Override; 4013 4014 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4015 4016 // Merge attributes from the parameters. 4017 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4018 oe = oldMethod->param_end(); 4019 for (ObjCMethodDecl::param_iterator 4020 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4021 ni != ne && oi != oe; ++ni, ++oi) 4022 mergeParamDeclAttributes(*ni, *oi, *this); 4023 4024 CheckObjCMethodOverride(newMethod, oldMethod); 4025 } 4026 4027 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4028 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4029 4030 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4031 ? diag::err_redefinition_different_type 4032 : diag::err_redeclaration_different_type) 4033 << New->getDeclName() << New->getType() << Old->getType(); 4034 4035 diag::kind PrevDiag; 4036 SourceLocation OldLocation; 4037 std::tie(PrevDiag, OldLocation) 4038 = getNoteDiagForInvalidRedeclaration(Old, New); 4039 S.Diag(OldLocation, PrevDiag); 4040 New->setInvalidDecl(); 4041 } 4042 4043 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4044 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4045 /// emitting diagnostics as appropriate. 4046 /// 4047 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4048 /// to here in AddInitializerToDecl. We can't check them before the initializer 4049 /// is attached. 4050 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4051 bool MergeTypeWithOld) { 4052 if (New->isInvalidDecl() || Old->isInvalidDecl()) 4053 return; 4054 4055 QualType MergedT; 4056 if (getLangOpts().CPlusPlus) { 4057 if (New->getType()->isUndeducedType()) { 4058 // We don't know what the new type is until the initializer is attached. 4059 return; 4060 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4061 // These could still be something that needs exception specs checked. 4062 return MergeVarDeclExceptionSpecs(New, Old); 4063 } 4064 // C++ [basic.link]p10: 4065 // [...] the types specified by all declarations referring to a given 4066 // object or function shall be identical, except that declarations for an 4067 // array object can specify array types that differ by the presence or 4068 // absence of a major array bound (8.3.4). 4069 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4070 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4071 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4072 4073 // We are merging a variable declaration New into Old. If it has an array 4074 // bound, and that bound differs from Old's bound, we should diagnose the 4075 // mismatch. 4076 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4077 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4078 PrevVD = PrevVD->getPreviousDecl()) { 4079 QualType PrevVDTy = PrevVD->getType(); 4080 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4081 continue; 4082 4083 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4084 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4085 } 4086 } 4087 4088 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4089 if (Context.hasSameType(OldArray->getElementType(), 4090 NewArray->getElementType())) 4091 MergedT = New->getType(); 4092 } 4093 // FIXME: Check visibility. New is hidden but has a complete type. If New 4094 // has no array bound, it should not inherit one from Old, if Old is not 4095 // visible. 4096 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4097 if (Context.hasSameType(OldArray->getElementType(), 4098 NewArray->getElementType())) 4099 MergedT = Old->getType(); 4100 } 4101 } 4102 else if (New->getType()->isObjCObjectPointerType() && 4103 Old->getType()->isObjCObjectPointerType()) { 4104 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4105 Old->getType()); 4106 } 4107 } else { 4108 // C 6.2.7p2: 4109 // All declarations that refer to the same object or function shall have 4110 // compatible type. 4111 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4112 } 4113 if (MergedT.isNull()) { 4114 // It's OK if we couldn't merge types if either type is dependent, for a 4115 // block-scope variable. In other cases (static data members of class 4116 // templates, variable templates, ...), we require the types to be 4117 // equivalent. 4118 // FIXME: The C++ standard doesn't say anything about this. 4119 if ((New->getType()->isDependentType() || 4120 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4121 // If the old type was dependent, we can't merge with it, so the new type 4122 // becomes dependent for now. We'll reproduce the original type when we 4123 // instantiate the TypeSourceInfo for the variable. 4124 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4125 New->setType(Context.DependentTy); 4126 return; 4127 } 4128 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4129 } 4130 4131 // Don't actually update the type on the new declaration if the old 4132 // declaration was an extern declaration in a different scope. 4133 if (MergeTypeWithOld) 4134 New->setType(MergedT); 4135 } 4136 4137 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4138 LookupResult &Previous) { 4139 // C11 6.2.7p4: 4140 // For an identifier with internal or external linkage declared 4141 // in a scope in which a prior declaration of that identifier is 4142 // visible, if the prior declaration specifies internal or 4143 // external linkage, the type of the identifier at the later 4144 // declaration becomes the composite type. 4145 // 4146 // If the variable isn't visible, we do not merge with its type. 4147 if (Previous.isShadowed()) 4148 return false; 4149 4150 if (S.getLangOpts().CPlusPlus) { 4151 // C++11 [dcl.array]p3: 4152 // If there is a preceding declaration of the entity in the same 4153 // scope in which the bound was specified, an omitted array bound 4154 // is taken to be the same as in that earlier declaration. 4155 return NewVD->isPreviousDeclInSameBlockScope() || 4156 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4157 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4158 } else { 4159 // If the old declaration was function-local, don't merge with its 4160 // type unless we're in the same function. 4161 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4162 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4163 } 4164 } 4165 4166 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4167 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4168 /// situation, merging decls or emitting diagnostics as appropriate. 4169 /// 4170 /// Tentative definition rules (C99 6.9.2p2) are checked by 4171 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4172 /// definitions here, since the initializer hasn't been attached. 4173 /// 4174 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4175 // If the new decl is already invalid, don't do any other checking. 4176 if (New->isInvalidDecl()) 4177 return; 4178 4179 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4180 return; 4181 4182 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4183 4184 // Verify the old decl was also a variable or variable template. 4185 VarDecl *Old = nullptr; 4186 VarTemplateDecl *OldTemplate = nullptr; 4187 if (Previous.isSingleResult()) { 4188 if (NewTemplate) { 4189 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4190 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4191 4192 if (auto *Shadow = 4193 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4194 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4195 return New->setInvalidDecl(); 4196 } else { 4197 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4198 4199 if (auto *Shadow = 4200 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4201 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4202 return New->setInvalidDecl(); 4203 } 4204 } 4205 if (!Old) { 4206 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4207 << New->getDeclName(); 4208 notePreviousDefinition(Previous.getRepresentativeDecl(), 4209 New->getLocation()); 4210 return New->setInvalidDecl(); 4211 } 4212 4213 // If the old declaration was found in an inline namespace and the new 4214 // declaration was qualified, update the DeclContext to match. 4215 adjustDeclContextForDeclaratorDecl(New, Old); 4216 4217 // Ensure the template parameters are compatible. 4218 if (NewTemplate && 4219 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4220 OldTemplate->getTemplateParameters(), 4221 /*Complain=*/true, TPL_TemplateMatch)) 4222 return New->setInvalidDecl(); 4223 4224 // C++ [class.mem]p1: 4225 // A member shall not be declared twice in the member-specification [...] 4226 // 4227 // Here, we need only consider static data members. 4228 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4229 Diag(New->getLocation(), diag::err_duplicate_member) 4230 << New->getIdentifier(); 4231 Diag(Old->getLocation(), diag::note_previous_declaration); 4232 New->setInvalidDecl(); 4233 } 4234 4235 mergeDeclAttributes(New, Old); 4236 // Warn if an already-declared variable is made a weak_import in a subsequent 4237 // declaration 4238 if (New->hasAttr<WeakImportAttr>() && 4239 Old->getStorageClass() == SC_None && 4240 !Old->hasAttr<WeakImportAttr>()) { 4241 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4242 Diag(Old->getLocation(), diag::note_previous_declaration); 4243 // Remove weak_import attribute on new declaration. 4244 New->dropAttr<WeakImportAttr>(); 4245 } 4246 4247 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4248 if (!Old->hasAttr<InternalLinkageAttr>()) { 4249 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4250 << ILA; 4251 Diag(Old->getLocation(), diag::note_previous_declaration); 4252 New->dropAttr<InternalLinkageAttr>(); 4253 } 4254 4255 // Merge the types. 4256 VarDecl *MostRecent = Old->getMostRecentDecl(); 4257 if (MostRecent != Old) { 4258 MergeVarDeclTypes(New, MostRecent, 4259 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4260 if (New->isInvalidDecl()) 4261 return; 4262 } 4263 4264 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4265 if (New->isInvalidDecl()) 4266 return; 4267 4268 diag::kind PrevDiag; 4269 SourceLocation OldLocation; 4270 std::tie(PrevDiag, OldLocation) = 4271 getNoteDiagForInvalidRedeclaration(Old, New); 4272 4273 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4274 if (New->getStorageClass() == SC_Static && 4275 !New->isStaticDataMember() && 4276 Old->hasExternalFormalLinkage()) { 4277 if (getLangOpts().MicrosoftExt) { 4278 Diag(New->getLocation(), diag::ext_static_non_static) 4279 << New->getDeclName(); 4280 Diag(OldLocation, PrevDiag); 4281 } else { 4282 Diag(New->getLocation(), diag::err_static_non_static) 4283 << New->getDeclName(); 4284 Diag(OldLocation, PrevDiag); 4285 return New->setInvalidDecl(); 4286 } 4287 } 4288 // C99 6.2.2p4: 4289 // For an identifier declared with the storage-class specifier 4290 // extern in a scope in which a prior declaration of that 4291 // identifier is visible,23) if the prior declaration specifies 4292 // internal or external linkage, the linkage of the identifier at 4293 // the later declaration is the same as the linkage specified at 4294 // the prior declaration. If no prior declaration is visible, or 4295 // if the prior declaration specifies no linkage, then the 4296 // identifier has external linkage. 4297 if (New->hasExternalStorage() && Old->hasLinkage()) 4298 /* Okay */; 4299 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4300 !New->isStaticDataMember() && 4301 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4302 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4303 Diag(OldLocation, PrevDiag); 4304 return New->setInvalidDecl(); 4305 } 4306 4307 // Check if extern is followed by non-extern and vice-versa. 4308 if (New->hasExternalStorage() && 4309 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4310 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4311 Diag(OldLocation, PrevDiag); 4312 return New->setInvalidDecl(); 4313 } 4314 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4315 !New->hasExternalStorage()) { 4316 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4317 Diag(OldLocation, PrevDiag); 4318 return New->setInvalidDecl(); 4319 } 4320 4321 if (CheckRedeclarationInModule(New, Old)) 4322 return; 4323 4324 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4325 4326 // FIXME: The test for external storage here seems wrong? We still 4327 // need to check for mismatches. 4328 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4329 // Don't complain about out-of-line definitions of static members. 4330 !(Old->getLexicalDeclContext()->isRecord() && 4331 !New->getLexicalDeclContext()->isRecord())) { 4332 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4333 Diag(OldLocation, PrevDiag); 4334 return New->setInvalidDecl(); 4335 } 4336 4337 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4338 if (VarDecl *Def = Old->getDefinition()) { 4339 // C++1z [dcl.fcn.spec]p4: 4340 // If the definition of a variable appears in a translation unit before 4341 // its first declaration as inline, the program is ill-formed. 4342 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4343 Diag(Def->getLocation(), diag::note_previous_definition); 4344 } 4345 } 4346 4347 // If this redeclaration makes the variable inline, we may need to add it to 4348 // UndefinedButUsed. 4349 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4350 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4351 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4352 SourceLocation())); 4353 4354 if (New->getTLSKind() != Old->getTLSKind()) { 4355 if (!Old->getTLSKind()) { 4356 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4357 Diag(OldLocation, PrevDiag); 4358 } else if (!New->getTLSKind()) { 4359 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4360 Diag(OldLocation, PrevDiag); 4361 } else { 4362 // Do not allow redeclaration to change the variable between requiring 4363 // static and dynamic initialization. 4364 // FIXME: GCC allows this, but uses the TLS keyword on the first 4365 // declaration to determine the kind. Do we need to be compatible here? 4366 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4367 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4368 Diag(OldLocation, PrevDiag); 4369 } 4370 } 4371 4372 // C++ doesn't have tentative definitions, so go right ahead and check here. 4373 if (getLangOpts().CPlusPlus && 4374 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4375 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4376 Old->getCanonicalDecl()->isConstexpr()) { 4377 // This definition won't be a definition any more once it's been merged. 4378 Diag(New->getLocation(), 4379 diag::warn_deprecated_redundant_constexpr_static_def); 4380 } else if (VarDecl *Def = Old->getDefinition()) { 4381 if (checkVarDeclRedefinition(Def, New)) 4382 return; 4383 } 4384 } 4385 4386 if (haveIncompatibleLanguageLinkages(Old, New)) { 4387 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4388 Diag(OldLocation, PrevDiag); 4389 New->setInvalidDecl(); 4390 return; 4391 } 4392 4393 // Merge "used" flag. 4394 if (Old->getMostRecentDecl()->isUsed(false)) 4395 New->setIsUsed(); 4396 4397 // Keep a chain of previous declarations. 4398 New->setPreviousDecl(Old); 4399 if (NewTemplate) 4400 NewTemplate->setPreviousDecl(OldTemplate); 4401 4402 // Inherit access appropriately. 4403 New->setAccess(Old->getAccess()); 4404 if (NewTemplate) 4405 NewTemplate->setAccess(New->getAccess()); 4406 4407 if (Old->isInline()) 4408 New->setImplicitlyInline(); 4409 } 4410 4411 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4412 SourceManager &SrcMgr = getSourceManager(); 4413 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4414 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4415 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4416 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4417 auto &HSI = PP.getHeaderSearchInfo(); 4418 StringRef HdrFilename = 4419 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4420 4421 auto noteFromModuleOrInclude = [&](Module *Mod, 4422 SourceLocation IncLoc) -> bool { 4423 // Redefinition errors with modules are common with non modular mapped 4424 // headers, example: a non-modular header H in module A that also gets 4425 // included directly in a TU. Pointing twice to the same header/definition 4426 // is confusing, try to get better diagnostics when modules is on. 4427 if (IncLoc.isValid()) { 4428 if (Mod) { 4429 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4430 << HdrFilename.str() << Mod->getFullModuleName(); 4431 if (!Mod->DefinitionLoc.isInvalid()) 4432 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4433 << Mod->getFullModuleName(); 4434 } else { 4435 Diag(IncLoc, diag::note_redefinition_include_same_file) 4436 << HdrFilename.str(); 4437 } 4438 return true; 4439 } 4440 4441 return false; 4442 }; 4443 4444 // Is it the same file and same offset? Provide more information on why 4445 // this leads to a redefinition error. 4446 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4447 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4448 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4449 bool EmittedDiag = 4450 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4451 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4452 4453 // If the header has no guards, emit a note suggesting one. 4454 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4455 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4456 4457 if (EmittedDiag) 4458 return; 4459 } 4460 4461 // Redefinition coming from different files or couldn't do better above. 4462 if (Old->getLocation().isValid()) 4463 Diag(Old->getLocation(), diag::note_previous_definition); 4464 } 4465 4466 /// We've just determined that \p Old and \p New both appear to be definitions 4467 /// of the same variable. Either diagnose or fix the problem. 4468 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4469 if (!hasVisibleDefinition(Old) && 4470 (New->getFormalLinkage() == InternalLinkage || 4471 New->isInline() || 4472 New->getDescribedVarTemplate() || 4473 New->getNumTemplateParameterLists() || 4474 New->getDeclContext()->isDependentContext())) { 4475 // The previous definition is hidden, and multiple definitions are 4476 // permitted (in separate TUs). Demote this to a declaration. 4477 New->demoteThisDefinitionToDeclaration(); 4478 4479 // Make the canonical definition visible. 4480 if (auto *OldTD = Old->getDescribedVarTemplate()) 4481 makeMergedDefinitionVisible(OldTD); 4482 makeMergedDefinitionVisible(Old); 4483 return false; 4484 } else { 4485 Diag(New->getLocation(), diag::err_redefinition) << New; 4486 notePreviousDefinition(Old, New->getLocation()); 4487 New->setInvalidDecl(); 4488 return true; 4489 } 4490 } 4491 4492 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4493 /// no declarator (e.g. "struct foo;") is parsed. 4494 Decl * 4495 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4496 RecordDecl *&AnonRecord) { 4497 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4498 AnonRecord); 4499 } 4500 4501 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4502 // disambiguate entities defined in different scopes. 4503 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4504 // compatibility. 4505 // We will pick our mangling number depending on which version of MSVC is being 4506 // targeted. 4507 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4508 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4509 ? S->getMSCurManglingNumber() 4510 : S->getMSLastManglingNumber(); 4511 } 4512 4513 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4514 if (!Context.getLangOpts().CPlusPlus) 4515 return; 4516 4517 if (isa<CXXRecordDecl>(Tag->getParent())) { 4518 // If this tag is the direct child of a class, number it if 4519 // it is anonymous. 4520 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4521 return; 4522 MangleNumberingContext &MCtx = 4523 Context.getManglingNumberContext(Tag->getParent()); 4524 Context.setManglingNumber( 4525 Tag, MCtx.getManglingNumber( 4526 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4527 return; 4528 } 4529 4530 // If this tag isn't a direct child of a class, number it if it is local. 4531 MangleNumberingContext *MCtx; 4532 Decl *ManglingContextDecl; 4533 std::tie(MCtx, ManglingContextDecl) = 4534 getCurrentMangleNumberContext(Tag->getDeclContext()); 4535 if (MCtx) { 4536 Context.setManglingNumber( 4537 Tag, MCtx->getManglingNumber( 4538 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4539 } 4540 } 4541 4542 namespace { 4543 struct NonCLikeKind { 4544 enum { 4545 None, 4546 BaseClass, 4547 DefaultMemberInit, 4548 Lambda, 4549 Friend, 4550 OtherMember, 4551 Invalid, 4552 } Kind = None; 4553 SourceRange Range; 4554 4555 explicit operator bool() { return Kind != None; } 4556 }; 4557 } 4558 4559 /// Determine whether a class is C-like, according to the rules of C++ 4560 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4561 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4562 if (RD->isInvalidDecl()) 4563 return {NonCLikeKind::Invalid, {}}; 4564 4565 // C++ [dcl.typedef]p9: [P1766R1] 4566 // An unnamed class with a typedef name for linkage purposes shall not 4567 // 4568 // -- have any base classes 4569 if (RD->getNumBases()) 4570 return {NonCLikeKind::BaseClass, 4571 SourceRange(RD->bases_begin()->getBeginLoc(), 4572 RD->bases_end()[-1].getEndLoc())}; 4573 bool Invalid = false; 4574 for (Decl *D : RD->decls()) { 4575 // Don't complain about things we already diagnosed. 4576 if (D->isInvalidDecl()) { 4577 Invalid = true; 4578 continue; 4579 } 4580 4581 // -- have any [...] default member initializers 4582 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4583 if (FD->hasInClassInitializer()) { 4584 auto *Init = FD->getInClassInitializer(); 4585 return {NonCLikeKind::DefaultMemberInit, 4586 Init ? Init->getSourceRange() : D->getSourceRange()}; 4587 } 4588 continue; 4589 } 4590 4591 // FIXME: We don't allow friend declarations. This violates the wording of 4592 // P1766, but not the intent. 4593 if (isa<FriendDecl>(D)) 4594 return {NonCLikeKind::Friend, D->getSourceRange()}; 4595 4596 // -- declare any members other than non-static data members, member 4597 // enumerations, or member classes, 4598 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4599 isa<EnumDecl>(D)) 4600 continue; 4601 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4602 if (!MemberRD) { 4603 if (D->isImplicit()) 4604 continue; 4605 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4606 } 4607 4608 // -- contain a lambda-expression, 4609 if (MemberRD->isLambda()) 4610 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4611 4612 // and all member classes shall also satisfy these requirements 4613 // (recursively). 4614 if (MemberRD->isThisDeclarationADefinition()) { 4615 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4616 return Kind; 4617 } 4618 } 4619 4620 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4621 } 4622 4623 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4624 TypedefNameDecl *NewTD) { 4625 if (TagFromDeclSpec->isInvalidDecl()) 4626 return; 4627 4628 // Do nothing if the tag already has a name for linkage purposes. 4629 if (TagFromDeclSpec->hasNameForLinkage()) 4630 return; 4631 4632 // A well-formed anonymous tag must always be a TUK_Definition. 4633 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4634 4635 // The type must match the tag exactly; no qualifiers allowed. 4636 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4637 Context.getTagDeclType(TagFromDeclSpec))) { 4638 if (getLangOpts().CPlusPlus) 4639 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4640 return; 4641 } 4642 4643 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4644 // An unnamed class with a typedef name for linkage purposes shall [be 4645 // C-like]. 4646 // 4647 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4648 // shouldn't happen, but there are constructs that the language rule doesn't 4649 // disallow for which we can't reasonably avoid computing linkage early. 4650 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4651 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4652 : NonCLikeKind(); 4653 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4654 if (NonCLike || ChangesLinkage) { 4655 if (NonCLike.Kind == NonCLikeKind::Invalid) 4656 return; 4657 4658 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4659 if (ChangesLinkage) { 4660 // If the linkage changes, we can't accept this as an extension. 4661 if (NonCLike.Kind == NonCLikeKind::None) 4662 DiagID = diag::err_typedef_changes_linkage; 4663 else 4664 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4665 } 4666 4667 SourceLocation FixitLoc = 4668 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4669 llvm::SmallString<40> TextToInsert; 4670 TextToInsert += ' '; 4671 TextToInsert += NewTD->getIdentifier()->getName(); 4672 4673 Diag(FixitLoc, DiagID) 4674 << isa<TypeAliasDecl>(NewTD) 4675 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4676 if (NonCLike.Kind != NonCLikeKind::None) { 4677 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4678 << NonCLike.Kind - 1 << NonCLike.Range; 4679 } 4680 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4681 << NewTD << isa<TypeAliasDecl>(NewTD); 4682 4683 if (ChangesLinkage) 4684 return; 4685 } 4686 4687 // Otherwise, set this as the anon-decl typedef for the tag. 4688 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4689 } 4690 4691 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4692 switch (T) { 4693 case DeclSpec::TST_class: 4694 return 0; 4695 case DeclSpec::TST_struct: 4696 return 1; 4697 case DeclSpec::TST_interface: 4698 return 2; 4699 case DeclSpec::TST_union: 4700 return 3; 4701 case DeclSpec::TST_enum: 4702 return 4; 4703 default: 4704 llvm_unreachable("unexpected type specifier"); 4705 } 4706 } 4707 4708 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4709 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4710 /// parameters to cope with template friend declarations. 4711 Decl * 4712 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4713 MultiTemplateParamsArg TemplateParams, 4714 bool IsExplicitInstantiation, 4715 RecordDecl *&AnonRecord) { 4716 Decl *TagD = nullptr; 4717 TagDecl *Tag = nullptr; 4718 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4719 DS.getTypeSpecType() == DeclSpec::TST_struct || 4720 DS.getTypeSpecType() == DeclSpec::TST_interface || 4721 DS.getTypeSpecType() == DeclSpec::TST_union || 4722 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4723 TagD = DS.getRepAsDecl(); 4724 4725 if (!TagD) // We probably had an error 4726 return nullptr; 4727 4728 // Note that the above type specs guarantee that the 4729 // type rep is a Decl, whereas in many of the others 4730 // it's a Type. 4731 if (isa<TagDecl>(TagD)) 4732 Tag = cast<TagDecl>(TagD); 4733 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4734 Tag = CTD->getTemplatedDecl(); 4735 } 4736 4737 if (Tag) { 4738 handleTagNumbering(Tag, S); 4739 Tag->setFreeStanding(); 4740 if (Tag->isInvalidDecl()) 4741 return Tag; 4742 } 4743 4744 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4745 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4746 // or incomplete types shall not be restrict-qualified." 4747 if (TypeQuals & DeclSpec::TQ_restrict) 4748 Diag(DS.getRestrictSpecLoc(), 4749 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4750 << DS.getSourceRange(); 4751 } 4752 4753 if (DS.isInlineSpecified()) 4754 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4755 << getLangOpts().CPlusPlus17; 4756 4757 if (DS.hasConstexprSpecifier()) { 4758 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4759 // and definitions of functions and variables. 4760 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4761 // the declaration of a function or function template 4762 if (Tag) 4763 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4764 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4765 << static_cast<int>(DS.getConstexprSpecifier()); 4766 else 4767 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4768 << static_cast<int>(DS.getConstexprSpecifier()); 4769 // Don't emit warnings after this error. 4770 return TagD; 4771 } 4772 4773 DiagnoseFunctionSpecifiers(DS); 4774 4775 if (DS.isFriendSpecified()) { 4776 // If we're dealing with a decl but not a TagDecl, assume that 4777 // whatever routines created it handled the friendship aspect. 4778 if (TagD && !Tag) 4779 return nullptr; 4780 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4781 } 4782 4783 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4784 bool IsExplicitSpecialization = 4785 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4786 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4787 !IsExplicitInstantiation && !IsExplicitSpecialization && 4788 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4789 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4790 // nested-name-specifier unless it is an explicit instantiation 4791 // or an explicit specialization. 4792 // 4793 // FIXME: We allow class template partial specializations here too, per the 4794 // obvious intent of DR1819. 4795 // 4796 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4797 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4798 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4799 return nullptr; 4800 } 4801 4802 // Track whether this decl-specifier declares anything. 4803 bool DeclaresAnything = true; 4804 4805 // Handle anonymous struct definitions. 4806 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4807 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4808 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4809 if (getLangOpts().CPlusPlus || 4810 Record->getDeclContext()->isRecord()) { 4811 // If CurContext is a DeclContext that can contain statements, 4812 // RecursiveASTVisitor won't visit the decls that 4813 // BuildAnonymousStructOrUnion() will put into CurContext. 4814 // Also store them here so that they can be part of the 4815 // DeclStmt that gets created in this case. 4816 // FIXME: Also return the IndirectFieldDecls created by 4817 // BuildAnonymousStructOr union, for the same reason? 4818 if (CurContext->isFunctionOrMethod()) 4819 AnonRecord = Record; 4820 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4821 Context.getPrintingPolicy()); 4822 } 4823 4824 DeclaresAnything = false; 4825 } 4826 } 4827 4828 // C11 6.7.2.1p2: 4829 // A struct-declaration that does not declare an anonymous structure or 4830 // anonymous union shall contain a struct-declarator-list. 4831 // 4832 // This rule also existed in C89 and C99; the grammar for struct-declaration 4833 // did not permit a struct-declaration without a struct-declarator-list. 4834 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4835 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4836 // Check for Microsoft C extension: anonymous struct/union member. 4837 // Handle 2 kinds of anonymous struct/union: 4838 // struct STRUCT; 4839 // union UNION; 4840 // and 4841 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4842 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4843 if ((Tag && Tag->getDeclName()) || 4844 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4845 RecordDecl *Record = nullptr; 4846 if (Tag) 4847 Record = dyn_cast<RecordDecl>(Tag); 4848 else if (const RecordType *RT = 4849 DS.getRepAsType().get()->getAsStructureType()) 4850 Record = RT->getDecl(); 4851 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4852 Record = UT->getDecl(); 4853 4854 if (Record && getLangOpts().MicrosoftExt) { 4855 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4856 << Record->isUnion() << DS.getSourceRange(); 4857 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4858 } 4859 4860 DeclaresAnything = false; 4861 } 4862 } 4863 4864 // Skip all the checks below if we have a type error. 4865 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4866 (TagD && TagD->isInvalidDecl())) 4867 return TagD; 4868 4869 if (getLangOpts().CPlusPlus && 4870 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4871 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4872 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4873 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4874 DeclaresAnything = false; 4875 4876 if (!DS.isMissingDeclaratorOk()) { 4877 // Customize diagnostic for a typedef missing a name. 4878 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4879 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4880 << DS.getSourceRange(); 4881 else 4882 DeclaresAnything = false; 4883 } 4884 4885 if (DS.isModulePrivateSpecified() && 4886 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4887 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4888 << Tag->getTagKind() 4889 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4890 4891 ActOnDocumentableDecl(TagD); 4892 4893 // C 6.7/2: 4894 // A declaration [...] shall declare at least a declarator [...], a tag, 4895 // or the members of an enumeration. 4896 // C++ [dcl.dcl]p3: 4897 // [If there are no declarators], and except for the declaration of an 4898 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4899 // names into the program, or shall redeclare a name introduced by a 4900 // previous declaration. 4901 if (!DeclaresAnything) { 4902 // In C, we allow this as a (popular) extension / bug. Don't bother 4903 // producing further diagnostics for redundant qualifiers after this. 4904 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4905 ? diag::err_no_declarators 4906 : diag::ext_no_declarators) 4907 << DS.getSourceRange(); 4908 return TagD; 4909 } 4910 4911 // C++ [dcl.stc]p1: 4912 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4913 // init-declarator-list of the declaration shall not be empty. 4914 // C++ [dcl.fct.spec]p1: 4915 // If a cv-qualifier appears in a decl-specifier-seq, the 4916 // init-declarator-list of the declaration shall not be empty. 4917 // 4918 // Spurious qualifiers here appear to be valid in C. 4919 unsigned DiagID = diag::warn_standalone_specifier; 4920 if (getLangOpts().CPlusPlus) 4921 DiagID = diag::ext_standalone_specifier; 4922 4923 // Note that a linkage-specification sets a storage class, but 4924 // 'extern "C" struct foo;' is actually valid and not theoretically 4925 // useless. 4926 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4927 if (SCS == DeclSpec::SCS_mutable) 4928 // Since mutable is not a viable storage class specifier in C, there is 4929 // no reason to treat it as an extension. Instead, diagnose as an error. 4930 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4931 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4932 Diag(DS.getStorageClassSpecLoc(), DiagID) 4933 << DeclSpec::getSpecifierName(SCS); 4934 } 4935 4936 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4937 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4938 << DeclSpec::getSpecifierName(TSCS); 4939 if (DS.getTypeQualifiers()) { 4940 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4941 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4942 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4943 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4944 // Restrict is covered above. 4945 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4946 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4947 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4948 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4949 } 4950 4951 // Warn about ignored type attributes, for example: 4952 // __attribute__((aligned)) struct A; 4953 // Attributes should be placed after tag to apply to type declaration. 4954 if (!DS.getAttributes().empty()) { 4955 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4956 if (TypeSpecType == DeclSpec::TST_class || 4957 TypeSpecType == DeclSpec::TST_struct || 4958 TypeSpecType == DeclSpec::TST_interface || 4959 TypeSpecType == DeclSpec::TST_union || 4960 TypeSpecType == DeclSpec::TST_enum) { 4961 for (const ParsedAttr &AL : DS.getAttributes()) 4962 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4963 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4964 } 4965 } 4966 4967 return TagD; 4968 } 4969 4970 /// We are trying to inject an anonymous member into the given scope; 4971 /// check if there's an existing declaration that can't be overloaded. 4972 /// 4973 /// \return true if this is a forbidden redeclaration 4974 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4975 Scope *S, 4976 DeclContext *Owner, 4977 DeclarationName Name, 4978 SourceLocation NameLoc, 4979 bool IsUnion) { 4980 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4981 Sema::ForVisibleRedeclaration); 4982 if (!SemaRef.LookupName(R, S)) return false; 4983 4984 // Pick a representative declaration. 4985 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4986 assert(PrevDecl && "Expected a non-null Decl"); 4987 4988 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4989 return false; 4990 4991 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4992 << IsUnion << Name; 4993 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4994 4995 return true; 4996 } 4997 4998 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4999 /// anonymous struct or union AnonRecord into the owning context Owner 5000 /// and scope S. This routine will be invoked just after we realize 5001 /// that an unnamed union or struct is actually an anonymous union or 5002 /// struct, e.g., 5003 /// 5004 /// @code 5005 /// union { 5006 /// int i; 5007 /// float f; 5008 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5009 /// // f into the surrounding scope.x 5010 /// @endcode 5011 /// 5012 /// This routine is recursive, injecting the names of nested anonymous 5013 /// structs/unions into the owning context and scope as well. 5014 static bool 5015 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5016 RecordDecl *AnonRecord, AccessSpecifier AS, 5017 SmallVectorImpl<NamedDecl *> &Chaining) { 5018 bool Invalid = false; 5019 5020 // Look every FieldDecl and IndirectFieldDecl with a name. 5021 for (auto *D : AnonRecord->decls()) { 5022 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5023 cast<NamedDecl>(D)->getDeclName()) { 5024 ValueDecl *VD = cast<ValueDecl>(D); 5025 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5026 VD->getLocation(), 5027 AnonRecord->isUnion())) { 5028 // C++ [class.union]p2: 5029 // The names of the members of an anonymous union shall be 5030 // distinct from the names of any other entity in the 5031 // scope in which the anonymous union is declared. 5032 Invalid = true; 5033 } else { 5034 // C++ [class.union]p2: 5035 // For the purpose of name lookup, after the anonymous union 5036 // definition, the members of the anonymous union are 5037 // considered to have been defined in the scope in which the 5038 // anonymous union is declared. 5039 unsigned OldChainingSize = Chaining.size(); 5040 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5041 Chaining.append(IF->chain_begin(), IF->chain_end()); 5042 else 5043 Chaining.push_back(VD); 5044 5045 assert(Chaining.size() >= 2); 5046 NamedDecl **NamedChain = 5047 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5048 for (unsigned i = 0; i < Chaining.size(); i++) 5049 NamedChain[i] = Chaining[i]; 5050 5051 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5052 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5053 VD->getType(), {NamedChain, Chaining.size()}); 5054 5055 for (const auto *Attr : VD->attrs()) 5056 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5057 5058 IndirectField->setAccess(AS); 5059 IndirectField->setImplicit(); 5060 SemaRef.PushOnScopeChains(IndirectField, S); 5061 5062 // That includes picking up the appropriate access specifier. 5063 if (AS != AS_none) IndirectField->setAccess(AS); 5064 5065 Chaining.resize(OldChainingSize); 5066 } 5067 } 5068 } 5069 5070 return Invalid; 5071 } 5072 5073 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5074 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5075 /// illegal input values are mapped to SC_None. 5076 static StorageClass 5077 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5078 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5079 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5080 "Parser allowed 'typedef' as storage class VarDecl."); 5081 switch (StorageClassSpec) { 5082 case DeclSpec::SCS_unspecified: return SC_None; 5083 case DeclSpec::SCS_extern: 5084 if (DS.isExternInLinkageSpec()) 5085 return SC_None; 5086 return SC_Extern; 5087 case DeclSpec::SCS_static: return SC_Static; 5088 case DeclSpec::SCS_auto: return SC_Auto; 5089 case DeclSpec::SCS_register: return SC_Register; 5090 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5091 // Illegal SCSs map to None: error reporting is up to the caller. 5092 case DeclSpec::SCS_mutable: // Fall through. 5093 case DeclSpec::SCS_typedef: return SC_None; 5094 } 5095 llvm_unreachable("unknown storage class specifier"); 5096 } 5097 5098 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5099 assert(Record->hasInClassInitializer()); 5100 5101 for (const auto *I : Record->decls()) { 5102 const auto *FD = dyn_cast<FieldDecl>(I); 5103 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5104 FD = IFD->getAnonField(); 5105 if (FD && FD->hasInClassInitializer()) 5106 return FD->getLocation(); 5107 } 5108 5109 llvm_unreachable("couldn't find in-class initializer"); 5110 } 5111 5112 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5113 SourceLocation DefaultInitLoc) { 5114 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5115 return; 5116 5117 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5118 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5119 } 5120 5121 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5122 CXXRecordDecl *AnonUnion) { 5123 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5124 return; 5125 5126 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5127 } 5128 5129 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5130 /// anonymous structure or union. Anonymous unions are a C++ feature 5131 /// (C++ [class.union]) and a C11 feature; anonymous structures 5132 /// are a C11 feature and GNU C++ extension. 5133 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5134 AccessSpecifier AS, 5135 RecordDecl *Record, 5136 const PrintingPolicy &Policy) { 5137 DeclContext *Owner = Record->getDeclContext(); 5138 5139 // Diagnose whether this anonymous struct/union is an extension. 5140 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5141 Diag(Record->getLocation(), diag::ext_anonymous_union); 5142 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5143 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5144 else if (!Record->isUnion() && !getLangOpts().C11) 5145 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5146 5147 // C and C++ require different kinds of checks for anonymous 5148 // structs/unions. 5149 bool Invalid = false; 5150 if (getLangOpts().CPlusPlus) { 5151 const char *PrevSpec = nullptr; 5152 if (Record->isUnion()) { 5153 // C++ [class.union]p6: 5154 // C++17 [class.union.anon]p2: 5155 // Anonymous unions declared in a named namespace or in the 5156 // global namespace shall be declared static. 5157 unsigned DiagID; 5158 DeclContext *OwnerScope = Owner->getRedeclContext(); 5159 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5160 (OwnerScope->isTranslationUnit() || 5161 (OwnerScope->isNamespace() && 5162 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5163 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5164 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5165 5166 // Recover by adding 'static'. 5167 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5168 PrevSpec, DiagID, Policy); 5169 } 5170 // C++ [class.union]p6: 5171 // A storage class is not allowed in a declaration of an 5172 // anonymous union in a class scope. 5173 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5174 isa<RecordDecl>(Owner)) { 5175 Diag(DS.getStorageClassSpecLoc(), 5176 diag::err_anonymous_union_with_storage_spec) 5177 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5178 5179 // Recover by removing the storage specifier. 5180 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5181 SourceLocation(), 5182 PrevSpec, DiagID, Context.getPrintingPolicy()); 5183 } 5184 } 5185 5186 // Ignore const/volatile/restrict qualifiers. 5187 if (DS.getTypeQualifiers()) { 5188 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5189 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5190 << Record->isUnion() << "const" 5191 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5192 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5193 Diag(DS.getVolatileSpecLoc(), 5194 diag::ext_anonymous_struct_union_qualified) 5195 << Record->isUnion() << "volatile" 5196 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5197 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5198 Diag(DS.getRestrictSpecLoc(), 5199 diag::ext_anonymous_struct_union_qualified) 5200 << Record->isUnion() << "restrict" 5201 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5202 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5203 Diag(DS.getAtomicSpecLoc(), 5204 diag::ext_anonymous_struct_union_qualified) 5205 << Record->isUnion() << "_Atomic" 5206 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5207 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5208 Diag(DS.getUnalignedSpecLoc(), 5209 diag::ext_anonymous_struct_union_qualified) 5210 << Record->isUnion() << "__unaligned" 5211 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5212 5213 DS.ClearTypeQualifiers(); 5214 } 5215 5216 // C++ [class.union]p2: 5217 // The member-specification of an anonymous union shall only 5218 // define non-static data members. [Note: nested types and 5219 // functions cannot be declared within an anonymous union. ] 5220 for (auto *Mem : Record->decls()) { 5221 // Ignore invalid declarations; we already diagnosed them. 5222 if (Mem->isInvalidDecl()) 5223 continue; 5224 5225 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5226 // C++ [class.union]p3: 5227 // An anonymous union shall not have private or protected 5228 // members (clause 11). 5229 assert(FD->getAccess() != AS_none); 5230 if (FD->getAccess() != AS_public) { 5231 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5232 << Record->isUnion() << (FD->getAccess() == AS_protected); 5233 Invalid = true; 5234 } 5235 5236 // C++ [class.union]p1 5237 // An object of a class with a non-trivial constructor, a non-trivial 5238 // copy constructor, a non-trivial destructor, or a non-trivial copy 5239 // assignment operator cannot be a member of a union, nor can an 5240 // array of such objects. 5241 if (CheckNontrivialField(FD)) 5242 Invalid = true; 5243 } else if (Mem->isImplicit()) { 5244 // Any implicit members are fine. 5245 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5246 // This is a type that showed up in an 5247 // elaborated-type-specifier inside the anonymous struct or 5248 // union, but which actually declares a type outside of the 5249 // anonymous struct or union. It's okay. 5250 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5251 if (!MemRecord->isAnonymousStructOrUnion() && 5252 MemRecord->getDeclName()) { 5253 // Visual C++ allows type definition in anonymous struct or union. 5254 if (getLangOpts().MicrosoftExt) 5255 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5256 << Record->isUnion(); 5257 else { 5258 // This is a nested type declaration. 5259 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5260 << Record->isUnion(); 5261 Invalid = true; 5262 } 5263 } else { 5264 // This is an anonymous type definition within another anonymous type. 5265 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5266 // not part of standard C++. 5267 Diag(MemRecord->getLocation(), 5268 diag::ext_anonymous_record_with_anonymous_type) 5269 << Record->isUnion(); 5270 } 5271 } else if (isa<AccessSpecDecl>(Mem)) { 5272 // Any access specifier is fine. 5273 } else if (isa<StaticAssertDecl>(Mem)) { 5274 // In C++1z, static_assert declarations are also fine. 5275 } else { 5276 // We have something that isn't a non-static data 5277 // member. Complain about it. 5278 unsigned DK = diag::err_anonymous_record_bad_member; 5279 if (isa<TypeDecl>(Mem)) 5280 DK = diag::err_anonymous_record_with_type; 5281 else if (isa<FunctionDecl>(Mem)) 5282 DK = diag::err_anonymous_record_with_function; 5283 else if (isa<VarDecl>(Mem)) 5284 DK = diag::err_anonymous_record_with_static; 5285 5286 // Visual C++ allows type definition in anonymous struct or union. 5287 if (getLangOpts().MicrosoftExt && 5288 DK == diag::err_anonymous_record_with_type) 5289 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5290 << Record->isUnion(); 5291 else { 5292 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5293 Invalid = true; 5294 } 5295 } 5296 } 5297 5298 // C++11 [class.union]p8 (DR1460): 5299 // At most one variant member of a union may have a 5300 // brace-or-equal-initializer. 5301 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5302 Owner->isRecord()) 5303 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5304 cast<CXXRecordDecl>(Record)); 5305 } 5306 5307 if (!Record->isUnion() && !Owner->isRecord()) { 5308 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5309 << getLangOpts().CPlusPlus; 5310 Invalid = true; 5311 } 5312 5313 // C++ [dcl.dcl]p3: 5314 // [If there are no declarators], and except for the declaration of an 5315 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5316 // names into the program 5317 // C++ [class.mem]p2: 5318 // each such member-declaration shall either declare at least one member 5319 // name of the class or declare at least one unnamed bit-field 5320 // 5321 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5322 if (getLangOpts().CPlusPlus && Record->field_empty()) 5323 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5324 5325 // Mock up a declarator. 5326 Declarator Dc(DS, DeclaratorContext::Member); 5327 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5328 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5329 5330 // Create a declaration for this anonymous struct/union. 5331 NamedDecl *Anon = nullptr; 5332 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5333 Anon = FieldDecl::Create( 5334 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5335 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5336 /*BitWidth=*/nullptr, /*Mutable=*/false, 5337 /*InitStyle=*/ICIS_NoInit); 5338 Anon->setAccess(AS); 5339 ProcessDeclAttributes(S, Anon, Dc); 5340 5341 if (getLangOpts().CPlusPlus) 5342 FieldCollector->Add(cast<FieldDecl>(Anon)); 5343 } else { 5344 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5345 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5346 if (SCSpec == DeclSpec::SCS_mutable) { 5347 // mutable can only appear on non-static class members, so it's always 5348 // an error here 5349 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5350 Invalid = true; 5351 SC = SC_None; 5352 } 5353 5354 assert(DS.getAttributes().empty() && "No attribute expected"); 5355 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5356 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5357 Context.getTypeDeclType(Record), TInfo, SC); 5358 5359 // Default-initialize the implicit variable. This initialization will be 5360 // trivial in almost all cases, except if a union member has an in-class 5361 // initializer: 5362 // union { int n = 0; }; 5363 ActOnUninitializedDecl(Anon); 5364 } 5365 Anon->setImplicit(); 5366 5367 // Mark this as an anonymous struct/union type. 5368 Record->setAnonymousStructOrUnion(true); 5369 5370 // Add the anonymous struct/union object to the current 5371 // context. We'll be referencing this object when we refer to one of 5372 // its members. 5373 Owner->addDecl(Anon); 5374 5375 // Inject the members of the anonymous struct/union into the owning 5376 // context and into the identifier resolver chain for name lookup 5377 // purposes. 5378 SmallVector<NamedDecl*, 2> Chain; 5379 Chain.push_back(Anon); 5380 5381 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5382 Invalid = true; 5383 5384 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5385 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5386 MangleNumberingContext *MCtx; 5387 Decl *ManglingContextDecl; 5388 std::tie(MCtx, ManglingContextDecl) = 5389 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5390 if (MCtx) { 5391 Context.setManglingNumber( 5392 NewVD, MCtx->getManglingNumber( 5393 NewVD, getMSManglingNumber(getLangOpts(), S))); 5394 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5395 } 5396 } 5397 } 5398 5399 if (Invalid) 5400 Anon->setInvalidDecl(); 5401 5402 return Anon; 5403 } 5404 5405 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5406 /// Microsoft C anonymous structure. 5407 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5408 /// Example: 5409 /// 5410 /// struct A { int a; }; 5411 /// struct B { struct A; int b; }; 5412 /// 5413 /// void foo() { 5414 /// B var; 5415 /// var.a = 3; 5416 /// } 5417 /// 5418 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5419 RecordDecl *Record) { 5420 assert(Record && "expected a record!"); 5421 5422 // Mock up a declarator. 5423 Declarator Dc(DS, DeclaratorContext::TypeName); 5424 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5425 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5426 5427 auto *ParentDecl = cast<RecordDecl>(CurContext); 5428 QualType RecTy = Context.getTypeDeclType(Record); 5429 5430 // Create a declaration for this anonymous struct. 5431 NamedDecl *Anon = 5432 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5433 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5434 /*BitWidth=*/nullptr, /*Mutable=*/false, 5435 /*InitStyle=*/ICIS_NoInit); 5436 Anon->setImplicit(); 5437 5438 // Add the anonymous struct object to the current context. 5439 CurContext->addDecl(Anon); 5440 5441 // Inject the members of the anonymous struct into the current 5442 // context and into the identifier resolver chain for name lookup 5443 // purposes. 5444 SmallVector<NamedDecl*, 2> Chain; 5445 Chain.push_back(Anon); 5446 5447 RecordDecl *RecordDef = Record->getDefinition(); 5448 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5449 diag::err_field_incomplete_or_sizeless) || 5450 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5451 AS_none, Chain)) { 5452 Anon->setInvalidDecl(); 5453 ParentDecl->setInvalidDecl(); 5454 } 5455 5456 return Anon; 5457 } 5458 5459 /// GetNameForDeclarator - Determine the full declaration name for the 5460 /// given Declarator. 5461 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5462 return GetNameFromUnqualifiedId(D.getName()); 5463 } 5464 5465 /// Retrieves the declaration name from a parsed unqualified-id. 5466 DeclarationNameInfo 5467 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5468 DeclarationNameInfo NameInfo; 5469 NameInfo.setLoc(Name.StartLocation); 5470 5471 switch (Name.getKind()) { 5472 5473 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5474 case UnqualifiedIdKind::IK_Identifier: 5475 NameInfo.setName(Name.Identifier); 5476 return NameInfo; 5477 5478 case UnqualifiedIdKind::IK_DeductionGuideName: { 5479 // C++ [temp.deduct.guide]p3: 5480 // The simple-template-id shall name a class template specialization. 5481 // The template-name shall be the same identifier as the template-name 5482 // of the simple-template-id. 5483 // These together intend to imply that the template-name shall name a 5484 // class template. 5485 // FIXME: template<typename T> struct X {}; 5486 // template<typename T> using Y = X<T>; 5487 // Y(int) -> Y<int>; 5488 // satisfies these rules but does not name a class template. 5489 TemplateName TN = Name.TemplateName.get().get(); 5490 auto *Template = TN.getAsTemplateDecl(); 5491 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5492 Diag(Name.StartLocation, 5493 diag::err_deduction_guide_name_not_class_template) 5494 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5495 if (Template) 5496 Diag(Template->getLocation(), diag::note_template_decl_here); 5497 return DeclarationNameInfo(); 5498 } 5499 5500 NameInfo.setName( 5501 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5502 return NameInfo; 5503 } 5504 5505 case UnqualifiedIdKind::IK_OperatorFunctionId: 5506 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5507 Name.OperatorFunctionId.Operator)); 5508 NameInfo.setCXXOperatorNameRange(SourceRange( 5509 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5510 return NameInfo; 5511 5512 case UnqualifiedIdKind::IK_LiteralOperatorId: 5513 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5514 Name.Identifier)); 5515 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5516 return NameInfo; 5517 5518 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5519 TypeSourceInfo *TInfo; 5520 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5521 if (Ty.isNull()) 5522 return DeclarationNameInfo(); 5523 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5524 Context.getCanonicalType(Ty))); 5525 NameInfo.setNamedTypeInfo(TInfo); 5526 return NameInfo; 5527 } 5528 5529 case UnqualifiedIdKind::IK_ConstructorName: { 5530 TypeSourceInfo *TInfo; 5531 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5532 if (Ty.isNull()) 5533 return DeclarationNameInfo(); 5534 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5535 Context.getCanonicalType(Ty))); 5536 NameInfo.setNamedTypeInfo(TInfo); 5537 return NameInfo; 5538 } 5539 5540 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5541 // In well-formed code, we can only have a constructor 5542 // template-id that refers to the current context, so go there 5543 // to find the actual type being constructed. 5544 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5545 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5546 return DeclarationNameInfo(); 5547 5548 // Determine the type of the class being constructed. 5549 QualType CurClassType = Context.getTypeDeclType(CurClass); 5550 5551 // FIXME: Check two things: that the template-id names the same type as 5552 // CurClassType, and that the template-id does not occur when the name 5553 // was qualified. 5554 5555 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5556 Context.getCanonicalType(CurClassType))); 5557 // FIXME: should we retrieve TypeSourceInfo? 5558 NameInfo.setNamedTypeInfo(nullptr); 5559 return NameInfo; 5560 } 5561 5562 case UnqualifiedIdKind::IK_DestructorName: { 5563 TypeSourceInfo *TInfo; 5564 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5565 if (Ty.isNull()) 5566 return DeclarationNameInfo(); 5567 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5568 Context.getCanonicalType(Ty))); 5569 NameInfo.setNamedTypeInfo(TInfo); 5570 return NameInfo; 5571 } 5572 5573 case UnqualifiedIdKind::IK_TemplateId: { 5574 TemplateName TName = Name.TemplateId->Template.get(); 5575 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5576 return Context.getNameForTemplate(TName, TNameLoc); 5577 } 5578 5579 } // switch (Name.getKind()) 5580 5581 llvm_unreachable("Unknown name kind"); 5582 } 5583 5584 static QualType getCoreType(QualType Ty) { 5585 do { 5586 if (Ty->isPointerType() || Ty->isReferenceType()) 5587 Ty = Ty->getPointeeType(); 5588 else if (Ty->isArrayType()) 5589 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5590 else 5591 return Ty.withoutLocalFastQualifiers(); 5592 } while (true); 5593 } 5594 5595 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5596 /// and Definition have "nearly" matching parameters. This heuristic is 5597 /// used to improve diagnostics in the case where an out-of-line function 5598 /// definition doesn't match any declaration within the class or namespace. 5599 /// Also sets Params to the list of indices to the parameters that differ 5600 /// between the declaration and the definition. If hasSimilarParameters 5601 /// returns true and Params is empty, then all of the parameters match. 5602 static bool hasSimilarParameters(ASTContext &Context, 5603 FunctionDecl *Declaration, 5604 FunctionDecl *Definition, 5605 SmallVectorImpl<unsigned> &Params) { 5606 Params.clear(); 5607 if (Declaration->param_size() != Definition->param_size()) 5608 return false; 5609 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5610 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5611 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5612 5613 // The parameter types are identical 5614 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5615 continue; 5616 5617 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5618 QualType DefParamBaseTy = getCoreType(DefParamTy); 5619 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5620 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5621 5622 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5623 (DeclTyName && DeclTyName == DefTyName)) 5624 Params.push_back(Idx); 5625 else // The two parameters aren't even close 5626 return false; 5627 } 5628 5629 return true; 5630 } 5631 5632 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5633 /// declarator needs to be rebuilt in the current instantiation. 5634 /// Any bits of declarator which appear before the name are valid for 5635 /// consideration here. That's specifically the type in the decl spec 5636 /// and the base type in any member-pointer chunks. 5637 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5638 DeclarationName Name) { 5639 // The types we specifically need to rebuild are: 5640 // - typenames, typeofs, and decltypes 5641 // - types which will become injected class names 5642 // Of course, we also need to rebuild any type referencing such a 5643 // type. It's safest to just say "dependent", but we call out a 5644 // few cases here. 5645 5646 DeclSpec &DS = D.getMutableDeclSpec(); 5647 switch (DS.getTypeSpecType()) { 5648 case DeclSpec::TST_typename: 5649 case DeclSpec::TST_typeofType: 5650 case DeclSpec::TST_underlyingType: 5651 case DeclSpec::TST_atomic: { 5652 // Grab the type from the parser. 5653 TypeSourceInfo *TSI = nullptr; 5654 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5655 if (T.isNull() || !T->isInstantiationDependentType()) break; 5656 5657 // Make sure there's a type source info. This isn't really much 5658 // of a waste; most dependent types should have type source info 5659 // attached already. 5660 if (!TSI) 5661 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5662 5663 // Rebuild the type in the current instantiation. 5664 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5665 if (!TSI) return true; 5666 5667 // Store the new type back in the decl spec. 5668 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5669 DS.UpdateTypeRep(LocType); 5670 break; 5671 } 5672 5673 case DeclSpec::TST_decltype: 5674 case DeclSpec::TST_typeofExpr: { 5675 Expr *E = DS.getRepAsExpr(); 5676 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5677 if (Result.isInvalid()) return true; 5678 DS.UpdateExprRep(Result.get()); 5679 break; 5680 } 5681 5682 default: 5683 // Nothing to do for these decl specs. 5684 break; 5685 } 5686 5687 // It doesn't matter what order we do this in. 5688 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5689 DeclaratorChunk &Chunk = D.getTypeObject(I); 5690 5691 // The only type information in the declarator which can come 5692 // before the declaration name is the base type of a member 5693 // pointer. 5694 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5695 continue; 5696 5697 // Rebuild the scope specifier in-place. 5698 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5699 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5700 return true; 5701 } 5702 5703 return false; 5704 } 5705 5706 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5707 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5708 // of system decl. 5709 if (D->getPreviousDecl() || D->isImplicit()) 5710 return; 5711 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5712 if (Status != ReservedIdentifierStatus::NotReserved && 5713 !Context.getSourceManager().isInSystemHeader(D->getLocation())) 5714 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5715 << D << static_cast<int>(Status); 5716 } 5717 5718 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5719 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5720 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5721 5722 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5723 Dcl && Dcl->getDeclContext()->isFileContext()) 5724 Dcl->setTopLevelDeclInObjCContainer(); 5725 5726 return Dcl; 5727 } 5728 5729 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5730 /// If T is the name of a class, then each of the following shall have a 5731 /// name different from T: 5732 /// - every static data member of class T; 5733 /// - every member function of class T 5734 /// - every member of class T that is itself a type; 5735 /// \returns true if the declaration name violates these rules. 5736 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5737 DeclarationNameInfo NameInfo) { 5738 DeclarationName Name = NameInfo.getName(); 5739 5740 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5741 while (Record && Record->isAnonymousStructOrUnion()) 5742 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5743 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5744 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5745 return true; 5746 } 5747 5748 return false; 5749 } 5750 5751 /// Diagnose a declaration whose declarator-id has the given 5752 /// nested-name-specifier. 5753 /// 5754 /// \param SS The nested-name-specifier of the declarator-id. 5755 /// 5756 /// \param DC The declaration context to which the nested-name-specifier 5757 /// resolves. 5758 /// 5759 /// \param Name The name of the entity being declared. 5760 /// 5761 /// \param Loc The location of the name of the entity being declared. 5762 /// 5763 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5764 /// we're declaring an explicit / partial specialization / instantiation. 5765 /// 5766 /// \returns true if we cannot safely recover from this error, false otherwise. 5767 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5768 DeclarationName Name, 5769 SourceLocation Loc, bool IsTemplateId) { 5770 DeclContext *Cur = CurContext; 5771 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5772 Cur = Cur->getParent(); 5773 5774 // If the user provided a superfluous scope specifier that refers back to the 5775 // class in which the entity is already declared, diagnose and ignore it. 5776 // 5777 // class X { 5778 // void X::f(); 5779 // }; 5780 // 5781 // Note, it was once ill-formed to give redundant qualification in all 5782 // contexts, but that rule was removed by DR482. 5783 if (Cur->Equals(DC)) { 5784 if (Cur->isRecord()) { 5785 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5786 : diag::err_member_extra_qualification) 5787 << Name << FixItHint::CreateRemoval(SS.getRange()); 5788 SS.clear(); 5789 } else { 5790 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5791 } 5792 return false; 5793 } 5794 5795 // Check whether the qualifying scope encloses the scope of the original 5796 // declaration. For a template-id, we perform the checks in 5797 // CheckTemplateSpecializationScope. 5798 if (!Cur->Encloses(DC) && !IsTemplateId) { 5799 if (Cur->isRecord()) 5800 Diag(Loc, diag::err_member_qualification) 5801 << Name << SS.getRange(); 5802 else if (isa<TranslationUnitDecl>(DC)) 5803 Diag(Loc, diag::err_invalid_declarator_global_scope) 5804 << Name << SS.getRange(); 5805 else if (isa<FunctionDecl>(Cur)) 5806 Diag(Loc, diag::err_invalid_declarator_in_function) 5807 << Name << SS.getRange(); 5808 else if (isa<BlockDecl>(Cur)) 5809 Diag(Loc, diag::err_invalid_declarator_in_block) 5810 << Name << SS.getRange(); 5811 else if (isa<ExportDecl>(Cur)) { 5812 if (!isa<NamespaceDecl>(DC)) 5813 Diag(Loc, diag::err_export_non_namespace_scope_name) 5814 << Name << SS.getRange(); 5815 else 5816 // The cases that DC is not NamespaceDecl should be handled in 5817 // CheckRedeclarationExported. 5818 return false; 5819 } else 5820 Diag(Loc, diag::err_invalid_declarator_scope) 5821 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5822 5823 return true; 5824 } 5825 5826 if (Cur->isRecord()) { 5827 // Cannot qualify members within a class. 5828 Diag(Loc, diag::err_member_qualification) 5829 << Name << SS.getRange(); 5830 SS.clear(); 5831 5832 // C++ constructors and destructors with incorrect scopes can break 5833 // our AST invariants by having the wrong underlying types. If 5834 // that's the case, then drop this declaration entirely. 5835 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5836 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5837 !Context.hasSameType(Name.getCXXNameType(), 5838 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5839 return true; 5840 5841 return false; 5842 } 5843 5844 // C++11 [dcl.meaning]p1: 5845 // [...] "The nested-name-specifier of the qualified declarator-id shall 5846 // not begin with a decltype-specifer" 5847 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5848 while (SpecLoc.getPrefix()) 5849 SpecLoc = SpecLoc.getPrefix(); 5850 if (isa_and_nonnull<DecltypeType>( 5851 SpecLoc.getNestedNameSpecifier()->getAsType())) 5852 Diag(Loc, diag::err_decltype_in_declarator) 5853 << SpecLoc.getTypeLoc().getSourceRange(); 5854 5855 return false; 5856 } 5857 5858 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5859 MultiTemplateParamsArg TemplateParamLists) { 5860 // TODO: consider using NameInfo for diagnostic. 5861 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5862 DeclarationName Name = NameInfo.getName(); 5863 5864 // All of these full declarators require an identifier. If it doesn't have 5865 // one, the ParsedFreeStandingDeclSpec action should be used. 5866 if (D.isDecompositionDeclarator()) { 5867 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5868 } else if (!Name) { 5869 if (!D.isInvalidType()) // Reject this if we think it is valid. 5870 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5871 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5872 return nullptr; 5873 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5874 return nullptr; 5875 5876 // The scope passed in may not be a decl scope. Zip up the scope tree until 5877 // we find one that is. 5878 while ((S->getFlags() & Scope::DeclScope) == 0 || 5879 (S->getFlags() & Scope::TemplateParamScope) != 0) 5880 S = S->getParent(); 5881 5882 DeclContext *DC = CurContext; 5883 if (D.getCXXScopeSpec().isInvalid()) 5884 D.setInvalidType(); 5885 else if (D.getCXXScopeSpec().isSet()) { 5886 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5887 UPPC_DeclarationQualifier)) 5888 return nullptr; 5889 5890 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5891 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5892 if (!DC || isa<EnumDecl>(DC)) { 5893 // If we could not compute the declaration context, it's because the 5894 // declaration context is dependent but does not refer to a class, 5895 // class template, or class template partial specialization. Complain 5896 // and return early, to avoid the coming semantic disaster. 5897 Diag(D.getIdentifierLoc(), 5898 diag::err_template_qualified_declarator_no_match) 5899 << D.getCXXScopeSpec().getScopeRep() 5900 << D.getCXXScopeSpec().getRange(); 5901 return nullptr; 5902 } 5903 bool IsDependentContext = DC->isDependentContext(); 5904 5905 if (!IsDependentContext && 5906 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5907 return nullptr; 5908 5909 // If a class is incomplete, do not parse entities inside it. 5910 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5911 Diag(D.getIdentifierLoc(), 5912 diag::err_member_def_undefined_record) 5913 << Name << DC << D.getCXXScopeSpec().getRange(); 5914 return nullptr; 5915 } 5916 if (!D.getDeclSpec().isFriendSpecified()) { 5917 if (diagnoseQualifiedDeclaration( 5918 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5919 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5920 if (DC->isRecord()) 5921 return nullptr; 5922 5923 D.setInvalidType(); 5924 } 5925 } 5926 5927 // Check whether we need to rebuild the type of the given 5928 // declaration in the current instantiation. 5929 if (EnteringContext && IsDependentContext && 5930 TemplateParamLists.size() != 0) { 5931 ContextRAII SavedContext(*this, DC); 5932 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5933 D.setInvalidType(); 5934 } 5935 } 5936 5937 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5938 QualType R = TInfo->getType(); 5939 5940 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5941 UPPC_DeclarationType)) 5942 D.setInvalidType(); 5943 5944 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5945 forRedeclarationInCurContext()); 5946 5947 // See if this is a redefinition of a variable in the same scope. 5948 if (!D.getCXXScopeSpec().isSet()) { 5949 bool IsLinkageLookup = false; 5950 bool CreateBuiltins = false; 5951 5952 // If the declaration we're planning to build will be a function 5953 // or object with linkage, then look for another declaration with 5954 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5955 // 5956 // If the declaration we're planning to build will be declared with 5957 // external linkage in the translation unit, create any builtin with 5958 // the same name. 5959 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5960 /* Do nothing*/; 5961 else if (CurContext->isFunctionOrMethod() && 5962 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5963 R->isFunctionType())) { 5964 IsLinkageLookup = true; 5965 CreateBuiltins = 5966 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5967 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5968 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5969 CreateBuiltins = true; 5970 5971 if (IsLinkageLookup) { 5972 Previous.clear(LookupRedeclarationWithLinkage); 5973 Previous.setRedeclarationKind(ForExternalRedeclaration); 5974 } 5975 5976 LookupName(Previous, S, CreateBuiltins); 5977 } else { // Something like "int foo::x;" 5978 LookupQualifiedName(Previous, DC); 5979 5980 // C++ [dcl.meaning]p1: 5981 // When the declarator-id is qualified, the declaration shall refer to a 5982 // previously declared member of the class or namespace to which the 5983 // qualifier refers (or, in the case of a namespace, of an element of the 5984 // inline namespace set of that namespace (7.3.1)) or to a specialization 5985 // thereof; [...] 5986 // 5987 // Note that we already checked the context above, and that we do not have 5988 // enough information to make sure that Previous contains the declaration 5989 // we want to match. For example, given: 5990 // 5991 // class X { 5992 // void f(); 5993 // void f(float); 5994 // }; 5995 // 5996 // void X::f(int) { } // ill-formed 5997 // 5998 // In this case, Previous will point to the overload set 5999 // containing the two f's declared in X, but neither of them 6000 // matches. 6001 6002 // C++ [dcl.meaning]p1: 6003 // [...] the member shall not merely have been introduced by a 6004 // using-declaration in the scope of the class or namespace nominated by 6005 // the nested-name-specifier of the declarator-id. 6006 RemoveUsingDecls(Previous); 6007 } 6008 6009 if (Previous.isSingleResult() && 6010 Previous.getFoundDecl()->isTemplateParameter()) { 6011 // Maybe we will complain about the shadowed template parameter. 6012 if (!D.isInvalidType()) 6013 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 6014 Previous.getFoundDecl()); 6015 6016 // Just pretend that we didn't see the previous declaration. 6017 Previous.clear(); 6018 } 6019 6020 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6021 // Forget that the previous declaration is the injected-class-name. 6022 Previous.clear(); 6023 6024 // In C++, the previous declaration we find might be a tag type 6025 // (class or enum). In this case, the new declaration will hide the 6026 // tag type. Note that this applies to functions, function templates, and 6027 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6028 if (Previous.isSingleTagDecl() && 6029 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6030 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6031 Previous.clear(); 6032 6033 // Check that there are no default arguments other than in the parameters 6034 // of a function declaration (C++ only). 6035 if (getLangOpts().CPlusPlus) 6036 CheckExtraCXXDefaultArguments(D); 6037 6038 NamedDecl *New; 6039 6040 bool AddToScope = true; 6041 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6042 if (TemplateParamLists.size()) { 6043 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6044 return nullptr; 6045 } 6046 6047 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6048 } else if (R->isFunctionType()) { 6049 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6050 TemplateParamLists, 6051 AddToScope); 6052 } else { 6053 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6054 AddToScope); 6055 } 6056 6057 if (!New) 6058 return nullptr; 6059 6060 // If this has an identifier and is not a function template specialization, 6061 // add it to the scope stack. 6062 if (New->getDeclName() && AddToScope) 6063 PushOnScopeChains(New, S); 6064 6065 if (isInOpenMPDeclareTargetContext()) 6066 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6067 6068 return New; 6069 } 6070 6071 /// Helper method to turn variable array types into constant array 6072 /// types in certain situations which would otherwise be errors (for 6073 /// GCC compatibility). 6074 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6075 ASTContext &Context, 6076 bool &SizeIsNegative, 6077 llvm::APSInt &Oversized) { 6078 // This method tries to turn a variable array into a constant 6079 // array even when the size isn't an ICE. This is necessary 6080 // for compatibility with code that depends on gcc's buggy 6081 // constant expression folding, like struct {char x[(int)(char*)2];} 6082 SizeIsNegative = false; 6083 Oversized = 0; 6084 6085 if (T->isDependentType()) 6086 return QualType(); 6087 6088 QualifierCollector Qs; 6089 const Type *Ty = Qs.strip(T); 6090 6091 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6092 QualType Pointee = PTy->getPointeeType(); 6093 QualType FixedType = 6094 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6095 Oversized); 6096 if (FixedType.isNull()) return FixedType; 6097 FixedType = Context.getPointerType(FixedType); 6098 return Qs.apply(Context, FixedType); 6099 } 6100 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6101 QualType Inner = PTy->getInnerType(); 6102 QualType FixedType = 6103 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6104 Oversized); 6105 if (FixedType.isNull()) return FixedType; 6106 FixedType = Context.getParenType(FixedType); 6107 return Qs.apply(Context, FixedType); 6108 } 6109 6110 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6111 if (!VLATy) 6112 return QualType(); 6113 6114 QualType ElemTy = VLATy->getElementType(); 6115 if (ElemTy->isVariablyModifiedType()) { 6116 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6117 SizeIsNegative, Oversized); 6118 if (ElemTy.isNull()) 6119 return QualType(); 6120 } 6121 6122 Expr::EvalResult Result; 6123 if (!VLATy->getSizeExpr() || 6124 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6125 return QualType(); 6126 6127 llvm::APSInt Res = Result.Val.getInt(); 6128 6129 // Check whether the array size is negative. 6130 if (Res.isSigned() && Res.isNegative()) { 6131 SizeIsNegative = true; 6132 return QualType(); 6133 } 6134 6135 // Check whether the array is too large to be addressed. 6136 unsigned ActiveSizeBits = 6137 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6138 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6139 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6140 : Res.getActiveBits(); 6141 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6142 Oversized = Res; 6143 return QualType(); 6144 } 6145 6146 QualType FoldedArrayType = Context.getConstantArrayType( 6147 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6148 return Qs.apply(Context, FoldedArrayType); 6149 } 6150 6151 static void 6152 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6153 SrcTL = SrcTL.getUnqualifiedLoc(); 6154 DstTL = DstTL.getUnqualifiedLoc(); 6155 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6156 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6157 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6158 DstPTL.getPointeeLoc()); 6159 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6160 return; 6161 } 6162 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6163 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6164 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6165 DstPTL.getInnerLoc()); 6166 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6167 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6168 return; 6169 } 6170 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6171 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6172 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6173 TypeLoc DstElemTL = DstATL.getElementLoc(); 6174 if (VariableArrayTypeLoc SrcElemATL = 6175 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6176 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6177 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6178 } else { 6179 DstElemTL.initializeFullCopy(SrcElemTL); 6180 } 6181 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6182 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6183 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6184 } 6185 6186 /// Helper method to turn variable array types into constant array 6187 /// types in certain situations which would otherwise be errors (for 6188 /// GCC compatibility). 6189 static TypeSourceInfo* 6190 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6191 ASTContext &Context, 6192 bool &SizeIsNegative, 6193 llvm::APSInt &Oversized) { 6194 QualType FixedTy 6195 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6196 SizeIsNegative, Oversized); 6197 if (FixedTy.isNull()) 6198 return nullptr; 6199 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6200 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6201 FixedTInfo->getTypeLoc()); 6202 return FixedTInfo; 6203 } 6204 6205 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6206 /// true if we were successful. 6207 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6208 QualType &T, SourceLocation Loc, 6209 unsigned FailedFoldDiagID) { 6210 bool SizeIsNegative; 6211 llvm::APSInt Oversized; 6212 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6213 TInfo, Context, SizeIsNegative, Oversized); 6214 if (FixedTInfo) { 6215 Diag(Loc, diag::ext_vla_folded_to_constant); 6216 TInfo = FixedTInfo; 6217 T = FixedTInfo->getType(); 6218 return true; 6219 } 6220 6221 if (SizeIsNegative) 6222 Diag(Loc, diag::err_typecheck_negative_array_size); 6223 else if (Oversized.getBoolValue()) 6224 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6225 else if (FailedFoldDiagID) 6226 Diag(Loc, FailedFoldDiagID); 6227 return false; 6228 } 6229 6230 /// Register the given locally-scoped extern "C" declaration so 6231 /// that it can be found later for redeclarations. We include any extern "C" 6232 /// declaration that is not visible in the translation unit here, not just 6233 /// function-scope declarations. 6234 void 6235 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6236 if (!getLangOpts().CPlusPlus && 6237 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6238 // Don't need to track declarations in the TU in C. 6239 return; 6240 6241 // Note that we have a locally-scoped external with this name. 6242 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6243 } 6244 6245 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6246 // FIXME: We can have multiple results via __attribute__((overloadable)). 6247 auto Result = Context.getExternCContextDecl()->lookup(Name); 6248 return Result.empty() ? nullptr : *Result.begin(); 6249 } 6250 6251 /// Diagnose function specifiers on a declaration of an identifier that 6252 /// does not identify a function. 6253 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6254 // FIXME: We should probably indicate the identifier in question to avoid 6255 // confusion for constructs like "virtual int a(), b;" 6256 if (DS.isVirtualSpecified()) 6257 Diag(DS.getVirtualSpecLoc(), 6258 diag::err_virtual_non_function); 6259 6260 if (DS.hasExplicitSpecifier()) 6261 Diag(DS.getExplicitSpecLoc(), 6262 diag::err_explicit_non_function); 6263 6264 if (DS.isNoreturnSpecified()) 6265 Diag(DS.getNoreturnSpecLoc(), 6266 diag::err_noreturn_non_function); 6267 } 6268 6269 NamedDecl* 6270 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6271 TypeSourceInfo *TInfo, LookupResult &Previous) { 6272 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6273 if (D.getCXXScopeSpec().isSet()) { 6274 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6275 << D.getCXXScopeSpec().getRange(); 6276 D.setInvalidType(); 6277 // Pretend we didn't see the scope specifier. 6278 DC = CurContext; 6279 Previous.clear(); 6280 } 6281 6282 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6283 6284 if (D.getDeclSpec().isInlineSpecified()) 6285 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6286 << getLangOpts().CPlusPlus17; 6287 if (D.getDeclSpec().hasConstexprSpecifier()) 6288 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6289 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6290 6291 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6292 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6293 Diag(D.getName().StartLocation, 6294 diag::err_deduction_guide_invalid_specifier) 6295 << "typedef"; 6296 else 6297 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6298 << D.getName().getSourceRange(); 6299 return nullptr; 6300 } 6301 6302 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6303 if (!NewTD) return nullptr; 6304 6305 // Handle attributes prior to checking for duplicates in MergeVarDecl 6306 ProcessDeclAttributes(S, NewTD, D); 6307 6308 CheckTypedefForVariablyModifiedType(S, NewTD); 6309 6310 bool Redeclaration = D.isRedeclaration(); 6311 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6312 D.setRedeclaration(Redeclaration); 6313 return ND; 6314 } 6315 6316 void 6317 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6318 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6319 // then it shall have block scope. 6320 // Note that variably modified types must be fixed before merging the decl so 6321 // that redeclarations will match. 6322 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6323 QualType T = TInfo->getType(); 6324 if (T->isVariablyModifiedType()) { 6325 setFunctionHasBranchProtectedScope(); 6326 6327 if (S->getFnParent() == nullptr) { 6328 bool SizeIsNegative; 6329 llvm::APSInt Oversized; 6330 TypeSourceInfo *FixedTInfo = 6331 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6332 SizeIsNegative, 6333 Oversized); 6334 if (FixedTInfo) { 6335 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6336 NewTD->setTypeSourceInfo(FixedTInfo); 6337 } else { 6338 if (SizeIsNegative) 6339 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6340 else if (T->isVariableArrayType()) 6341 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6342 else if (Oversized.getBoolValue()) 6343 Diag(NewTD->getLocation(), diag::err_array_too_large) 6344 << toString(Oversized, 10); 6345 else 6346 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6347 NewTD->setInvalidDecl(); 6348 } 6349 } 6350 } 6351 } 6352 6353 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6354 /// declares a typedef-name, either using the 'typedef' type specifier or via 6355 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6356 NamedDecl* 6357 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6358 LookupResult &Previous, bool &Redeclaration) { 6359 6360 // Find the shadowed declaration before filtering for scope. 6361 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6362 6363 // Merge the decl with the existing one if appropriate. If the decl is 6364 // in an outer scope, it isn't the same thing. 6365 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6366 /*AllowInlineNamespace*/false); 6367 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6368 if (!Previous.empty()) { 6369 Redeclaration = true; 6370 MergeTypedefNameDecl(S, NewTD, Previous); 6371 } else { 6372 inferGslPointerAttribute(NewTD); 6373 } 6374 6375 if (ShadowedDecl && !Redeclaration) 6376 CheckShadow(NewTD, ShadowedDecl, Previous); 6377 6378 // If this is the C FILE type, notify the AST context. 6379 if (IdentifierInfo *II = NewTD->getIdentifier()) 6380 if (!NewTD->isInvalidDecl() && 6381 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6382 if (II->isStr("FILE")) 6383 Context.setFILEDecl(NewTD); 6384 else if (II->isStr("jmp_buf")) 6385 Context.setjmp_bufDecl(NewTD); 6386 else if (II->isStr("sigjmp_buf")) 6387 Context.setsigjmp_bufDecl(NewTD); 6388 else if (II->isStr("ucontext_t")) 6389 Context.setucontext_tDecl(NewTD); 6390 } 6391 6392 return NewTD; 6393 } 6394 6395 /// Determines whether the given declaration is an out-of-scope 6396 /// previous declaration. 6397 /// 6398 /// This routine should be invoked when name lookup has found a 6399 /// previous declaration (PrevDecl) that is not in the scope where a 6400 /// new declaration by the same name is being introduced. If the new 6401 /// declaration occurs in a local scope, previous declarations with 6402 /// linkage may still be considered previous declarations (C99 6403 /// 6.2.2p4-5, C++ [basic.link]p6). 6404 /// 6405 /// \param PrevDecl the previous declaration found by name 6406 /// lookup 6407 /// 6408 /// \param DC the context in which the new declaration is being 6409 /// declared. 6410 /// 6411 /// \returns true if PrevDecl is an out-of-scope previous declaration 6412 /// for a new delcaration with the same name. 6413 static bool 6414 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6415 ASTContext &Context) { 6416 if (!PrevDecl) 6417 return false; 6418 6419 if (!PrevDecl->hasLinkage()) 6420 return false; 6421 6422 if (Context.getLangOpts().CPlusPlus) { 6423 // C++ [basic.link]p6: 6424 // If there is a visible declaration of an entity with linkage 6425 // having the same name and type, ignoring entities declared 6426 // outside the innermost enclosing namespace scope, the block 6427 // scope declaration declares that same entity and receives the 6428 // linkage of the previous declaration. 6429 DeclContext *OuterContext = DC->getRedeclContext(); 6430 if (!OuterContext->isFunctionOrMethod()) 6431 // This rule only applies to block-scope declarations. 6432 return false; 6433 6434 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6435 if (PrevOuterContext->isRecord()) 6436 // We found a member function: ignore it. 6437 return false; 6438 6439 // Find the innermost enclosing namespace for the new and 6440 // previous declarations. 6441 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6442 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6443 6444 // The previous declaration is in a different namespace, so it 6445 // isn't the same function. 6446 if (!OuterContext->Equals(PrevOuterContext)) 6447 return false; 6448 } 6449 6450 return true; 6451 } 6452 6453 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6454 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6455 if (!SS.isSet()) return; 6456 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6457 } 6458 6459 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6460 QualType type = decl->getType(); 6461 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6462 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6463 // Various kinds of declaration aren't allowed to be __autoreleasing. 6464 unsigned kind = -1U; 6465 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6466 if (var->hasAttr<BlocksAttr>()) 6467 kind = 0; // __block 6468 else if (!var->hasLocalStorage()) 6469 kind = 1; // global 6470 } else if (isa<ObjCIvarDecl>(decl)) { 6471 kind = 3; // ivar 6472 } else if (isa<FieldDecl>(decl)) { 6473 kind = 2; // field 6474 } 6475 6476 if (kind != -1U) { 6477 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6478 << kind; 6479 } 6480 } else if (lifetime == Qualifiers::OCL_None) { 6481 // Try to infer lifetime. 6482 if (!type->isObjCLifetimeType()) 6483 return false; 6484 6485 lifetime = type->getObjCARCImplicitLifetime(); 6486 type = Context.getLifetimeQualifiedType(type, lifetime); 6487 decl->setType(type); 6488 } 6489 6490 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6491 // Thread-local variables cannot have lifetime. 6492 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6493 var->getTLSKind()) { 6494 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6495 << var->getType(); 6496 return true; 6497 } 6498 } 6499 6500 return false; 6501 } 6502 6503 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6504 if (Decl->getType().hasAddressSpace()) 6505 return; 6506 if (Decl->getType()->isDependentType()) 6507 return; 6508 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6509 QualType Type = Var->getType(); 6510 if (Type->isSamplerT() || Type->isVoidType()) 6511 return; 6512 LangAS ImplAS = LangAS::opencl_private; 6513 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6514 // __opencl_c_program_scope_global_variables feature, the address space 6515 // for a variable at program scope or a static or extern variable inside 6516 // a function are inferred to be __global. 6517 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6518 Var->hasGlobalStorage()) 6519 ImplAS = LangAS::opencl_global; 6520 // If the original type from a decayed type is an array type and that array 6521 // type has no address space yet, deduce it now. 6522 if (auto DT = dyn_cast<DecayedType>(Type)) { 6523 auto OrigTy = DT->getOriginalType(); 6524 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6525 // Add the address space to the original array type and then propagate 6526 // that to the element type through `getAsArrayType`. 6527 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6528 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6529 // Re-generate the decayed type. 6530 Type = Context.getDecayedType(OrigTy); 6531 } 6532 } 6533 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6534 // Apply any qualifiers (including address space) from the array type to 6535 // the element type. This implements C99 6.7.3p8: "If the specification of 6536 // an array type includes any type qualifiers, the element type is so 6537 // qualified, not the array type." 6538 if (Type->isArrayType()) 6539 Type = QualType(Context.getAsArrayType(Type), 0); 6540 Decl->setType(Type); 6541 } 6542 } 6543 6544 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6545 // Ensure that an auto decl is deduced otherwise the checks below might cache 6546 // the wrong linkage. 6547 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6548 6549 // 'weak' only applies to declarations with external linkage. 6550 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6551 if (!ND.isExternallyVisible()) { 6552 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6553 ND.dropAttr<WeakAttr>(); 6554 } 6555 } 6556 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6557 if (ND.isExternallyVisible()) { 6558 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6559 ND.dropAttr<WeakRefAttr>(); 6560 ND.dropAttr<AliasAttr>(); 6561 } 6562 } 6563 6564 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6565 if (VD->hasInit()) { 6566 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6567 assert(VD->isThisDeclarationADefinition() && 6568 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6569 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6570 VD->dropAttr<AliasAttr>(); 6571 } 6572 } 6573 } 6574 6575 // 'selectany' only applies to externally visible variable declarations. 6576 // It does not apply to functions. 6577 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6578 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6579 S.Diag(Attr->getLocation(), 6580 diag::err_attribute_selectany_non_extern_data); 6581 ND.dropAttr<SelectAnyAttr>(); 6582 } 6583 } 6584 6585 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6586 auto *VD = dyn_cast<VarDecl>(&ND); 6587 bool IsAnonymousNS = false; 6588 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6589 if (VD) { 6590 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6591 while (NS && !IsAnonymousNS) { 6592 IsAnonymousNS = NS->isAnonymousNamespace(); 6593 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6594 } 6595 } 6596 // dll attributes require external linkage. Static locals may have external 6597 // linkage but still cannot be explicitly imported or exported. 6598 // In Microsoft mode, a variable defined in anonymous namespace must have 6599 // external linkage in order to be exported. 6600 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6601 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6602 (!AnonNSInMicrosoftMode && 6603 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6604 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6605 << &ND << Attr; 6606 ND.setInvalidDecl(); 6607 } 6608 } 6609 6610 // Check the attributes on the function type, if any. 6611 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6612 // Don't declare this variable in the second operand of the for-statement; 6613 // GCC miscompiles that by ending its lifetime before evaluating the 6614 // third operand. See gcc.gnu.org/PR86769. 6615 AttributedTypeLoc ATL; 6616 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6617 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6618 TL = ATL.getModifiedLoc()) { 6619 // The [[lifetimebound]] attribute can be applied to the implicit object 6620 // parameter of a non-static member function (other than a ctor or dtor) 6621 // by applying it to the function type. 6622 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6623 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6624 if (!MD || MD->isStatic()) { 6625 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6626 << !MD << A->getRange(); 6627 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6628 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6629 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6630 } 6631 } 6632 } 6633 } 6634 } 6635 6636 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6637 NamedDecl *NewDecl, 6638 bool IsSpecialization, 6639 bool IsDefinition) { 6640 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6641 return; 6642 6643 bool IsTemplate = false; 6644 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6645 OldDecl = OldTD->getTemplatedDecl(); 6646 IsTemplate = true; 6647 if (!IsSpecialization) 6648 IsDefinition = false; 6649 } 6650 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6651 NewDecl = NewTD->getTemplatedDecl(); 6652 IsTemplate = true; 6653 } 6654 6655 if (!OldDecl || !NewDecl) 6656 return; 6657 6658 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6659 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6660 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6661 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6662 6663 // dllimport and dllexport are inheritable attributes so we have to exclude 6664 // inherited attribute instances. 6665 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6666 (NewExportAttr && !NewExportAttr->isInherited()); 6667 6668 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6669 // the only exception being explicit specializations. 6670 // Implicitly generated declarations are also excluded for now because there 6671 // is no other way to switch these to use dllimport or dllexport. 6672 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6673 6674 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6675 // Allow with a warning for free functions and global variables. 6676 bool JustWarn = false; 6677 if (!OldDecl->isCXXClassMember()) { 6678 auto *VD = dyn_cast<VarDecl>(OldDecl); 6679 if (VD && !VD->getDescribedVarTemplate()) 6680 JustWarn = true; 6681 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6682 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6683 JustWarn = true; 6684 } 6685 6686 // We cannot change a declaration that's been used because IR has already 6687 // been emitted. Dllimported functions will still work though (modulo 6688 // address equality) as they can use the thunk. 6689 if (OldDecl->isUsed()) 6690 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6691 JustWarn = false; 6692 6693 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6694 : diag::err_attribute_dll_redeclaration; 6695 S.Diag(NewDecl->getLocation(), DiagID) 6696 << NewDecl 6697 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6698 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6699 if (!JustWarn) { 6700 NewDecl->setInvalidDecl(); 6701 return; 6702 } 6703 } 6704 6705 // A redeclaration is not allowed to drop a dllimport attribute, the only 6706 // exceptions being inline function definitions (except for function 6707 // templates), local extern declarations, qualified friend declarations or 6708 // special MSVC extension: in the last case, the declaration is treated as if 6709 // it were marked dllexport. 6710 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6711 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6712 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6713 // Ignore static data because out-of-line definitions are diagnosed 6714 // separately. 6715 IsStaticDataMember = VD->isStaticDataMember(); 6716 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6717 VarDecl::DeclarationOnly; 6718 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6719 IsInline = FD->isInlined(); 6720 IsQualifiedFriend = FD->getQualifier() && 6721 FD->getFriendObjectKind() == Decl::FOK_Declared; 6722 } 6723 6724 if (OldImportAttr && !HasNewAttr && 6725 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6726 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6727 if (IsMicrosoftABI && IsDefinition) { 6728 S.Diag(NewDecl->getLocation(), 6729 diag::warn_redeclaration_without_import_attribute) 6730 << NewDecl; 6731 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6732 NewDecl->dropAttr<DLLImportAttr>(); 6733 NewDecl->addAttr( 6734 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6735 } else { 6736 S.Diag(NewDecl->getLocation(), 6737 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6738 << NewDecl << OldImportAttr; 6739 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6740 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6741 OldDecl->dropAttr<DLLImportAttr>(); 6742 NewDecl->dropAttr<DLLImportAttr>(); 6743 } 6744 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6745 // In MinGW, seeing a function declared inline drops the dllimport 6746 // attribute. 6747 OldDecl->dropAttr<DLLImportAttr>(); 6748 NewDecl->dropAttr<DLLImportAttr>(); 6749 S.Diag(NewDecl->getLocation(), 6750 diag::warn_dllimport_dropped_from_inline_function) 6751 << NewDecl << OldImportAttr; 6752 } 6753 6754 // A specialization of a class template member function is processed here 6755 // since it's a redeclaration. If the parent class is dllexport, the 6756 // specialization inherits that attribute. This doesn't happen automatically 6757 // since the parent class isn't instantiated until later. 6758 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6759 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6760 !NewImportAttr && !NewExportAttr) { 6761 if (const DLLExportAttr *ParentExportAttr = 6762 MD->getParent()->getAttr<DLLExportAttr>()) { 6763 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6764 NewAttr->setInherited(true); 6765 NewDecl->addAttr(NewAttr); 6766 } 6767 } 6768 } 6769 } 6770 6771 /// Given that we are within the definition of the given function, 6772 /// will that definition behave like C99's 'inline', where the 6773 /// definition is discarded except for optimization purposes? 6774 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6775 // Try to avoid calling GetGVALinkageForFunction. 6776 6777 // All cases of this require the 'inline' keyword. 6778 if (!FD->isInlined()) return false; 6779 6780 // This is only possible in C++ with the gnu_inline attribute. 6781 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6782 return false; 6783 6784 // Okay, go ahead and call the relatively-more-expensive function. 6785 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6786 } 6787 6788 /// Determine whether a variable is extern "C" prior to attaching 6789 /// an initializer. We can't just call isExternC() here, because that 6790 /// will also compute and cache whether the declaration is externally 6791 /// visible, which might change when we attach the initializer. 6792 /// 6793 /// This can only be used if the declaration is known to not be a 6794 /// redeclaration of an internal linkage declaration. 6795 /// 6796 /// For instance: 6797 /// 6798 /// auto x = []{}; 6799 /// 6800 /// Attaching the initializer here makes this declaration not externally 6801 /// visible, because its type has internal linkage. 6802 /// 6803 /// FIXME: This is a hack. 6804 template<typename T> 6805 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6806 if (S.getLangOpts().CPlusPlus) { 6807 // In C++, the overloadable attribute negates the effects of extern "C". 6808 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6809 return false; 6810 6811 // So do CUDA's host/device attributes. 6812 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6813 D->template hasAttr<CUDAHostAttr>())) 6814 return false; 6815 } 6816 return D->isExternC(); 6817 } 6818 6819 static bool shouldConsiderLinkage(const VarDecl *VD) { 6820 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6821 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6822 isa<OMPDeclareMapperDecl>(DC)) 6823 return VD->hasExternalStorage(); 6824 if (DC->isFileContext()) 6825 return true; 6826 if (DC->isRecord()) 6827 return false; 6828 if (isa<RequiresExprBodyDecl>(DC)) 6829 return false; 6830 llvm_unreachable("Unexpected context"); 6831 } 6832 6833 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6834 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6835 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6836 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6837 return true; 6838 if (DC->isRecord()) 6839 return false; 6840 llvm_unreachable("Unexpected context"); 6841 } 6842 6843 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6844 ParsedAttr::Kind Kind) { 6845 // Check decl attributes on the DeclSpec. 6846 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6847 return true; 6848 6849 // Walk the declarator structure, checking decl attributes that were in a type 6850 // position to the decl itself. 6851 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6852 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6853 return true; 6854 } 6855 6856 // Finally, check attributes on the decl itself. 6857 return PD.getAttributes().hasAttribute(Kind); 6858 } 6859 6860 /// Adjust the \c DeclContext for a function or variable that might be a 6861 /// function-local external declaration. 6862 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6863 if (!DC->isFunctionOrMethod()) 6864 return false; 6865 6866 // If this is a local extern function or variable declared within a function 6867 // template, don't add it into the enclosing namespace scope until it is 6868 // instantiated; it might have a dependent type right now. 6869 if (DC->isDependentContext()) 6870 return true; 6871 6872 // C++11 [basic.link]p7: 6873 // When a block scope declaration of an entity with linkage is not found to 6874 // refer to some other declaration, then that entity is a member of the 6875 // innermost enclosing namespace. 6876 // 6877 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6878 // semantically-enclosing namespace, not a lexically-enclosing one. 6879 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6880 DC = DC->getParent(); 6881 return true; 6882 } 6883 6884 /// Returns true if given declaration has external C language linkage. 6885 static bool isDeclExternC(const Decl *D) { 6886 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6887 return FD->isExternC(); 6888 if (const auto *VD = dyn_cast<VarDecl>(D)) 6889 return VD->isExternC(); 6890 6891 llvm_unreachable("Unknown type of decl!"); 6892 } 6893 6894 /// Returns true if there hasn't been any invalid type diagnosed. 6895 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6896 DeclContext *DC = NewVD->getDeclContext(); 6897 QualType R = NewVD->getType(); 6898 6899 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6900 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6901 // argument. 6902 if (R->isImageType() || R->isPipeType()) { 6903 Se.Diag(NewVD->getLocation(), 6904 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6905 << R; 6906 NewVD->setInvalidDecl(); 6907 return false; 6908 } 6909 6910 // OpenCL v1.2 s6.9.r: 6911 // The event type cannot be used to declare a program scope variable. 6912 // OpenCL v2.0 s6.9.q: 6913 // The clk_event_t and reserve_id_t types cannot be declared in program 6914 // scope. 6915 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6916 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6917 Se.Diag(NewVD->getLocation(), 6918 diag::err_invalid_type_for_program_scope_var) 6919 << R; 6920 NewVD->setInvalidDecl(); 6921 return false; 6922 } 6923 } 6924 6925 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6926 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6927 Se.getLangOpts())) { 6928 QualType NR = R.getCanonicalType(); 6929 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6930 NR->isReferenceType()) { 6931 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6932 NR->isFunctionReferenceType()) { 6933 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6934 << NR->isReferenceType(); 6935 NewVD->setInvalidDecl(); 6936 return false; 6937 } 6938 NR = NR->getPointeeType(); 6939 } 6940 } 6941 6942 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6943 Se.getLangOpts())) { 6944 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6945 // half array type (unless the cl_khr_fp16 extension is enabled). 6946 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6947 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6948 NewVD->setInvalidDecl(); 6949 return false; 6950 } 6951 } 6952 6953 // OpenCL v1.2 s6.9.r: 6954 // The event type cannot be used with the __local, __constant and __global 6955 // address space qualifiers. 6956 if (R->isEventT()) { 6957 if (R.getAddressSpace() != LangAS::opencl_private) { 6958 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6959 NewVD->setInvalidDecl(); 6960 return false; 6961 } 6962 } 6963 6964 if (R->isSamplerT()) { 6965 // OpenCL v1.2 s6.9.b p4: 6966 // The sampler type cannot be used with the __local and __global address 6967 // space qualifiers. 6968 if (R.getAddressSpace() == LangAS::opencl_local || 6969 R.getAddressSpace() == LangAS::opencl_global) { 6970 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 6971 NewVD->setInvalidDecl(); 6972 } 6973 6974 // OpenCL v1.2 s6.12.14.1: 6975 // A global sampler must be declared with either the constant address 6976 // space qualifier or with the const qualifier. 6977 if (DC->isTranslationUnit() && 6978 !(R.getAddressSpace() == LangAS::opencl_constant || 6979 R.isConstQualified())) { 6980 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 6981 NewVD->setInvalidDecl(); 6982 } 6983 if (NewVD->isInvalidDecl()) 6984 return false; 6985 } 6986 6987 return true; 6988 } 6989 6990 template <typename AttrTy> 6991 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 6992 const TypedefNameDecl *TND = TT->getDecl(); 6993 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 6994 AttrTy *Clone = Attribute->clone(S.Context); 6995 Clone->setInherited(true); 6996 D->addAttr(Clone); 6997 } 6998 } 6999 7000 NamedDecl *Sema::ActOnVariableDeclarator( 7001 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7002 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7003 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7004 QualType R = TInfo->getType(); 7005 DeclarationName Name = GetNameForDeclarator(D).getName(); 7006 7007 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7008 7009 if (D.isDecompositionDeclarator()) { 7010 // Take the name of the first declarator as our name for diagnostic 7011 // purposes. 7012 auto &Decomp = D.getDecompositionDeclarator(); 7013 if (!Decomp.bindings().empty()) { 7014 II = Decomp.bindings()[0].Name; 7015 Name = II; 7016 } 7017 } else if (!II) { 7018 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7019 return nullptr; 7020 } 7021 7022 7023 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7024 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7025 7026 // dllimport globals without explicit storage class are treated as extern. We 7027 // have to change the storage class this early to get the right DeclContext. 7028 if (SC == SC_None && !DC->isRecord() && 7029 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7030 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7031 SC = SC_Extern; 7032 7033 DeclContext *OriginalDC = DC; 7034 bool IsLocalExternDecl = SC == SC_Extern && 7035 adjustContextForLocalExternDecl(DC); 7036 7037 if (SCSpec == DeclSpec::SCS_mutable) { 7038 // mutable can only appear on non-static class members, so it's always 7039 // an error here 7040 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7041 D.setInvalidType(); 7042 SC = SC_None; 7043 } 7044 7045 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7046 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7047 D.getDeclSpec().getStorageClassSpecLoc())) { 7048 // In C++11, the 'register' storage class specifier is deprecated. 7049 // Suppress the warning in system macros, it's used in macros in some 7050 // popular C system headers, such as in glibc's htonl() macro. 7051 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7052 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7053 : diag::warn_deprecated_register) 7054 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7055 } 7056 7057 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7058 7059 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7060 // C99 6.9p2: The storage-class specifiers auto and register shall not 7061 // appear in the declaration specifiers in an external declaration. 7062 // Global Register+Asm is a GNU extension we support. 7063 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7064 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7065 D.setInvalidType(); 7066 } 7067 } 7068 7069 // If this variable has a VLA type and an initializer, try to 7070 // fold to a constant-sized type. This is otherwise invalid. 7071 if (D.hasInitializer() && R->isVariableArrayType()) 7072 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7073 /*DiagID=*/0); 7074 7075 bool IsMemberSpecialization = false; 7076 bool IsVariableTemplateSpecialization = false; 7077 bool IsPartialSpecialization = false; 7078 bool IsVariableTemplate = false; 7079 VarDecl *NewVD = nullptr; 7080 VarTemplateDecl *NewTemplate = nullptr; 7081 TemplateParameterList *TemplateParams = nullptr; 7082 if (!getLangOpts().CPlusPlus) { 7083 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7084 II, R, TInfo, SC); 7085 7086 if (R->getContainedDeducedType()) 7087 ParsingInitForAutoVars.insert(NewVD); 7088 7089 if (D.isInvalidType()) 7090 NewVD->setInvalidDecl(); 7091 7092 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7093 NewVD->hasLocalStorage()) 7094 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7095 NTCUC_AutoVar, NTCUK_Destruct); 7096 } else { 7097 bool Invalid = false; 7098 7099 if (DC->isRecord() && !CurContext->isRecord()) { 7100 // This is an out-of-line definition of a static data member. 7101 switch (SC) { 7102 case SC_None: 7103 break; 7104 case SC_Static: 7105 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7106 diag::err_static_out_of_line) 7107 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7108 break; 7109 case SC_Auto: 7110 case SC_Register: 7111 case SC_Extern: 7112 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7113 // to names of variables declared in a block or to function parameters. 7114 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7115 // of class members 7116 7117 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7118 diag::err_storage_class_for_static_member) 7119 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7120 break; 7121 case SC_PrivateExtern: 7122 llvm_unreachable("C storage class in c++!"); 7123 } 7124 } 7125 7126 if (SC == SC_Static && CurContext->isRecord()) { 7127 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7128 // Walk up the enclosing DeclContexts to check for any that are 7129 // incompatible with static data members. 7130 const DeclContext *FunctionOrMethod = nullptr; 7131 const CXXRecordDecl *AnonStruct = nullptr; 7132 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7133 if (Ctxt->isFunctionOrMethod()) { 7134 FunctionOrMethod = Ctxt; 7135 break; 7136 } 7137 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7138 if (ParentDecl && !ParentDecl->getDeclName()) { 7139 AnonStruct = ParentDecl; 7140 break; 7141 } 7142 } 7143 if (FunctionOrMethod) { 7144 // C++ [class.static.data]p5: A local class shall not have static data 7145 // members. 7146 Diag(D.getIdentifierLoc(), 7147 diag::err_static_data_member_not_allowed_in_local_class) 7148 << Name << RD->getDeclName() << RD->getTagKind(); 7149 } else if (AnonStruct) { 7150 // C++ [class.static.data]p4: Unnamed classes and classes contained 7151 // directly or indirectly within unnamed classes shall not contain 7152 // static data members. 7153 Diag(D.getIdentifierLoc(), 7154 diag::err_static_data_member_not_allowed_in_anon_struct) 7155 << Name << AnonStruct->getTagKind(); 7156 Invalid = true; 7157 } else if (RD->isUnion()) { 7158 // C++98 [class.union]p1: If a union contains a static data member, 7159 // the program is ill-formed. C++11 drops this restriction. 7160 Diag(D.getIdentifierLoc(), 7161 getLangOpts().CPlusPlus11 7162 ? diag::warn_cxx98_compat_static_data_member_in_union 7163 : diag::ext_static_data_member_in_union) << Name; 7164 } 7165 } 7166 } 7167 7168 // Match up the template parameter lists with the scope specifier, then 7169 // determine whether we have a template or a template specialization. 7170 bool InvalidScope = false; 7171 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7172 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7173 D.getCXXScopeSpec(), 7174 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7175 ? D.getName().TemplateId 7176 : nullptr, 7177 TemplateParamLists, 7178 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7179 Invalid |= InvalidScope; 7180 7181 if (TemplateParams) { 7182 if (!TemplateParams->size() && 7183 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7184 // There is an extraneous 'template<>' for this variable. Complain 7185 // about it, but allow the declaration of the variable. 7186 Diag(TemplateParams->getTemplateLoc(), 7187 diag::err_template_variable_noparams) 7188 << II 7189 << SourceRange(TemplateParams->getTemplateLoc(), 7190 TemplateParams->getRAngleLoc()); 7191 TemplateParams = nullptr; 7192 } else { 7193 // Check that we can declare a template here. 7194 if (CheckTemplateDeclScope(S, TemplateParams)) 7195 return nullptr; 7196 7197 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7198 // This is an explicit specialization or a partial specialization. 7199 IsVariableTemplateSpecialization = true; 7200 IsPartialSpecialization = TemplateParams->size() > 0; 7201 } else { // if (TemplateParams->size() > 0) 7202 // This is a template declaration. 7203 IsVariableTemplate = true; 7204 7205 // Only C++1y supports variable templates (N3651). 7206 Diag(D.getIdentifierLoc(), 7207 getLangOpts().CPlusPlus14 7208 ? diag::warn_cxx11_compat_variable_template 7209 : diag::ext_variable_template); 7210 } 7211 } 7212 } else { 7213 // Check that we can declare a member specialization here. 7214 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7215 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7216 return nullptr; 7217 assert((Invalid || 7218 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7219 "should have a 'template<>' for this decl"); 7220 } 7221 7222 if (IsVariableTemplateSpecialization) { 7223 SourceLocation TemplateKWLoc = 7224 TemplateParamLists.size() > 0 7225 ? TemplateParamLists[0]->getTemplateLoc() 7226 : SourceLocation(); 7227 DeclResult Res = ActOnVarTemplateSpecialization( 7228 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7229 IsPartialSpecialization); 7230 if (Res.isInvalid()) 7231 return nullptr; 7232 NewVD = cast<VarDecl>(Res.get()); 7233 AddToScope = false; 7234 } else if (D.isDecompositionDeclarator()) { 7235 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7236 D.getIdentifierLoc(), R, TInfo, SC, 7237 Bindings); 7238 } else 7239 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7240 D.getIdentifierLoc(), II, R, TInfo, SC); 7241 7242 // If this is supposed to be a variable template, create it as such. 7243 if (IsVariableTemplate) { 7244 NewTemplate = 7245 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7246 TemplateParams, NewVD); 7247 NewVD->setDescribedVarTemplate(NewTemplate); 7248 } 7249 7250 // If this decl has an auto type in need of deduction, make a note of the 7251 // Decl so we can diagnose uses of it in its own initializer. 7252 if (R->getContainedDeducedType()) 7253 ParsingInitForAutoVars.insert(NewVD); 7254 7255 if (D.isInvalidType() || Invalid) { 7256 NewVD->setInvalidDecl(); 7257 if (NewTemplate) 7258 NewTemplate->setInvalidDecl(); 7259 } 7260 7261 SetNestedNameSpecifier(*this, NewVD, D); 7262 7263 // If we have any template parameter lists that don't directly belong to 7264 // the variable (matching the scope specifier), store them. 7265 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7266 if (TemplateParamLists.size() > VDTemplateParamLists) 7267 NewVD->setTemplateParameterListsInfo( 7268 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7269 } 7270 7271 if (D.getDeclSpec().isInlineSpecified()) { 7272 if (!getLangOpts().CPlusPlus) { 7273 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7274 << 0; 7275 } else if (CurContext->isFunctionOrMethod()) { 7276 // 'inline' is not allowed on block scope variable declaration. 7277 Diag(D.getDeclSpec().getInlineSpecLoc(), 7278 diag::err_inline_declaration_block_scope) << Name 7279 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7280 } else { 7281 Diag(D.getDeclSpec().getInlineSpecLoc(), 7282 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7283 : diag::ext_inline_variable); 7284 NewVD->setInlineSpecified(); 7285 } 7286 } 7287 7288 // Set the lexical context. If the declarator has a C++ scope specifier, the 7289 // lexical context will be different from the semantic context. 7290 NewVD->setLexicalDeclContext(CurContext); 7291 if (NewTemplate) 7292 NewTemplate->setLexicalDeclContext(CurContext); 7293 7294 if (IsLocalExternDecl) { 7295 if (D.isDecompositionDeclarator()) 7296 for (auto *B : Bindings) 7297 B->setLocalExternDecl(); 7298 else 7299 NewVD->setLocalExternDecl(); 7300 } 7301 7302 bool EmitTLSUnsupportedError = false; 7303 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7304 // C++11 [dcl.stc]p4: 7305 // When thread_local is applied to a variable of block scope the 7306 // storage-class-specifier static is implied if it does not appear 7307 // explicitly. 7308 // Core issue: 'static' is not implied if the variable is declared 7309 // 'extern'. 7310 if (NewVD->hasLocalStorage() && 7311 (SCSpec != DeclSpec::SCS_unspecified || 7312 TSCS != DeclSpec::TSCS_thread_local || 7313 !DC->isFunctionOrMethod())) 7314 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7315 diag::err_thread_non_global) 7316 << DeclSpec::getSpecifierName(TSCS); 7317 else if (!Context.getTargetInfo().isTLSSupported()) { 7318 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7319 getLangOpts().SYCLIsDevice) { 7320 // Postpone error emission until we've collected attributes required to 7321 // figure out whether it's a host or device variable and whether the 7322 // error should be ignored. 7323 EmitTLSUnsupportedError = true; 7324 // We still need to mark the variable as TLS so it shows up in AST with 7325 // proper storage class for other tools to use even if we're not going 7326 // to emit any code for it. 7327 NewVD->setTSCSpec(TSCS); 7328 } else 7329 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7330 diag::err_thread_unsupported); 7331 } else 7332 NewVD->setTSCSpec(TSCS); 7333 } 7334 7335 switch (D.getDeclSpec().getConstexprSpecifier()) { 7336 case ConstexprSpecKind::Unspecified: 7337 break; 7338 7339 case ConstexprSpecKind::Consteval: 7340 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7341 diag::err_constexpr_wrong_decl_kind) 7342 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7343 LLVM_FALLTHROUGH; 7344 7345 case ConstexprSpecKind::Constexpr: 7346 NewVD->setConstexpr(true); 7347 // C++1z [dcl.spec.constexpr]p1: 7348 // A static data member declared with the constexpr specifier is 7349 // implicitly an inline variable. 7350 if (NewVD->isStaticDataMember() && 7351 (getLangOpts().CPlusPlus17 || 7352 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7353 NewVD->setImplicitlyInline(); 7354 break; 7355 7356 case ConstexprSpecKind::Constinit: 7357 if (!NewVD->hasGlobalStorage()) 7358 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7359 diag::err_constinit_local_variable); 7360 else 7361 NewVD->addAttr(ConstInitAttr::Create( 7362 Context, D.getDeclSpec().getConstexprSpecLoc(), 7363 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7364 break; 7365 } 7366 7367 // C99 6.7.4p3 7368 // An inline definition of a function with external linkage shall 7369 // not contain a definition of a modifiable object with static or 7370 // thread storage duration... 7371 // We only apply this when the function is required to be defined 7372 // elsewhere, i.e. when the function is not 'extern inline'. Note 7373 // that a local variable with thread storage duration still has to 7374 // be marked 'static'. Also note that it's possible to get these 7375 // semantics in C++ using __attribute__((gnu_inline)). 7376 if (SC == SC_Static && S->getFnParent() != nullptr && 7377 !NewVD->getType().isConstQualified()) { 7378 FunctionDecl *CurFD = getCurFunctionDecl(); 7379 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7380 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7381 diag::warn_static_local_in_extern_inline); 7382 MaybeSuggestAddingStaticToDecl(CurFD); 7383 } 7384 } 7385 7386 if (D.getDeclSpec().isModulePrivateSpecified()) { 7387 if (IsVariableTemplateSpecialization) 7388 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7389 << (IsPartialSpecialization ? 1 : 0) 7390 << FixItHint::CreateRemoval( 7391 D.getDeclSpec().getModulePrivateSpecLoc()); 7392 else if (IsMemberSpecialization) 7393 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7394 << 2 7395 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7396 else if (NewVD->hasLocalStorage()) 7397 Diag(NewVD->getLocation(), diag::err_module_private_local) 7398 << 0 << NewVD 7399 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7400 << FixItHint::CreateRemoval( 7401 D.getDeclSpec().getModulePrivateSpecLoc()); 7402 else { 7403 NewVD->setModulePrivate(); 7404 if (NewTemplate) 7405 NewTemplate->setModulePrivate(); 7406 for (auto *B : Bindings) 7407 B->setModulePrivate(); 7408 } 7409 } 7410 7411 if (getLangOpts().OpenCL) { 7412 deduceOpenCLAddressSpace(NewVD); 7413 7414 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7415 if (TSC != TSCS_unspecified) { 7416 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7417 diag::err_opencl_unknown_type_specifier) 7418 << getLangOpts().getOpenCLVersionString() 7419 << DeclSpec::getSpecifierName(TSC) << 1; 7420 NewVD->setInvalidDecl(); 7421 } 7422 } 7423 7424 // Handle attributes prior to checking for duplicates in MergeVarDecl 7425 ProcessDeclAttributes(S, NewVD, D); 7426 7427 // FIXME: This is probably the wrong location to be doing this and we should 7428 // probably be doing this for more attributes (especially for function 7429 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7430 // the code to copy attributes would be generated by TableGen. 7431 if (R->isFunctionPointerType()) 7432 if (const auto *TT = R->getAs<TypedefType>()) 7433 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7434 7435 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7436 getLangOpts().SYCLIsDevice) { 7437 if (EmitTLSUnsupportedError && 7438 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7439 (getLangOpts().OpenMPIsDevice && 7440 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7441 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7442 diag::err_thread_unsupported); 7443 7444 if (EmitTLSUnsupportedError && 7445 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7446 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7447 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7448 // storage [duration]." 7449 if (SC == SC_None && S->getFnParent() != nullptr && 7450 (NewVD->hasAttr<CUDASharedAttr>() || 7451 NewVD->hasAttr<CUDAConstantAttr>())) { 7452 NewVD->setStorageClass(SC_Static); 7453 } 7454 } 7455 7456 // Ensure that dllimport globals without explicit storage class are treated as 7457 // extern. The storage class is set above using parsed attributes. Now we can 7458 // check the VarDecl itself. 7459 assert(!NewVD->hasAttr<DLLImportAttr>() || 7460 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7461 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7462 7463 // In auto-retain/release, infer strong retension for variables of 7464 // retainable type. 7465 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7466 NewVD->setInvalidDecl(); 7467 7468 // Handle GNU asm-label extension (encoded as an attribute). 7469 if (Expr *E = (Expr*)D.getAsmLabel()) { 7470 // The parser guarantees this is a string. 7471 StringLiteral *SE = cast<StringLiteral>(E); 7472 StringRef Label = SE->getString(); 7473 if (S->getFnParent() != nullptr) { 7474 switch (SC) { 7475 case SC_None: 7476 case SC_Auto: 7477 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7478 break; 7479 case SC_Register: 7480 // Local Named register 7481 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7482 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7483 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7484 break; 7485 case SC_Static: 7486 case SC_Extern: 7487 case SC_PrivateExtern: 7488 break; 7489 } 7490 } else if (SC == SC_Register) { 7491 // Global Named register 7492 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7493 const auto &TI = Context.getTargetInfo(); 7494 bool HasSizeMismatch; 7495 7496 if (!TI.isValidGCCRegisterName(Label)) 7497 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7498 else if (!TI.validateGlobalRegisterVariable(Label, 7499 Context.getTypeSize(R), 7500 HasSizeMismatch)) 7501 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7502 else if (HasSizeMismatch) 7503 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7504 } 7505 7506 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7507 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7508 NewVD->setInvalidDecl(true); 7509 } 7510 } 7511 7512 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7513 /*IsLiteralLabel=*/true, 7514 SE->getStrTokenLoc(0))); 7515 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7516 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7517 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7518 if (I != ExtnameUndeclaredIdentifiers.end()) { 7519 if (isDeclExternC(NewVD)) { 7520 NewVD->addAttr(I->second); 7521 ExtnameUndeclaredIdentifiers.erase(I); 7522 } else 7523 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7524 << /*Variable*/1 << NewVD; 7525 } 7526 } 7527 7528 // Find the shadowed declaration before filtering for scope. 7529 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7530 ? getShadowedDeclaration(NewVD, Previous) 7531 : nullptr; 7532 7533 // Don't consider existing declarations that are in a different 7534 // scope and are out-of-semantic-context declarations (if the new 7535 // declaration has linkage). 7536 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7537 D.getCXXScopeSpec().isNotEmpty() || 7538 IsMemberSpecialization || 7539 IsVariableTemplateSpecialization); 7540 7541 // Check whether the previous declaration is in the same block scope. This 7542 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7543 if (getLangOpts().CPlusPlus && 7544 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7545 NewVD->setPreviousDeclInSameBlockScope( 7546 Previous.isSingleResult() && !Previous.isShadowed() && 7547 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7548 7549 if (!getLangOpts().CPlusPlus) { 7550 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7551 } else { 7552 // If this is an explicit specialization of a static data member, check it. 7553 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7554 CheckMemberSpecialization(NewVD, Previous)) 7555 NewVD->setInvalidDecl(); 7556 7557 // Merge the decl with the existing one if appropriate. 7558 if (!Previous.empty()) { 7559 if (Previous.isSingleResult() && 7560 isa<FieldDecl>(Previous.getFoundDecl()) && 7561 D.getCXXScopeSpec().isSet()) { 7562 // The user tried to define a non-static data member 7563 // out-of-line (C++ [dcl.meaning]p1). 7564 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7565 << D.getCXXScopeSpec().getRange(); 7566 Previous.clear(); 7567 NewVD->setInvalidDecl(); 7568 } 7569 } else if (D.getCXXScopeSpec().isSet()) { 7570 // No previous declaration in the qualifying scope. 7571 Diag(D.getIdentifierLoc(), diag::err_no_member) 7572 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7573 << D.getCXXScopeSpec().getRange(); 7574 NewVD->setInvalidDecl(); 7575 } 7576 7577 if (!IsVariableTemplateSpecialization) 7578 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7579 7580 if (NewTemplate) { 7581 VarTemplateDecl *PrevVarTemplate = 7582 NewVD->getPreviousDecl() 7583 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7584 : nullptr; 7585 7586 // Check the template parameter list of this declaration, possibly 7587 // merging in the template parameter list from the previous variable 7588 // template declaration. 7589 if (CheckTemplateParameterList( 7590 TemplateParams, 7591 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7592 : nullptr, 7593 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7594 DC->isDependentContext()) 7595 ? TPC_ClassTemplateMember 7596 : TPC_VarTemplate)) 7597 NewVD->setInvalidDecl(); 7598 7599 // If we are providing an explicit specialization of a static variable 7600 // template, make a note of that. 7601 if (PrevVarTemplate && 7602 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7603 PrevVarTemplate->setMemberSpecialization(); 7604 } 7605 } 7606 7607 // Diagnose shadowed variables iff this isn't a redeclaration. 7608 if (ShadowedDecl && !D.isRedeclaration()) 7609 CheckShadow(NewVD, ShadowedDecl, Previous); 7610 7611 ProcessPragmaWeak(S, NewVD); 7612 7613 // If this is the first declaration of an extern C variable, update 7614 // the map of such variables. 7615 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7616 isIncompleteDeclExternC(*this, NewVD)) 7617 RegisterLocallyScopedExternCDecl(NewVD, S); 7618 7619 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7620 MangleNumberingContext *MCtx; 7621 Decl *ManglingContextDecl; 7622 std::tie(MCtx, ManglingContextDecl) = 7623 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7624 if (MCtx) { 7625 Context.setManglingNumber( 7626 NewVD, MCtx->getManglingNumber( 7627 NewVD, getMSManglingNumber(getLangOpts(), S))); 7628 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7629 } 7630 } 7631 7632 // Special handling of variable named 'main'. 7633 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7634 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7635 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7636 7637 // C++ [basic.start.main]p3 7638 // A program that declares a variable main at global scope is ill-formed. 7639 if (getLangOpts().CPlusPlus) 7640 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7641 7642 // In C, and external-linkage variable named main results in undefined 7643 // behavior. 7644 else if (NewVD->hasExternalFormalLinkage()) 7645 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7646 } 7647 7648 if (D.isRedeclaration() && !Previous.empty()) { 7649 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7650 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7651 D.isFunctionDefinition()); 7652 } 7653 7654 if (NewTemplate) { 7655 if (NewVD->isInvalidDecl()) 7656 NewTemplate->setInvalidDecl(); 7657 ActOnDocumentableDecl(NewTemplate); 7658 return NewTemplate; 7659 } 7660 7661 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7662 CompleteMemberSpecialization(NewVD, Previous); 7663 7664 return NewVD; 7665 } 7666 7667 /// Enum describing the %select options in diag::warn_decl_shadow. 7668 enum ShadowedDeclKind { 7669 SDK_Local, 7670 SDK_Global, 7671 SDK_StaticMember, 7672 SDK_Field, 7673 SDK_Typedef, 7674 SDK_Using, 7675 SDK_StructuredBinding 7676 }; 7677 7678 /// Determine what kind of declaration we're shadowing. 7679 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7680 const DeclContext *OldDC) { 7681 if (isa<TypeAliasDecl>(ShadowedDecl)) 7682 return SDK_Using; 7683 else if (isa<TypedefDecl>(ShadowedDecl)) 7684 return SDK_Typedef; 7685 else if (isa<BindingDecl>(ShadowedDecl)) 7686 return SDK_StructuredBinding; 7687 else if (isa<RecordDecl>(OldDC)) 7688 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7689 7690 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7691 } 7692 7693 /// Return the location of the capture if the given lambda captures the given 7694 /// variable \p VD, or an invalid source location otherwise. 7695 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7696 const VarDecl *VD) { 7697 for (const Capture &Capture : LSI->Captures) { 7698 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7699 return Capture.getLocation(); 7700 } 7701 return SourceLocation(); 7702 } 7703 7704 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7705 const LookupResult &R) { 7706 // Only diagnose if we're shadowing an unambiguous field or variable. 7707 if (R.getResultKind() != LookupResult::Found) 7708 return false; 7709 7710 // Return false if warning is ignored. 7711 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7712 } 7713 7714 /// Return the declaration shadowed by the given variable \p D, or null 7715 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7716 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7717 const LookupResult &R) { 7718 if (!shouldWarnIfShadowedDecl(Diags, R)) 7719 return nullptr; 7720 7721 // Don't diagnose declarations at file scope. 7722 if (D->hasGlobalStorage()) 7723 return nullptr; 7724 7725 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7726 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7727 : nullptr; 7728 } 7729 7730 /// Return the declaration shadowed by the given typedef \p D, or null 7731 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7732 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7733 const LookupResult &R) { 7734 // Don't warn if typedef declaration is part of a class 7735 if (D->getDeclContext()->isRecord()) 7736 return nullptr; 7737 7738 if (!shouldWarnIfShadowedDecl(Diags, R)) 7739 return nullptr; 7740 7741 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7742 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7743 } 7744 7745 /// Return the declaration shadowed by the given variable \p D, or null 7746 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7747 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7748 const LookupResult &R) { 7749 if (!shouldWarnIfShadowedDecl(Diags, R)) 7750 return nullptr; 7751 7752 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7753 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7754 : nullptr; 7755 } 7756 7757 /// Diagnose variable or built-in function shadowing. Implements 7758 /// -Wshadow. 7759 /// 7760 /// This method is called whenever a VarDecl is added to a "useful" 7761 /// scope. 7762 /// 7763 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7764 /// \param R the lookup of the name 7765 /// 7766 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7767 const LookupResult &R) { 7768 DeclContext *NewDC = D->getDeclContext(); 7769 7770 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7771 // Fields are not shadowed by variables in C++ static methods. 7772 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7773 if (MD->isStatic()) 7774 return; 7775 7776 // Fields shadowed by constructor parameters are a special case. Usually 7777 // the constructor initializes the field with the parameter. 7778 if (isa<CXXConstructorDecl>(NewDC)) 7779 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7780 // Remember that this was shadowed so we can either warn about its 7781 // modification or its existence depending on warning settings. 7782 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7783 return; 7784 } 7785 } 7786 7787 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7788 if (shadowedVar->isExternC()) { 7789 // For shadowing external vars, make sure that we point to the global 7790 // declaration, not a locally scoped extern declaration. 7791 for (auto I : shadowedVar->redecls()) 7792 if (I->isFileVarDecl()) { 7793 ShadowedDecl = I; 7794 break; 7795 } 7796 } 7797 7798 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7799 7800 unsigned WarningDiag = diag::warn_decl_shadow; 7801 SourceLocation CaptureLoc; 7802 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7803 isa<CXXMethodDecl>(NewDC)) { 7804 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7805 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7806 if (RD->getLambdaCaptureDefault() == LCD_None) { 7807 // Try to avoid warnings for lambdas with an explicit capture list. 7808 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7809 // Warn only when the lambda captures the shadowed decl explicitly. 7810 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7811 if (CaptureLoc.isInvalid()) 7812 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7813 } else { 7814 // Remember that this was shadowed so we can avoid the warning if the 7815 // shadowed decl isn't captured and the warning settings allow it. 7816 cast<LambdaScopeInfo>(getCurFunction()) 7817 ->ShadowingDecls.push_back( 7818 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7819 return; 7820 } 7821 } 7822 7823 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7824 // A variable can't shadow a local variable in an enclosing scope, if 7825 // they are separated by a non-capturing declaration context. 7826 for (DeclContext *ParentDC = NewDC; 7827 ParentDC && !ParentDC->Equals(OldDC); 7828 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7829 // Only block literals, captured statements, and lambda expressions 7830 // can capture; other scopes don't. 7831 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7832 !isLambdaCallOperator(ParentDC)) { 7833 return; 7834 } 7835 } 7836 } 7837 } 7838 } 7839 7840 // Only warn about certain kinds of shadowing for class members. 7841 if (NewDC && NewDC->isRecord()) { 7842 // In particular, don't warn about shadowing non-class members. 7843 if (!OldDC->isRecord()) 7844 return; 7845 7846 // TODO: should we warn about static data members shadowing 7847 // static data members from base classes? 7848 7849 // TODO: don't diagnose for inaccessible shadowed members. 7850 // This is hard to do perfectly because we might friend the 7851 // shadowing context, but that's just a false negative. 7852 } 7853 7854 7855 DeclarationName Name = R.getLookupName(); 7856 7857 // Emit warning and note. 7858 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7859 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7860 if (!CaptureLoc.isInvalid()) 7861 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7862 << Name << /*explicitly*/ 1; 7863 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7864 } 7865 7866 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7867 /// when these variables are captured by the lambda. 7868 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7869 for (const auto &Shadow : LSI->ShadowingDecls) { 7870 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7871 // Try to avoid the warning when the shadowed decl isn't captured. 7872 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7873 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7874 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7875 ? diag::warn_decl_shadow_uncaptured_local 7876 : diag::warn_decl_shadow) 7877 << Shadow.VD->getDeclName() 7878 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7879 if (!CaptureLoc.isInvalid()) 7880 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7881 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7882 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7883 } 7884 } 7885 7886 /// Check -Wshadow without the advantage of a previous lookup. 7887 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7888 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7889 return; 7890 7891 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7892 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7893 LookupName(R, S); 7894 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7895 CheckShadow(D, ShadowedDecl, R); 7896 } 7897 7898 /// Check if 'E', which is an expression that is about to be modified, refers 7899 /// to a constructor parameter that shadows a field. 7900 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7901 // Quickly ignore expressions that can't be shadowing ctor parameters. 7902 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7903 return; 7904 E = E->IgnoreParenImpCasts(); 7905 auto *DRE = dyn_cast<DeclRefExpr>(E); 7906 if (!DRE) 7907 return; 7908 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7909 auto I = ShadowingDecls.find(D); 7910 if (I == ShadowingDecls.end()) 7911 return; 7912 const NamedDecl *ShadowedDecl = I->second; 7913 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7914 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7915 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7916 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7917 7918 // Avoid issuing multiple warnings about the same decl. 7919 ShadowingDecls.erase(I); 7920 } 7921 7922 /// Check for conflict between this global or extern "C" declaration and 7923 /// previous global or extern "C" declarations. This is only used in C++. 7924 template<typename T> 7925 static bool checkGlobalOrExternCConflict( 7926 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7927 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7928 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7929 7930 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7931 // The common case: this global doesn't conflict with any extern "C" 7932 // declaration. 7933 return false; 7934 } 7935 7936 if (Prev) { 7937 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7938 // Both the old and new declarations have C language linkage. This is a 7939 // redeclaration. 7940 Previous.clear(); 7941 Previous.addDecl(Prev); 7942 return true; 7943 } 7944 7945 // This is a global, non-extern "C" declaration, and there is a previous 7946 // non-global extern "C" declaration. Diagnose if this is a variable 7947 // declaration. 7948 if (!isa<VarDecl>(ND)) 7949 return false; 7950 } else { 7951 // The declaration is extern "C". Check for any declaration in the 7952 // translation unit which might conflict. 7953 if (IsGlobal) { 7954 // We have already performed the lookup into the translation unit. 7955 IsGlobal = false; 7956 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7957 I != E; ++I) { 7958 if (isa<VarDecl>(*I)) { 7959 Prev = *I; 7960 break; 7961 } 7962 } 7963 } else { 7964 DeclContext::lookup_result R = 7965 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7966 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7967 I != E; ++I) { 7968 if (isa<VarDecl>(*I)) { 7969 Prev = *I; 7970 break; 7971 } 7972 // FIXME: If we have any other entity with this name in global scope, 7973 // the declaration is ill-formed, but that is a defect: it breaks the 7974 // 'stat' hack, for instance. Only variables can have mangled name 7975 // clashes with extern "C" declarations, so only they deserve a 7976 // diagnostic. 7977 } 7978 } 7979 7980 if (!Prev) 7981 return false; 7982 } 7983 7984 // Use the first declaration's location to ensure we point at something which 7985 // is lexically inside an extern "C" linkage-spec. 7986 assert(Prev && "should have found a previous declaration to diagnose"); 7987 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7988 Prev = FD->getFirstDecl(); 7989 else 7990 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7991 7992 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7993 << IsGlobal << ND; 7994 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7995 << IsGlobal; 7996 return false; 7997 } 7998 7999 /// Apply special rules for handling extern "C" declarations. Returns \c true 8000 /// if we have found that this is a redeclaration of some prior entity. 8001 /// 8002 /// Per C++ [dcl.link]p6: 8003 /// Two declarations [for a function or variable] with C language linkage 8004 /// with the same name that appear in different scopes refer to the same 8005 /// [entity]. An entity with C language linkage shall not be declared with 8006 /// the same name as an entity in global scope. 8007 template<typename T> 8008 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8009 LookupResult &Previous) { 8010 if (!S.getLangOpts().CPlusPlus) { 8011 // In C, when declaring a global variable, look for a corresponding 'extern' 8012 // variable declared in function scope. We don't need this in C++, because 8013 // we find local extern decls in the surrounding file-scope DeclContext. 8014 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8015 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8016 Previous.clear(); 8017 Previous.addDecl(Prev); 8018 return true; 8019 } 8020 } 8021 return false; 8022 } 8023 8024 // A declaration in the translation unit can conflict with an extern "C" 8025 // declaration. 8026 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8027 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8028 8029 // An extern "C" declaration can conflict with a declaration in the 8030 // translation unit or can be a redeclaration of an extern "C" declaration 8031 // in another scope. 8032 if (isIncompleteDeclExternC(S,ND)) 8033 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8034 8035 // Neither global nor extern "C": nothing to do. 8036 return false; 8037 } 8038 8039 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8040 // If the decl is already known invalid, don't check it. 8041 if (NewVD->isInvalidDecl()) 8042 return; 8043 8044 QualType T = NewVD->getType(); 8045 8046 // Defer checking an 'auto' type until its initializer is attached. 8047 if (T->isUndeducedType()) 8048 return; 8049 8050 if (NewVD->hasAttrs()) 8051 CheckAlignasUnderalignment(NewVD); 8052 8053 if (T->isObjCObjectType()) { 8054 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8055 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8056 T = Context.getObjCObjectPointerType(T); 8057 NewVD->setType(T); 8058 } 8059 8060 // Emit an error if an address space was applied to decl with local storage. 8061 // This includes arrays of objects with address space qualifiers, but not 8062 // automatic variables that point to other address spaces. 8063 // ISO/IEC TR 18037 S5.1.2 8064 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8065 T.getAddressSpace() != LangAS::Default) { 8066 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8067 NewVD->setInvalidDecl(); 8068 return; 8069 } 8070 8071 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8072 // scope. 8073 if (getLangOpts().OpenCLVersion == 120 && 8074 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8075 getLangOpts()) && 8076 NewVD->isStaticLocal()) { 8077 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8078 NewVD->setInvalidDecl(); 8079 return; 8080 } 8081 8082 if (getLangOpts().OpenCL) { 8083 if (!diagnoseOpenCLTypes(*this, NewVD)) 8084 return; 8085 8086 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8087 if (NewVD->hasAttr<BlocksAttr>()) { 8088 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8089 return; 8090 } 8091 8092 if (T->isBlockPointerType()) { 8093 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8094 // can't use 'extern' storage class. 8095 if (!T.isConstQualified()) { 8096 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8097 << 0 /*const*/; 8098 NewVD->setInvalidDecl(); 8099 return; 8100 } 8101 if (NewVD->hasExternalStorage()) { 8102 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8103 NewVD->setInvalidDecl(); 8104 return; 8105 } 8106 } 8107 8108 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8109 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8110 NewVD->hasExternalStorage()) { 8111 if (!T->isSamplerT() && !T->isDependentType() && 8112 !(T.getAddressSpace() == LangAS::opencl_constant || 8113 (T.getAddressSpace() == LangAS::opencl_global && 8114 getOpenCLOptions().areProgramScopeVariablesSupported( 8115 getLangOpts())))) { 8116 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8117 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8118 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8119 << Scope << "global or constant"; 8120 else 8121 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8122 << Scope << "constant"; 8123 NewVD->setInvalidDecl(); 8124 return; 8125 } 8126 } else { 8127 if (T.getAddressSpace() == LangAS::opencl_global) { 8128 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8129 << 1 /*is any function*/ << "global"; 8130 NewVD->setInvalidDecl(); 8131 return; 8132 } 8133 if (T.getAddressSpace() == LangAS::opencl_constant || 8134 T.getAddressSpace() == LangAS::opencl_local) { 8135 FunctionDecl *FD = getCurFunctionDecl(); 8136 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8137 // in functions. 8138 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8139 if (T.getAddressSpace() == LangAS::opencl_constant) 8140 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8141 << 0 /*non-kernel only*/ << "constant"; 8142 else 8143 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8144 << 0 /*non-kernel only*/ << "local"; 8145 NewVD->setInvalidDecl(); 8146 return; 8147 } 8148 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8149 // in the outermost scope of a kernel function. 8150 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8151 if (!getCurScope()->isFunctionScope()) { 8152 if (T.getAddressSpace() == LangAS::opencl_constant) 8153 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8154 << "constant"; 8155 else 8156 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8157 << "local"; 8158 NewVD->setInvalidDecl(); 8159 return; 8160 } 8161 } 8162 } else if (T.getAddressSpace() != LangAS::opencl_private && 8163 // If we are parsing a template we didn't deduce an addr 8164 // space yet. 8165 T.getAddressSpace() != LangAS::Default) { 8166 // Do not allow other address spaces on automatic variable. 8167 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8168 NewVD->setInvalidDecl(); 8169 return; 8170 } 8171 } 8172 } 8173 8174 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8175 && !NewVD->hasAttr<BlocksAttr>()) { 8176 if (getLangOpts().getGC() != LangOptions::NonGC) 8177 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8178 else { 8179 assert(!getLangOpts().ObjCAutoRefCount); 8180 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8181 } 8182 } 8183 8184 bool isVM = T->isVariablyModifiedType(); 8185 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8186 NewVD->hasAttr<BlocksAttr>()) 8187 setFunctionHasBranchProtectedScope(); 8188 8189 if ((isVM && NewVD->hasLinkage()) || 8190 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8191 bool SizeIsNegative; 8192 llvm::APSInt Oversized; 8193 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8194 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8195 QualType FixedT; 8196 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8197 FixedT = FixedTInfo->getType(); 8198 else if (FixedTInfo) { 8199 // Type and type-as-written are canonically different. We need to fix up 8200 // both types separately. 8201 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8202 Oversized); 8203 } 8204 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8205 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8206 // FIXME: This won't give the correct result for 8207 // int a[10][n]; 8208 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8209 8210 if (NewVD->isFileVarDecl()) 8211 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8212 << SizeRange; 8213 else if (NewVD->isStaticLocal()) 8214 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8215 << SizeRange; 8216 else 8217 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8218 << SizeRange; 8219 NewVD->setInvalidDecl(); 8220 return; 8221 } 8222 8223 if (!FixedTInfo) { 8224 if (NewVD->isFileVarDecl()) 8225 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8226 else 8227 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8228 NewVD->setInvalidDecl(); 8229 return; 8230 } 8231 8232 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8233 NewVD->setType(FixedT); 8234 NewVD->setTypeSourceInfo(FixedTInfo); 8235 } 8236 8237 if (T->isVoidType()) { 8238 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8239 // of objects and functions. 8240 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8241 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8242 << T; 8243 NewVD->setInvalidDecl(); 8244 return; 8245 } 8246 } 8247 8248 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8249 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8250 NewVD->setInvalidDecl(); 8251 return; 8252 } 8253 8254 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8255 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8256 NewVD->setInvalidDecl(); 8257 return; 8258 } 8259 8260 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8261 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8262 NewVD->setInvalidDecl(); 8263 return; 8264 } 8265 8266 if (NewVD->isConstexpr() && !T->isDependentType() && 8267 RequireLiteralType(NewVD->getLocation(), T, 8268 diag::err_constexpr_var_non_literal)) { 8269 NewVD->setInvalidDecl(); 8270 return; 8271 } 8272 8273 // PPC MMA non-pointer types are not allowed as non-local variable types. 8274 if (Context.getTargetInfo().getTriple().isPPC64() && 8275 !NewVD->isLocalVarDecl() && 8276 CheckPPCMMAType(T, NewVD->getLocation())) { 8277 NewVD->setInvalidDecl(); 8278 return; 8279 } 8280 } 8281 8282 /// Perform semantic checking on a newly-created variable 8283 /// declaration. 8284 /// 8285 /// This routine performs all of the type-checking required for a 8286 /// variable declaration once it has been built. It is used both to 8287 /// check variables after they have been parsed and their declarators 8288 /// have been translated into a declaration, and to check variables 8289 /// that have been instantiated from a template. 8290 /// 8291 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8292 /// 8293 /// Returns true if the variable declaration is a redeclaration. 8294 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8295 CheckVariableDeclarationType(NewVD); 8296 8297 // If the decl is already known invalid, don't check it. 8298 if (NewVD->isInvalidDecl()) 8299 return false; 8300 8301 // If we did not find anything by this name, look for a non-visible 8302 // extern "C" declaration with the same name. 8303 if (Previous.empty() && 8304 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8305 Previous.setShadowed(); 8306 8307 if (!Previous.empty()) { 8308 MergeVarDecl(NewVD, Previous); 8309 return true; 8310 } 8311 return false; 8312 } 8313 8314 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8315 /// and if so, check that it's a valid override and remember it. 8316 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8317 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8318 8319 // Look for methods in base classes that this method might override. 8320 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8321 /*DetectVirtual=*/false); 8322 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8323 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8324 DeclarationName Name = MD->getDeclName(); 8325 8326 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8327 // We really want to find the base class destructor here. 8328 QualType T = Context.getTypeDeclType(BaseRecord); 8329 CanQualType CT = Context.getCanonicalType(T); 8330 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8331 } 8332 8333 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8334 CXXMethodDecl *BaseMD = 8335 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8336 if (!BaseMD || !BaseMD->isVirtual() || 8337 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8338 /*ConsiderCudaAttrs=*/true, 8339 // C++2a [class.virtual]p2 does not consider requires 8340 // clauses when overriding. 8341 /*ConsiderRequiresClauses=*/false)) 8342 continue; 8343 8344 if (Overridden.insert(BaseMD).second) { 8345 MD->addOverriddenMethod(BaseMD); 8346 CheckOverridingFunctionReturnType(MD, BaseMD); 8347 CheckOverridingFunctionAttributes(MD, BaseMD); 8348 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8349 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8350 } 8351 8352 // A method can only override one function from each base class. We 8353 // don't track indirectly overridden methods from bases of bases. 8354 return true; 8355 } 8356 8357 return false; 8358 }; 8359 8360 DC->lookupInBases(VisitBase, Paths); 8361 return !Overridden.empty(); 8362 } 8363 8364 namespace { 8365 // Struct for holding all of the extra arguments needed by 8366 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8367 struct ActOnFDArgs { 8368 Scope *S; 8369 Declarator &D; 8370 MultiTemplateParamsArg TemplateParamLists; 8371 bool AddToScope; 8372 }; 8373 } // end anonymous namespace 8374 8375 namespace { 8376 8377 // Callback to only accept typo corrections that have a non-zero edit distance. 8378 // Also only accept corrections that have the same parent decl. 8379 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8380 public: 8381 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8382 CXXRecordDecl *Parent) 8383 : Context(Context), OriginalFD(TypoFD), 8384 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8385 8386 bool ValidateCandidate(const TypoCorrection &candidate) override { 8387 if (candidate.getEditDistance() == 0) 8388 return false; 8389 8390 SmallVector<unsigned, 1> MismatchedParams; 8391 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8392 CDeclEnd = candidate.end(); 8393 CDecl != CDeclEnd; ++CDecl) { 8394 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8395 8396 if (FD && !FD->hasBody() && 8397 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8398 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8399 CXXRecordDecl *Parent = MD->getParent(); 8400 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8401 return true; 8402 } else if (!ExpectedParent) { 8403 return true; 8404 } 8405 } 8406 } 8407 8408 return false; 8409 } 8410 8411 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8412 return std::make_unique<DifferentNameValidatorCCC>(*this); 8413 } 8414 8415 private: 8416 ASTContext &Context; 8417 FunctionDecl *OriginalFD; 8418 CXXRecordDecl *ExpectedParent; 8419 }; 8420 8421 } // end anonymous namespace 8422 8423 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8424 TypoCorrectedFunctionDefinitions.insert(F); 8425 } 8426 8427 /// Generate diagnostics for an invalid function redeclaration. 8428 /// 8429 /// This routine handles generating the diagnostic messages for an invalid 8430 /// function redeclaration, including finding possible similar declarations 8431 /// or performing typo correction if there are no previous declarations with 8432 /// the same name. 8433 /// 8434 /// Returns a NamedDecl iff typo correction was performed and substituting in 8435 /// the new declaration name does not cause new errors. 8436 static NamedDecl *DiagnoseInvalidRedeclaration( 8437 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8438 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8439 DeclarationName Name = NewFD->getDeclName(); 8440 DeclContext *NewDC = NewFD->getDeclContext(); 8441 SmallVector<unsigned, 1> MismatchedParams; 8442 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8443 TypoCorrection Correction; 8444 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8445 unsigned DiagMsg = 8446 IsLocalFriend ? diag::err_no_matching_local_friend : 8447 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8448 diag::err_member_decl_does_not_match; 8449 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8450 IsLocalFriend ? Sema::LookupLocalFriendName 8451 : Sema::LookupOrdinaryName, 8452 Sema::ForVisibleRedeclaration); 8453 8454 NewFD->setInvalidDecl(); 8455 if (IsLocalFriend) 8456 SemaRef.LookupName(Prev, S); 8457 else 8458 SemaRef.LookupQualifiedName(Prev, NewDC); 8459 assert(!Prev.isAmbiguous() && 8460 "Cannot have an ambiguity in previous-declaration lookup"); 8461 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8462 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8463 MD ? MD->getParent() : nullptr); 8464 if (!Prev.empty()) { 8465 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8466 Func != FuncEnd; ++Func) { 8467 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8468 if (FD && 8469 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8470 // Add 1 to the index so that 0 can mean the mismatch didn't 8471 // involve a parameter 8472 unsigned ParamNum = 8473 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8474 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8475 } 8476 } 8477 // If the qualified name lookup yielded nothing, try typo correction 8478 } else if ((Correction = SemaRef.CorrectTypo( 8479 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8480 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8481 IsLocalFriend ? nullptr : NewDC))) { 8482 // Set up everything for the call to ActOnFunctionDeclarator 8483 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8484 ExtraArgs.D.getIdentifierLoc()); 8485 Previous.clear(); 8486 Previous.setLookupName(Correction.getCorrection()); 8487 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8488 CDeclEnd = Correction.end(); 8489 CDecl != CDeclEnd; ++CDecl) { 8490 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8491 if (FD && !FD->hasBody() && 8492 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8493 Previous.addDecl(FD); 8494 } 8495 } 8496 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8497 8498 NamedDecl *Result; 8499 // Retry building the function declaration with the new previous 8500 // declarations, and with errors suppressed. 8501 { 8502 // Trap errors. 8503 Sema::SFINAETrap Trap(SemaRef); 8504 8505 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8506 // pieces need to verify the typo-corrected C++ declaration and hopefully 8507 // eliminate the need for the parameter pack ExtraArgs. 8508 Result = SemaRef.ActOnFunctionDeclarator( 8509 ExtraArgs.S, ExtraArgs.D, 8510 Correction.getCorrectionDecl()->getDeclContext(), 8511 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8512 ExtraArgs.AddToScope); 8513 8514 if (Trap.hasErrorOccurred()) 8515 Result = nullptr; 8516 } 8517 8518 if (Result) { 8519 // Determine which correction we picked. 8520 Decl *Canonical = Result->getCanonicalDecl(); 8521 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8522 I != E; ++I) 8523 if ((*I)->getCanonicalDecl() == Canonical) 8524 Correction.setCorrectionDecl(*I); 8525 8526 // Let Sema know about the correction. 8527 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8528 SemaRef.diagnoseTypo( 8529 Correction, 8530 SemaRef.PDiag(IsLocalFriend 8531 ? diag::err_no_matching_local_friend_suggest 8532 : diag::err_member_decl_does_not_match_suggest) 8533 << Name << NewDC << IsDefinition); 8534 return Result; 8535 } 8536 8537 // Pretend the typo correction never occurred 8538 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8539 ExtraArgs.D.getIdentifierLoc()); 8540 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8541 Previous.clear(); 8542 Previous.setLookupName(Name); 8543 } 8544 8545 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8546 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8547 8548 bool NewFDisConst = false; 8549 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8550 NewFDisConst = NewMD->isConst(); 8551 8552 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8553 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8554 NearMatch != NearMatchEnd; ++NearMatch) { 8555 FunctionDecl *FD = NearMatch->first; 8556 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8557 bool FDisConst = MD && MD->isConst(); 8558 bool IsMember = MD || !IsLocalFriend; 8559 8560 // FIXME: These notes are poorly worded for the local friend case. 8561 if (unsigned Idx = NearMatch->second) { 8562 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8563 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8564 if (Loc.isInvalid()) Loc = FD->getLocation(); 8565 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8566 : diag::note_local_decl_close_param_match) 8567 << Idx << FDParam->getType() 8568 << NewFD->getParamDecl(Idx - 1)->getType(); 8569 } else if (FDisConst != NewFDisConst) { 8570 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8571 << NewFDisConst << FD->getSourceRange().getEnd() 8572 << (NewFDisConst 8573 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 8574 .getConstQualifierLoc()) 8575 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 8576 .getRParenLoc() 8577 .getLocWithOffset(1), 8578 " const")); 8579 } else 8580 SemaRef.Diag(FD->getLocation(), 8581 IsMember ? diag::note_member_def_close_match 8582 : diag::note_local_decl_close_match); 8583 } 8584 return nullptr; 8585 } 8586 8587 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8588 switch (D.getDeclSpec().getStorageClassSpec()) { 8589 default: llvm_unreachable("Unknown storage class!"); 8590 case DeclSpec::SCS_auto: 8591 case DeclSpec::SCS_register: 8592 case DeclSpec::SCS_mutable: 8593 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8594 diag::err_typecheck_sclass_func); 8595 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8596 D.setInvalidType(); 8597 break; 8598 case DeclSpec::SCS_unspecified: break; 8599 case DeclSpec::SCS_extern: 8600 if (D.getDeclSpec().isExternInLinkageSpec()) 8601 return SC_None; 8602 return SC_Extern; 8603 case DeclSpec::SCS_static: { 8604 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8605 // C99 6.7.1p5: 8606 // The declaration of an identifier for a function that has 8607 // block scope shall have no explicit storage-class specifier 8608 // other than extern 8609 // See also (C++ [dcl.stc]p4). 8610 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8611 diag::err_static_block_func); 8612 break; 8613 } else 8614 return SC_Static; 8615 } 8616 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8617 } 8618 8619 // No explicit storage class has already been returned 8620 return SC_None; 8621 } 8622 8623 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8624 DeclContext *DC, QualType &R, 8625 TypeSourceInfo *TInfo, 8626 StorageClass SC, 8627 bool &IsVirtualOkay) { 8628 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8629 DeclarationName Name = NameInfo.getName(); 8630 8631 FunctionDecl *NewFD = nullptr; 8632 bool isInline = D.getDeclSpec().isInlineSpecified(); 8633 8634 if (!SemaRef.getLangOpts().CPlusPlus) { 8635 // Determine whether the function was written with a 8636 // prototype. This true when: 8637 // - there is a prototype in the declarator, or 8638 // - the type R of the function is some kind of typedef or other non- 8639 // attributed reference to a type name (which eventually refers to a 8640 // function type). 8641 bool HasPrototype = 8642 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8643 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8644 8645 NewFD = FunctionDecl::Create( 8646 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8647 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8648 ConstexprSpecKind::Unspecified, 8649 /*TrailingRequiresClause=*/nullptr); 8650 if (D.isInvalidType()) 8651 NewFD->setInvalidDecl(); 8652 8653 return NewFD; 8654 } 8655 8656 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8657 8658 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8659 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8660 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8661 diag::err_constexpr_wrong_decl_kind) 8662 << static_cast<int>(ConstexprKind); 8663 ConstexprKind = ConstexprSpecKind::Unspecified; 8664 D.getMutableDeclSpec().ClearConstexprSpec(); 8665 } 8666 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8667 8668 // Check that the return type is not an abstract class type. 8669 // For record types, this is done by the AbstractClassUsageDiagnoser once 8670 // the class has been completely parsed. 8671 if (!DC->isRecord() && 8672 SemaRef.RequireNonAbstractType( 8673 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8674 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8675 D.setInvalidType(); 8676 8677 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8678 // This is a C++ constructor declaration. 8679 assert(DC->isRecord() && 8680 "Constructors can only be declared in a member context"); 8681 8682 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8683 return CXXConstructorDecl::Create( 8684 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8685 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8686 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8687 InheritedConstructor(), TrailingRequiresClause); 8688 8689 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8690 // This is a C++ destructor declaration. 8691 if (DC->isRecord()) { 8692 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8693 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8694 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8695 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8696 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8697 /*isImplicitlyDeclared=*/false, ConstexprKind, 8698 TrailingRequiresClause); 8699 8700 // If the destructor needs an implicit exception specification, set it 8701 // now. FIXME: It'd be nice to be able to create the right type to start 8702 // with, but the type needs to reference the destructor declaration. 8703 if (SemaRef.getLangOpts().CPlusPlus11) 8704 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8705 8706 IsVirtualOkay = true; 8707 return NewDD; 8708 8709 } else { 8710 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8711 D.setInvalidType(); 8712 8713 // Create a FunctionDecl to satisfy the function definition parsing 8714 // code path. 8715 return FunctionDecl::Create( 8716 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8717 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8718 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8719 } 8720 8721 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8722 if (!DC->isRecord()) { 8723 SemaRef.Diag(D.getIdentifierLoc(), 8724 diag::err_conv_function_not_member); 8725 return nullptr; 8726 } 8727 8728 SemaRef.CheckConversionDeclarator(D, R, SC); 8729 if (D.isInvalidType()) 8730 return nullptr; 8731 8732 IsVirtualOkay = true; 8733 return CXXConversionDecl::Create( 8734 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8735 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8736 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8737 TrailingRequiresClause); 8738 8739 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8740 if (TrailingRequiresClause) 8741 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8742 diag::err_trailing_requires_clause_on_deduction_guide) 8743 << TrailingRequiresClause->getSourceRange(); 8744 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8745 8746 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8747 ExplicitSpecifier, NameInfo, R, TInfo, 8748 D.getEndLoc()); 8749 } else if (DC->isRecord()) { 8750 // If the name of the function is the same as the name of the record, 8751 // then this must be an invalid constructor that has a return type. 8752 // (The parser checks for a return type and makes the declarator a 8753 // constructor if it has no return type). 8754 if (Name.getAsIdentifierInfo() && 8755 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8756 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8757 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8758 << SourceRange(D.getIdentifierLoc()); 8759 return nullptr; 8760 } 8761 8762 // This is a C++ method declaration. 8763 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8764 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8765 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8766 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8767 IsVirtualOkay = !Ret->isStatic(); 8768 return Ret; 8769 } else { 8770 bool isFriend = 8771 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8772 if (!isFriend && SemaRef.CurContext->isRecord()) 8773 return nullptr; 8774 8775 // Determine whether the function was written with a 8776 // prototype. This true when: 8777 // - we're in C++ (where every function has a prototype), 8778 return FunctionDecl::Create( 8779 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8780 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8781 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8782 } 8783 } 8784 8785 enum OpenCLParamType { 8786 ValidKernelParam, 8787 PtrPtrKernelParam, 8788 PtrKernelParam, 8789 InvalidAddrSpacePtrKernelParam, 8790 InvalidKernelParam, 8791 RecordKernelParam 8792 }; 8793 8794 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8795 // Size dependent types are just typedefs to normal integer types 8796 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8797 // integers other than by their names. 8798 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8799 8800 // Remove typedefs one by one until we reach a typedef 8801 // for a size dependent type. 8802 QualType DesugaredTy = Ty; 8803 do { 8804 ArrayRef<StringRef> Names(SizeTypeNames); 8805 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8806 if (Names.end() != Match) 8807 return true; 8808 8809 Ty = DesugaredTy; 8810 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8811 } while (DesugaredTy != Ty); 8812 8813 return false; 8814 } 8815 8816 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8817 if (PT->isDependentType()) 8818 return InvalidKernelParam; 8819 8820 if (PT->isPointerType() || PT->isReferenceType()) { 8821 QualType PointeeType = PT->getPointeeType(); 8822 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8823 PointeeType.getAddressSpace() == LangAS::opencl_private || 8824 PointeeType.getAddressSpace() == LangAS::Default) 8825 return InvalidAddrSpacePtrKernelParam; 8826 8827 if (PointeeType->isPointerType()) { 8828 // This is a pointer to pointer parameter. 8829 // Recursively check inner type. 8830 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8831 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8832 ParamKind == InvalidKernelParam) 8833 return ParamKind; 8834 8835 return PtrPtrKernelParam; 8836 } 8837 8838 // C++ for OpenCL v1.0 s2.4: 8839 // Moreover the types used in parameters of the kernel functions must be: 8840 // Standard layout types for pointer parameters. The same applies to 8841 // reference if an implementation supports them in kernel parameters. 8842 if (S.getLangOpts().OpenCLCPlusPlus && 8843 !S.getOpenCLOptions().isAvailableOption( 8844 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8845 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8846 !PointeeType->isStandardLayoutType()) 8847 return InvalidKernelParam; 8848 8849 return PtrKernelParam; 8850 } 8851 8852 // OpenCL v1.2 s6.9.k: 8853 // Arguments to kernel functions in a program cannot be declared with the 8854 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8855 // uintptr_t or a struct and/or union that contain fields declared to be one 8856 // of these built-in scalar types. 8857 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8858 return InvalidKernelParam; 8859 8860 if (PT->isImageType()) 8861 return PtrKernelParam; 8862 8863 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8864 return InvalidKernelParam; 8865 8866 // OpenCL extension spec v1.2 s9.5: 8867 // This extension adds support for half scalar and vector types as built-in 8868 // types that can be used for arithmetic operations, conversions etc. 8869 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8870 PT->isHalfType()) 8871 return InvalidKernelParam; 8872 8873 // Look into an array argument to check if it has a forbidden type. 8874 if (PT->isArrayType()) { 8875 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8876 // Call ourself to check an underlying type of an array. Since the 8877 // getPointeeOrArrayElementType returns an innermost type which is not an 8878 // array, this recursive call only happens once. 8879 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8880 } 8881 8882 // C++ for OpenCL v1.0 s2.4: 8883 // Moreover the types used in parameters of the kernel functions must be: 8884 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8885 // types) for parameters passed by value; 8886 if (S.getLangOpts().OpenCLCPlusPlus && 8887 !S.getOpenCLOptions().isAvailableOption( 8888 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8889 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 8890 return InvalidKernelParam; 8891 8892 if (PT->isRecordType()) 8893 return RecordKernelParam; 8894 8895 return ValidKernelParam; 8896 } 8897 8898 static void checkIsValidOpenCLKernelParameter( 8899 Sema &S, 8900 Declarator &D, 8901 ParmVarDecl *Param, 8902 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8903 QualType PT = Param->getType(); 8904 8905 // Cache the valid types we encounter to avoid rechecking structs that are 8906 // used again 8907 if (ValidTypes.count(PT.getTypePtr())) 8908 return; 8909 8910 switch (getOpenCLKernelParameterType(S, PT)) { 8911 case PtrPtrKernelParam: 8912 // OpenCL v3.0 s6.11.a: 8913 // A kernel function argument cannot be declared as a pointer to a pointer 8914 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8915 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 8916 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8917 D.setInvalidType(); 8918 return; 8919 } 8920 8921 ValidTypes.insert(PT.getTypePtr()); 8922 return; 8923 8924 case InvalidAddrSpacePtrKernelParam: 8925 // OpenCL v1.0 s6.5: 8926 // __kernel function arguments declared to be a pointer of a type can point 8927 // to one of the following address spaces only : __global, __local or 8928 // __constant. 8929 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8930 D.setInvalidType(); 8931 return; 8932 8933 // OpenCL v1.2 s6.9.k: 8934 // Arguments to kernel functions in a program cannot be declared with the 8935 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8936 // uintptr_t or a struct and/or union that contain fields declared to be 8937 // one of these built-in scalar types. 8938 8939 case InvalidKernelParam: 8940 // OpenCL v1.2 s6.8 n: 8941 // A kernel function argument cannot be declared 8942 // of event_t type. 8943 // Do not diagnose half type since it is diagnosed as invalid argument 8944 // type for any function elsewhere. 8945 if (!PT->isHalfType()) { 8946 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8947 8948 // Explain what typedefs are involved. 8949 const TypedefType *Typedef = nullptr; 8950 while ((Typedef = PT->getAs<TypedefType>())) { 8951 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8952 // SourceLocation may be invalid for a built-in type. 8953 if (Loc.isValid()) 8954 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8955 PT = Typedef->desugar(); 8956 } 8957 } 8958 8959 D.setInvalidType(); 8960 return; 8961 8962 case PtrKernelParam: 8963 case ValidKernelParam: 8964 ValidTypes.insert(PT.getTypePtr()); 8965 return; 8966 8967 case RecordKernelParam: 8968 break; 8969 } 8970 8971 // Track nested structs we will inspect 8972 SmallVector<const Decl *, 4> VisitStack; 8973 8974 // Track where we are in the nested structs. Items will migrate from 8975 // VisitStack to HistoryStack as we do the DFS for bad field. 8976 SmallVector<const FieldDecl *, 4> HistoryStack; 8977 HistoryStack.push_back(nullptr); 8978 8979 // At this point we already handled everything except of a RecordType or 8980 // an ArrayType of a RecordType. 8981 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8982 const RecordType *RecTy = 8983 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8984 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8985 8986 VisitStack.push_back(RecTy->getDecl()); 8987 assert(VisitStack.back() && "First decl null?"); 8988 8989 do { 8990 const Decl *Next = VisitStack.pop_back_val(); 8991 if (!Next) { 8992 assert(!HistoryStack.empty()); 8993 // Found a marker, we have gone up a level 8994 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8995 ValidTypes.insert(Hist->getType().getTypePtr()); 8996 8997 continue; 8998 } 8999 9000 // Adds everything except the original parameter declaration (which is not a 9001 // field itself) to the history stack. 9002 const RecordDecl *RD; 9003 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9004 HistoryStack.push_back(Field); 9005 9006 QualType FieldTy = Field->getType(); 9007 // Other field types (known to be valid or invalid) are handled while we 9008 // walk around RecordDecl::fields(). 9009 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9010 "Unexpected type."); 9011 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9012 9013 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9014 } else { 9015 RD = cast<RecordDecl>(Next); 9016 } 9017 9018 // Add a null marker so we know when we've gone back up a level 9019 VisitStack.push_back(nullptr); 9020 9021 for (const auto *FD : RD->fields()) { 9022 QualType QT = FD->getType(); 9023 9024 if (ValidTypes.count(QT.getTypePtr())) 9025 continue; 9026 9027 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9028 if (ParamType == ValidKernelParam) 9029 continue; 9030 9031 if (ParamType == RecordKernelParam) { 9032 VisitStack.push_back(FD); 9033 continue; 9034 } 9035 9036 // OpenCL v1.2 s6.9.p: 9037 // Arguments to kernel functions that are declared to be a struct or union 9038 // do not allow OpenCL objects to be passed as elements of the struct or 9039 // union. 9040 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9041 ParamType == InvalidAddrSpacePtrKernelParam) { 9042 S.Diag(Param->getLocation(), 9043 diag::err_record_with_pointers_kernel_param) 9044 << PT->isUnionType() 9045 << PT; 9046 } else { 9047 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9048 } 9049 9050 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9051 << OrigRecDecl->getDeclName(); 9052 9053 // We have an error, now let's go back up through history and show where 9054 // the offending field came from 9055 for (ArrayRef<const FieldDecl *>::const_iterator 9056 I = HistoryStack.begin() + 1, 9057 E = HistoryStack.end(); 9058 I != E; ++I) { 9059 const FieldDecl *OuterField = *I; 9060 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9061 << OuterField->getType(); 9062 } 9063 9064 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9065 << QT->isPointerType() 9066 << QT; 9067 D.setInvalidType(); 9068 return; 9069 } 9070 } while (!VisitStack.empty()); 9071 } 9072 9073 /// Find the DeclContext in which a tag is implicitly declared if we see an 9074 /// elaborated type specifier in the specified context, and lookup finds 9075 /// nothing. 9076 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9077 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9078 DC = DC->getParent(); 9079 return DC; 9080 } 9081 9082 /// Find the Scope in which a tag is implicitly declared if we see an 9083 /// elaborated type specifier in the specified context, and lookup finds 9084 /// nothing. 9085 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9086 while (S->isClassScope() || 9087 (LangOpts.CPlusPlus && 9088 S->isFunctionPrototypeScope()) || 9089 ((S->getFlags() & Scope::DeclScope) == 0) || 9090 (S->getEntity() && S->getEntity()->isTransparentContext())) 9091 S = S->getParent(); 9092 return S; 9093 } 9094 9095 NamedDecl* 9096 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9097 TypeSourceInfo *TInfo, LookupResult &Previous, 9098 MultiTemplateParamsArg TemplateParamListsRef, 9099 bool &AddToScope) { 9100 QualType R = TInfo->getType(); 9101 9102 assert(R->isFunctionType()); 9103 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9104 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9105 9106 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9107 for (TemplateParameterList *TPL : TemplateParamListsRef) 9108 TemplateParamLists.push_back(TPL); 9109 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9110 if (!TemplateParamLists.empty() && 9111 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9112 TemplateParamLists.back() = Invented; 9113 else 9114 TemplateParamLists.push_back(Invented); 9115 } 9116 9117 // TODO: consider using NameInfo for diagnostic. 9118 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9119 DeclarationName Name = NameInfo.getName(); 9120 StorageClass SC = getFunctionStorageClass(*this, D); 9121 9122 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9123 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9124 diag::err_invalid_thread) 9125 << DeclSpec::getSpecifierName(TSCS); 9126 9127 if (D.isFirstDeclarationOfMember()) 9128 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9129 D.getIdentifierLoc()); 9130 9131 bool isFriend = false; 9132 FunctionTemplateDecl *FunctionTemplate = nullptr; 9133 bool isMemberSpecialization = false; 9134 bool isFunctionTemplateSpecialization = false; 9135 9136 bool isDependentClassScopeExplicitSpecialization = false; 9137 bool HasExplicitTemplateArgs = false; 9138 TemplateArgumentListInfo TemplateArgs; 9139 9140 bool isVirtualOkay = false; 9141 9142 DeclContext *OriginalDC = DC; 9143 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9144 9145 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9146 isVirtualOkay); 9147 if (!NewFD) return nullptr; 9148 9149 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9150 NewFD->setTopLevelDeclInObjCContainer(); 9151 9152 // Set the lexical context. If this is a function-scope declaration, or has a 9153 // C++ scope specifier, or is the object of a friend declaration, the lexical 9154 // context will be different from the semantic context. 9155 NewFD->setLexicalDeclContext(CurContext); 9156 9157 if (IsLocalExternDecl) 9158 NewFD->setLocalExternDecl(); 9159 9160 if (getLangOpts().CPlusPlus) { 9161 bool isInline = D.getDeclSpec().isInlineSpecified(); 9162 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9163 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9164 isFriend = D.getDeclSpec().isFriendSpecified(); 9165 if (isFriend && !isInline && D.isFunctionDefinition()) { 9166 // C++ [class.friend]p5 9167 // A function can be defined in a friend declaration of a 9168 // class . . . . Such a function is implicitly inline. 9169 NewFD->setImplicitlyInline(); 9170 } 9171 9172 // If this is a method defined in an __interface, and is not a constructor 9173 // or an overloaded operator, then set the pure flag (isVirtual will already 9174 // return true). 9175 if (const CXXRecordDecl *Parent = 9176 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9177 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9178 NewFD->setPure(true); 9179 9180 // C++ [class.union]p2 9181 // A union can have member functions, but not virtual functions. 9182 if (isVirtual && Parent->isUnion()) { 9183 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9184 NewFD->setInvalidDecl(); 9185 } 9186 if ((Parent->isClass() || Parent->isStruct()) && 9187 Parent->hasAttr<SYCLSpecialClassAttr>() && 9188 NewFD->getKind() == Decl::Kind::CXXMethod && 9189 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9190 if (auto *Def = Parent->getDefinition()) 9191 Def->setInitMethod(true); 9192 } 9193 } 9194 9195 SetNestedNameSpecifier(*this, NewFD, D); 9196 isMemberSpecialization = false; 9197 isFunctionTemplateSpecialization = false; 9198 if (D.isInvalidType()) 9199 NewFD->setInvalidDecl(); 9200 9201 // Match up the template parameter lists with the scope specifier, then 9202 // determine whether we have a template or a template specialization. 9203 bool Invalid = false; 9204 TemplateParameterList *TemplateParams = 9205 MatchTemplateParametersToScopeSpecifier( 9206 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9207 D.getCXXScopeSpec(), 9208 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9209 ? D.getName().TemplateId 9210 : nullptr, 9211 TemplateParamLists, isFriend, isMemberSpecialization, 9212 Invalid); 9213 if (TemplateParams) { 9214 // Check that we can declare a template here. 9215 if (CheckTemplateDeclScope(S, TemplateParams)) 9216 NewFD->setInvalidDecl(); 9217 9218 if (TemplateParams->size() > 0) { 9219 // This is a function template 9220 9221 // A destructor cannot be a template. 9222 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9223 Diag(NewFD->getLocation(), diag::err_destructor_template); 9224 NewFD->setInvalidDecl(); 9225 } 9226 9227 // If we're adding a template to a dependent context, we may need to 9228 // rebuilding some of the types used within the template parameter list, 9229 // now that we know what the current instantiation is. 9230 if (DC->isDependentContext()) { 9231 ContextRAII SavedContext(*this, DC); 9232 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9233 Invalid = true; 9234 } 9235 9236 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9237 NewFD->getLocation(), 9238 Name, TemplateParams, 9239 NewFD); 9240 FunctionTemplate->setLexicalDeclContext(CurContext); 9241 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9242 9243 // For source fidelity, store the other template param lists. 9244 if (TemplateParamLists.size() > 1) { 9245 NewFD->setTemplateParameterListsInfo(Context, 9246 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9247 .drop_back(1)); 9248 } 9249 } else { 9250 // This is a function template specialization. 9251 isFunctionTemplateSpecialization = true; 9252 // For source fidelity, store all the template param lists. 9253 if (TemplateParamLists.size() > 0) 9254 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9255 9256 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9257 if (isFriend) { 9258 // We want to remove the "template<>", found here. 9259 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9260 9261 // If we remove the template<> and the name is not a 9262 // template-id, we're actually silently creating a problem: 9263 // the friend declaration will refer to an untemplated decl, 9264 // and clearly the user wants a template specialization. So 9265 // we need to insert '<>' after the name. 9266 SourceLocation InsertLoc; 9267 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9268 InsertLoc = D.getName().getSourceRange().getEnd(); 9269 InsertLoc = getLocForEndOfToken(InsertLoc); 9270 } 9271 9272 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9273 << Name << RemoveRange 9274 << FixItHint::CreateRemoval(RemoveRange) 9275 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9276 Invalid = true; 9277 } 9278 } 9279 } else { 9280 // Check that we can declare a template here. 9281 if (!TemplateParamLists.empty() && isMemberSpecialization && 9282 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9283 NewFD->setInvalidDecl(); 9284 9285 // All template param lists were matched against the scope specifier: 9286 // this is NOT (an explicit specialization of) a template. 9287 if (TemplateParamLists.size() > 0) 9288 // For source fidelity, store all the template param lists. 9289 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9290 } 9291 9292 if (Invalid) { 9293 NewFD->setInvalidDecl(); 9294 if (FunctionTemplate) 9295 FunctionTemplate->setInvalidDecl(); 9296 } 9297 9298 // C++ [dcl.fct.spec]p5: 9299 // The virtual specifier shall only be used in declarations of 9300 // nonstatic class member functions that appear within a 9301 // member-specification of a class declaration; see 10.3. 9302 // 9303 if (isVirtual && !NewFD->isInvalidDecl()) { 9304 if (!isVirtualOkay) { 9305 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9306 diag::err_virtual_non_function); 9307 } else if (!CurContext->isRecord()) { 9308 // 'virtual' was specified outside of the class. 9309 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9310 diag::err_virtual_out_of_class) 9311 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9312 } else if (NewFD->getDescribedFunctionTemplate()) { 9313 // C++ [temp.mem]p3: 9314 // A member function template shall not be virtual. 9315 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9316 diag::err_virtual_member_function_template) 9317 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9318 } else { 9319 // Okay: Add virtual to the method. 9320 NewFD->setVirtualAsWritten(true); 9321 } 9322 9323 if (getLangOpts().CPlusPlus14 && 9324 NewFD->getReturnType()->isUndeducedType()) 9325 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9326 } 9327 9328 if (getLangOpts().CPlusPlus14 && 9329 (NewFD->isDependentContext() || 9330 (isFriend && CurContext->isDependentContext())) && 9331 NewFD->getReturnType()->isUndeducedType()) { 9332 // If the function template is referenced directly (for instance, as a 9333 // member of the current instantiation), pretend it has a dependent type. 9334 // This is not really justified by the standard, but is the only sane 9335 // thing to do. 9336 // FIXME: For a friend function, we have not marked the function as being 9337 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9338 const FunctionProtoType *FPT = 9339 NewFD->getType()->castAs<FunctionProtoType>(); 9340 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9341 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9342 FPT->getExtProtoInfo())); 9343 } 9344 9345 // C++ [dcl.fct.spec]p3: 9346 // The inline specifier shall not appear on a block scope function 9347 // declaration. 9348 if (isInline && !NewFD->isInvalidDecl()) { 9349 if (CurContext->isFunctionOrMethod()) { 9350 // 'inline' is not allowed on block scope function declaration. 9351 Diag(D.getDeclSpec().getInlineSpecLoc(), 9352 diag::err_inline_declaration_block_scope) << Name 9353 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9354 } 9355 } 9356 9357 // C++ [dcl.fct.spec]p6: 9358 // The explicit specifier shall be used only in the declaration of a 9359 // constructor or conversion function within its class definition; 9360 // see 12.3.1 and 12.3.2. 9361 if (hasExplicit && !NewFD->isInvalidDecl() && 9362 !isa<CXXDeductionGuideDecl>(NewFD)) { 9363 if (!CurContext->isRecord()) { 9364 // 'explicit' was specified outside of the class. 9365 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9366 diag::err_explicit_out_of_class) 9367 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9368 } else if (!isa<CXXConstructorDecl>(NewFD) && 9369 !isa<CXXConversionDecl>(NewFD)) { 9370 // 'explicit' was specified on a function that wasn't a constructor 9371 // or conversion function. 9372 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9373 diag::err_explicit_non_ctor_or_conv_function) 9374 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9375 } 9376 } 9377 9378 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9379 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9380 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9381 // are implicitly inline. 9382 NewFD->setImplicitlyInline(); 9383 9384 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9385 // be either constructors or to return a literal type. Therefore, 9386 // destructors cannot be declared constexpr. 9387 if (isa<CXXDestructorDecl>(NewFD) && 9388 (!getLangOpts().CPlusPlus20 || 9389 ConstexprKind == ConstexprSpecKind::Consteval)) { 9390 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9391 << static_cast<int>(ConstexprKind); 9392 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9393 ? ConstexprSpecKind::Unspecified 9394 : ConstexprSpecKind::Constexpr); 9395 } 9396 // C++20 [dcl.constexpr]p2: An allocation function, or a 9397 // deallocation function shall not be declared with the consteval 9398 // specifier. 9399 if (ConstexprKind == ConstexprSpecKind::Consteval && 9400 (NewFD->getOverloadedOperator() == OO_New || 9401 NewFD->getOverloadedOperator() == OO_Array_New || 9402 NewFD->getOverloadedOperator() == OO_Delete || 9403 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9404 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9405 diag::err_invalid_consteval_decl_kind) 9406 << NewFD; 9407 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9408 } 9409 } 9410 9411 // If __module_private__ was specified, mark the function accordingly. 9412 if (D.getDeclSpec().isModulePrivateSpecified()) { 9413 if (isFunctionTemplateSpecialization) { 9414 SourceLocation ModulePrivateLoc 9415 = D.getDeclSpec().getModulePrivateSpecLoc(); 9416 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9417 << 0 9418 << FixItHint::CreateRemoval(ModulePrivateLoc); 9419 } else { 9420 NewFD->setModulePrivate(); 9421 if (FunctionTemplate) 9422 FunctionTemplate->setModulePrivate(); 9423 } 9424 } 9425 9426 if (isFriend) { 9427 if (FunctionTemplate) { 9428 FunctionTemplate->setObjectOfFriendDecl(); 9429 FunctionTemplate->setAccess(AS_public); 9430 } 9431 NewFD->setObjectOfFriendDecl(); 9432 NewFD->setAccess(AS_public); 9433 } 9434 9435 // If a function is defined as defaulted or deleted, mark it as such now. 9436 // We'll do the relevant checks on defaulted / deleted functions later. 9437 switch (D.getFunctionDefinitionKind()) { 9438 case FunctionDefinitionKind::Declaration: 9439 case FunctionDefinitionKind::Definition: 9440 break; 9441 9442 case FunctionDefinitionKind::Defaulted: 9443 NewFD->setDefaulted(); 9444 break; 9445 9446 case FunctionDefinitionKind::Deleted: 9447 NewFD->setDeletedAsWritten(); 9448 break; 9449 } 9450 9451 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9452 D.isFunctionDefinition()) { 9453 // C++ [class.mfct]p2: 9454 // A member function may be defined (8.4) in its class definition, in 9455 // which case it is an inline member function (7.1.2) 9456 NewFD->setImplicitlyInline(); 9457 } 9458 9459 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9460 !CurContext->isRecord()) { 9461 // C++ [class.static]p1: 9462 // A data or function member of a class may be declared static 9463 // in a class definition, in which case it is a static member of 9464 // the class. 9465 9466 // Complain about the 'static' specifier if it's on an out-of-line 9467 // member function definition. 9468 9469 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9470 // member function template declaration and class member template 9471 // declaration (MSVC versions before 2015), warn about this. 9472 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9473 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9474 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9475 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9476 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9477 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9478 } 9479 9480 // C++11 [except.spec]p15: 9481 // A deallocation function with no exception-specification is treated 9482 // as if it were specified with noexcept(true). 9483 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9484 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9485 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9486 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9487 NewFD->setType(Context.getFunctionType( 9488 FPT->getReturnType(), FPT->getParamTypes(), 9489 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9490 } 9491 9492 // Filter out previous declarations that don't match the scope. 9493 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9494 D.getCXXScopeSpec().isNotEmpty() || 9495 isMemberSpecialization || 9496 isFunctionTemplateSpecialization); 9497 9498 // Handle GNU asm-label extension (encoded as an attribute). 9499 if (Expr *E = (Expr*) D.getAsmLabel()) { 9500 // The parser guarantees this is a string. 9501 StringLiteral *SE = cast<StringLiteral>(E); 9502 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9503 /*IsLiteralLabel=*/true, 9504 SE->getStrTokenLoc(0))); 9505 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9506 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9507 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9508 if (I != ExtnameUndeclaredIdentifiers.end()) { 9509 if (isDeclExternC(NewFD)) { 9510 NewFD->addAttr(I->second); 9511 ExtnameUndeclaredIdentifiers.erase(I); 9512 } else 9513 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9514 << /*Variable*/0 << NewFD; 9515 } 9516 } 9517 9518 // Copy the parameter declarations from the declarator D to the function 9519 // declaration NewFD, if they are available. First scavenge them into Params. 9520 SmallVector<ParmVarDecl*, 16> Params; 9521 unsigned FTIIdx; 9522 if (D.isFunctionDeclarator(FTIIdx)) { 9523 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9524 9525 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9526 // function that takes no arguments, not a function that takes a 9527 // single void argument. 9528 // We let through "const void" here because Sema::GetTypeForDeclarator 9529 // already checks for that case. 9530 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9531 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9532 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9533 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9534 Param->setDeclContext(NewFD); 9535 Params.push_back(Param); 9536 9537 if (Param->isInvalidDecl()) 9538 NewFD->setInvalidDecl(); 9539 } 9540 } 9541 9542 if (!getLangOpts().CPlusPlus) { 9543 // In C, find all the tag declarations from the prototype and move them 9544 // into the function DeclContext. Remove them from the surrounding tag 9545 // injection context of the function, which is typically but not always 9546 // the TU. 9547 DeclContext *PrototypeTagContext = 9548 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9549 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9550 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9551 9552 // We don't want to reparent enumerators. Look at their parent enum 9553 // instead. 9554 if (!TD) { 9555 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9556 TD = cast<EnumDecl>(ECD->getDeclContext()); 9557 } 9558 if (!TD) 9559 continue; 9560 DeclContext *TagDC = TD->getLexicalDeclContext(); 9561 if (!TagDC->containsDecl(TD)) 9562 continue; 9563 TagDC->removeDecl(TD); 9564 TD->setDeclContext(NewFD); 9565 NewFD->addDecl(TD); 9566 9567 // Preserve the lexical DeclContext if it is not the surrounding tag 9568 // injection context of the FD. In this example, the semantic context of 9569 // E will be f and the lexical context will be S, while both the 9570 // semantic and lexical contexts of S will be f: 9571 // void f(struct S { enum E { a } f; } s); 9572 if (TagDC != PrototypeTagContext) 9573 TD->setLexicalDeclContext(TagDC); 9574 } 9575 } 9576 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9577 // When we're declaring a function with a typedef, typeof, etc as in the 9578 // following example, we'll need to synthesize (unnamed) 9579 // parameters for use in the declaration. 9580 // 9581 // @code 9582 // typedef void fn(int); 9583 // fn f; 9584 // @endcode 9585 9586 // Synthesize a parameter for each argument type. 9587 for (const auto &AI : FT->param_types()) { 9588 ParmVarDecl *Param = 9589 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9590 Param->setScopeInfo(0, Params.size()); 9591 Params.push_back(Param); 9592 } 9593 } else { 9594 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9595 "Should not need args for typedef of non-prototype fn"); 9596 } 9597 9598 // Finally, we know we have the right number of parameters, install them. 9599 NewFD->setParams(Params); 9600 9601 if (D.getDeclSpec().isNoreturnSpecified()) 9602 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9603 D.getDeclSpec().getNoreturnSpecLoc(), 9604 AttributeCommonInfo::AS_Keyword)); 9605 9606 // Functions returning a variably modified type violate C99 6.7.5.2p2 9607 // because all functions have linkage. 9608 if (!NewFD->isInvalidDecl() && 9609 NewFD->getReturnType()->isVariablyModifiedType()) { 9610 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9611 NewFD->setInvalidDecl(); 9612 } 9613 9614 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9615 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9616 !NewFD->hasAttr<SectionAttr>()) 9617 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9618 Context, PragmaClangTextSection.SectionName, 9619 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9620 9621 // Apply an implicit SectionAttr if #pragma code_seg is active. 9622 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9623 !NewFD->hasAttr<SectionAttr>()) { 9624 NewFD->addAttr(SectionAttr::CreateImplicit( 9625 Context, CodeSegStack.CurrentValue->getString(), 9626 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9627 SectionAttr::Declspec_allocate)); 9628 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9629 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9630 ASTContext::PSF_Read, 9631 NewFD)) 9632 NewFD->dropAttr<SectionAttr>(); 9633 } 9634 9635 // Apply an implicit CodeSegAttr from class declspec or 9636 // apply an implicit SectionAttr from #pragma code_seg if active. 9637 if (!NewFD->hasAttr<CodeSegAttr>()) { 9638 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9639 D.isFunctionDefinition())) { 9640 NewFD->addAttr(SAttr); 9641 } 9642 } 9643 9644 // Handle attributes. 9645 ProcessDeclAttributes(S, NewFD, D); 9646 9647 if (getLangOpts().OpenCL) { 9648 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9649 // type declaration will generate a compilation error. 9650 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9651 if (AddressSpace != LangAS::Default) { 9652 Diag(NewFD->getLocation(), 9653 diag::err_opencl_return_value_with_address_space); 9654 NewFD->setInvalidDecl(); 9655 } 9656 } 9657 9658 if (!getLangOpts().CPlusPlus) { 9659 // Perform semantic checking on the function declaration. 9660 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9661 CheckMain(NewFD, D.getDeclSpec()); 9662 9663 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9664 CheckMSVCRTEntryPoint(NewFD); 9665 9666 if (!NewFD->isInvalidDecl()) 9667 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9668 isMemberSpecialization)); 9669 else if (!Previous.empty()) 9670 // Recover gracefully from an invalid redeclaration. 9671 D.setRedeclaration(true); 9672 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9673 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9674 "previous declaration set still overloaded"); 9675 9676 // Diagnose no-prototype function declarations with calling conventions that 9677 // don't support variadic calls. Only do this in C and do it after merging 9678 // possibly prototyped redeclarations. 9679 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9680 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9681 CallingConv CC = FT->getExtInfo().getCC(); 9682 if (!supportsVariadicCall(CC)) { 9683 // Windows system headers sometimes accidentally use stdcall without 9684 // (void) parameters, so we relax this to a warning. 9685 int DiagID = 9686 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9687 Diag(NewFD->getLocation(), DiagID) 9688 << FunctionType::getNameForCallConv(CC); 9689 } 9690 } 9691 9692 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9693 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9694 checkNonTrivialCUnion(NewFD->getReturnType(), 9695 NewFD->getReturnTypeSourceRange().getBegin(), 9696 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9697 } else { 9698 // C++11 [replacement.functions]p3: 9699 // The program's definitions shall not be specified as inline. 9700 // 9701 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9702 // 9703 // Suppress the diagnostic if the function is __attribute__((used)), since 9704 // that forces an external definition to be emitted. 9705 if (D.getDeclSpec().isInlineSpecified() && 9706 NewFD->isReplaceableGlobalAllocationFunction() && 9707 !NewFD->hasAttr<UsedAttr>()) 9708 Diag(D.getDeclSpec().getInlineSpecLoc(), 9709 diag::ext_operator_new_delete_declared_inline) 9710 << NewFD->getDeclName(); 9711 9712 // If the declarator is a template-id, translate the parser's template 9713 // argument list into our AST format. 9714 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9715 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9716 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9717 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9718 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9719 TemplateId->NumArgs); 9720 translateTemplateArguments(TemplateArgsPtr, 9721 TemplateArgs); 9722 9723 HasExplicitTemplateArgs = true; 9724 9725 if (NewFD->isInvalidDecl()) { 9726 HasExplicitTemplateArgs = false; 9727 } else if (FunctionTemplate) { 9728 // Function template with explicit template arguments. 9729 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9730 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9731 9732 HasExplicitTemplateArgs = false; 9733 } else { 9734 assert((isFunctionTemplateSpecialization || 9735 D.getDeclSpec().isFriendSpecified()) && 9736 "should have a 'template<>' for this decl"); 9737 // "friend void foo<>(int);" is an implicit specialization decl. 9738 isFunctionTemplateSpecialization = true; 9739 } 9740 } else if (isFriend && isFunctionTemplateSpecialization) { 9741 // This combination is only possible in a recovery case; the user 9742 // wrote something like: 9743 // template <> friend void foo(int); 9744 // which we're recovering from as if the user had written: 9745 // friend void foo<>(int); 9746 // Go ahead and fake up a template id. 9747 HasExplicitTemplateArgs = true; 9748 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9749 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9750 } 9751 9752 // We do not add HD attributes to specializations here because 9753 // they may have different constexpr-ness compared to their 9754 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9755 // may end up with different effective targets. Instead, a 9756 // specialization inherits its target attributes from its template 9757 // in the CheckFunctionTemplateSpecialization() call below. 9758 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9759 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9760 9761 // If it's a friend (and only if it's a friend), it's possible 9762 // that either the specialized function type or the specialized 9763 // template is dependent, and therefore matching will fail. In 9764 // this case, don't check the specialization yet. 9765 if (isFunctionTemplateSpecialization && isFriend && 9766 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9767 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9768 TemplateArgs.arguments()))) { 9769 assert(HasExplicitTemplateArgs && 9770 "friend function specialization without template args"); 9771 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9772 Previous)) 9773 NewFD->setInvalidDecl(); 9774 } else if (isFunctionTemplateSpecialization) { 9775 if (CurContext->isDependentContext() && CurContext->isRecord() 9776 && !isFriend) { 9777 isDependentClassScopeExplicitSpecialization = true; 9778 } else if (!NewFD->isInvalidDecl() && 9779 CheckFunctionTemplateSpecialization( 9780 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9781 Previous)) 9782 NewFD->setInvalidDecl(); 9783 9784 // C++ [dcl.stc]p1: 9785 // A storage-class-specifier shall not be specified in an explicit 9786 // specialization (14.7.3) 9787 FunctionTemplateSpecializationInfo *Info = 9788 NewFD->getTemplateSpecializationInfo(); 9789 if (Info && SC != SC_None) { 9790 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9791 Diag(NewFD->getLocation(), 9792 diag::err_explicit_specialization_inconsistent_storage_class) 9793 << SC 9794 << FixItHint::CreateRemoval( 9795 D.getDeclSpec().getStorageClassSpecLoc()); 9796 9797 else 9798 Diag(NewFD->getLocation(), 9799 diag::ext_explicit_specialization_storage_class) 9800 << FixItHint::CreateRemoval( 9801 D.getDeclSpec().getStorageClassSpecLoc()); 9802 } 9803 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9804 if (CheckMemberSpecialization(NewFD, Previous)) 9805 NewFD->setInvalidDecl(); 9806 } 9807 9808 // Perform semantic checking on the function declaration. 9809 if (!isDependentClassScopeExplicitSpecialization) { 9810 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9811 CheckMain(NewFD, D.getDeclSpec()); 9812 9813 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9814 CheckMSVCRTEntryPoint(NewFD); 9815 9816 if (!NewFD->isInvalidDecl()) 9817 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9818 isMemberSpecialization)); 9819 else if (!Previous.empty()) 9820 // Recover gracefully from an invalid redeclaration. 9821 D.setRedeclaration(true); 9822 } 9823 9824 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9825 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9826 "previous declaration set still overloaded"); 9827 9828 NamedDecl *PrincipalDecl = (FunctionTemplate 9829 ? cast<NamedDecl>(FunctionTemplate) 9830 : NewFD); 9831 9832 if (isFriend && NewFD->getPreviousDecl()) { 9833 AccessSpecifier Access = AS_public; 9834 if (!NewFD->isInvalidDecl()) 9835 Access = NewFD->getPreviousDecl()->getAccess(); 9836 9837 NewFD->setAccess(Access); 9838 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9839 } 9840 9841 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9842 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9843 PrincipalDecl->setNonMemberOperator(); 9844 9845 // If we have a function template, check the template parameter 9846 // list. This will check and merge default template arguments. 9847 if (FunctionTemplate) { 9848 FunctionTemplateDecl *PrevTemplate = 9849 FunctionTemplate->getPreviousDecl(); 9850 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9851 PrevTemplate ? PrevTemplate->getTemplateParameters() 9852 : nullptr, 9853 D.getDeclSpec().isFriendSpecified() 9854 ? (D.isFunctionDefinition() 9855 ? TPC_FriendFunctionTemplateDefinition 9856 : TPC_FriendFunctionTemplate) 9857 : (D.getCXXScopeSpec().isSet() && 9858 DC && DC->isRecord() && 9859 DC->isDependentContext()) 9860 ? TPC_ClassTemplateMember 9861 : TPC_FunctionTemplate); 9862 } 9863 9864 if (NewFD->isInvalidDecl()) { 9865 // Ignore all the rest of this. 9866 } else if (!D.isRedeclaration()) { 9867 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9868 AddToScope }; 9869 // Fake up an access specifier if it's supposed to be a class member. 9870 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9871 NewFD->setAccess(AS_public); 9872 9873 // Qualified decls generally require a previous declaration. 9874 if (D.getCXXScopeSpec().isSet()) { 9875 // ...with the major exception of templated-scope or 9876 // dependent-scope friend declarations. 9877 9878 // TODO: we currently also suppress this check in dependent 9879 // contexts because (1) the parameter depth will be off when 9880 // matching friend templates and (2) we might actually be 9881 // selecting a friend based on a dependent factor. But there 9882 // are situations where these conditions don't apply and we 9883 // can actually do this check immediately. 9884 // 9885 // Unless the scope is dependent, it's always an error if qualified 9886 // redeclaration lookup found nothing at all. Diagnose that now; 9887 // nothing will diagnose that error later. 9888 if (isFriend && 9889 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9890 (!Previous.empty() && CurContext->isDependentContext()))) { 9891 // ignore these 9892 } else if (NewFD->isCPUDispatchMultiVersion() || 9893 NewFD->isCPUSpecificMultiVersion()) { 9894 // ignore this, we allow the redeclaration behavior here to create new 9895 // versions of the function. 9896 } else { 9897 // The user tried to provide an out-of-line definition for a 9898 // function that is a member of a class or namespace, but there 9899 // was no such member function declared (C++ [class.mfct]p2, 9900 // C++ [namespace.memdef]p2). For example: 9901 // 9902 // class X { 9903 // void f() const; 9904 // }; 9905 // 9906 // void X::f() { } // ill-formed 9907 // 9908 // Complain about this problem, and attempt to suggest close 9909 // matches (e.g., those that differ only in cv-qualifiers and 9910 // whether the parameter types are references). 9911 9912 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9913 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9914 AddToScope = ExtraArgs.AddToScope; 9915 return Result; 9916 } 9917 } 9918 9919 // Unqualified local friend declarations are required to resolve 9920 // to something. 9921 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9922 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9923 *this, Previous, NewFD, ExtraArgs, true, S)) { 9924 AddToScope = ExtraArgs.AddToScope; 9925 return Result; 9926 } 9927 } 9928 } else if (!D.isFunctionDefinition() && 9929 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9930 !isFriend && !isFunctionTemplateSpecialization && 9931 !isMemberSpecialization) { 9932 // An out-of-line member function declaration must also be a 9933 // definition (C++ [class.mfct]p2). 9934 // Note that this is not the case for explicit specializations of 9935 // function templates or member functions of class templates, per 9936 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9937 // extension for compatibility with old SWIG code which likes to 9938 // generate them. 9939 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9940 << D.getCXXScopeSpec().getRange(); 9941 } 9942 } 9943 9944 // If this is the first declaration of a library builtin function, add 9945 // attributes as appropriate. 9946 if (!D.isRedeclaration() && 9947 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9948 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9949 if (unsigned BuiltinID = II->getBuiltinID()) { 9950 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9951 // Validate the type matches unless this builtin is specified as 9952 // matching regardless of its declared type. 9953 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9954 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9955 } else { 9956 ASTContext::GetBuiltinTypeError Error; 9957 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9958 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9959 9960 if (!Error && !BuiltinType.isNull() && 9961 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9962 NewFD->getType(), BuiltinType)) 9963 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9964 } 9965 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9966 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9967 // FIXME: We should consider this a builtin only in the std namespace. 9968 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9969 } 9970 } 9971 } 9972 } 9973 9974 ProcessPragmaWeak(S, NewFD); 9975 checkAttributesAfterMerging(*this, *NewFD); 9976 9977 AddKnownFunctionAttributes(NewFD); 9978 9979 if (NewFD->hasAttr<OverloadableAttr>() && 9980 !NewFD->getType()->getAs<FunctionProtoType>()) { 9981 Diag(NewFD->getLocation(), 9982 diag::err_attribute_overloadable_no_prototype) 9983 << NewFD; 9984 9985 // Turn this into a variadic function with no parameters. 9986 const auto *FT = NewFD->getType()->castAs<FunctionType>(); 9987 FunctionProtoType::ExtProtoInfo EPI( 9988 Context.getDefaultCallingConvention(true, false)); 9989 EPI.Variadic = true; 9990 EPI.ExtInfo = FT->getExtInfo(); 9991 9992 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9993 NewFD->setType(R); 9994 } 9995 9996 // If there's a #pragma GCC visibility in scope, and this isn't a class 9997 // member, set the visibility of this function. 9998 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9999 AddPushedVisibilityAttribute(NewFD); 10000 10001 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10002 // marking the function. 10003 AddCFAuditedAttribute(NewFD); 10004 10005 // If this is a function definition, check if we have to apply optnone due to 10006 // a pragma. 10007 if(D.isFunctionDefinition()) 10008 AddRangeBasedOptnone(NewFD); 10009 10010 // If this is the first declaration of an extern C variable, update 10011 // the map of such variables. 10012 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10013 isIncompleteDeclExternC(*this, NewFD)) 10014 RegisterLocallyScopedExternCDecl(NewFD, S); 10015 10016 // Set this FunctionDecl's range up to the right paren. 10017 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10018 10019 if (D.isRedeclaration() && !Previous.empty()) { 10020 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10021 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10022 isMemberSpecialization || 10023 isFunctionTemplateSpecialization, 10024 D.isFunctionDefinition()); 10025 } 10026 10027 if (getLangOpts().CUDA) { 10028 IdentifierInfo *II = NewFD->getIdentifier(); 10029 if (II && II->isStr(getCudaConfigureFuncName()) && 10030 !NewFD->isInvalidDecl() && 10031 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10032 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10033 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10034 << getCudaConfigureFuncName(); 10035 Context.setcudaConfigureCallDecl(NewFD); 10036 } 10037 10038 // Variadic functions, other than a *declaration* of printf, are not allowed 10039 // in device-side CUDA code, unless someone passed 10040 // -fcuda-allow-variadic-functions. 10041 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10042 (NewFD->hasAttr<CUDADeviceAttr>() || 10043 NewFD->hasAttr<CUDAGlobalAttr>()) && 10044 !(II && II->isStr("printf") && NewFD->isExternC() && 10045 !D.isFunctionDefinition())) { 10046 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10047 } 10048 } 10049 10050 MarkUnusedFileScopedDecl(NewFD); 10051 10052 10053 10054 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10055 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10056 if (SC == SC_Static) { 10057 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10058 D.setInvalidType(); 10059 } 10060 10061 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10062 if (!NewFD->getReturnType()->isVoidType()) { 10063 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10064 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10065 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10066 : FixItHint()); 10067 D.setInvalidType(); 10068 } 10069 10070 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10071 for (auto Param : NewFD->parameters()) 10072 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10073 10074 if (getLangOpts().OpenCLCPlusPlus) { 10075 if (DC->isRecord()) { 10076 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10077 D.setInvalidType(); 10078 } 10079 if (FunctionTemplate) { 10080 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10081 D.setInvalidType(); 10082 } 10083 } 10084 } 10085 10086 if (getLangOpts().CPlusPlus) { 10087 if (FunctionTemplate) { 10088 if (NewFD->isInvalidDecl()) 10089 FunctionTemplate->setInvalidDecl(); 10090 return FunctionTemplate; 10091 } 10092 10093 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10094 CompleteMemberSpecialization(NewFD, Previous); 10095 } 10096 10097 for (const ParmVarDecl *Param : NewFD->parameters()) { 10098 QualType PT = Param->getType(); 10099 10100 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10101 // types. 10102 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10103 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10104 QualType ElemTy = PipeTy->getElementType(); 10105 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10106 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10107 D.setInvalidType(); 10108 } 10109 } 10110 } 10111 } 10112 10113 // Here we have an function template explicit specialization at class scope. 10114 // The actual specialization will be postponed to template instatiation 10115 // time via the ClassScopeFunctionSpecializationDecl node. 10116 if (isDependentClassScopeExplicitSpecialization) { 10117 ClassScopeFunctionSpecializationDecl *NewSpec = 10118 ClassScopeFunctionSpecializationDecl::Create( 10119 Context, CurContext, NewFD->getLocation(), 10120 cast<CXXMethodDecl>(NewFD), 10121 HasExplicitTemplateArgs, TemplateArgs); 10122 CurContext->addDecl(NewSpec); 10123 AddToScope = false; 10124 } 10125 10126 // Diagnose availability attributes. Availability cannot be used on functions 10127 // that are run during load/unload. 10128 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10129 if (NewFD->hasAttr<ConstructorAttr>()) { 10130 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10131 << 1; 10132 NewFD->dropAttr<AvailabilityAttr>(); 10133 } 10134 if (NewFD->hasAttr<DestructorAttr>()) { 10135 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10136 << 2; 10137 NewFD->dropAttr<AvailabilityAttr>(); 10138 } 10139 } 10140 10141 // Diagnose no_builtin attribute on function declaration that are not a 10142 // definition. 10143 // FIXME: We should really be doing this in 10144 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10145 // the FunctionDecl and at this point of the code 10146 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10147 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10148 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10149 switch (D.getFunctionDefinitionKind()) { 10150 case FunctionDefinitionKind::Defaulted: 10151 case FunctionDefinitionKind::Deleted: 10152 Diag(NBA->getLocation(), 10153 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10154 << NBA->getSpelling(); 10155 break; 10156 case FunctionDefinitionKind::Declaration: 10157 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10158 << NBA->getSpelling(); 10159 break; 10160 case FunctionDefinitionKind::Definition: 10161 break; 10162 } 10163 10164 return NewFD; 10165 } 10166 10167 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10168 /// when __declspec(code_seg) "is applied to a class, all member functions of 10169 /// the class and nested classes -- this includes compiler-generated special 10170 /// member functions -- are put in the specified segment." 10171 /// The actual behavior is a little more complicated. The Microsoft compiler 10172 /// won't check outer classes if there is an active value from #pragma code_seg. 10173 /// The CodeSeg is always applied from the direct parent but only from outer 10174 /// classes when the #pragma code_seg stack is empty. See: 10175 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10176 /// available since MS has removed the page. 10177 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10178 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10179 if (!Method) 10180 return nullptr; 10181 const CXXRecordDecl *Parent = Method->getParent(); 10182 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10183 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10184 NewAttr->setImplicit(true); 10185 return NewAttr; 10186 } 10187 10188 // The Microsoft compiler won't check outer classes for the CodeSeg 10189 // when the #pragma code_seg stack is active. 10190 if (S.CodeSegStack.CurrentValue) 10191 return nullptr; 10192 10193 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10194 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10195 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10196 NewAttr->setImplicit(true); 10197 return NewAttr; 10198 } 10199 } 10200 return nullptr; 10201 } 10202 10203 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10204 /// containing class. Otherwise it will return implicit SectionAttr if the 10205 /// function is a definition and there is an active value on CodeSegStack 10206 /// (from the current #pragma code-seg value). 10207 /// 10208 /// \param FD Function being declared. 10209 /// \param IsDefinition Whether it is a definition or just a declarartion. 10210 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10211 /// nullptr if no attribute should be added. 10212 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10213 bool IsDefinition) { 10214 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10215 return A; 10216 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10217 CodeSegStack.CurrentValue) 10218 return SectionAttr::CreateImplicit( 10219 getASTContext(), CodeSegStack.CurrentValue->getString(), 10220 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10221 SectionAttr::Declspec_allocate); 10222 return nullptr; 10223 } 10224 10225 /// Determines if we can perform a correct type check for \p D as a 10226 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10227 /// best-effort check. 10228 /// 10229 /// \param NewD The new declaration. 10230 /// \param OldD The old declaration. 10231 /// \param NewT The portion of the type of the new declaration to check. 10232 /// \param OldT The portion of the type of the old declaration to check. 10233 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10234 QualType NewT, QualType OldT) { 10235 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10236 return true; 10237 10238 // For dependently-typed local extern declarations and friends, we can't 10239 // perform a correct type check in general until instantiation: 10240 // 10241 // int f(); 10242 // template<typename T> void g() { T f(); } 10243 // 10244 // (valid if g() is only instantiated with T = int). 10245 if (NewT->isDependentType() && 10246 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10247 return false; 10248 10249 // Similarly, if the previous declaration was a dependent local extern 10250 // declaration, we don't really know its type yet. 10251 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10252 return false; 10253 10254 return true; 10255 } 10256 10257 /// Checks if the new declaration declared in dependent context must be 10258 /// put in the same redeclaration chain as the specified declaration. 10259 /// 10260 /// \param D Declaration that is checked. 10261 /// \param PrevDecl Previous declaration found with proper lookup method for the 10262 /// same declaration name. 10263 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10264 /// belongs to. 10265 /// 10266 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10267 if (!D->getLexicalDeclContext()->isDependentContext()) 10268 return true; 10269 10270 // Don't chain dependent friend function definitions until instantiation, to 10271 // permit cases like 10272 // 10273 // void func(); 10274 // template<typename T> class C1 { friend void func() {} }; 10275 // template<typename T> class C2 { friend void func() {} }; 10276 // 10277 // ... which is valid if only one of C1 and C2 is ever instantiated. 10278 // 10279 // FIXME: This need only apply to function definitions. For now, we proxy 10280 // this by checking for a file-scope function. We do not want this to apply 10281 // to friend declarations nominating member functions, because that gets in 10282 // the way of access checks. 10283 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10284 return false; 10285 10286 auto *VD = dyn_cast<ValueDecl>(D); 10287 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10288 return !VD || !PrevVD || 10289 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10290 PrevVD->getType()); 10291 } 10292 10293 /// Check the target attribute of the function for MultiVersion 10294 /// validity. 10295 /// 10296 /// Returns true if there was an error, false otherwise. 10297 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10298 const auto *TA = FD->getAttr<TargetAttr>(); 10299 assert(TA && "MultiVersion Candidate requires a target attribute"); 10300 ParsedTargetAttr ParseInfo = TA->parse(); 10301 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10302 enum ErrType { Feature = 0, Architecture = 1 }; 10303 10304 if (!ParseInfo.Architecture.empty() && 10305 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10306 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10307 << Architecture << ParseInfo.Architecture; 10308 return true; 10309 } 10310 10311 for (const auto &Feat : ParseInfo.Features) { 10312 auto BareFeat = StringRef{Feat}.substr(1); 10313 if (Feat[0] == '-') { 10314 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10315 << Feature << ("no-" + BareFeat).str(); 10316 return true; 10317 } 10318 10319 if (!TargetInfo.validateCpuSupports(BareFeat) || 10320 !TargetInfo.isValidFeatureName(BareFeat)) { 10321 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10322 << Feature << BareFeat; 10323 return true; 10324 } 10325 } 10326 return false; 10327 } 10328 10329 // Provide a white-list of attributes that are allowed to be combined with 10330 // multiversion functions. 10331 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10332 MultiVersionKind MVType) { 10333 // Note: this list/diagnosis must match the list in 10334 // checkMultiversionAttributesAllSame. 10335 switch (Kind) { 10336 default: 10337 return false; 10338 case attr::Used: 10339 return MVType == MultiVersionKind::Target; 10340 case attr::NonNull: 10341 case attr::NoThrow: 10342 return true; 10343 } 10344 } 10345 10346 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10347 const FunctionDecl *FD, 10348 const FunctionDecl *CausedFD, 10349 MultiVersionKind MVType) { 10350 const auto Diagnose = [FD, CausedFD, MVType](Sema &S, const Attr *A) { 10351 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10352 << static_cast<unsigned>(MVType) << A; 10353 if (CausedFD) 10354 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10355 return true; 10356 }; 10357 10358 for (const Attr *A : FD->attrs()) { 10359 switch (A->getKind()) { 10360 case attr::CPUDispatch: 10361 case attr::CPUSpecific: 10362 if (MVType != MultiVersionKind::CPUDispatch && 10363 MVType != MultiVersionKind::CPUSpecific) 10364 return Diagnose(S, A); 10365 break; 10366 case attr::Target: 10367 if (MVType != MultiVersionKind::Target) 10368 return Diagnose(S, A); 10369 break; 10370 case attr::TargetClones: 10371 if (MVType != MultiVersionKind::TargetClones) 10372 return Diagnose(S, A); 10373 break; 10374 default: 10375 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10376 return Diagnose(S, A); 10377 break; 10378 } 10379 } 10380 return false; 10381 } 10382 10383 bool Sema::areMultiversionVariantFunctionsCompatible( 10384 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10385 const PartialDiagnostic &NoProtoDiagID, 10386 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10387 const PartialDiagnosticAt &NoSupportDiagIDAt, 10388 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10389 bool ConstexprSupported, bool CLinkageMayDiffer) { 10390 enum DoesntSupport { 10391 FuncTemplates = 0, 10392 VirtFuncs = 1, 10393 DeducedReturn = 2, 10394 Constructors = 3, 10395 Destructors = 4, 10396 DeletedFuncs = 5, 10397 DefaultedFuncs = 6, 10398 ConstexprFuncs = 7, 10399 ConstevalFuncs = 8, 10400 Lambda = 9, 10401 }; 10402 enum Different { 10403 CallingConv = 0, 10404 ReturnType = 1, 10405 ConstexprSpec = 2, 10406 InlineSpec = 3, 10407 Linkage = 4, 10408 LanguageLinkage = 5, 10409 }; 10410 10411 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10412 !OldFD->getType()->getAs<FunctionProtoType>()) { 10413 Diag(OldFD->getLocation(), NoProtoDiagID); 10414 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10415 return true; 10416 } 10417 10418 if (NoProtoDiagID.getDiagID() != 0 && 10419 !NewFD->getType()->getAs<FunctionProtoType>()) 10420 return Diag(NewFD->getLocation(), NoProtoDiagID); 10421 10422 if (!TemplatesSupported && 10423 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10424 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10425 << FuncTemplates; 10426 10427 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10428 if (NewCXXFD->isVirtual()) 10429 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10430 << VirtFuncs; 10431 10432 if (isa<CXXConstructorDecl>(NewCXXFD)) 10433 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10434 << Constructors; 10435 10436 if (isa<CXXDestructorDecl>(NewCXXFD)) 10437 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10438 << Destructors; 10439 } 10440 10441 if (NewFD->isDeleted()) 10442 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10443 << DeletedFuncs; 10444 10445 if (NewFD->isDefaulted()) 10446 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10447 << DefaultedFuncs; 10448 10449 if (!ConstexprSupported && NewFD->isConstexpr()) 10450 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10451 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10452 10453 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10454 const auto *NewType = cast<FunctionType>(NewQType); 10455 QualType NewReturnType = NewType->getReturnType(); 10456 10457 if (NewReturnType->isUndeducedType()) 10458 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10459 << DeducedReturn; 10460 10461 // Ensure the return type is identical. 10462 if (OldFD) { 10463 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10464 const auto *OldType = cast<FunctionType>(OldQType); 10465 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10466 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10467 10468 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10469 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10470 10471 QualType OldReturnType = OldType->getReturnType(); 10472 10473 if (OldReturnType != NewReturnType) 10474 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10475 10476 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10477 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10478 10479 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10480 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10481 10482 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10483 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10484 10485 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10486 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10487 10488 if (CheckEquivalentExceptionSpec( 10489 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10490 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10491 return true; 10492 } 10493 return false; 10494 } 10495 10496 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10497 const FunctionDecl *NewFD, 10498 bool CausesMV, 10499 MultiVersionKind MVType) { 10500 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10501 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10502 if (OldFD) 10503 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10504 return true; 10505 } 10506 10507 bool IsCPUSpecificCPUDispatchMVType = 10508 MVType == MultiVersionKind::CPUDispatch || 10509 MVType == MultiVersionKind::CPUSpecific; 10510 10511 if (CausesMV && OldFD && 10512 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10513 return true; 10514 10515 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10516 return true; 10517 10518 // Only allow transition to MultiVersion if it hasn't been used. 10519 if (OldFD && CausesMV && OldFD->isUsed(false)) 10520 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10521 10522 return S.areMultiversionVariantFunctionsCompatible( 10523 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10524 PartialDiagnosticAt(NewFD->getLocation(), 10525 S.PDiag(diag::note_multiversioning_caused_here)), 10526 PartialDiagnosticAt(NewFD->getLocation(), 10527 S.PDiag(diag::err_multiversion_doesnt_support) 10528 << static_cast<unsigned>(MVType)), 10529 PartialDiagnosticAt(NewFD->getLocation(), 10530 S.PDiag(diag::err_multiversion_diff)), 10531 /*TemplatesSupported=*/false, 10532 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10533 /*CLinkageMayDiffer=*/false); 10534 } 10535 10536 /// Check the validity of a multiversion function declaration that is the 10537 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10538 /// 10539 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10540 /// 10541 /// Returns true if there was an error, false otherwise. 10542 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10543 MultiVersionKind MVType, 10544 const TargetAttr *TA) { 10545 assert(MVType != MultiVersionKind::None && 10546 "Function lacks multiversion attribute"); 10547 10548 // Target only causes MV if it is default, otherwise this is a normal 10549 // function. 10550 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10551 return false; 10552 10553 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10554 FD->setInvalidDecl(); 10555 return true; 10556 } 10557 10558 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10559 FD->setInvalidDecl(); 10560 return true; 10561 } 10562 10563 FD->setIsMultiVersion(); 10564 return false; 10565 } 10566 10567 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10568 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10569 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10570 return true; 10571 } 10572 10573 return false; 10574 } 10575 10576 static bool CheckTargetCausesMultiVersioning( 10577 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10578 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10579 LookupResult &Previous) { 10580 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10581 ParsedTargetAttr NewParsed = NewTA->parse(); 10582 // Sort order doesn't matter, it just needs to be consistent. 10583 llvm::sort(NewParsed.Features); 10584 10585 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10586 // to change, this is a simple redeclaration. 10587 if (!NewTA->isDefaultVersion() && 10588 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10589 return false; 10590 10591 // Otherwise, this decl causes MultiVersioning. 10592 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10593 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10594 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10595 NewFD->setInvalidDecl(); 10596 return true; 10597 } 10598 10599 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10600 MultiVersionKind::Target)) { 10601 NewFD->setInvalidDecl(); 10602 return true; 10603 } 10604 10605 if (CheckMultiVersionValue(S, NewFD)) { 10606 NewFD->setInvalidDecl(); 10607 return true; 10608 } 10609 10610 // If this is 'default', permit the forward declaration. 10611 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10612 Redeclaration = true; 10613 OldDecl = OldFD; 10614 OldFD->setIsMultiVersion(); 10615 NewFD->setIsMultiVersion(); 10616 return false; 10617 } 10618 10619 if (CheckMultiVersionValue(S, OldFD)) { 10620 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10621 NewFD->setInvalidDecl(); 10622 return true; 10623 } 10624 10625 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10626 10627 if (OldParsed == NewParsed) { 10628 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10629 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10630 NewFD->setInvalidDecl(); 10631 return true; 10632 } 10633 10634 for (const auto *FD : OldFD->redecls()) { 10635 const auto *CurTA = FD->getAttr<TargetAttr>(); 10636 // We allow forward declarations before ANY multiversioning attributes, but 10637 // nothing after the fact. 10638 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10639 (!CurTA || CurTA->isInherited())) { 10640 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10641 << 0; 10642 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10643 NewFD->setInvalidDecl(); 10644 return true; 10645 } 10646 } 10647 10648 OldFD->setIsMultiVersion(); 10649 NewFD->setIsMultiVersion(); 10650 Redeclaration = false; 10651 MergeTypeWithPrevious = false; 10652 OldDecl = nullptr; 10653 Previous.clear(); 10654 return false; 10655 } 10656 10657 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 10658 MultiVersionKind New) { 10659 if (Old == New || Old == MultiVersionKind::None || 10660 New == MultiVersionKind::None) 10661 return true; 10662 10663 return (Old == MultiVersionKind::CPUDispatch && 10664 New == MultiVersionKind::CPUSpecific) || 10665 (Old == MultiVersionKind::CPUSpecific && 10666 New == MultiVersionKind::CPUDispatch); 10667 } 10668 10669 /// Check the validity of a new function declaration being added to an existing 10670 /// multiversioned declaration collection. 10671 static bool CheckMultiVersionAdditionalDecl( 10672 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10673 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10674 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10675 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 10676 bool &MergeTypeWithPrevious, LookupResult &Previous) { 10677 10678 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10679 // Disallow mixing of multiversioning types. 10680 if (!MultiVersionTypesCompatible(OldMVType, NewMVType)) { 10681 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10682 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10683 NewFD->setInvalidDecl(); 10684 return true; 10685 } 10686 10687 ParsedTargetAttr NewParsed; 10688 if (NewTA) { 10689 NewParsed = NewTA->parse(); 10690 llvm::sort(NewParsed.Features); 10691 } 10692 10693 bool UseMemberUsingDeclRules = 10694 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10695 10696 // Next, check ALL non-overloads to see if this is a redeclaration of a 10697 // previous member of the MultiVersion set. 10698 for (NamedDecl *ND : Previous) { 10699 FunctionDecl *CurFD = ND->getAsFunction(); 10700 if (!CurFD) 10701 continue; 10702 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10703 continue; 10704 10705 switch (NewMVType) { 10706 case MultiVersionKind::None: 10707 assert(OldMVType == MultiVersionKind::TargetClones && 10708 "Only target_clones can be omitted in subsequent declarations"); 10709 break; 10710 case MultiVersionKind::Target: { 10711 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10712 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10713 NewFD->setIsMultiVersion(); 10714 Redeclaration = true; 10715 OldDecl = ND; 10716 return false; 10717 } 10718 10719 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10720 if (CurParsed == NewParsed) { 10721 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10722 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10723 NewFD->setInvalidDecl(); 10724 return true; 10725 } 10726 break; 10727 } 10728 case MultiVersionKind::TargetClones: { 10729 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 10730 Redeclaration = true; 10731 OldDecl = CurFD; 10732 MergeTypeWithPrevious = true; 10733 NewFD->setIsMultiVersion(); 10734 10735 if (CurClones && NewClones && 10736 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 10737 !std::equal(CurClones->featuresStrs_begin(), 10738 CurClones->featuresStrs_end(), 10739 NewClones->featuresStrs_begin()))) { 10740 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 10741 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10742 NewFD->setInvalidDecl(); 10743 return true; 10744 } 10745 10746 return false; 10747 } 10748 case MultiVersionKind::CPUSpecific: 10749 case MultiVersionKind::CPUDispatch: { 10750 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10751 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10752 // Handle CPUDispatch/CPUSpecific versions. 10753 // Only 1 CPUDispatch function is allowed, this will make it go through 10754 // the redeclaration errors. 10755 if (NewMVType == MultiVersionKind::CPUDispatch && 10756 CurFD->hasAttr<CPUDispatchAttr>()) { 10757 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10758 std::equal( 10759 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10760 NewCPUDisp->cpus_begin(), 10761 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10762 return Cur->getName() == New->getName(); 10763 })) { 10764 NewFD->setIsMultiVersion(); 10765 Redeclaration = true; 10766 OldDecl = ND; 10767 return false; 10768 } 10769 10770 // If the declarations don't match, this is an error condition. 10771 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10772 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10773 NewFD->setInvalidDecl(); 10774 return true; 10775 } 10776 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10777 10778 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10779 std::equal( 10780 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10781 NewCPUSpec->cpus_begin(), 10782 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10783 return Cur->getName() == New->getName(); 10784 })) { 10785 NewFD->setIsMultiVersion(); 10786 Redeclaration = true; 10787 OldDecl = ND; 10788 return false; 10789 } 10790 10791 // Only 1 version of CPUSpecific is allowed for each CPU. 10792 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10793 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10794 if (CurII == NewII) { 10795 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10796 << NewII; 10797 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10798 NewFD->setInvalidDecl(); 10799 return true; 10800 } 10801 } 10802 } 10803 } 10804 break; 10805 } 10806 } 10807 } 10808 10809 // Else, this is simply a non-redecl case. Checking the 'value' is only 10810 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10811 // handled in the attribute adding step. 10812 if (NewMVType == MultiVersionKind::Target && 10813 CheckMultiVersionValue(S, NewFD)) { 10814 NewFD->setInvalidDecl(); 10815 return true; 10816 } 10817 10818 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10819 !OldFD->isMultiVersion(), NewMVType)) { 10820 NewFD->setInvalidDecl(); 10821 return true; 10822 } 10823 10824 // Permit forward declarations in the case where these two are compatible. 10825 if (!OldFD->isMultiVersion()) { 10826 OldFD->setIsMultiVersion(); 10827 NewFD->setIsMultiVersion(); 10828 Redeclaration = true; 10829 OldDecl = OldFD; 10830 return false; 10831 } 10832 10833 NewFD->setIsMultiVersion(); 10834 Redeclaration = false; 10835 MergeTypeWithPrevious = false; 10836 OldDecl = nullptr; 10837 Previous.clear(); 10838 return false; 10839 } 10840 10841 /// Check the validity of a mulitversion function declaration. 10842 /// Also sets the multiversion'ness' of the function itself. 10843 /// 10844 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10845 /// 10846 /// Returns true if there was an error, false otherwise. 10847 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10848 bool &Redeclaration, NamedDecl *&OldDecl, 10849 bool &MergeTypeWithPrevious, 10850 LookupResult &Previous) { 10851 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10852 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10853 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10854 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 10855 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10856 10857 // Main isn't allowed to become a multiversion function, however it IS 10858 // permitted to have 'main' be marked with the 'target' optimization hint. 10859 if (NewFD->isMain()) { 10860 if (MVType != MultiVersionKind::None && 10861 !(MVType == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { 10862 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10863 NewFD->setInvalidDecl(); 10864 return true; 10865 } 10866 return false; 10867 } 10868 10869 if (!OldDecl || !OldDecl->getAsFunction() || 10870 OldDecl->getDeclContext()->getRedeclContext() != 10871 NewFD->getDeclContext()->getRedeclContext()) { 10872 // If there's no previous declaration, AND this isn't attempting to cause 10873 // multiversioning, this isn't an error condition. 10874 if (MVType == MultiVersionKind::None) 10875 return false; 10876 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10877 } 10878 10879 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10880 10881 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10882 return false; 10883 10884 // Multiversioned redeclarations aren't allowed to omit the attribute, except 10885 // for target_clones. 10886 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None && 10887 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { 10888 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10889 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10890 NewFD->setInvalidDecl(); 10891 return true; 10892 } 10893 10894 if (!OldFD->isMultiVersion()) { 10895 switch (MVType) { 10896 case MultiVersionKind::Target: 10897 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10898 Redeclaration, OldDecl, 10899 MergeTypeWithPrevious, Previous); 10900 case MultiVersionKind::TargetClones: 10901 if (OldFD->isUsed(false)) { 10902 NewFD->setInvalidDecl(); 10903 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10904 } 10905 OldFD->setIsMultiVersion(); 10906 break; 10907 case MultiVersionKind::CPUDispatch: 10908 case MultiVersionKind::CPUSpecific: 10909 case MultiVersionKind::None: 10910 break; 10911 } 10912 } 10913 // Handle the target potentially causes multiversioning case. 10914 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10915 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10916 Redeclaration, OldDecl, 10917 MergeTypeWithPrevious, Previous); 10918 10919 // At this point, we have a multiversion function decl (in OldFD) AND an 10920 // appropriate attribute in the current function decl. Resolve that these are 10921 // still compatible with previous declarations. 10922 return CheckMultiVersionAdditionalDecl( 10923 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, NewClones, 10924 Redeclaration, OldDecl, MergeTypeWithPrevious, Previous); 10925 } 10926 10927 /// Perform semantic checking of a new function declaration. 10928 /// 10929 /// Performs semantic analysis of the new function declaration 10930 /// NewFD. This routine performs all semantic checking that does not 10931 /// require the actual declarator involved in the declaration, and is 10932 /// used both for the declaration of functions as they are parsed 10933 /// (called via ActOnDeclarator) and for the declaration of functions 10934 /// that have been instantiated via C++ template instantiation (called 10935 /// via InstantiateDecl). 10936 /// 10937 /// \param IsMemberSpecialization whether this new function declaration is 10938 /// a member specialization (that replaces any definition provided by the 10939 /// previous declaration). 10940 /// 10941 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10942 /// 10943 /// \returns true if the function declaration is a redeclaration. 10944 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10945 LookupResult &Previous, 10946 bool IsMemberSpecialization) { 10947 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10948 "Variably modified return types are not handled here"); 10949 10950 // Determine whether the type of this function should be merged with 10951 // a previous visible declaration. This never happens for functions in C++, 10952 // and always happens in C if the previous declaration was visible. 10953 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10954 !Previous.isShadowed(); 10955 10956 bool Redeclaration = false; 10957 NamedDecl *OldDecl = nullptr; 10958 bool MayNeedOverloadableChecks = false; 10959 10960 // Merge or overload the declaration with an existing declaration of 10961 // the same name, if appropriate. 10962 if (!Previous.empty()) { 10963 // Determine whether NewFD is an overload of PrevDecl or 10964 // a declaration that requires merging. If it's an overload, 10965 // there's no more work to do here; we'll just add the new 10966 // function to the scope. 10967 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10968 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10969 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10970 Redeclaration = true; 10971 OldDecl = Candidate; 10972 } 10973 } else { 10974 MayNeedOverloadableChecks = true; 10975 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10976 /*NewIsUsingDecl*/ false)) { 10977 case Ovl_Match: 10978 Redeclaration = true; 10979 break; 10980 10981 case Ovl_NonFunction: 10982 Redeclaration = true; 10983 break; 10984 10985 case Ovl_Overload: 10986 Redeclaration = false; 10987 break; 10988 } 10989 } 10990 } 10991 10992 // Check for a previous extern "C" declaration with this name. 10993 if (!Redeclaration && 10994 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10995 if (!Previous.empty()) { 10996 // This is an extern "C" declaration with the same name as a previous 10997 // declaration, and thus redeclares that entity... 10998 Redeclaration = true; 10999 OldDecl = Previous.getFoundDecl(); 11000 MergeTypeWithPrevious = false; 11001 11002 // ... except in the presence of __attribute__((overloadable)). 11003 if (OldDecl->hasAttr<OverloadableAttr>() || 11004 NewFD->hasAttr<OverloadableAttr>()) { 11005 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11006 MayNeedOverloadableChecks = true; 11007 Redeclaration = false; 11008 OldDecl = nullptr; 11009 } 11010 } 11011 } 11012 } 11013 11014 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 11015 MergeTypeWithPrevious, Previous)) 11016 return Redeclaration; 11017 11018 // PPC MMA non-pointer types are not allowed as function return types. 11019 if (Context.getTargetInfo().getTriple().isPPC64() && 11020 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11021 NewFD->setInvalidDecl(); 11022 } 11023 11024 // C++11 [dcl.constexpr]p8: 11025 // A constexpr specifier for a non-static member function that is not 11026 // a constructor declares that member function to be const. 11027 // 11028 // This needs to be delayed until we know whether this is an out-of-line 11029 // definition of a static member function. 11030 // 11031 // This rule is not present in C++1y, so we produce a backwards 11032 // compatibility warning whenever it happens in C++11. 11033 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11034 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11035 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11036 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11037 CXXMethodDecl *OldMD = nullptr; 11038 if (OldDecl) 11039 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11040 if (!OldMD || !OldMD->isStatic()) { 11041 const FunctionProtoType *FPT = 11042 MD->getType()->castAs<FunctionProtoType>(); 11043 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11044 EPI.TypeQuals.addConst(); 11045 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11046 FPT->getParamTypes(), EPI)); 11047 11048 // Warn that we did this, if we're not performing template instantiation. 11049 // In that case, we'll have warned already when the template was defined. 11050 if (!inTemplateInstantiation()) { 11051 SourceLocation AddConstLoc; 11052 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11053 .IgnoreParens().getAs<FunctionTypeLoc>()) 11054 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11055 11056 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11057 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11058 } 11059 } 11060 } 11061 11062 if (Redeclaration) { 11063 // NewFD and OldDecl represent declarations that need to be 11064 // merged. 11065 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 11066 NewFD->setInvalidDecl(); 11067 return Redeclaration; 11068 } 11069 11070 Previous.clear(); 11071 Previous.addDecl(OldDecl); 11072 11073 if (FunctionTemplateDecl *OldTemplateDecl = 11074 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11075 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11076 FunctionTemplateDecl *NewTemplateDecl 11077 = NewFD->getDescribedFunctionTemplate(); 11078 assert(NewTemplateDecl && "Template/non-template mismatch"); 11079 11080 // The call to MergeFunctionDecl above may have created some state in 11081 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11082 // can add it as a redeclaration. 11083 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11084 11085 NewFD->setPreviousDeclaration(OldFD); 11086 if (NewFD->isCXXClassMember()) { 11087 NewFD->setAccess(OldTemplateDecl->getAccess()); 11088 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11089 } 11090 11091 // If this is an explicit specialization of a member that is a function 11092 // template, mark it as a member specialization. 11093 if (IsMemberSpecialization && 11094 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11095 NewTemplateDecl->setMemberSpecialization(); 11096 assert(OldTemplateDecl->isMemberSpecialization()); 11097 // Explicit specializations of a member template do not inherit deleted 11098 // status from the parent member template that they are specializing. 11099 if (OldFD->isDeleted()) { 11100 // FIXME: This assert will not hold in the presence of modules. 11101 assert(OldFD->getCanonicalDecl() == OldFD); 11102 // FIXME: We need an update record for this AST mutation. 11103 OldFD->setDeletedAsWritten(false); 11104 } 11105 } 11106 11107 } else { 11108 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11109 auto *OldFD = cast<FunctionDecl>(OldDecl); 11110 // This needs to happen first so that 'inline' propagates. 11111 NewFD->setPreviousDeclaration(OldFD); 11112 if (NewFD->isCXXClassMember()) 11113 NewFD->setAccess(OldFD->getAccess()); 11114 } 11115 } 11116 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11117 !NewFD->getAttr<OverloadableAttr>()) { 11118 assert((Previous.empty() || 11119 llvm::any_of(Previous, 11120 [](const NamedDecl *ND) { 11121 return ND->hasAttr<OverloadableAttr>(); 11122 })) && 11123 "Non-redecls shouldn't happen without overloadable present"); 11124 11125 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11126 const auto *FD = dyn_cast<FunctionDecl>(ND); 11127 return FD && !FD->hasAttr<OverloadableAttr>(); 11128 }); 11129 11130 if (OtherUnmarkedIter != Previous.end()) { 11131 Diag(NewFD->getLocation(), 11132 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11133 Diag((*OtherUnmarkedIter)->getLocation(), 11134 diag::note_attribute_overloadable_prev_overload) 11135 << false; 11136 11137 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11138 } 11139 } 11140 11141 if (LangOpts.OpenMP) 11142 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11143 11144 // Semantic checking for this function declaration (in isolation). 11145 11146 if (getLangOpts().CPlusPlus) { 11147 // C++-specific checks. 11148 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11149 CheckConstructor(Constructor); 11150 } else if (CXXDestructorDecl *Destructor = 11151 dyn_cast<CXXDestructorDecl>(NewFD)) { 11152 CXXRecordDecl *Record = Destructor->getParent(); 11153 QualType ClassType = Context.getTypeDeclType(Record); 11154 11155 // FIXME: Shouldn't we be able to perform this check even when the class 11156 // type is dependent? Both gcc and edg can handle that. 11157 if (!ClassType->isDependentType()) { 11158 DeclarationName Name 11159 = Context.DeclarationNames.getCXXDestructorName( 11160 Context.getCanonicalType(ClassType)); 11161 if (NewFD->getDeclName() != Name) { 11162 Diag(NewFD->getLocation(), diag::err_destructor_name); 11163 NewFD->setInvalidDecl(); 11164 return Redeclaration; 11165 } 11166 } 11167 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11168 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11169 CheckDeductionGuideTemplate(TD); 11170 11171 // A deduction guide is not on the list of entities that can be 11172 // explicitly specialized. 11173 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11174 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11175 << /*explicit specialization*/ 1; 11176 } 11177 11178 // Find any virtual functions that this function overrides. 11179 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11180 if (!Method->isFunctionTemplateSpecialization() && 11181 !Method->getDescribedFunctionTemplate() && 11182 Method->isCanonicalDecl()) { 11183 AddOverriddenMethods(Method->getParent(), Method); 11184 } 11185 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11186 // C++2a [class.virtual]p6 11187 // A virtual method shall not have a requires-clause. 11188 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11189 diag::err_constrained_virtual_method); 11190 11191 if (Method->isStatic()) 11192 checkThisInStaticMemberFunctionType(Method); 11193 } 11194 11195 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11196 ActOnConversionDeclarator(Conversion); 11197 11198 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11199 if (NewFD->isOverloadedOperator() && 11200 CheckOverloadedOperatorDeclaration(NewFD)) { 11201 NewFD->setInvalidDecl(); 11202 return Redeclaration; 11203 } 11204 11205 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11206 if (NewFD->getLiteralIdentifier() && 11207 CheckLiteralOperatorDeclaration(NewFD)) { 11208 NewFD->setInvalidDecl(); 11209 return Redeclaration; 11210 } 11211 11212 // In C++, check default arguments now that we have merged decls. Unless 11213 // the lexical context is the class, because in this case this is done 11214 // during delayed parsing anyway. 11215 if (!CurContext->isRecord()) 11216 CheckCXXDefaultArguments(NewFD); 11217 11218 // If this function is declared as being extern "C", then check to see if 11219 // the function returns a UDT (class, struct, or union type) that is not C 11220 // compatible, and if it does, warn the user. 11221 // But, issue any diagnostic on the first declaration only. 11222 if (Previous.empty() && NewFD->isExternC()) { 11223 QualType R = NewFD->getReturnType(); 11224 if (R->isIncompleteType() && !R->isVoidType()) 11225 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11226 << NewFD << R; 11227 else if (!R.isPODType(Context) && !R->isVoidType() && 11228 !R->isObjCObjectPointerType()) 11229 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11230 } 11231 11232 // C++1z [dcl.fct]p6: 11233 // [...] whether the function has a non-throwing exception-specification 11234 // [is] part of the function type 11235 // 11236 // This results in an ABI break between C++14 and C++17 for functions whose 11237 // declared type includes an exception-specification in a parameter or 11238 // return type. (Exception specifications on the function itself are OK in 11239 // most cases, and exception specifications are not permitted in most other 11240 // contexts where they could make it into a mangling.) 11241 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11242 auto HasNoexcept = [&](QualType T) -> bool { 11243 // Strip off declarator chunks that could be between us and a function 11244 // type. We don't need to look far, exception specifications are very 11245 // restricted prior to C++17. 11246 if (auto *RT = T->getAs<ReferenceType>()) 11247 T = RT->getPointeeType(); 11248 else if (T->isAnyPointerType()) 11249 T = T->getPointeeType(); 11250 else if (auto *MPT = T->getAs<MemberPointerType>()) 11251 T = MPT->getPointeeType(); 11252 if (auto *FPT = T->getAs<FunctionProtoType>()) 11253 if (FPT->isNothrow()) 11254 return true; 11255 return false; 11256 }; 11257 11258 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11259 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11260 for (QualType T : FPT->param_types()) 11261 AnyNoexcept |= HasNoexcept(T); 11262 if (AnyNoexcept) 11263 Diag(NewFD->getLocation(), 11264 diag::warn_cxx17_compat_exception_spec_in_signature) 11265 << NewFD; 11266 } 11267 11268 if (!Redeclaration && LangOpts.CUDA) 11269 checkCUDATargetOverload(NewFD, Previous); 11270 } 11271 return Redeclaration; 11272 } 11273 11274 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11275 // C++11 [basic.start.main]p3: 11276 // A program that [...] declares main to be inline, static or 11277 // constexpr is ill-formed. 11278 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11279 // appear in a declaration of main. 11280 // static main is not an error under C99, but we should warn about it. 11281 // We accept _Noreturn main as an extension. 11282 if (FD->getStorageClass() == SC_Static) 11283 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11284 ? diag::err_static_main : diag::warn_static_main) 11285 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11286 if (FD->isInlineSpecified()) 11287 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11288 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11289 if (DS.isNoreturnSpecified()) { 11290 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11291 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11292 Diag(NoreturnLoc, diag::ext_noreturn_main); 11293 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11294 << FixItHint::CreateRemoval(NoreturnRange); 11295 } 11296 if (FD->isConstexpr()) { 11297 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11298 << FD->isConsteval() 11299 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11300 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11301 } 11302 11303 if (getLangOpts().OpenCL) { 11304 Diag(FD->getLocation(), diag::err_opencl_no_main) 11305 << FD->hasAttr<OpenCLKernelAttr>(); 11306 FD->setInvalidDecl(); 11307 return; 11308 } 11309 11310 QualType T = FD->getType(); 11311 assert(T->isFunctionType() && "function decl is not of function type"); 11312 const FunctionType* FT = T->castAs<FunctionType>(); 11313 11314 // Set default calling convention for main() 11315 if (FT->getCallConv() != CC_C) { 11316 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11317 FD->setType(QualType(FT, 0)); 11318 T = Context.getCanonicalType(FD->getType()); 11319 } 11320 11321 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11322 // In C with GNU extensions we allow main() to have non-integer return 11323 // type, but we should warn about the extension, and we disable the 11324 // implicit-return-zero rule. 11325 11326 // GCC in C mode accepts qualified 'int'. 11327 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11328 FD->setHasImplicitReturnZero(true); 11329 else { 11330 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11331 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11332 if (RTRange.isValid()) 11333 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11334 << FixItHint::CreateReplacement(RTRange, "int"); 11335 } 11336 } else { 11337 // In C and C++, main magically returns 0 if you fall off the end; 11338 // set the flag which tells us that. 11339 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11340 11341 // All the standards say that main() should return 'int'. 11342 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11343 FD->setHasImplicitReturnZero(true); 11344 else { 11345 // Otherwise, this is just a flat-out error. 11346 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11347 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11348 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11349 : FixItHint()); 11350 FD->setInvalidDecl(true); 11351 } 11352 } 11353 11354 // Treat protoless main() as nullary. 11355 if (isa<FunctionNoProtoType>(FT)) return; 11356 11357 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11358 unsigned nparams = FTP->getNumParams(); 11359 assert(FD->getNumParams() == nparams); 11360 11361 bool HasExtraParameters = (nparams > 3); 11362 11363 if (FTP->isVariadic()) { 11364 Diag(FD->getLocation(), diag::ext_variadic_main); 11365 // FIXME: if we had information about the location of the ellipsis, we 11366 // could add a FixIt hint to remove it as a parameter. 11367 } 11368 11369 // Darwin passes an undocumented fourth argument of type char**. If 11370 // other platforms start sprouting these, the logic below will start 11371 // getting shifty. 11372 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11373 HasExtraParameters = false; 11374 11375 if (HasExtraParameters) { 11376 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11377 FD->setInvalidDecl(true); 11378 nparams = 3; 11379 } 11380 11381 // FIXME: a lot of the following diagnostics would be improved 11382 // if we had some location information about types. 11383 11384 QualType CharPP = 11385 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11386 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11387 11388 for (unsigned i = 0; i < nparams; ++i) { 11389 QualType AT = FTP->getParamType(i); 11390 11391 bool mismatch = true; 11392 11393 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11394 mismatch = false; 11395 else if (Expected[i] == CharPP) { 11396 // As an extension, the following forms are okay: 11397 // char const ** 11398 // char const * const * 11399 // char * const * 11400 11401 QualifierCollector qs; 11402 const PointerType* PT; 11403 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11404 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11405 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11406 Context.CharTy)) { 11407 qs.removeConst(); 11408 mismatch = !qs.empty(); 11409 } 11410 } 11411 11412 if (mismatch) { 11413 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11414 // TODO: suggest replacing given type with expected type 11415 FD->setInvalidDecl(true); 11416 } 11417 } 11418 11419 if (nparams == 1 && !FD->isInvalidDecl()) { 11420 Diag(FD->getLocation(), diag::warn_main_one_arg); 11421 } 11422 11423 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11424 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11425 FD->setInvalidDecl(); 11426 } 11427 } 11428 11429 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11430 11431 // Default calling convention for main and wmain is __cdecl 11432 if (FD->getName() == "main" || FD->getName() == "wmain") 11433 return false; 11434 11435 // Default calling convention for MinGW is __cdecl 11436 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11437 if (T.isWindowsGNUEnvironment()) 11438 return false; 11439 11440 // Default calling convention for WinMain, wWinMain and DllMain 11441 // is __stdcall on 32 bit Windows 11442 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11443 return true; 11444 11445 return false; 11446 } 11447 11448 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11449 QualType T = FD->getType(); 11450 assert(T->isFunctionType() && "function decl is not of function type"); 11451 const FunctionType *FT = T->castAs<FunctionType>(); 11452 11453 // Set an implicit return of 'zero' if the function can return some integral, 11454 // enumeration, pointer or nullptr type. 11455 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11456 FT->getReturnType()->isAnyPointerType() || 11457 FT->getReturnType()->isNullPtrType()) 11458 // DllMain is exempt because a return value of zero means it failed. 11459 if (FD->getName() != "DllMain") 11460 FD->setHasImplicitReturnZero(true); 11461 11462 // Explicity specified calling conventions are applied to MSVC entry points 11463 if (!hasExplicitCallingConv(T)) { 11464 if (isDefaultStdCall(FD, *this)) { 11465 if (FT->getCallConv() != CC_X86StdCall) { 11466 FT = Context.adjustFunctionType( 11467 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11468 FD->setType(QualType(FT, 0)); 11469 } 11470 } else if (FT->getCallConv() != CC_C) { 11471 FT = Context.adjustFunctionType(FT, 11472 FT->getExtInfo().withCallingConv(CC_C)); 11473 FD->setType(QualType(FT, 0)); 11474 } 11475 } 11476 11477 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11478 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11479 FD->setInvalidDecl(); 11480 } 11481 } 11482 11483 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11484 // FIXME: Need strict checking. In C89, we need to check for 11485 // any assignment, increment, decrement, function-calls, or 11486 // commas outside of a sizeof. In C99, it's the same list, 11487 // except that the aforementioned are allowed in unevaluated 11488 // expressions. Everything else falls under the 11489 // "may accept other forms of constant expressions" exception. 11490 // 11491 // Regular C++ code will not end up here (exceptions: language extensions, 11492 // OpenCL C++ etc), so the constant expression rules there don't matter. 11493 if (Init->isValueDependent()) { 11494 assert(Init->containsErrors() && 11495 "Dependent code should only occur in error-recovery path."); 11496 return true; 11497 } 11498 const Expr *Culprit; 11499 if (Init->isConstantInitializer(Context, false, &Culprit)) 11500 return false; 11501 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11502 << Culprit->getSourceRange(); 11503 return true; 11504 } 11505 11506 namespace { 11507 // Visits an initialization expression to see if OrigDecl is evaluated in 11508 // its own initialization and throws a warning if it does. 11509 class SelfReferenceChecker 11510 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11511 Sema &S; 11512 Decl *OrigDecl; 11513 bool isRecordType; 11514 bool isPODType; 11515 bool isReferenceType; 11516 11517 bool isInitList; 11518 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11519 11520 public: 11521 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11522 11523 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11524 S(S), OrigDecl(OrigDecl) { 11525 isPODType = false; 11526 isRecordType = false; 11527 isReferenceType = false; 11528 isInitList = false; 11529 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11530 isPODType = VD->getType().isPODType(S.Context); 11531 isRecordType = VD->getType()->isRecordType(); 11532 isReferenceType = VD->getType()->isReferenceType(); 11533 } 11534 } 11535 11536 // For most expressions, just call the visitor. For initializer lists, 11537 // track the index of the field being initialized since fields are 11538 // initialized in order allowing use of previously initialized fields. 11539 void CheckExpr(Expr *E) { 11540 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11541 if (!InitList) { 11542 Visit(E); 11543 return; 11544 } 11545 11546 // Track and increment the index here. 11547 isInitList = true; 11548 InitFieldIndex.push_back(0); 11549 for (auto Child : InitList->children()) { 11550 CheckExpr(cast<Expr>(Child)); 11551 ++InitFieldIndex.back(); 11552 } 11553 InitFieldIndex.pop_back(); 11554 } 11555 11556 // Returns true if MemberExpr is checked and no further checking is needed. 11557 // Returns false if additional checking is required. 11558 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11559 llvm::SmallVector<FieldDecl*, 4> Fields; 11560 Expr *Base = E; 11561 bool ReferenceField = false; 11562 11563 // Get the field members used. 11564 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11565 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11566 if (!FD) 11567 return false; 11568 Fields.push_back(FD); 11569 if (FD->getType()->isReferenceType()) 11570 ReferenceField = true; 11571 Base = ME->getBase()->IgnoreParenImpCasts(); 11572 } 11573 11574 // Keep checking only if the base Decl is the same. 11575 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11576 if (!DRE || DRE->getDecl() != OrigDecl) 11577 return false; 11578 11579 // A reference field can be bound to an unininitialized field. 11580 if (CheckReference && !ReferenceField) 11581 return true; 11582 11583 // Convert FieldDecls to their index number. 11584 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11585 for (const FieldDecl *I : llvm::reverse(Fields)) 11586 UsedFieldIndex.push_back(I->getFieldIndex()); 11587 11588 // See if a warning is needed by checking the first difference in index 11589 // numbers. If field being used has index less than the field being 11590 // initialized, then the use is safe. 11591 for (auto UsedIter = UsedFieldIndex.begin(), 11592 UsedEnd = UsedFieldIndex.end(), 11593 OrigIter = InitFieldIndex.begin(), 11594 OrigEnd = InitFieldIndex.end(); 11595 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11596 if (*UsedIter < *OrigIter) 11597 return true; 11598 if (*UsedIter > *OrigIter) 11599 break; 11600 } 11601 11602 // TODO: Add a different warning which will print the field names. 11603 HandleDeclRefExpr(DRE); 11604 return true; 11605 } 11606 11607 // For most expressions, the cast is directly above the DeclRefExpr. 11608 // For conditional operators, the cast can be outside the conditional 11609 // operator if both expressions are DeclRefExpr's. 11610 void HandleValue(Expr *E) { 11611 E = E->IgnoreParens(); 11612 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11613 HandleDeclRefExpr(DRE); 11614 return; 11615 } 11616 11617 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11618 Visit(CO->getCond()); 11619 HandleValue(CO->getTrueExpr()); 11620 HandleValue(CO->getFalseExpr()); 11621 return; 11622 } 11623 11624 if (BinaryConditionalOperator *BCO = 11625 dyn_cast<BinaryConditionalOperator>(E)) { 11626 Visit(BCO->getCond()); 11627 HandleValue(BCO->getFalseExpr()); 11628 return; 11629 } 11630 11631 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11632 HandleValue(OVE->getSourceExpr()); 11633 return; 11634 } 11635 11636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11637 if (BO->getOpcode() == BO_Comma) { 11638 Visit(BO->getLHS()); 11639 HandleValue(BO->getRHS()); 11640 return; 11641 } 11642 } 11643 11644 if (isa<MemberExpr>(E)) { 11645 if (isInitList) { 11646 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11647 false /*CheckReference*/)) 11648 return; 11649 } 11650 11651 Expr *Base = E->IgnoreParenImpCasts(); 11652 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11653 // Check for static member variables and don't warn on them. 11654 if (!isa<FieldDecl>(ME->getMemberDecl())) 11655 return; 11656 Base = ME->getBase()->IgnoreParenImpCasts(); 11657 } 11658 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11659 HandleDeclRefExpr(DRE); 11660 return; 11661 } 11662 11663 Visit(E); 11664 } 11665 11666 // Reference types not handled in HandleValue are handled here since all 11667 // uses of references are bad, not just r-value uses. 11668 void VisitDeclRefExpr(DeclRefExpr *E) { 11669 if (isReferenceType) 11670 HandleDeclRefExpr(E); 11671 } 11672 11673 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11674 if (E->getCastKind() == CK_LValueToRValue) { 11675 HandleValue(E->getSubExpr()); 11676 return; 11677 } 11678 11679 Inherited::VisitImplicitCastExpr(E); 11680 } 11681 11682 void VisitMemberExpr(MemberExpr *E) { 11683 if (isInitList) { 11684 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11685 return; 11686 } 11687 11688 // Don't warn on arrays since they can be treated as pointers. 11689 if (E->getType()->canDecayToPointerType()) return; 11690 11691 // Warn when a non-static method call is followed by non-static member 11692 // field accesses, which is followed by a DeclRefExpr. 11693 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11694 bool Warn = (MD && !MD->isStatic()); 11695 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11696 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11697 if (!isa<FieldDecl>(ME->getMemberDecl())) 11698 Warn = false; 11699 Base = ME->getBase()->IgnoreParenImpCasts(); 11700 } 11701 11702 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11703 if (Warn) 11704 HandleDeclRefExpr(DRE); 11705 return; 11706 } 11707 11708 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11709 // Visit that expression. 11710 Visit(Base); 11711 } 11712 11713 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11714 Expr *Callee = E->getCallee(); 11715 11716 if (isa<UnresolvedLookupExpr>(Callee)) 11717 return Inherited::VisitCXXOperatorCallExpr(E); 11718 11719 Visit(Callee); 11720 for (auto Arg: E->arguments()) 11721 HandleValue(Arg->IgnoreParenImpCasts()); 11722 } 11723 11724 void VisitUnaryOperator(UnaryOperator *E) { 11725 // For POD record types, addresses of its own members are well-defined. 11726 if (E->getOpcode() == UO_AddrOf && isRecordType && 11727 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11728 if (!isPODType) 11729 HandleValue(E->getSubExpr()); 11730 return; 11731 } 11732 11733 if (E->isIncrementDecrementOp()) { 11734 HandleValue(E->getSubExpr()); 11735 return; 11736 } 11737 11738 Inherited::VisitUnaryOperator(E); 11739 } 11740 11741 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11742 11743 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11744 if (E->getConstructor()->isCopyConstructor()) { 11745 Expr *ArgExpr = E->getArg(0); 11746 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11747 if (ILE->getNumInits() == 1) 11748 ArgExpr = ILE->getInit(0); 11749 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11750 if (ICE->getCastKind() == CK_NoOp) 11751 ArgExpr = ICE->getSubExpr(); 11752 HandleValue(ArgExpr); 11753 return; 11754 } 11755 Inherited::VisitCXXConstructExpr(E); 11756 } 11757 11758 void VisitCallExpr(CallExpr *E) { 11759 // Treat std::move as a use. 11760 if (E->isCallToStdMove()) { 11761 HandleValue(E->getArg(0)); 11762 return; 11763 } 11764 11765 Inherited::VisitCallExpr(E); 11766 } 11767 11768 void VisitBinaryOperator(BinaryOperator *E) { 11769 if (E->isCompoundAssignmentOp()) { 11770 HandleValue(E->getLHS()); 11771 Visit(E->getRHS()); 11772 return; 11773 } 11774 11775 Inherited::VisitBinaryOperator(E); 11776 } 11777 11778 // A custom visitor for BinaryConditionalOperator is needed because the 11779 // regular visitor would check the condition and true expression separately 11780 // but both point to the same place giving duplicate diagnostics. 11781 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11782 Visit(E->getCond()); 11783 Visit(E->getFalseExpr()); 11784 } 11785 11786 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11787 Decl* ReferenceDecl = DRE->getDecl(); 11788 if (OrigDecl != ReferenceDecl) return; 11789 unsigned diag; 11790 if (isReferenceType) { 11791 diag = diag::warn_uninit_self_reference_in_reference_init; 11792 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11793 diag = diag::warn_static_self_reference_in_init; 11794 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11795 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11796 DRE->getDecl()->getType()->isRecordType()) { 11797 diag = diag::warn_uninit_self_reference_in_init; 11798 } else { 11799 // Local variables will be handled by the CFG analysis. 11800 return; 11801 } 11802 11803 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11804 S.PDiag(diag) 11805 << DRE->getDecl() << OrigDecl->getLocation() 11806 << DRE->getSourceRange()); 11807 } 11808 }; 11809 11810 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11811 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11812 bool DirectInit) { 11813 // Parameters arguments are occassionially constructed with itself, 11814 // for instance, in recursive functions. Skip them. 11815 if (isa<ParmVarDecl>(OrigDecl)) 11816 return; 11817 11818 E = E->IgnoreParens(); 11819 11820 // Skip checking T a = a where T is not a record or reference type. 11821 // Doing so is a way to silence uninitialized warnings. 11822 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11823 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11824 if (ICE->getCastKind() == CK_LValueToRValue) 11825 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11826 if (DRE->getDecl() == OrigDecl) 11827 return; 11828 11829 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11830 } 11831 } // end anonymous namespace 11832 11833 namespace { 11834 // Simple wrapper to add the name of a variable or (if no variable is 11835 // available) a DeclarationName into a diagnostic. 11836 struct VarDeclOrName { 11837 VarDecl *VDecl; 11838 DeclarationName Name; 11839 11840 friend const Sema::SemaDiagnosticBuilder & 11841 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11842 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11843 } 11844 }; 11845 } // end anonymous namespace 11846 11847 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11848 DeclarationName Name, QualType Type, 11849 TypeSourceInfo *TSI, 11850 SourceRange Range, bool DirectInit, 11851 Expr *Init) { 11852 bool IsInitCapture = !VDecl; 11853 assert((!VDecl || !VDecl->isInitCapture()) && 11854 "init captures are expected to be deduced prior to initialization"); 11855 11856 VarDeclOrName VN{VDecl, Name}; 11857 11858 DeducedType *Deduced = Type->getContainedDeducedType(); 11859 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11860 11861 // C++11 [dcl.spec.auto]p3 11862 if (!Init) { 11863 assert(VDecl && "no init for init capture deduction?"); 11864 11865 // Except for class argument deduction, and then for an initializing 11866 // declaration only, i.e. no static at class scope or extern. 11867 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11868 VDecl->hasExternalStorage() || 11869 VDecl->isStaticDataMember()) { 11870 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11871 << VDecl->getDeclName() << Type; 11872 return QualType(); 11873 } 11874 } 11875 11876 ArrayRef<Expr*> DeduceInits; 11877 if (Init) 11878 DeduceInits = Init; 11879 11880 if (DirectInit) { 11881 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11882 DeduceInits = PL->exprs(); 11883 } 11884 11885 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11886 assert(VDecl && "non-auto type for init capture deduction?"); 11887 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11888 InitializationKind Kind = InitializationKind::CreateForInit( 11889 VDecl->getLocation(), DirectInit, Init); 11890 // FIXME: Initialization should not be taking a mutable list of inits. 11891 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11892 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11893 InitsCopy); 11894 } 11895 11896 if (DirectInit) { 11897 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11898 DeduceInits = IL->inits(); 11899 } 11900 11901 // Deduction only works if we have exactly one source expression. 11902 if (DeduceInits.empty()) { 11903 // It isn't possible to write this directly, but it is possible to 11904 // end up in this situation with "auto x(some_pack...);" 11905 Diag(Init->getBeginLoc(), IsInitCapture 11906 ? diag::err_init_capture_no_expression 11907 : diag::err_auto_var_init_no_expression) 11908 << VN << Type << Range; 11909 return QualType(); 11910 } 11911 11912 if (DeduceInits.size() > 1) { 11913 Diag(DeduceInits[1]->getBeginLoc(), 11914 IsInitCapture ? diag::err_init_capture_multiple_expressions 11915 : diag::err_auto_var_init_multiple_expressions) 11916 << VN << Type << Range; 11917 return QualType(); 11918 } 11919 11920 Expr *DeduceInit = DeduceInits[0]; 11921 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11922 Diag(Init->getBeginLoc(), IsInitCapture 11923 ? diag::err_init_capture_paren_braces 11924 : diag::err_auto_var_init_paren_braces) 11925 << isa<InitListExpr>(Init) << VN << Type << Range; 11926 return QualType(); 11927 } 11928 11929 // Expressions default to 'id' when we're in a debugger. 11930 bool DefaultedAnyToId = false; 11931 if (getLangOpts().DebuggerCastResultToId && 11932 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11933 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11934 if (Result.isInvalid()) { 11935 return QualType(); 11936 } 11937 Init = Result.get(); 11938 DefaultedAnyToId = true; 11939 } 11940 11941 // C++ [dcl.decomp]p1: 11942 // If the assignment-expression [...] has array type A and no ref-qualifier 11943 // is present, e has type cv A 11944 if (VDecl && isa<DecompositionDecl>(VDecl) && 11945 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11946 DeduceInit->getType()->isConstantArrayType()) 11947 return Context.getQualifiedType(DeduceInit->getType(), 11948 Type.getQualifiers()); 11949 11950 QualType DeducedType; 11951 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11952 if (!IsInitCapture) 11953 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11954 else if (isa<InitListExpr>(Init)) 11955 Diag(Range.getBegin(), 11956 diag::err_init_capture_deduction_failure_from_init_list) 11957 << VN 11958 << (DeduceInit->getType().isNull() ? TSI->getType() 11959 : DeduceInit->getType()) 11960 << DeduceInit->getSourceRange(); 11961 else 11962 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11963 << VN << TSI->getType() 11964 << (DeduceInit->getType().isNull() ? TSI->getType() 11965 : DeduceInit->getType()) 11966 << DeduceInit->getSourceRange(); 11967 } 11968 11969 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11970 // 'id' instead of a specific object type prevents most of our usual 11971 // checks. 11972 // We only want to warn outside of template instantiations, though: 11973 // inside a template, the 'id' could have come from a parameter. 11974 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11975 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11976 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11977 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11978 } 11979 11980 return DeducedType; 11981 } 11982 11983 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11984 Expr *Init) { 11985 assert(!Init || !Init->containsErrors()); 11986 QualType DeducedType = deduceVarTypeFromInitializer( 11987 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11988 VDecl->getSourceRange(), DirectInit, Init); 11989 if (DeducedType.isNull()) { 11990 VDecl->setInvalidDecl(); 11991 return true; 11992 } 11993 11994 VDecl->setType(DeducedType); 11995 assert(VDecl->isLinkageValid()); 11996 11997 // In ARC, infer lifetime. 11998 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11999 VDecl->setInvalidDecl(); 12000 12001 if (getLangOpts().OpenCL) 12002 deduceOpenCLAddressSpace(VDecl); 12003 12004 // If this is a redeclaration, check that the type we just deduced matches 12005 // the previously declared type. 12006 if (VarDecl *Old = VDecl->getPreviousDecl()) { 12007 // We never need to merge the type, because we cannot form an incomplete 12008 // array of auto, nor deduce such a type. 12009 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 12010 } 12011 12012 // Check the deduced type is valid for a variable declaration. 12013 CheckVariableDeclarationType(VDecl); 12014 return VDecl->isInvalidDecl(); 12015 } 12016 12017 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 12018 SourceLocation Loc) { 12019 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 12020 Init = EWC->getSubExpr(); 12021 12022 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 12023 Init = CE->getSubExpr(); 12024 12025 QualType InitType = Init->getType(); 12026 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12027 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 12028 "shouldn't be called if type doesn't have a non-trivial C struct"); 12029 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 12030 for (auto I : ILE->inits()) { 12031 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 12032 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12033 continue; 12034 SourceLocation SL = I->getExprLoc(); 12035 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 12036 } 12037 return; 12038 } 12039 12040 if (isa<ImplicitValueInitExpr>(Init)) { 12041 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12042 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 12043 NTCUK_Init); 12044 } else { 12045 // Assume all other explicit initializers involving copying some existing 12046 // object. 12047 // TODO: ignore any explicit initializers where we can guarantee 12048 // copy-elision. 12049 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 12050 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 12051 } 12052 } 12053 12054 namespace { 12055 12056 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 12057 // Ignore unavailable fields. A field can be marked as unavailable explicitly 12058 // in the source code or implicitly by the compiler if it is in a union 12059 // defined in a system header and has non-trivial ObjC ownership 12060 // qualifications. We don't want those fields to participate in determining 12061 // whether the containing union is non-trivial. 12062 return FD->hasAttr<UnavailableAttr>(); 12063 } 12064 12065 struct DiagNonTrivalCUnionDefaultInitializeVisitor 12066 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12067 void> { 12068 using Super = 12069 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12070 void>; 12071 12072 DiagNonTrivalCUnionDefaultInitializeVisitor( 12073 QualType OrigTy, SourceLocation OrigLoc, 12074 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12075 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12076 12077 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 12078 const FieldDecl *FD, bool InNonTrivialUnion) { 12079 if (const auto *AT = S.Context.getAsArrayType(QT)) 12080 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12081 InNonTrivialUnion); 12082 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 12083 } 12084 12085 void visitARCStrong(QualType QT, const FieldDecl *FD, 12086 bool InNonTrivialUnion) { 12087 if (InNonTrivialUnion) 12088 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12089 << 1 << 0 << QT << FD->getName(); 12090 } 12091 12092 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12093 if (InNonTrivialUnion) 12094 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12095 << 1 << 0 << QT << FD->getName(); 12096 } 12097 12098 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12099 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12100 if (RD->isUnion()) { 12101 if (OrigLoc.isValid()) { 12102 bool IsUnion = false; 12103 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12104 IsUnion = OrigRD->isUnion(); 12105 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12106 << 0 << OrigTy << IsUnion << UseContext; 12107 // Reset OrigLoc so that this diagnostic is emitted only once. 12108 OrigLoc = SourceLocation(); 12109 } 12110 InNonTrivialUnion = true; 12111 } 12112 12113 if (InNonTrivialUnion) 12114 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12115 << 0 << 0 << QT.getUnqualifiedType() << ""; 12116 12117 for (const FieldDecl *FD : RD->fields()) 12118 if (!shouldIgnoreForRecordTriviality(FD)) 12119 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12120 } 12121 12122 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12123 12124 // The non-trivial C union type or the struct/union type that contains a 12125 // non-trivial C union. 12126 QualType OrigTy; 12127 SourceLocation OrigLoc; 12128 Sema::NonTrivialCUnionContext UseContext; 12129 Sema &S; 12130 }; 12131 12132 struct DiagNonTrivalCUnionDestructedTypeVisitor 12133 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12134 using Super = 12135 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12136 12137 DiagNonTrivalCUnionDestructedTypeVisitor( 12138 QualType OrigTy, SourceLocation OrigLoc, 12139 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12140 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12141 12142 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12143 const FieldDecl *FD, bool InNonTrivialUnion) { 12144 if (const auto *AT = S.Context.getAsArrayType(QT)) 12145 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12146 InNonTrivialUnion); 12147 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12148 } 12149 12150 void visitARCStrong(QualType QT, const FieldDecl *FD, 12151 bool InNonTrivialUnion) { 12152 if (InNonTrivialUnion) 12153 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12154 << 1 << 1 << QT << FD->getName(); 12155 } 12156 12157 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12158 if (InNonTrivialUnion) 12159 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12160 << 1 << 1 << QT << FD->getName(); 12161 } 12162 12163 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12164 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12165 if (RD->isUnion()) { 12166 if (OrigLoc.isValid()) { 12167 bool IsUnion = false; 12168 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12169 IsUnion = OrigRD->isUnion(); 12170 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12171 << 1 << OrigTy << IsUnion << UseContext; 12172 // Reset OrigLoc so that this diagnostic is emitted only once. 12173 OrigLoc = SourceLocation(); 12174 } 12175 InNonTrivialUnion = true; 12176 } 12177 12178 if (InNonTrivialUnion) 12179 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12180 << 0 << 1 << QT.getUnqualifiedType() << ""; 12181 12182 for (const FieldDecl *FD : RD->fields()) 12183 if (!shouldIgnoreForRecordTriviality(FD)) 12184 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12185 } 12186 12187 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12188 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12189 bool InNonTrivialUnion) {} 12190 12191 // The non-trivial C union type or the struct/union type that contains a 12192 // non-trivial C union. 12193 QualType OrigTy; 12194 SourceLocation OrigLoc; 12195 Sema::NonTrivialCUnionContext UseContext; 12196 Sema &S; 12197 }; 12198 12199 struct DiagNonTrivalCUnionCopyVisitor 12200 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12201 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12202 12203 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12204 Sema::NonTrivialCUnionContext UseContext, 12205 Sema &S) 12206 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12207 12208 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12209 const FieldDecl *FD, bool InNonTrivialUnion) { 12210 if (const auto *AT = S.Context.getAsArrayType(QT)) 12211 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12212 InNonTrivialUnion); 12213 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12214 } 12215 12216 void visitARCStrong(QualType QT, const FieldDecl *FD, 12217 bool InNonTrivialUnion) { 12218 if (InNonTrivialUnion) 12219 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12220 << 1 << 2 << QT << FD->getName(); 12221 } 12222 12223 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12224 if (InNonTrivialUnion) 12225 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12226 << 1 << 2 << QT << FD->getName(); 12227 } 12228 12229 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12230 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12231 if (RD->isUnion()) { 12232 if (OrigLoc.isValid()) { 12233 bool IsUnion = false; 12234 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12235 IsUnion = OrigRD->isUnion(); 12236 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12237 << 2 << OrigTy << IsUnion << UseContext; 12238 // Reset OrigLoc so that this diagnostic is emitted only once. 12239 OrigLoc = SourceLocation(); 12240 } 12241 InNonTrivialUnion = true; 12242 } 12243 12244 if (InNonTrivialUnion) 12245 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12246 << 0 << 2 << QT.getUnqualifiedType() << ""; 12247 12248 for (const FieldDecl *FD : RD->fields()) 12249 if (!shouldIgnoreForRecordTriviality(FD)) 12250 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12251 } 12252 12253 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12254 const FieldDecl *FD, bool InNonTrivialUnion) {} 12255 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12256 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12257 bool InNonTrivialUnion) {} 12258 12259 // The non-trivial C union type or the struct/union type that contains a 12260 // non-trivial C union. 12261 QualType OrigTy; 12262 SourceLocation OrigLoc; 12263 Sema::NonTrivialCUnionContext UseContext; 12264 Sema &S; 12265 }; 12266 12267 } // namespace 12268 12269 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12270 NonTrivialCUnionContext UseContext, 12271 unsigned NonTrivialKind) { 12272 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12273 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12274 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12275 "shouldn't be called if type doesn't have a non-trivial C union"); 12276 12277 if ((NonTrivialKind & NTCUK_Init) && 12278 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12279 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12280 .visit(QT, nullptr, false); 12281 if ((NonTrivialKind & NTCUK_Destruct) && 12282 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12283 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12284 .visit(QT, nullptr, false); 12285 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12286 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12287 .visit(QT, nullptr, false); 12288 } 12289 12290 /// AddInitializerToDecl - Adds the initializer Init to the 12291 /// declaration dcl. If DirectInit is true, this is C++ direct 12292 /// initialization rather than copy initialization. 12293 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12294 // If there is no declaration, there was an error parsing it. Just ignore 12295 // the initializer. 12296 if (!RealDecl || RealDecl->isInvalidDecl()) { 12297 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12298 return; 12299 } 12300 12301 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12302 // Pure-specifiers are handled in ActOnPureSpecifier. 12303 Diag(Method->getLocation(), diag::err_member_function_initialization) 12304 << Method->getDeclName() << Init->getSourceRange(); 12305 Method->setInvalidDecl(); 12306 return; 12307 } 12308 12309 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12310 if (!VDecl) { 12311 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12312 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12313 RealDecl->setInvalidDecl(); 12314 return; 12315 } 12316 12317 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12318 if (VDecl->getType()->isUndeducedType()) { 12319 // Attempt typo correction early so that the type of the init expression can 12320 // be deduced based on the chosen correction if the original init contains a 12321 // TypoExpr. 12322 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12323 if (!Res.isUsable()) { 12324 // There are unresolved typos in Init, just drop them. 12325 // FIXME: improve the recovery strategy to preserve the Init. 12326 RealDecl->setInvalidDecl(); 12327 return; 12328 } 12329 if (Res.get()->containsErrors()) { 12330 // Invalidate the decl as we don't know the type for recovery-expr yet. 12331 RealDecl->setInvalidDecl(); 12332 VDecl->setInit(Res.get()); 12333 return; 12334 } 12335 Init = Res.get(); 12336 12337 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12338 return; 12339 } 12340 12341 // dllimport cannot be used on variable definitions. 12342 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12343 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12344 VDecl->setInvalidDecl(); 12345 return; 12346 } 12347 12348 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12349 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12350 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12351 VDecl->setInvalidDecl(); 12352 return; 12353 } 12354 12355 if (!VDecl->getType()->isDependentType()) { 12356 // A definition must end up with a complete type, which means it must be 12357 // complete with the restriction that an array type might be completed by 12358 // the initializer; note that later code assumes this restriction. 12359 QualType BaseDeclType = VDecl->getType(); 12360 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12361 BaseDeclType = Array->getElementType(); 12362 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12363 diag::err_typecheck_decl_incomplete_type)) { 12364 RealDecl->setInvalidDecl(); 12365 return; 12366 } 12367 12368 // The variable can not have an abstract class type. 12369 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12370 diag::err_abstract_type_in_decl, 12371 AbstractVariableType)) 12372 VDecl->setInvalidDecl(); 12373 } 12374 12375 // If adding the initializer will turn this declaration into a definition, 12376 // and we already have a definition for this variable, diagnose or otherwise 12377 // handle the situation. 12378 if (VarDecl *Def = VDecl->getDefinition()) 12379 if (Def != VDecl && 12380 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12381 !VDecl->isThisDeclarationADemotedDefinition() && 12382 checkVarDeclRedefinition(Def, VDecl)) 12383 return; 12384 12385 if (getLangOpts().CPlusPlus) { 12386 // C++ [class.static.data]p4 12387 // If a static data member is of const integral or const 12388 // enumeration type, its declaration in the class definition can 12389 // specify a constant-initializer which shall be an integral 12390 // constant expression (5.19). In that case, the member can appear 12391 // in integral constant expressions. The member shall still be 12392 // defined in a namespace scope if it is used in the program and the 12393 // namespace scope definition shall not contain an initializer. 12394 // 12395 // We already performed a redefinition check above, but for static 12396 // data members we also need to check whether there was an in-class 12397 // declaration with an initializer. 12398 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12399 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12400 << VDecl->getDeclName(); 12401 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12402 diag::note_previous_initializer) 12403 << 0; 12404 return; 12405 } 12406 12407 if (VDecl->hasLocalStorage()) 12408 setFunctionHasBranchProtectedScope(); 12409 12410 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12411 VDecl->setInvalidDecl(); 12412 return; 12413 } 12414 } 12415 12416 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12417 // a kernel function cannot be initialized." 12418 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12419 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12420 VDecl->setInvalidDecl(); 12421 return; 12422 } 12423 12424 // The LoaderUninitialized attribute acts as a definition (of undef). 12425 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12426 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12427 VDecl->setInvalidDecl(); 12428 return; 12429 } 12430 12431 // Get the decls type and save a reference for later, since 12432 // CheckInitializerTypes may change it. 12433 QualType DclT = VDecl->getType(), SavT = DclT; 12434 12435 // Expressions default to 'id' when we're in a debugger 12436 // and we are assigning it to a variable of Objective-C pointer type. 12437 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12438 Init->getType() == Context.UnknownAnyTy) { 12439 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12440 if (Result.isInvalid()) { 12441 VDecl->setInvalidDecl(); 12442 return; 12443 } 12444 Init = Result.get(); 12445 } 12446 12447 // Perform the initialization. 12448 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12449 if (!VDecl->isInvalidDecl()) { 12450 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12451 InitializationKind Kind = InitializationKind::CreateForInit( 12452 VDecl->getLocation(), DirectInit, Init); 12453 12454 MultiExprArg Args = Init; 12455 if (CXXDirectInit) 12456 Args = MultiExprArg(CXXDirectInit->getExprs(), 12457 CXXDirectInit->getNumExprs()); 12458 12459 // Try to correct any TypoExprs in the initialization arguments. 12460 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12461 ExprResult Res = CorrectDelayedTyposInExpr( 12462 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12463 [this, Entity, Kind](Expr *E) { 12464 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12465 return Init.Failed() ? ExprError() : E; 12466 }); 12467 if (Res.isInvalid()) { 12468 VDecl->setInvalidDecl(); 12469 } else if (Res.get() != Args[Idx]) { 12470 Args[Idx] = Res.get(); 12471 } 12472 } 12473 if (VDecl->isInvalidDecl()) 12474 return; 12475 12476 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12477 /*TopLevelOfInitList=*/false, 12478 /*TreatUnavailableAsInvalid=*/false); 12479 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12480 if (Result.isInvalid()) { 12481 // If the provided initializer fails to initialize the var decl, 12482 // we attach a recovery expr for better recovery. 12483 auto RecoveryExpr = 12484 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12485 if (RecoveryExpr.get()) 12486 VDecl->setInit(RecoveryExpr.get()); 12487 return; 12488 } 12489 12490 Init = Result.getAs<Expr>(); 12491 } 12492 12493 // Check for self-references within variable initializers. 12494 // Variables declared within a function/method body (except for references) 12495 // are handled by a dataflow analysis. 12496 // This is undefined behavior in C++, but valid in C. 12497 if (getLangOpts().CPlusPlus) 12498 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12499 VDecl->getType()->isReferenceType()) 12500 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12501 12502 // If the type changed, it means we had an incomplete type that was 12503 // completed by the initializer. For example: 12504 // int ary[] = { 1, 3, 5 }; 12505 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12506 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12507 VDecl->setType(DclT); 12508 12509 if (!VDecl->isInvalidDecl()) { 12510 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12511 12512 if (VDecl->hasAttr<BlocksAttr>()) 12513 checkRetainCycles(VDecl, Init); 12514 12515 // It is safe to assign a weak reference into a strong variable. 12516 // Although this code can still have problems: 12517 // id x = self.weakProp; 12518 // id y = self.weakProp; 12519 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12520 // paths through the function. This should be revisited if 12521 // -Wrepeated-use-of-weak is made flow-sensitive. 12522 if (FunctionScopeInfo *FSI = getCurFunction()) 12523 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12524 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12525 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12526 Init->getBeginLoc())) 12527 FSI->markSafeWeakUse(Init); 12528 } 12529 12530 // The initialization is usually a full-expression. 12531 // 12532 // FIXME: If this is a braced initialization of an aggregate, it is not 12533 // an expression, and each individual field initializer is a separate 12534 // full-expression. For instance, in: 12535 // 12536 // struct Temp { ~Temp(); }; 12537 // struct S { S(Temp); }; 12538 // struct T { S a, b; } t = { Temp(), Temp() } 12539 // 12540 // we should destroy the first Temp before constructing the second. 12541 ExprResult Result = 12542 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12543 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12544 if (Result.isInvalid()) { 12545 VDecl->setInvalidDecl(); 12546 return; 12547 } 12548 Init = Result.get(); 12549 12550 // Attach the initializer to the decl. 12551 VDecl->setInit(Init); 12552 12553 if (VDecl->isLocalVarDecl()) { 12554 // Don't check the initializer if the declaration is malformed. 12555 if (VDecl->isInvalidDecl()) { 12556 // do nothing 12557 12558 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12559 // This is true even in C++ for OpenCL. 12560 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12561 CheckForConstantInitializer(Init, DclT); 12562 12563 // Otherwise, C++ does not restrict the initializer. 12564 } else if (getLangOpts().CPlusPlus) { 12565 // do nothing 12566 12567 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12568 // static storage duration shall be constant expressions or string literals. 12569 } else if (VDecl->getStorageClass() == SC_Static) { 12570 CheckForConstantInitializer(Init, DclT); 12571 12572 // C89 is stricter than C99 for aggregate initializers. 12573 // C89 6.5.7p3: All the expressions [...] in an initializer list 12574 // for an object that has aggregate or union type shall be 12575 // constant expressions. 12576 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12577 isa<InitListExpr>(Init)) { 12578 const Expr *Culprit; 12579 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12580 Diag(Culprit->getExprLoc(), 12581 diag::ext_aggregate_init_not_constant) 12582 << Culprit->getSourceRange(); 12583 } 12584 } 12585 12586 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12587 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12588 if (VDecl->hasLocalStorage()) 12589 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12590 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12591 VDecl->getLexicalDeclContext()->isRecord()) { 12592 // This is an in-class initialization for a static data member, e.g., 12593 // 12594 // struct S { 12595 // static const int value = 17; 12596 // }; 12597 12598 // C++ [class.mem]p4: 12599 // A member-declarator can contain a constant-initializer only 12600 // if it declares a static member (9.4) of const integral or 12601 // const enumeration type, see 9.4.2. 12602 // 12603 // C++11 [class.static.data]p3: 12604 // If a non-volatile non-inline const static data member is of integral 12605 // or enumeration type, its declaration in the class definition can 12606 // specify a brace-or-equal-initializer in which every initializer-clause 12607 // that is an assignment-expression is a constant expression. A static 12608 // data member of literal type can be declared in the class definition 12609 // with the constexpr specifier; if so, its declaration shall specify a 12610 // brace-or-equal-initializer in which every initializer-clause that is 12611 // an assignment-expression is a constant expression. 12612 12613 // Do nothing on dependent types. 12614 if (DclT->isDependentType()) { 12615 12616 // Allow any 'static constexpr' members, whether or not they are of literal 12617 // type. We separately check that every constexpr variable is of literal 12618 // type. 12619 } else if (VDecl->isConstexpr()) { 12620 12621 // Require constness. 12622 } else if (!DclT.isConstQualified()) { 12623 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12624 << Init->getSourceRange(); 12625 VDecl->setInvalidDecl(); 12626 12627 // We allow integer constant expressions in all cases. 12628 } else if (DclT->isIntegralOrEnumerationType()) { 12629 // Check whether the expression is a constant expression. 12630 SourceLocation Loc; 12631 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12632 // In C++11, a non-constexpr const static data member with an 12633 // in-class initializer cannot be volatile. 12634 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12635 else if (Init->isValueDependent()) 12636 ; // Nothing to check. 12637 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12638 ; // Ok, it's an ICE! 12639 else if (Init->getType()->isScopedEnumeralType() && 12640 Init->isCXX11ConstantExpr(Context)) 12641 ; // Ok, it is a scoped-enum constant expression. 12642 else if (Init->isEvaluatable(Context)) { 12643 // If we can constant fold the initializer through heroics, accept it, 12644 // but report this as a use of an extension for -pedantic. 12645 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12646 << Init->getSourceRange(); 12647 } else { 12648 // Otherwise, this is some crazy unknown case. Report the issue at the 12649 // location provided by the isIntegerConstantExpr failed check. 12650 Diag(Loc, diag::err_in_class_initializer_non_constant) 12651 << Init->getSourceRange(); 12652 VDecl->setInvalidDecl(); 12653 } 12654 12655 // We allow foldable floating-point constants as an extension. 12656 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12657 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12658 // it anyway and provide a fixit to add the 'constexpr'. 12659 if (getLangOpts().CPlusPlus11) { 12660 Diag(VDecl->getLocation(), 12661 diag::ext_in_class_initializer_float_type_cxx11) 12662 << DclT << Init->getSourceRange(); 12663 Diag(VDecl->getBeginLoc(), 12664 diag::note_in_class_initializer_float_type_cxx11) 12665 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12666 } else { 12667 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12668 << DclT << Init->getSourceRange(); 12669 12670 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12671 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12672 << Init->getSourceRange(); 12673 VDecl->setInvalidDecl(); 12674 } 12675 } 12676 12677 // Suggest adding 'constexpr' in C++11 for literal types. 12678 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12679 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12680 << DclT << Init->getSourceRange() 12681 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12682 VDecl->setConstexpr(true); 12683 12684 } else { 12685 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12686 << DclT << Init->getSourceRange(); 12687 VDecl->setInvalidDecl(); 12688 } 12689 } else if (VDecl->isFileVarDecl()) { 12690 // In C, extern is typically used to avoid tentative definitions when 12691 // declaring variables in headers, but adding an intializer makes it a 12692 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12693 // In C++, extern is often used to give implictly static const variables 12694 // external linkage, so don't warn in that case. If selectany is present, 12695 // this might be header code intended for C and C++ inclusion, so apply the 12696 // C++ rules. 12697 if (VDecl->getStorageClass() == SC_Extern && 12698 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12699 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12700 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12701 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12702 Diag(VDecl->getLocation(), diag::warn_extern_init); 12703 12704 // In Microsoft C++ mode, a const variable defined in namespace scope has 12705 // external linkage by default if the variable is declared with 12706 // __declspec(dllexport). 12707 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12708 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12709 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12710 VDecl->setStorageClass(SC_Extern); 12711 12712 // C99 6.7.8p4. All file scoped initializers need to be constant. 12713 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12714 CheckForConstantInitializer(Init, DclT); 12715 } 12716 12717 QualType InitType = Init->getType(); 12718 if (!InitType.isNull() && 12719 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12720 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12721 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12722 12723 // We will represent direct-initialization similarly to copy-initialization: 12724 // int x(1); -as-> int x = 1; 12725 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12726 // 12727 // Clients that want to distinguish between the two forms, can check for 12728 // direct initializer using VarDecl::getInitStyle(). 12729 // A major benefit is that clients that don't particularly care about which 12730 // exactly form was it (like the CodeGen) can handle both cases without 12731 // special case code. 12732 12733 // C++ 8.5p11: 12734 // The form of initialization (using parentheses or '=') is generally 12735 // insignificant, but does matter when the entity being initialized has a 12736 // class type. 12737 if (CXXDirectInit) { 12738 assert(DirectInit && "Call-style initializer must be direct init."); 12739 VDecl->setInitStyle(VarDecl::CallInit); 12740 } else if (DirectInit) { 12741 // This must be list-initialization. No other way is direct-initialization. 12742 VDecl->setInitStyle(VarDecl::ListInit); 12743 } 12744 12745 if (LangOpts.OpenMP && 12746 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 12747 VDecl->isFileVarDecl()) 12748 DeclsToCheckForDeferredDiags.insert(VDecl); 12749 CheckCompleteVariableDeclaration(VDecl); 12750 } 12751 12752 /// ActOnInitializerError - Given that there was an error parsing an 12753 /// initializer for the given declaration, try to at least re-establish 12754 /// invariants such as whether a variable's type is either dependent or 12755 /// complete. 12756 void Sema::ActOnInitializerError(Decl *D) { 12757 // Our main concern here is re-establishing invariants like "a 12758 // variable's type is either dependent or complete". 12759 if (!D || D->isInvalidDecl()) return; 12760 12761 VarDecl *VD = dyn_cast<VarDecl>(D); 12762 if (!VD) return; 12763 12764 // Bindings are not usable if we can't make sense of the initializer. 12765 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12766 for (auto *BD : DD->bindings()) 12767 BD->setInvalidDecl(); 12768 12769 // Auto types are meaningless if we can't make sense of the initializer. 12770 if (VD->getType()->isUndeducedType()) { 12771 D->setInvalidDecl(); 12772 return; 12773 } 12774 12775 QualType Ty = VD->getType(); 12776 if (Ty->isDependentType()) return; 12777 12778 // Require a complete type. 12779 if (RequireCompleteType(VD->getLocation(), 12780 Context.getBaseElementType(Ty), 12781 diag::err_typecheck_decl_incomplete_type)) { 12782 VD->setInvalidDecl(); 12783 return; 12784 } 12785 12786 // Require a non-abstract type. 12787 if (RequireNonAbstractType(VD->getLocation(), Ty, 12788 diag::err_abstract_type_in_decl, 12789 AbstractVariableType)) { 12790 VD->setInvalidDecl(); 12791 return; 12792 } 12793 12794 // Don't bother complaining about constructors or destructors, 12795 // though. 12796 } 12797 12798 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12799 // If there is no declaration, there was an error parsing it. Just ignore it. 12800 if (!RealDecl) 12801 return; 12802 12803 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12804 QualType Type = Var->getType(); 12805 12806 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12807 if (isa<DecompositionDecl>(RealDecl)) { 12808 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12809 Var->setInvalidDecl(); 12810 return; 12811 } 12812 12813 if (Type->isUndeducedType() && 12814 DeduceVariableDeclarationType(Var, false, nullptr)) 12815 return; 12816 12817 // C++11 [class.static.data]p3: A static data member can be declared with 12818 // the constexpr specifier; if so, its declaration shall specify 12819 // a brace-or-equal-initializer. 12820 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12821 // the definition of a variable [...] or the declaration of a static data 12822 // member. 12823 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12824 !Var->isThisDeclarationADemotedDefinition()) { 12825 if (Var->isStaticDataMember()) { 12826 // C++1z removes the relevant rule; the in-class declaration is always 12827 // a definition there. 12828 if (!getLangOpts().CPlusPlus17 && 12829 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12830 Diag(Var->getLocation(), 12831 diag::err_constexpr_static_mem_var_requires_init) 12832 << Var; 12833 Var->setInvalidDecl(); 12834 return; 12835 } 12836 } else { 12837 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12838 Var->setInvalidDecl(); 12839 return; 12840 } 12841 } 12842 12843 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12844 // be initialized. 12845 if (!Var->isInvalidDecl() && 12846 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12847 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12848 bool HasConstExprDefaultConstructor = false; 12849 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12850 for (auto *Ctor : RD->ctors()) { 12851 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12852 Ctor->getMethodQualifiers().getAddressSpace() == 12853 LangAS::opencl_constant) { 12854 HasConstExprDefaultConstructor = true; 12855 } 12856 } 12857 } 12858 if (!HasConstExprDefaultConstructor) { 12859 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12860 Var->setInvalidDecl(); 12861 return; 12862 } 12863 } 12864 12865 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12866 if (Var->getStorageClass() == SC_Extern) { 12867 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12868 << Var; 12869 Var->setInvalidDecl(); 12870 return; 12871 } 12872 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12873 diag::err_typecheck_decl_incomplete_type)) { 12874 Var->setInvalidDecl(); 12875 return; 12876 } 12877 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12878 if (!RD->hasTrivialDefaultConstructor()) { 12879 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12880 Var->setInvalidDecl(); 12881 return; 12882 } 12883 } 12884 // The declaration is unitialized, no need for further checks. 12885 return; 12886 } 12887 12888 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12889 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12890 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12891 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12892 NTCUC_DefaultInitializedObject, NTCUK_Init); 12893 12894 12895 switch (DefKind) { 12896 case VarDecl::Definition: 12897 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12898 break; 12899 12900 // We have an out-of-line definition of a static data member 12901 // that has an in-class initializer, so we type-check this like 12902 // a declaration. 12903 // 12904 LLVM_FALLTHROUGH; 12905 12906 case VarDecl::DeclarationOnly: 12907 // It's only a declaration. 12908 12909 // Block scope. C99 6.7p7: If an identifier for an object is 12910 // declared with no linkage (C99 6.2.2p6), the type for the 12911 // object shall be complete. 12912 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12913 !Var->hasLinkage() && !Var->isInvalidDecl() && 12914 RequireCompleteType(Var->getLocation(), Type, 12915 diag::err_typecheck_decl_incomplete_type)) 12916 Var->setInvalidDecl(); 12917 12918 // Make sure that the type is not abstract. 12919 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12920 RequireNonAbstractType(Var->getLocation(), Type, 12921 diag::err_abstract_type_in_decl, 12922 AbstractVariableType)) 12923 Var->setInvalidDecl(); 12924 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12925 Var->getStorageClass() == SC_PrivateExtern) { 12926 Diag(Var->getLocation(), diag::warn_private_extern); 12927 Diag(Var->getLocation(), diag::note_private_extern); 12928 } 12929 12930 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12931 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12932 ExternalDeclarations.push_back(Var); 12933 12934 return; 12935 12936 case VarDecl::TentativeDefinition: 12937 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12938 // object that has file scope without an initializer, and without a 12939 // storage-class specifier or with the storage-class specifier "static", 12940 // constitutes a tentative definition. Note: A tentative definition with 12941 // external linkage is valid (C99 6.2.2p5). 12942 if (!Var->isInvalidDecl()) { 12943 if (const IncompleteArrayType *ArrayT 12944 = Context.getAsIncompleteArrayType(Type)) { 12945 if (RequireCompleteSizedType( 12946 Var->getLocation(), ArrayT->getElementType(), 12947 diag::err_array_incomplete_or_sizeless_type)) 12948 Var->setInvalidDecl(); 12949 } else if (Var->getStorageClass() == SC_Static) { 12950 // C99 6.9.2p3: If the declaration of an identifier for an object is 12951 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12952 // declared type shall not be an incomplete type. 12953 // NOTE: code such as the following 12954 // static struct s; 12955 // struct s { int a; }; 12956 // is accepted by gcc. Hence here we issue a warning instead of 12957 // an error and we do not invalidate the static declaration. 12958 // NOTE: to avoid multiple warnings, only check the first declaration. 12959 if (Var->isFirstDecl()) 12960 RequireCompleteType(Var->getLocation(), Type, 12961 diag::ext_typecheck_decl_incomplete_type); 12962 } 12963 } 12964 12965 // Record the tentative definition; we're done. 12966 if (!Var->isInvalidDecl()) 12967 TentativeDefinitions.push_back(Var); 12968 return; 12969 } 12970 12971 // Provide a specific diagnostic for uninitialized variable 12972 // definitions with incomplete array type. 12973 if (Type->isIncompleteArrayType()) { 12974 Diag(Var->getLocation(), 12975 diag::err_typecheck_incomplete_array_needs_initializer); 12976 Var->setInvalidDecl(); 12977 return; 12978 } 12979 12980 // Provide a specific diagnostic for uninitialized variable 12981 // definitions with reference type. 12982 if (Type->isReferenceType()) { 12983 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12984 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12985 Var->setInvalidDecl(); 12986 return; 12987 } 12988 12989 // Do not attempt to type-check the default initializer for a 12990 // variable with dependent type. 12991 if (Type->isDependentType()) 12992 return; 12993 12994 if (Var->isInvalidDecl()) 12995 return; 12996 12997 if (!Var->hasAttr<AliasAttr>()) { 12998 if (RequireCompleteType(Var->getLocation(), 12999 Context.getBaseElementType(Type), 13000 diag::err_typecheck_decl_incomplete_type)) { 13001 Var->setInvalidDecl(); 13002 return; 13003 } 13004 } else { 13005 return; 13006 } 13007 13008 // The variable can not have an abstract class type. 13009 if (RequireNonAbstractType(Var->getLocation(), Type, 13010 diag::err_abstract_type_in_decl, 13011 AbstractVariableType)) { 13012 Var->setInvalidDecl(); 13013 return; 13014 } 13015 13016 // Check for jumps past the implicit initializer. C++0x 13017 // clarifies that this applies to a "variable with automatic 13018 // storage duration", not a "local variable". 13019 // C++11 [stmt.dcl]p3 13020 // A program that jumps from a point where a variable with automatic 13021 // storage duration is not in scope to a point where it is in scope is 13022 // ill-formed unless the variable has scalar type, class type with a 13023 // trivial default constructor and a trivial destructor, a cv-qualified 13024 // version of one of these types, or an array of one of the preceding 13025 // types and is declared without an initializer. 13026 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 13027 if (const RecordType *Record 13028 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 13029 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 13030 // Mark the function (if we're in one) for further checking even if the 13031 // looser rules of C++11 do not require such checks, so that we can 13032 // diagnose incompatibilities with C++98. 13033 if (!CXXRecord->isPOD()) 13034 setFunctionHasBranchProtectedScope(); 13035 } 13036 } 13037 // In OpenCL, we can't initialize objects in the __local address space, 13038 // even implicitly, so don't synthesize an implicit initializer. 13039 if (getLangOpts().OpenCL && 13040 Var->getType().getAddressSpace() == LangAS::opencl_local) 13041 return; 13042 // C++03 [dcl.init]p9: 13043 // If no initializer is specified for an object, and the 13044 // object is of (possibly cv-qualified) non-POD class type (or 13045 // array thereof), the object shall be default-initialized; if 13046 // the object is of const-qualified type, the underlying class 13047 // type shall have a user-declared default 13048 // constructor. Otherwise, if no initializer is specified for 13049 // a non- static object, the object and its subobjects, if 13050 // any, have an indeterminate initial value); if the object 13051 // or any of its subobjects are of const-qualified type, the 13052 // program is ill-formed. 13053 // C++0x [dcl.init]p11: 13054 // If no initializer is specified for an object, the object is 13055 // default-initialized; [...]. 13056 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 13057 InitializationKind Kind 13058 = InitializationKind::CreateDefault(Var->getLocation()); 13059 13060 InitializationSequence InitSeq(*this, Entity, Kind, None); 13061 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 13062 13063 if (Init.get()) { 13064 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 13065 // This is important for template substitution. 13066 Var->setInitStyle(VarDecl::CallInit); 13067 } else if (Init.isInvalid()) { 13068 // If default-init fails, attach a recovery-expr initializer to track 13069 // that initialization was attempted and failed. 13070 auto RecoveryExpr = 13071 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 13072 if (RecoveryExpr.get()) 13073 Var->setInit(RecoveryExpr.get()); 13074 } 13075 13076 CheckCompleteVariableDeclaration(Var); 13077 } 13078 } 13079 13080 void Sema::ActOnCXXForRangeDecl(Decl *D) { 13081 // If there is no declaration, there was an error parsing it. Ignore it. 13082 if (!D) 13083 return; 13084 13085 VarDecl *VD = dyn_cast<VarDecl>(D); 13086 if (!VD) { 13087 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 13088 D->setInvalidDecl(); 13089 return; 13090 } 13091 13092 VD->setCXXForRangeDecl(true); 13093 13094 // for-range-declaration cannot be given a storage class specifier. 13095 int Error = -1; 13096 switch (VD->getStorageClass()) { 13097 case SC_None: 13098 break; 13099 case SC_Extern: 13100 Error = 0; 13101 break; 13102 case SC_Static: 13103 Error = 1; 13104 break; 13105 case SC_PrivateExtern: 13106 Error = 2; 13107 break; 13108 case SC_Auto: 13109 Error = 3; 13110 break; 13111 case SC_Register: 13112 Error = 4; 13113 break; 13114 } 13115 13116 // for-range-declaration cannot be given a storage class specifier con't. 13117 switch (VD->getTSCSpec()) { 13118 case TSCS_thread_local: 13119 Error = 6; 13120 break; 13121 case TSCS___thread: 13122 case TSCS__Thread_local: 13123 case TSCS_unspecified: 13124 break; 13125 } 13126 13127 if (Error != -1) { 13128 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 13129 << VD << Error; 13130 D->setInvalidDecl(); 13131 } 13132 } 13133 13134 StmtResult 13135 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13136 IdentifierInfo *Ident, 13137 ParsedAttributes &Attrs, 13138 SourceLocation AttrEnd) { 13139 // C++1y [stmt.iter]p1: 13140 // A range-based for statement of the form 13141 // for ( for-range-identifier : for-range-initializer ) statement 13142 // is equivalent to 13143 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13144 DeclSpec DS(Attrs.getPool().getFactory()); 13145 13146 const char *PrevSpec; 13147 unsigned DiagID; 13148 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13149 getPrintingPolicy()); 13150 13151 Declarator D(DS, DeclaratorContext::ForInit); 13152 D.SetIdentifier(Ident, IdentLoc); 13153 D.takeAttributes(Attrs, AttrEnd); 13154 13155 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13156 IdentLoc); 13157 Decl *Var = ActOnDeclarator(S, D); 13158 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13159 FinalizeDeclaration(Var); 13160 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13161 AttrEnd.isValid() ? AttrEnd : IdentLoc); 13162 } 13163 13164 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13165 if (var->isInvalidDecl()) return; 13166 13167 MaybeAddCUDAConstantAttr(var); 13168 13169 if (getLangOpts().OpenCL) { 13170 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13171 // initialiser 13172 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13173 !var->hasInit()) { 13174 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13175 << 1 /*Init*/; 13176 var->setInvalidDecl(); 13177 return; 13178 } 13179 } 13180 13181 // In Objective-C, don't allow jumps past the implicit initialization of a 13182 // local retaining variable. 13183 if (getLangOpts().ObjC && 13184 var->hasLocalStorage()) { 13185 switch (var->getType().getObjCLifetime()) { 13186 case Qualifiers::OCL_None: 13187 case Qualifiers::OCL_ExplicitNone: 13188 case Qualifiers::OCL_Autoreleasing: 13189 break; 13190 13191 case Qualifiers::OCL_Weak: 13192 case Qualifiers::OCL_Strong: 13193 setFunctionHasBranchProtectedScope(); 13194 break; 13195 } 13196 } 13197 13198 if (var->hasLocalStorage() && 13199 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13200 setFunctionHasBranchProtectedScope(); 13201 13202 // Warn about externally-visible variables being defined without a 13203 // prior declaration. We only want to do this for global 13204 // declarations, but we also specifically need to avoid doing it for 13205 // class members because the linkage of an anonymous class can 13206 // change if it's later given a typedef name. 13207 if (var->isThisDeclarationADefinition() && 13208 var->getDeclContext()->getRedeclContext()->isFileContext() && 13209 var->isExternallyVisible() && var->hasLinkage() && 13210 !var->isInline() && !var->getDescribedVarTemplate() && 13211 !isa<VarTemplatePartialSpecializationDecl>(var) && 13212 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13213 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13214 var->getLocation())) { 13215 // Find a previous declaration that's not a definition. 13216 VarDecl *prev = var->getPreviousDecl(); 13217 while (prev && prev->isThisDeclarationADefinition()) 13218 prev = prev->getPreviousDecl(); 13219 13220 if (!prev) { 13221 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13222 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13223 << /* variable */ 0; 13224 } 13225 } 13226 13227 // Cache the result of checking for constant initialization. 13228 Optional<bool> CacheHasConstInit; 13229 const Expr *CacheCulprit = nullptr; 13230 auto checkConstInit = [&]() mutable { 13231 if (!CacheHasConstInit) 13232 CacheHasConstInit = var->getInit()->isConstantInitializer( 13233 Context, var->getType()->isReferenceType(), &CacheCulprit); 13234 return *CacheHasConstInit; 13235 }; 13236 13237 if (var->getTLSKind() == VarDecl::TLS_Static) { 13238 if (var->getType().isDestructedType()) { 13239 // GNU C++98 edits for __thread, [basic.start.term]p3: 13240 // The type of an object with thread storage duration shall not 13241 // have a non-trivial destructor. 13242 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13243 if (getLangOpts().CPlusPlus11) 13244 Diag(var->getLocation(), diag::note_use_thread_local); 13245 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13246 if (!checkConstInit()) { 13247 // GNU C++98 edits for __thread, [basic.start.init]p4: 13248 // An object of thread storage duration shall not require dynamic 13249 // initialization. 13250 // FIXME: Need strict checking here. 13251 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13252 << CacheCulprit->getSourceRange(); 13253 if (getLangOpts().CPlusPlus11) 13254 Diag(var->getLocation(), diag::note_use_thread_local); 13255 } 13256 } 13257 } 13258 13259 13260 if (!var->getType()->isStructureType() && var->hasInit() && 13261 isa<InitListExpr>(var->getInit())) { 13262 const auto *ILE = cast<InitListExpr>(var->getInit()); 13263 unsigned NumInits = ILE->getNumInits(); 13264 if (NumInits > 2) 13265 for (unsigned I = 0; I < NumInits; ++I) { 13266 const auto *Init = ILE->getInit(I); 13267 if (!Init) 13268 break; 13269 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13270 if (!SL) 13271 break; 13272 13273 unsigned NumConcat = SL->getNumConcatenated(); 13274 // Diagnose missing comma in string array initialization. 13275 // Do not warn when all the elements in the initializer are concatenated 13276 // together. Do not warn for macros too. 13277 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13278 bool OnlyOneMissingComma = true; 13279 for (unsigned J = I + 1; J < NumInits; ++J) { 13280 const auto *Init = ILE->getInit(J); 13281 if (!Init) 13282 break; 13283 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13284 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13285 OnlyOneMissingComma = false; 13286 break; 13287 } 13288 } 13289 13290 if (OnlyOneMissingComma) { 13291 SmallVector<FixItHint, 1> Hints; 13292 for (unsigned i = 0; i < NumConcat - 1; ++i) 13293 Hints.push_back(FixItHint::CreateInsertion( 13294 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13295 13296 Diag(SL->getStrTokenLoc(1), 13297 diag::warn_concatenated_literal_array_init) 13298 << Hints; 13299 Diag(SL->getBeginLoc(), 13300 diag::note_concatenated_string_literal_silence); 13301 } 13302 // In any case, stop now. 13303 break; 13304 } 13305 } 13306 } 13307 13308 13309 QualType type = var->getType(); 13310 13311 if (var->hasAttr<BlocksAttr>()) 13312 getCurFunction()->addByrefBlockVar(var); 13313 13314 Expr *Init = var->getInit(); 13315 bool GlobalStorage = var->hasGlobalStorage(); 13316 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13317 QualType baseType = Context.getBaseElementType(type); 13318 bool HasConstInit = true; 13319 13320 // Check whether the initializer is sufficiently constant. 13321 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13322 !Init->isValueDependent() && 13323 (GlobalStorage || var->isConstexpr() || 13324 var->mightBeUsableInConstantExpressions(Context))) { 13325 // If this variable might have a constant initializer or might be usable in 13326 // constant expressions, check whether or not it actually is now. We can't 13327 // do this lazily, because the result might depend on things that change 13328 // later, such as which constexpr functions happen to be defined. 13329 SmallVector<PartialDiagnosticAt, 8> Notes; 13330 if (!getLangOpts().CPlusPlus11) { 13331 // Prior to C++11, in contexts where a constant initializer is required, 13332 // the set of valid constant initializers is described by syntactic rules 13333 // in [expr.const]p2-6. 13334 // FIXME: Stricter checking for these rules would be useful for constinit / 13335 // -Wglobal-constructors. 13336 HasConstInit = checkConstInit(); 13337 13338 // Compute and cache the constant value, and remember that we have a 13339 // constant initializer. 13340 if (HasConstInit) { 13341 (void)var->checkForConstantInitialization(Notes); 13342 Notes.clear(); 13343 } else if (CacheCulprit) { 13344 Notes.emplace_back(CacheCulprit->getExprLoc(), 13345 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13346 Notes.back().second << CacheCulprit->getSourceRange(); 13347 } 13348 } else { 13349 // Evaluate the initializer to see if it's a constant initializer. 13350 HasConstInit = var->checkForConstantInitialization(Notes); 13351 } 13352 13353 if (HasConstInit) { 13354 // FIXME: Consider replacing the initializer with a ConstantExpr. 13355 } else if (var->isConstexpr()) { 13356 SourceLocation DiagLoc = var->getLocation(); 13357 // If the note doesn't add any useful information other than a source 13358 // location, fold it into the primary diagnostic. 13359 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13360 diag::note_invalid_subexpr_in_const_expr) { 13361 DiagLoc = Notes[0].first; 13362 Notes.clear(); 13363 } 13364 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13365 << var << Init->getSourceRange(); 13366 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13367 Diag(Notes[I].first, Notes[I].second); 13368 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13369 auto *Attr = var->getAttr<ConstInitAttr>(); 13370 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13371 << Init->getSourceRange(); 13372 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13373 << Attr->getRange() << Attr->isConstinit(); 13374 for (auto &it : Notes) 13375 Diag(it.first, it.second); 13376 } else if (IsGlobal && 13377 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13378 var->getLocation())) { 13379 // Warn about globals which don't have a constant initializer. Don't 13380 // warn about globals with a non-trivial destructor because we already 13381 // warned about them. 13382 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13383 if (!(RD && !RD->hasTrivialDestructor())) { 13384 // checkConstInit() here permits trivial default initialization even in 13385 // C++11 onwards, where such an initializer is not a constant initializer 13386 // but nonetheless doesn't require a global constructor. 13387 if (!checkConstInit()) 13388 Diag(var->getLocation(), diag::warn_global_constructor) 13389 << Init->getSourceRange(); 13390 } 13391 } 13392 } 13393 13394 // Apply section attributes and pragmas to global variables. 13395 if (GlobalStorage && var->isThisDeclarationADefinition() && 13396 !inTemplateInstantiation()) { 13397 PragmaStack<StringLiteral *> *Stack = nullptr; 13398 int SectionFlags = ASTContext::PSF_Read; 13399 if (var->getType().isConstQualified()) { 13400 if (HasConstInit) 13401 Stack = &ConstSegStack; 13402 else { 13403 Stack = &BSSSegStack; 13404 SectionFlags |= ASTContext::PSF_Write; 13405 } 13406 } else if (var->hasInit() && HasConstInit) { 13407 Stack = &DataSegStack; 13408 SectionFlags |= ASTContext::PSF_Write; 13409 } else { 13410 Stack = &BSSSegStack; 13411 SectionFlags |= ASTContext::PSF_Write; 13412 } 13413 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13414 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13415 SectionFlags |= ASTContext::PSF_Implicit; 13416 UnifySection(SA->getName(), SectionFlags, var); 13417 } else if (Stack->CurrentValue) { 13418 SectionFlags |= ASTContext::PSF_Implicit; 13419 auto SectionName = Stack->CurrentValue->getString(); 13420 var->addAttr(SectionAttr::CreateImplicit( 13421 Context, SectionName, Stack->CurrentPragmaLocation, 13422 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13423 if (UnifySection(SectionName, SectionFlags, var)) 13424 var->dropAttr<SectionAttr>(); 13425 } 13426 13427 // Apply the init_seg attribute if this has an initializer. If the 13428 // initializer turns out to not be dynamic, we'll end up ignoring this 13429 // attribute. 13430 if (CurInitSeg && var->getInit()) 13431 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13432 CurInitSegLoc, 13433 AttributeCommonInfo::AS_Pragma)); 13434 } 13435 13436 // All the following checks are C++ only. 13437 if (!getLangOpts().CPlusPlus) { 13438 // If this variable must be emitted, add it as an initializer for the 13439 // current module. 13440 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13441 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13442 return; 13443 } 13444 13445 // Require the destructor. 13446 if (!type->isDependentType()) 13447 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13448 FinalizeVarWithDestructor(var, recordType); 13449 13450 // If this variable must be emitted, add it as an initializer for the current 13451 // module. 13452 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13453 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13454 13455 // Build the bindings if this is a structured binding declaration. 13456 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13457 CheckCompleteDecompositionDeclaration(DD); 13458 } 13459 13460 /// Check if VD needs to be dllexport/dllimport due to being in a 13461 /// dllexport/import function. 13462 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13463 assert(VD->isStaticLocal()); 13464 13465 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13466 13467 // Find outermost function when VD is in lambda function. 13468 while (FD && !getDLLAttr(FD) && 13469 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13470 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13471 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13472 } 13473 13474 if (!FD) 13475 return; 13476 13477 // Static locals inherit dll attributes from their function. 13478 if (Attr *A = getDLLAttr(FD)) { 13479 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13480 NewAttr->setInherited(true); 13481 VD->addAttr(NewAttr); 13482 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13483 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13484 NewAttr->setInherited(true); 13485 VD->addAttr(NewAttr); 13486 13487 // Export this function to enforce exporting this static variable even 13488 // if it is not used in this compilation unit. 13489 if (!FD->hasAttr<DLLExportAttr>()) 13490 FD->addAttr(NewAttr); 13491 13492 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13493 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13494 NewAttr->setInherited(true); 13495 VD->addAttr(NewAttr); 13496 } 13497 } 13498 13499 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13500 /// any semantic actions necessary after any initializer has been attached. 13501 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13502 // Note that we are no longer parsing the initializer for this declaration. 13503 ParsingInitForAutoVars.erase(ThisDecl); 13504 13505 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13506 if (!VD) 13507 return; 13508 13509 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13510 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13511 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13512 if (PragmaClangBSSSection.Valid) 13513 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13514 Context, PragmaClangBSSSection.SectionName, 13515 PragmaClangBSSSection.PragmaLocation, 13516 AttributeCommonInfo::AS_Pragma)); 13517 if (PragmaClangDataSection.Valid) 13518 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13519 Context, PragmaClangDataSection.SectionName, 13520 PragmaClangDataSection.PragmaLocation, 13521 AttributeCommonInfo::AS_Pragma)); 13522 if (PragmaClangRodataSection.Valid) 13523 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13524 Context, PragmaClangRodataSection.SectionName, 13525 PragmaClangRodataSection.PragmaLocation, 13526 AttributeCommonInfo::AS_Pragma)); 13527 if (PragmaClangRelroSection.Valid) 13528 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13529 Context, PragmaClangRelroSection.SectionName, 13530 PragmaClangRelroSection.PragmaLocation, 13531 AttributeCommonInfo::AS_Pragma)); 13532 } 13533 13534 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13535 for (auto *BD : DD->bindings()) { 13536 FinalizeDeclaration(BD); 13537 } 13538 } 13539 13540 checkAttributesAfterMerging(*this, *VD); 13541 13542 // Perform TLS alignment check here after attributes attached to the variable 13543 // which may affect the alignment have been processed. Only perform the check 13544 // if the target has a maximum TLS alignment (zero means no constraints). 13545 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13546 // Protect the check so that it's not performed on dependent types and 13547 // dependent alignments (we can't determine the alignment in that case). 13548 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13549 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13550 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13551 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13552 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13553 << (unsigned)MaxAlignChars.getQuantity(); 13554 } 13555 } 13556 } 13557 13558 if (VD->isStaticLocal()) 13559 CheckStaticLocalForDllExport(VD); 13560 13561 // Perform check for initializers of device-side global variables. 13562 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13563 // 7.5). We must also apply the same checks to all __shared__ 13564 // variables whether they are local or not. CUDA also allows 13565 // constant initializers for __constant__ and __device__ variables. 13566 if (getLangOpts().CUDA) 13567 checkAllowedCUDAInitializer(VD); 13568 13569 // Grab the dllimport or dllexport attribute off of the VarDecl. 13570 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13571 13572 // Imported static data members cannot be defined out-of-line. 13573 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13574 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13575 VD->isThisDeclarationADefinition()) { 13576 // We allow definitions of dllimport class template static data members 13577 // with a warning. 13578 CXXRecordDecl *Context = 13579 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13580 bool IsClassTemplateMember = 13581 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13582 Context->getDescribedClassTemplate(); 13583 13584 Diag(VD->getLocation(), 13585 IsClassTemplateMember 13586 ? diag::warn_attribute_dllimport_static_field_definition 13587 : diag::err_attribute_dllimport_static_field_definition); 13588 Diag(IA->getLocation(), diag::note_attribute); 13589 if (!IsClassTemplateMember) 13590 VD->setInvalidDecl(); 13591 } 13592 } 13593 13594 // dllimport/dllexport variables cannot be thread local, their TLS index 13595 // isn't exported with the variable. 13596 if (DLLAttr && VD->getTLSKind()) { 13597 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13598 if (F && getDLLAttr(F)) { 13599 assert(VD->isStaticLocal()); 13600 // But if this is a static local in a dlimport/dllexport function, the 13601 // function will never be inlined, which means the var would never be 13602 // imported, so having it marked import/export is safe. 13603 } else { 13604 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13605 << DLLAttr; 13606 VD->setInvalidDecl(); 13607 } 13608 } 13609 13610 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13611 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13612 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13613 << Attr; 13614 VD->dropAttr<UsedAttr>(); 13615 } 13616 } 13617 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13618 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13619 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13620 << Attr; 13621 VD->dropAttr<RetainAttr>(); 13622 } 13623 } 13624 13625 const DeclContext *DC = VD->getDeclContext(); 13626 // If there's a #pragma GCC visibility in scope, and this isn't a class 13627 // member, set the visibility of this variable. 13628 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13629 AddPushedVisibilityAttribute(VD); 13630 13631 // FIXME: Warn on unused var template partial specializations. 13632 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13633 MarkUnusedFileScopedDecl(VD); 13634 13635 // Now we have parsed the initializer and can update the table of magic 13636 // tag values. 13637 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13638 !VD->getType()->isIntegralOrEnumerationType()) 13639 return; 13640 13641 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13642 const Expr *MagicValueExpr = VD->getInit(); 13643 if (!MagicValueExpr) { 13644 continue; 13645 } 13646 Optional<llvm::APSInt> MagicValueInt; 13647 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13648 Diag(I->getRange().getBegin(), 13649 diag::err_type_tag_for_datatype_not_ice) 13650 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13651 continue; 13652 } 13653 if (MagicValueInt->getActiveBits() > 64) { 13654 Diag(I->getRange().getBegin(), 13655 diag::err_type_tag_for_datatype_too_large) 13656 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13657 continue; 13658 } 13659 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13660 RegisterTypeTagForDatatype(I->getArgumentKind(), 13661 MagicValue, 13662 I->getMatchingCType(), 13663 I->getLayoutCompatible(), 13664 I->getMustBeNull()); 13665 } 13666 } 13667 13668 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13669 auto *VD = dyn_cast<VarDecl>(DD); 13670 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13671 } 13672 13673 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13674 ArrayRef<Decl *> Group) { 13675 SmallVector<Decl*, 8> Decls; 13676 13677 if (DS.isTypeSpecOwned()) 13678 Decls.push_back(DS.getRepAsDecl()); 13679 13680 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13681 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13682 bool DiagnosedMultipleDecomps = false; 13683 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13684 bool DiagnosedNonDeducedAuto = false; 13685 13686 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13687 if (Decl *D = Group[i]) { 13688 // For declarators, there are some additional syntactic-ish checks we need 13689 // to perform. 13690 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13691 if (!FirstDeclaratorInGroup) 13692 FirstDeclaratorInGroup = DD; 13693 if (!FirstDecompDeclaratorInGroup) 13694 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13695 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13696 !hasDeducedAuto(DD)) 13697 FirstNonDeducedAutoInGroup = DD; 13698 13699 if (FirstDeclaratorInGroup != DD) { 13700 // A decomposition declaration cannot be combined with any other 13701 // declaration in the same group. 13702 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13703 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13704 diag::err_decomp_decl_not_alone) 13705 << FirstDeclaratorInGroup->getSourceRange() 13706 << DD->getSourceRange(); 13707 DiagnosedMultipleDecomps = true; 13708 } 13709 13710 // A declarator that uses 'auto' in any way other than to declare a 13711 // variable with a deduced type cannot be combined with any other 13712 // declarator in the same group. 13713 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13714 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13715 diag::err_auto_non_deduced_not_alone) 13716 << FirstNonDeducedAutoInGroup->getType() 13717 ->hasAutoForTrailingReturnType() 13718 << FirstDeclaratorInGroup->getSourceRange() 13719 << DD->getSourceRange(); 13720 DiagnosedNonDeducedAuto = true; 13721 } 13722 } 13723 } 13724 13725 Decls.push_back(D); 13726 } 13727 } 13728 13729 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13730 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13731 handleTagNumbering(Tag, S); 13732 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13733 getLangOpts().CPlusPlus) 13734 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13735 } 13736 } 13737 13738 return BuildDeclaratorGroup(Decls); 13739 } 13740 13741 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13742 /// group, performing any necessary semantic checking. 13743 Sema::DeclGroupPtrTy 13744 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13745 // C++14 [dcl.spec.auto]p7: (DR1347) 13746 // If the type that replaces the placeholder type is not the same in each 13747 // deduction, the program is ill-formed. 13748 if (Group.size() > 1) { 13749 QualType Deduced; 13750 VarDecl *DeducedDecl = nullptr; 13751 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13752 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13753 if (!D || D->isInvalidDecl()) 13754 break; 13755 DeducedType *DT = D->getType()->getContainedDeducedType(); 13756 if (!DT || DT->getDeducedType().isNull()) 13757 continue; 13758 if (Deduced.isNull()) { 13759 Deduced = DT->getDeducedType(); 13760 DeducedDecl = D; 13761 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13762 auto *AT = dyn_cast<AutoType>(DT); 13763 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13764 diag::err_auto_different_deductions) 13765 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13766 << DeducedDecl->getDeclName() << DT->getDeducedType() 13767 << D->getDeclName(); 13768 if (DeducedDecl->hasInit()) 13769 Dia << DeducedDecl->getInit()->getSourceRange(); 13770 if (D->getInit()) 13771 Dia << D->getInit()->getSourceRange(); 13772 D->setInvalidDecl(); 13773 break; 13774 } 13775 } 13776 } 13777 13778 ActOnDocumentableDecls(Group); 13779 13780 return DeclGroupPtrTy::make( 13781 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13782 } 13783 13784 void Sema::ActOnDocumentableDecl(Decl *D) { 13785 ActOnDocumentableDecls(D); 13786 } 13787 13788 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13789 // Don't parse the comment if Doxygen diagnostics are ignored. 13790 if (Group.empty() || !Group[0]) 13791 return; 13792 13793 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13794 Group[0]->getLocation()) && 13795 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13796 Group[0]->getLocation())) 13797 return; 13798 13799 if (Group.size() >= 2) { 13800 // This is a decl group. Normally it will contain only declarations 13801 // produced from declarator list. But in case we have any definitions or 13802 // additional declaration references: 13803 // 'typedef struct S {} S;' 13804 // 'typedef struct S *S;' 13805 // 'struct S *pS;' 13806 // FinalizeDeclaratorGroup adds these as separate declarations. 13807 Decl *MaybeTagDecl = Group[0]; 13808 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13809 Group = Group.slice(1); 13810 } 13811 } 13812 13813 // FIMXE: We assume every Decl in the group is in the same file. 13814 // This is false when preprocessor constructs the group from decls in 13815 // different files (e. g. macros or #include). 13816 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13817 } 13818 13819 /// Common checks for a parameter-declaration that should apply to both function 13820 /// parameters and non-type template parameters. 13821 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13822 // Check that there are no default arguments inside the type of this 13823 // parameter. 13824 if (getLangOpts().CPlusPlus) 13825 CheckExtraCXXDefaultArguments(D); 13826 13827 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13828 if (D.getCXXScopeSpec().isSet()) { 13829 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13830 << D.getCXXScopeSpec().getRange(); 13831 } 13832 13833 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13834 // simple identifier except [...irrelevant cases...]. 13835 switch (D.getName().getKind()) { 13836 case UnqualifiedIdKind::IK_Identifier: 13837 break; 13838 13839 case UnqualifiedIdKind::IK_OperatorFunctionId: 13840 case UnqualifiedIdKind::IK_ConversionFunctionId: 13841 case UnqualifiedIdKind::IK_LiteralOperatorId: 13842 case UnqualifiedIdKind::IK_ConstructorName: 13843 case UnqualifiedIdKind::IK_DestructorName: 13844 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13845 case UnqualifiedIdKind::IK_DeductionGuideName: 13846 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13847 << GetNameForDeclarator(D).getName(); 13848 break; 13849 13850 case UnqualifiedIdKind::IK_TemplateId: 13851 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13852 // GetNameForDeclarator would not produce a useful name in this case. 13853 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13854 break; 13855 } 13856 } 13857 13858 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13859 /// to introduce parameters into function prototype scope. 13860 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13861 const DeclSpec &DS = D.getDeclSpec(); 13862 13863 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13864 13865 // C++03 [dcl.stc]p2 also permits 'auto'. 13866 StorageClass SC = SC_None; 13867 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13868 SC = SC_Register; 13869 // In C++11, the 'register' storage class specifier is deprecated. 13870 // In C++17, it is not allowed, but we tolerate it as an extension. 13871 if (getLangOpts().CPlusPlus11) { 13872 Diag(DS.getStorageClassSpecLoc(), 13873 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13874 : diag::warn_deprecated_register) 13875 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13876 } 13877 } else if (getLangOpts().CPlusPlus && 13878 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13879 SC = SC_Auto; 13880 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13881 Diag(DS.getStorageClassSpecLoc(), 13882 diag::err_invalid_storage_class_in_func_decl); 13883 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13884 } 13885 13886 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13887 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13888 << DeclSpec::getSpecifierName(TSCS); 13889 if (DS.isInlineSpecified()) 13890 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13891 << getLangOpts().CPlusPlus17; 13892 if (DS.hasConstexprSpecifier()) 13893 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13894 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13895 13896 DiagnoseFunctionSpecifiers(DS); 13897 13898 CheckFunctionOrTemplateParamDeclarator(S, D); 13899 13900 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13901 QualType parmDeclType = TInfo->getType(); 13902 13903 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13904 IdentifierInfo *II = D.getIdentifier(); 13905 if (II) { 13906 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13907 ForVisibleRedeclaration); 13908 LookupName(R, S); 13909 if (R.isSingleResult()) { 13910 NamedDecl *PrevDecl = R.getFoundDecl(); 13911 if (PrevDecl->isTemplateParameter()) { 13912 // Maybe we will complain about the shadowed template parameter. 13913 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13914 // Just pretend that we didn't see the previous declaration. 13915 PrevDecl = nullptr; 13916 } else if (S->isDeclScope(PrevDecl)) { 13917 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13918 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13919 13920 // Recover by removing the name 13921 II = nullptr; 13922 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13923 D.setInvalidType(true); 13924 } 13925 } 13926 } 13927 13928 // Temporarily put parameter variables in the translation unit, not 13929 // the enclosing context. This prevents them from accidentally 13930 // looking like class members in C++. 13931 ParmVarDecl *New = 13932 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13933 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13934 13935 if (D.isInvalidType()) 13936 New->setInvalidDecl(); 13937 13938 assert(S->isFunctionPrototypeScope()); 13939 assert(S->getFunctionPrototypeDepth() >= 1); 13940 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13941 S->getNextFunctionPrototypeIndex()); 13942 13943 // Add the parameter declaration into this scope. 13944 S->AddDecl(New); 13945 if (II) 13946 IdResolver.AddDecl(New); 13947 13948 ProcessDeclAttributes(S, New, D); 13949 13950 if (D.getDeclSpec().isModulePrivateSpecified()) 13951 Diag(New->getLocation(), diag::err_module_private_local) 13952 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13953 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13954 13955 if (New->hasAttr<BlocksAttr>()) { 13956 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13957 } 13958 13959 if (getLangOpts().OpenCL) 13960 deduceOpenCLAddressSpace(New); 13961 13962 return New; 13963 } 13964 13965 /// Synthesizes a variable for a parameter arising from a 13966 /// typedef. 13967 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13968 SourceLocation Loc, 13969 QualType T) { 13970 /* FIXME: setting StartLoc == Loc. 13971 Would it be worth to modify callers so as to provide proper source 13972 location for the unnamed parameters, embedding the parameter's type? */ 13973 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13974 T, Context.getTrivialTypeSourceInfo(T, Loc), 13975 SC_None, nullptr); 13976 Param->setImplicit(); 13977 return Param; 13978 } 13979 13980 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13981 // Don't diagnose unused-parameter errors in template instantiations; we 13982 // will already have done so in the template itself. 13983 if (inTemplateInstantiation()) 13984 return; 13985 13986 for (const ParmVarDecl *Parameter : Parameters) { 13987 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13988 !Parameter->hasAttr<UnusedAttr>()) { 13989 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13990 << Parameter->getDeclName(); 13991 } 13992 } 13993 } 13994 13995 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13996 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13997 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13998 return; 13999 14000 // Warn if the return value is pass-by-value and larger than the specified 14001 // threshold. 14002 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 14003 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 14004 if (Size > LangOpts.NumLargeByValueCopy) 14005 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 14006 } 14007 14008 // Warn if any parameter is pass-by-value and larger than the specified 14009 // threshold. 14010 for (const ParmVarDecl *Parameter : Parameters) { 14011 QualType T = Parameter->getType(); 14012 if (T->isDependentType() || !T.isPODType(Context)) 14013 continue; 14014 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 14015 if (Size > LangOpts.NumLargeByValueCopy) 14016 Diag(Parameter->getLocation(), diag::warn_parameter_size) 14017 << Parameter << Size; 14018 } 14019 } 14020 14021 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 14022 SourceLocation NameLoc, IdentifierInfo *Name, 14023 QualType T, TypeSourceInfo *TSInfo, 14024 StorageClass SC) { 14025 // In ARC, infer a lifetime qualifier for appropriate parameter types. 14026 if (getLangOpts().ObjCAutoRefCount && 14027 T.getObjCLifetime() == Qualifiers::OCL_None && 14028 T->isObjCLifetimeType()) { 14029 14030 Qualifiers::ObjCLifetime lifetime; 14031 14032 // Special cases for arrays: 14033 // - if it's const, use __unsafe_unretained 14034 // - otherwise, it's an error 14035 if (T->isArrayType()) { 14036 if (!T.isConstQualified()) { 14037 if (DelayedDiagnostics.shouldDelayDiagnostics()) 14038 DelayedDiagnostics.add( 14039 sema::DelayedDiagnostic::makeForbiddenType( 14040 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 14041 else 14042 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 14043 << TSInfo->getTypeLoc().getSourceRange(); 14044 } 14045 lifetime = Qualifiers::OCL_ExplicitNone; 14046 } else { 14047 lifetime = T->getObjCARCImplicitLifetime(); 14048 } 14049 T = Context.getLifetimeQualifiedType(T, lifetime); 14050 } 14051 14052 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 14053 Context.getAdjustedParameterType(T), 14054 TSInfo, SC, nullptr); 14055 14056 // Make a note if we created a new pack in the scope of a lambda, so that 14057 // we know that references to that pack must also be expanded within the 14058 // lambda scope. 14059 if (New->isParameterPack()) 14060 if (auto *LSI = getEnclosingLambda()) 14061 LSI->LocalPacks.push_back(New); 14062 14063 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 14064 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14065 checkNonTrivialCUnion(New->getType(), New->getLocation(), 14066 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 14067 14068 // Parameters can not be abstract class types. 14069 // For record types, this is done by the AbstractClassUsageDiagnoser once 14070 // the class has been completely parsed. 14071 if (!CurContext->isRecord() && 14072 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 14073 AbstractParamType)) 14074 New->setInvalidDecl(); 14075 14076 // Parameter declarators cannot be interface types. All ObjC objects are 14077 // passed by reference. 14078 if (T->isObjCObjectType()) { 14079 SourceLocation TypeEndLoc = 14080 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 14081 Diag(NameLoc, 14082 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 14083 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 14084 T = Context.getObjCObjectPointerType(T); 14085 New->setType(T); 14086 } 14087 14088 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 14089 // duration shall not be qualified by an address-space qualifier." 14090 // Since all parameters have automatic store duration, they can not have 14091 // an address space. 14092 if (T.getAddressSpace() != LangAS::Default && 14093 // OpenCL allows function arguments declared to be an array of a type 14094 // to be qualified with an address space. 14095 !(getLangOpts().OpenCL && 14096 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 14097 Diag(NameLoc, diag::err_arg_with_address_space); 14098 New->setInvalidDecl(); 14099 } 14100 14101 // PPC MMA non-pointer types are not allowed as function argument types. 14102 if (Context.getTargetInfo().getTriple().isPPC64() && 14103 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 14104 New->setInvalidDecl(); 14105 } 14106 14107 return New; 14108 } 14109 14110 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 14111 SourceLocation LocAfterDecls) { 14112 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 14113 14114 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 14115 // for a K&R function. 14116 if (!FTI.hasPrototype) { 14117 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 14118 --i; 14119 if (FTI.Params[i].Param == nullptr) { 14120 SmallString<256> Code; 14121 llvm::raw_svector_ostream(Code) 14122 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 14123 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 14124 << FTI.Params[i].Ident 14125 << FixItHint::CreateInsertion(LocAfterDecls, Code); 14126 14127 // Implicitly declare the argument as type 'int' for lack of a better 14128 // type. 14129 AttributeFactory attrs; 14130 DeclSpec DS(attrs); 14131 const char* PrevSpec; // unused 14132 unsigned DiagID; // unused 14133 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14134 DiagID, Context.getPrintingPolicy()); 14135 // Use the identifier location for the type source range. 14136 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14137 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14138 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14139 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14140 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14141 } 14142 } 14143 } 14144 } 14145 14146 Decl * 14147 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14148 MultiTemplateParamsArg TemplateParameterLists, 14149 SkipBodyInfo *SkipBody) { 14150 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14151 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14152 Scope *ParentScope = FnBodyScope->getParent(); 14153 14154 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14155 // we define a non-templated function definition, we will create a declaration 14156 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14157 // The base function declaration will have the equivalent of an `omp declare 14158 // variant` annotation which specifies the mangled definition as a 14159 // specialization function under the OpenMP context defined as part of the 14160 // `omp begin declare variant`. 14161 SmallVector<FunctionDecl *, 4> Bases; 14162 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14163 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14164 ParentScope, D, TemplateParameterLists, Bases); 14165 14166 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14167 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14168 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14169 14170 if (!Bases.empty()) 14171 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14172 14173 return Dcl; 14174 } 14175 14176 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14177 Consumer.HandleInlineFunctionDefinition(D); 14178 } 14179 14180 static bool 14181 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14182 const FunctionDecl *&PossiblePrototype) { 14183 // Don't warn about invalid declarations. 14184 if (FD->isInvalidDecl()) 14185 return false; 14186 14187 // Or declarations that aren't global. 14188 if (!FD->isGlobal()) 14189 return false; 14190 14191 // Don't warn about C++ member functions. 14192 if (isa<CXXMethodDecl>(FD)) 14193 return false; 14194 14195 // Don't warn about 'main'. 14196 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14197 if (IdentifierInfo *II = FD->getIdentifier()) 14198 if (II->isStr("main") || II->isStr("efi_main")) 14199 return false; 14200 14201 // Don't warn about inline functions. 14202 if (FD->isInlined()) 14203 return false; 14204 14205 // Don't warn about function templates. 14206 if (FD->getDescribedFunctionTemplate()) 14207 return false; 14208 14209 // Don't warn about function template specializations. 14210 if (FD->isFunctionTemplateSpecialization()) 14211 return false; 14212 14213 // Don't warn for OpenCL kernels. 14214 if (FD->hasAttr<OpenCLKernelAttr>()) 14215 return false; 14216 14217 // Don't warn on explicitly deleted functions. 14218 if (FD->isDeleted()) 14219 return false; 14220 14221 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14222 Prev; Prev = Prev->getPreviousDecl()) { 14223 // Ignore any declarations that occur in function or method 14224 // scope, because they aren't visible from the header. 14225 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14226 continue; 14227 14228 PossiblePrototype = Prev; 14229 return Prev->getType()->isFunctionNoProtoType(); 14230 } 14231 14232 return true; 14233 } 14234 14235 void 14236 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14237 const FunctionDecl *EffectiveDefinition, 14238 SkipBodyInfo *SkipBody) { 14239 const FunctionDecl *Definition = EffectiveDefinition; 14240 if (!Definition && 14241 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14242 return; 14243 14244 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14245 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14246 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14247 // A merged copy of the same function, instantiated as a member of 14248 // the same class, is OK. 14249 if (declaresSameEntity(OrigFD, OrigDef) && 14250 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14251 cast<Decl>(FD->getLexicalDeclContext()))) 14252 return; 14253 } 14254 } 14255 } 14256 14257 if (canRedefineFunction(Definition, getLangOpts())) 14258 return; 14259 14260 // Don't emit an error when this is redefinition of a typo-corrected 14261 // definition. 14262 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14263 return; 14264 14265 // If we don't have a visible definition of the function, and it's inline or 14266 // a template, skip the new definition. 14267 if (SkipBody && !hasVisibleDefinition(Definition) && 14268 (Definition->getFormalLinkage() == InternalLinkage || 14269 Definition->isInlined() || 14270 Definition->getDescribedFunctionTemplate() || 14271 Definition->getNumTemplateParameterLists())) { 14272 SkipBody->ShouldSkip = true; 14273 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14274 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14275 makeMergedDefinitionVisible(TD); 14276 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14277 return; 14278 } 14279 14280 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14281 Definition->getStorageClass() == SC_Extern) 14282 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14283 << FD << getLangOpts().CPlusPlus; 14284 else 14285 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14286 14287 Diag(Definition->getLocation(), diag::note_previous_definition); 14288 FD->setInvalidDecl(); 14289 } 14290 14291 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14292 Sema &S) { 14293 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14294 14295 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14296 LSI->CallOperator = CallOperator; 14297 LSI->Lambda = LambdaClass; 14298 LSI->ReturnType = CallOperator->getReturnType(); 14299 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14300 14301 if (LCD == LCD_None) 14302 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14303 else if (LCD == LCD_ByCopy) 14304 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14305 else if (LCD == LCD_ByRef) 14306 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14307 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14308 14309 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14310 LSI->Mutable = !CallOperator->isConst(); 14311 14312 // Add the captures to the LSI so they can be noted as already 14313 // captured within tryCaptureVar. 14314 auto I = LambdaClass->field_begin(); 14315 for (const auto &C : LambdaClass->captures()) { 14316 if (C.capturesVariable()) { 14317 VarDecl *VD = C.getCapturedVar(); 14318 if (VD->isInitCapture()) 14319 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14320 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14321 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14322 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14323 /*EllipsisLoc*/C.isPackExpansion() 14324 ? C.getEllipsisLoc() : SourceLocation(), 14325 I->getType(), /*Invalid*/false); 14326 14327 } else if (C.capturesThis()) { 14328 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14329 C.getCaptureKind() == LCK_StarThis); 14330 } else { 14331 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14332 I->getType()); 14333 } 14334 ++I; 14335 } 14336 } 14337 14338 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14339 SkipBodyInfo *SkipBody) { 14340 if (!D) { 14341 // Parsing the function declaration failed in some way. Push on a fake scope 14342 // anyway so we can try to parse the function body. 14343 PushFunctionScope(); 14344 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14345 return D; 14346 } 14347 14348 FunctionDecl *FD = nullptr; 14349 14350 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14351 FD = FunTmpl->getTemplatedDecl(); 14352 else 14353 FD = cast<FunctionDecl>(D); 14354 14355 // Do not push if it is a lambda because one is already pushed when building 14356 // the lambda in ActOnStartOfLambdaDefinition(). 14357 if (!isLambdaCallOperator(FD)) 14358 PushExpressionEvaluationContext( 14359 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14360 : ExprEvalContexts.back().Context); 14361 14362 // Check for defining attributes before the check for redefinition. 14363 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14364 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14365 FD->dropAttr<AliasAttr>(); 14366 FD->setInvalidDecl(); 14367 } 14368 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14369 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14370 FD->dropAttr<IFuncAttr>(); 14371 FD->setInvalidDecl(); 14372 } 14373 14374 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14375 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14376 Ctor->isDefaultConstructor() && 14377 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14378 // If this is an MS ABI dllexport default constructor, instantiate any 14379 // default arguments. 14380 InstantiateDefaultCtorDefaultArgs(Ctor); 14381 } 14382 } 14383 14384 // See if this is a redefinition. If 'will have body' (or similar) is already 14385 // set, then these checks were already performed when it was set. 14386 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14387 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14388 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14389 14390 // If we're skipping the body, we're done. Don't enter the scope. 14391 if (SkipBody && SkipBody->ShouldSkip) 14392 return D; 14393 } 14394 14395 // Mark this function as "will have a body eventually". This lets users to 14396 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14397 // this function. 14398 FD->setWillHaveBody(); 14399 14400 // If we are instantiating a generic lambda call operator, push 14401 // a LambdaScopeInfo onto the function stack. But use the information 14402 // that's already been calculated (ActOnLambdaExpr) to prime the current 14403 // LambdaScopeInfo. 14404 // When the template operator is being specialized, the LambdaScopeInfo, 14405 // has to be properly restored so that tryCaptureVariable doesn't try 14406 // and capture any new variables. In addition when calculating potential 14407 // captures during transformation of nested lambdas, it is necessary to 14408 // have the LSI properly restored. 14409 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14410 assert(inTemplateInstantiation() && 14411 "There should be an active template instantiation on the stack " 14412 "when instantiating a generic lambda!"); 14413 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14414 } else { 14415 // Enter a new function scope 14416 PushFunctionScope(); 14417 } 14418 14419 // Builtin functions cannot be defined. 14420 if (unsigned BuiltinID = FD->getBuiltinID()) { 14421 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14422 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14423 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14424 FD->setInvalidDecl(); 14425 } 14426 } 14427 14428 // The return type of a function definition must be complete 14429 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14430 QualType ResultType = FD->getReturnType(); 14431 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14432 !FD->isInvalidDecl() && 14433 RequireCompleteType(FD->getLocation(), ResultType, 14434 diag::err_func_def_incomplete_result)) 14435 FD->setInvalidDecl(); 14436 14437 if (FnBodyScope) 14438 PushDeclContext(FnBodyScope, FD); 14439 14440 // Check the validity of our function parameters 14441 CheckParmsForFunctionDef(FD->parameters(), 14442 /*CheckParameterNames=*/true); 14443 14444 // Add non-parameter declarations already in the function to the current 14445 // scope. 14446 if (FnBodyScope) { 14447 for (Decl *NPD : FD->decls()) { 14448 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14449 if (!NonParmDecl) 14450 continue; 14451 assert(!isa<ParmVarDecl>(NonParmDecl) && 14452 "parameters should not be in newly created FD yet"); 14453 14454 // If the decl has a name, make it accessible in the current scope. 14455 if (NonParmDecl->getDeclName()) 14456 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14457 14458 // Similarly, dive into enums and fish their constants out, making them 14459 // accessible in this scope. 14460 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14461 for (auto *EI : ED->enumerators()) 14462 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14463 } 14464 } 14465 } 14466 14467 // Introduce our parameters into the function scope 14468 for (auto Param : FD->parameters()) { 14469 Param->setOwningFunction(FD); 14470 14471 // If this has an identifier, add it to the scope stack. 14472 if (Param->getIdentifier() && FnBodyScope) { 14473 CheckShadow(FnBodyScope, Param); 14474 14475 PushOnScopeChains(Param, FnBodyScope); 14476 } 14477 } 14478 14479 // Ensure that the function's exception specification is instantiated. 14480 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14481 ResolveExceptionSpec(D->getLocation(), FPT); 14482 14483 // dllimport cannot be applied to non-inline function definitions. 14484 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14485 !FD->isTemplateInstantiation()) { 14486 assert(!FD->hasAttr<DLLExportAttr>()); 14487 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14488 FD->setInvalidDecl(); 14489 return D; 14490 } 14491 // We want to attach documentation to original Decl (which might be 14492 // a function template). 14493 ActOnDocumentableDecl(D); 14494 if (getCurLexicalContext()->isObjCContainer() && 14495 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14496 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14497 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14498 14499 return D; 14500 } 14501 14502 /// Given the set of return statements within a function body, 14503 /// compute the variables that are subject to the named return value 14504 /// optimization. 14505 /// 14506 /// Each of the variables that is subject to the named return value 14507 /// optimization will be marked as NRVO variables in the AST, and any 14508 /// return statement that has a marked NRVO variable as its NRVO candidate can 14509 /// use the named return value optimization. 14510 /// 14511 /// This function applies a very simplistic algorithm for NRVO: if every return 14512 /// statement in the scope of a variable has the same NRVO candidate, that 14513 /// candidate is an NRVO variable. 14514 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14515 ReturnStmt **Returns = Scope->Returns.data(); 14516 14517 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14518 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14519 if (!NRVOCandidate->isNRVOVariable()) 14520 Returns[I]->setNRVOCandidate(nullptr); 14521 } 14522 } 14523 } 14524 14525 bool Sema::canDelayFunctionBody(const Declarator &D) { 14526 // We can't delay parsing the body of a constexpr function template (yet). 14527 if (D.getDeclSpec().hasConstexprSpecifier()) 14528 return false; 14529 14530 // We can't delay parsing the body of a function template with a deduced 14531 // return type (yet). 14532 if (D.getDeclSpec().hasAutoTypeSpec()) { 14533 // If the placeholder introduces a non-deduced trailing return type, 14534 // we can still delay parsing it. 14535 if (D.getNumTypeObjects()) { 14536 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14537 if (Outer.Kind == DeclaratorChunk::Function && 14538 Outer.Fun.hasTrailingReturnType()) { 14539 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14540 return Ty.isNull() || !Ty->isUndeducedType(); 14541 } 14542 } 14543 return false; 14544 } 14545 14546 return true; 14547 } 14548 14549 bool Sema::canSkipFunctionBody(Decl *D) { 14550 // We cannot skip the body of a function (or function template) which is 14551 // constexpr, since we may need to evaluate its body in order to parse the 14552 // rest of the file. 14553 // We cannot skip the body of a function with an undeduced return type, 14554 // because any callers of that function need to know the type. 14555 if (const FunctionDecl *FD = D->getAsFunction()) { 14556 if (FD->isConstexpr()) 14557 return false; 14558 // We can't simply call Type::isUndeducedType here, because inside template 14559 // auto can be deduced to a dependent type, which is not considered 14560 // "undeduced". 14561 if (FD->getReturnType()->getContainedDeducedType()) 14562 return false; 14563 } 14564 return Consumer.shouldSkipFunctionBody(D); 14565 } 14566 14567 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14568 if (!Decl) 14569 return nullptr; 14570 if (FunctionDecl *FD = Decl->getAsFunction()) 14571 FD->setHasSkippedBody(); 14572 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14573 MD->setHasSkippedBody(); 14574 return Decl; 14575 } 14576 14577 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14578 return ActOnFinishFunctionBody(D, BodyArg, false); 14579 } 14580 14581 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14582 /// body. 14583 class ExitFunctionBodyRAII { 14584 public: 14585 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14586 ~ExitFunctionBodyRAII() { 14587 if (!IsLambda) 14588 S.PopExpressionEvaluationContext(); 14589 } 14590 14591 private: 14592 Sema &S; 14593 bool IsLambda = false; 14594 }; 14595 14596 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14597 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14598 14599 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14600 if (EscapeInfo.count(BD)) 14601 return EscapeInfo[BD]; 14602 14603 bool R = false; 14604 const BlockDecl *CurBD = BD; 14605 14606 do { 14607 R = !CurBD->doesNotEscape(); 14608 if (R) 14609 break; 14610 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14611 } while (CurBD); 14612 14613 return EscapeInfo[BD] = R; 14614 }; 14615 14616 // If the location where 'self' is implicitly retained is inside a escaping 14617 // block, emit a diagnostic. 14618 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14619 S.ImplicitlyRetainedSelfLocs) 14620 if (IsOrNestedInEscapingBlock(P.second)) 14621 S.Diag(P.first, diag::warn_implicitly_retains_self) 14622 << FixItHint::CreateInsertion(P.first, "self->"); 14623 } 14624 14625 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14626 bool IsInstantiation) { 14627 FunctionScopeInfo *FSI = getCurFunction(); 14628 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14629 14630 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14631 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14632 14633 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14634 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14635 14636 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14637 CheckCompletedCoroutineBody(FD, Body); 14638 14639 { 14640 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14641 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14642 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14643 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14644 14645 if (FD) { 14646 FD->setBody(Body); 14647 FD->setWillHaveBody(false); 14648 14649 if (getLangOpts().CPlusPlus14) { 14650 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14651 FD->getReturnType()->isUndeducedType()) { 14652 // If the function has a deduced result type but contains no 'return' 14653 // statements, the result type as written must be exactly 'auto', and 14654 // the deduced result type is 'void'. 14655 if (!FD->getReturnType()->getAs<AutoType>()) { 14656 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14657 << FD->getReturnType(); 14658 FD->setInvalidDecl(); 14659 } else { 14660 // Substitute 'void' for the 'auto' in the type. 14661 TypeLoc ResultType = getReturnTypeLoc(FD); 14662 Context.adjustDeducedFunctionResultType( 14663 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14664 } 14665 } 14666 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14667 // In C++11, we don't use 'auto' deduction rules for lambda call 14668 // operators because we don't support return type deduction. 14669 auto *LSI = getCurLambda(); 14670 if (LSI->HasImplicitReturnType) { 14671 deduceClosureReturnType(*LSI); 14672 14673 // C++11 [expr.prim.lambda]p4: 14674 // [...] if there are no return statements in the compound-statement 14675 // [the deduced type is] the type void 14676 QualType RetType = 14677 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14678 14679 // Update the return type to the deduced type. 14680 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14681 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14682 Proto->getExtProtoInfo())); 14683 } 14684 } 14685 14686 // If the function implicitly returns zero (like 'main') or is naked, 14687 // don't complain about missing return statements. 14688 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14689 WP.disableCheckFallThrough(); 14690 14691 // MSVC permits the use of pure specifier (=0) on function definition, 14692 // defined at class scope, warn about this non-standard construct. 14693 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14694 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14695 14696 if (!FD->isInvalidDecl()) { 14697 // Don't diagnose unused parameters of defaulted or deleted functions. 14698 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14699 DiagnoseUnusedParameters(FD->parameters()); 14700 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14701 FD->getReturnType(), FD); 14702 14703 // If this is a structor, we need a vtable. 14704 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14705 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14706 else if (CXXDestructorDecl *Destructor = 14707 dyn_cast<CXXDestructorDecl>(FD)) 14708 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14709 14710 // Try to apply the named return value optimization. We have to check 14711 // if we can do this here because lambdas keep return statements around 14712 // to deduce an implicit return type. 14713 if (FD->getReturnType()->isRecordType() && 14714 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14715 computeNRVO(Body, FSI); 14716 } 14717 14718 // GNU warning -Wmissing-prototypes: 14719 // Warn if a global function is defined without a previous 14720 // prototype declaration. This warning is issued even if the 14721 // definition itself provides a prototype. The aim is to detect 14722 // global functions that fail to be declared in header files. 14723 const FunctionDecl *PossiblePrototype = nullptr; 14724 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14725 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14726 14727 if (PossiblePrototype) { 14728 // We found a declaration that is not a prototype, 14729 // but that could be a zero-parameter prototype 14730 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14731 TypeLoc TL = TI->getTypeLoc(); 14732 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14733 Diag(PossiblePrototype->getLocation(), 14734 diag::note_declaration_not_a_prototype) 14735 << (FD->getNumParams() != 0) 14736 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 14737 FTL.getRParenLoc(), "void") 14738 : FixItHint{}); 14739 } 14740 } else { 14741 // Returns true if the token beginning at this Loc is `const`. 14742 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14743 const LangOptions &LangOpts) { 14744 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14745 if (LocInfo.first.isInvalid()) 14746 return false; 14747 14748 bool Invalid = false; 14749 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14750 if (Invalid) 14751 return false; 14752 14753 if (LocInfo.second > Buffer.size()) 14754 return false; 14755 14756 const char *LexStart = Buffer.data() + LocInfo.second; 14757 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14758 14759 return StartTok.consume_front("const") && 14760 (StartTok.empty() || isWhitespace(StartTok[0]) || 14761 StartTok.startswith("/*") || StartTok.startswith("//")); 14762 }; 14763 14764 auto findBeginLoc = [&]() { 14765 // If the return type has `const` qualifier, we want to insert 14766 // `static` before `const` (and not before the typename). 14767 if ((FD->getReturnType()->isAnyPointerType() && 14768 FD->getReturnType()->getPointeeType().isConstQualified()) || 14769 FD->getReturnType().isConstQualified()) { 14770 // But only do this if we can determine where the `const` is. 14771 14772 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14773 getLangOpts())) 14774 14775 return FD->getBeginLoc(); 14776 } 14777 return FD->getTypeSpecStartLoc(); 14778 }; 14779 Diag(FD->getTypeSpecStartLoc(), 14780 diag::note_static_for_internal_linkage) 14781 << /* function */ 1 14782 << (FD->getStorageClass() == SC_None 14783 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14784 : FixItHint{}); 14785 } 14786 14787 // GNU warning -Wstrict-prototypes 14788 // Warn if K&R function is defined without a previous declaration. 14789 // This warning is issued only if the definition itself does not 14790 // provide a prototype. Only K&R definitions do not provide a 14791 // prototype. 14792 if (!FD->hasWrittenPrototype()) { 14793 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14794 TypeLoc TL = TI->getTypeLoc(); 14795 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14796 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14797 } 14798 } 14799 14800 // Warn on CPUDispatch with an actual body. 14801 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14802 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14803 if (!CmpndBody->body_empty()) 14804 Diag(CmpndBody->body_front()->getBeginLoc(), 14805 diag::warn_dispatch_body_ignored); 14806 14807 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14808 const CXXMethodDecl *KeyFunction; 14809 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14810 MD->isVirtual() && 14811 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14812 MD == KeyFunction->getCanonicalDecl()) { 14813 // Update the key-function state if necessary for this ABI. 14814 if (FD->isInlined() && 14815 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14816 Context.setNonKeyFunction(MD); 14817 14818 // If the newly-chosen key function is already defined, then we 14819 // need to mark the vtable as used retroactively. 14820 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14821 const FunctionDecl *Definition; 14822 if (KeyFunction && KeyFunction->isDefined(Definition)) 14823 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14824 } else { 14825 // We just defined they key function; mark the vtable as used. 14826 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14827 } 14828 } 14829 } 14830 14831 assert( 14832 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14833 "Function parsing confused"); 14834 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14835 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14836 MD->setBody(Body); 14837 if (!MD->isInvalidDecl()) { 14838 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14839 MD->getReturnType(), MD); 14840 14841 if (Body) 14842 computeNRVO(Body, FSI); 14843 } 14844 if (FSI->ObjCShouldCallSuper) { 14845 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14846 << MD->getSelector().getAsString(); 14847 FSI->ObjCShouldCallSuper = false; 14848 } 14849 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14850 const ObjCMethodDecl *InitMethod = nullptr; 14851 bool isDesignated = 14852 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14853 assert(isDesignated && InitMethod); 14854 (void)isDesignated; 14855 14856 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14857 auto IFace = MD->getClassInterface(); 14858 if (!IFace) 14859 return false; 14860 auto SuperD = IFace->getSuperClass(); 14861 if (!SuperD) 14862 return false; 14863 return SuperD->getIdentifier() == 14864 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14865 }; 14866 // Don't issue this warning for unavailable inits or direct subclasses 14867 // of NSObject. 14868 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14869 Diag(MD->getLocation(), 14870 diag::warn_objc_designated_init_missing_super_call); 14871 Diag(InitMethod->getLocation(), 14872 diag::note_objc_designated_init_marked_here); 14873 } 14874 FSI->ObjCWarnForNoDesignatedInitChain = false; 14875 } 14876 if (FSI->ObjCWarnForNoInitDelegation) { 14877 // Don't issue this warning for unavaialable inits. 14878 if (!MD->isUnavailable()) 14879 Diag(MD->getLocation(), 14880 diag::warn_objc_secondary_init_missing_init_call); 14881 FSI->ObjCWarnForNoInitDelegation = false; 14882 } 14883 14884 diagnoseImplicitlyRetainedSelf(*this); 14885 } else { 14886 // Parsing the function declaration failed in some way. Pop the fake scope 14887 // we pushed on. 14888 PopFunctionScopeInfo(ActivePolicy, dcl); 14889 return nullptr; 14890 } 14891 14892 if (Body && FSI->HasPotentialAvailabilityViolations) 14893 DiagnoseUnguardedAvailabilityViolations(dcl); 14894 14895 assert(!FSI->ObjCShouldCallSuper && 14896 "This should only be set for ObjC methods, which should have been " 14897 "handled in the block above."); 14898 14899 // Verify and clean out per-function state. 14900 if (Body && (!FD || !FD->isDefaulted())) { 14901 // C++ constructors that have function-try-blocks can't have return 14902 // statements in the handlers of that block. (C++ [except.handle]p14) 14903 // Verify this. 14904 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14905 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14906 14907 // Verify that gotos and switch cases don't jump into scopes illegally. 14908 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 14909 DiagnoseInvalidJumps(Body); 14910 14911 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14912 if (!Destructor->getParent()->isDependentType()) 14913 CheckDestructor(Destructor); 14914 14915 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14916 Destructor->getParent()); 14917 } 14918 14919 // If any errors have occurred, clear out any temporaries that may have 14920 // been leftover. This ensures that these temporaries won't be picked up 14921 // for deletion in some later function. 14922 if (hasUncompilableErrorOccurred() || 14923 getDiagnostics().getSuppressAllDiagnostics()) { 14924 DiscardCleanupsInEvaluationContext(); 14925 } 14926 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 14927 // Since the body is valid, issue any analysis-based warnings that are 14928 // enabled. 14929 ActivePolicy = &WP; 14930 } 14931 14932 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14933 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14934 FD->setInvalidDecl(); 14935 14936 if (FD && FD->hasAttr<NakedAttr>()) { 14937 for (const Stmt *S : Body->children()) { 14938 // Allow local register variables without initializer as they don't 14939 // require prologue. 14940 bool RegisterVariables = false; 14941 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14942 for (const auto *Decl : DS->decls()) { 14943 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14944 RegisterVariables = 14945 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14946 if (!RegisterVariables) 14947 break; 14948 } 14949 } 14950 } 14951 if (RegisterVariables) 14952 continue; 14953 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14954 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14955 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14956 FD->setInvalidDecl(); 14957 break; 14958 } 14959 } 14960 } 14961 14962 assert(ExprCleanupObjects.size() == 14963 ExprEvalContexts.back().NumCleanupObjects && 14964 "Leftover temporaries in function"); 14965 assert(!Cleanup.exprNeedsCleanups() && 14966 "Unaccounted cleanups in function"); 14967 assert(MaybeODRUseExprs.empty() && 14968 "Leftover expressions for odr-use checking"); 14969 } 14970 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 14971 // the declaration context below. Otherwise, we're unable to transform 14972 // 'this' expressions when transforming immediate context functions. 14973 14974 if (!IsInstantiation) 14975 PopDeclContext(); 14976 14977 PopFunctionScopeInfo(ActivePolicy, dcl); 14978 // If any errors have occurred, clear out any temporaries that may have 14979 // been leftover. This ensures that these temporaries won't be picked up for 14980 // deletion in some later function. 14981 if (hasUncompilableErrorOccurred()) { 14982 DiscardCleanupsInEvaluationContext(); 14983 } 14984 14985 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 14986 !LangOpts.OMPTargetTriples.empty())) || 14987 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14988 auto ES = getEmissionStatus(FD); 14989 if (ES == Sema::FunctionEmissionStatus::Emitted || 14990 ES == Sema::FunctionEmissionStatus::Unknown) 14991 DeclsToCheckForDeferredDiags.insert(FD); 14992 } 14993 14994 if (FD && !FD->isDeleted()) 14995 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 14996 14997 return dcl; 14998 } 14999 15000 /// When we finish delayed parsing of an attribute, we must attach it to the 15001 /// relevant Decl. 15002 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 15003 ParsedAttributes &Attrs) { 15004 // Always attach attributes to the underlying decl. 15005 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 15006 D = TD->getTemplatedDecl(); 15007 ProcessDeclAttributeList(S, D, Attrs); 15008 15009 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 15010 if (Method->isStatic()) 15011 checkThisInStaticMemberFunctionAttributes(Method); 15012 } 15013 15014 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 15015 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 15016 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 15017 IdentifierInfo &II, Scope *S) { 15018 // Find the scope in which the identifier is injected and the corresponding 15019 // DeclContext. 15020 // FIXME: C89 does not say what happens if there is no enclosing block scope. 15021 // In that case, we inject the declaration into the translation unit scope 15022 // instead. 15023 Scope *BlockScope = S; 15024 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 15025 BlockScope = BlockScope->getParent(); 15026 15027 Scope *ContextScope = BlockScope; 15028 while (!ContextScope->getEntity()) 15029 ContextScope = ContextScope->getParent(); 15030 ContextRAII SavedContext(*this, ContextScope->getEntity()); 15031 15032 // Before we produce a declaration for an implicitly defined 15033 // function, see whether there was a locally-scoped declaration of 15034 // this name as a function or variable. If so, use that 15035 // (non-visible) declaration, and complain about it. 15036 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 15037 if (ExternCPrev) { 15038 // We still need to inject the function into the enclosing block scope so 15039 // that later (non-call) uses can see it. 15040 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 15041 15042 // C89 footnote 38: 15043 // If in fact it is not defined as having type "function returning int", 15044 // the behavior is undefined. 15045 if (!isa<FunctionDecl>(ExternCPrev) || 15046 !Context.typesAreCompatible( 15047 cast<FunctionDecl>(ExternCPrev)->getType(), 15048 Context.getFunctionNoProtoType(Context.IntTy))) { 15049 Diag(Loc, diag::ext_use_out_of_scope_declaration) 15050 << ExternCPrev << !getLangOpts().C99; 15051 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 15052 return ExternCPrev; 15053 } 15054 } 15055 15056 // Extension in C99. Legal in C90, but warn about it. 15057 unsigned diag_id; 15058 if (II.getName().startswith("__builtin_")) 15059 diag_id = diag::warn_builtin_unknown; 15060 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 15061 else if (getLangOpts().OpenCL) 15062 diag_id = diag::err_opencl_implicit_function_decl; 15063 else if (getLangOpts().C99) 15064 diag_id = diag::ext_implicit_function_decl; 15065 else 15066 diag_id = diag::warn_implicit_function_decl; 15067 15068 TypoCorrection Corrected; 15069 // Because typo correction is expensive, only do it if the implicit 15070 // function declaration is going to be treated as an error. 15071 // 15072 // Perform the corection before issuing the main diagnostic, as some consumers 15073 // use typo-correction callbacks to enhance the main diagnostic. 15074 if (S && !ExternCPrev && 15075 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 15076 DeclFilterCCC<FunctionDecl> CCC{}; 15077 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 15078 S, nullptr, CCC, CTK_NonError); 15079 } 15080 15081 Diag(Loc, diag_id) << &II; 15082 if (Corrected) 15083 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 15084 /*ErrorRecovery*/ false); 15085 15086 // If we found a prior declaration of this function, don't bother building 15087 // another one. We've already pushed that one into scope, so there's nothing 15088 // more to do. 15089 if (ExternCPrev) 15090 return ExternCPrev; 15091 15092 // Set a Declarator for the implicit definition: int foo(); 15093 const char *Dummy; 15094 AttributeFactory attrFactory; 15095 DeclSpec DS(attrFactory); 15096 unsigned DiagID; 15097 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 15098 Context.getPrintingPolicy()); 15099 (void)Error; // Silence warning. 15100 assert(!Error && "Error setting up implicit decl!"); 15101 SourceLocation NoLoc; 15102 Declarator D(DS, DeclaratorContext::Block); 15103 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 15104 /*IsAmbiguous=*/false, 15105 /*LParenLoc=*/NoLoc, 15106 /*Params=*/nullptr, 15107 /*NumParams=*/0, 15108 /*EllipsisLoc=*/NoLoc, 15109 /*RParenLoc=*/NoLoc, 15110 /*RefQualifierIsLvalueRef=*/true, 15111 /*RefQualifierLoc=*/NoLoc, 15112 /*MutableLoc=*/NoLoc, EST_None, 15113 /*ESpecRange=*/SourceRange(), 15114 /*Exceptions=*/nullptr, 15115 /*ExceptionRanges=*/nullptr, 15116 /*NumExceptions=*/0, 15117 /*NoexceptExpr=*/nullptr, 15118 /*ExceptionSpecTokens=*/nullptr, 15119 /*DeclsInPrototype=*/None, Loc, 15120 Loc, D), 15121 std::move(DS.getAttributes()), SourceLocation()); 15122 D.SetIdentifier(&II, Loc); 15123 15124 // Insert this function into the enclosing block scope. 15125 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 15126 FD->setImplicit(); 15127 15128 AddKnownFunctionAttributes(FD); 15129 15130 return FD; 15131 } 15132 15133 /// If this function is a C++ replaceable global allocation function 15134 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15135 /// adds any function attributes that we know a priori based on the standard. 15136 /// 15137 /// We need to check for duplicate attributes both here and where user-written 15138 /// attributes are applied to declarations. 15139 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15140 FunctionDecl *FD) { 15141 if (FD->isInvalidDecl()) 15142 return; 15143 15144 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15145 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15146 return; 15147 15148 Optional<unsigned> AlignmentParam; 15149 bool IsNothrow = false; 15150 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15151 return; 15152 15153 // C++2a [basic.stc.dynamic.allocation]p4: 15154 // An allocation function that has a non-throwing exception specification 15155 // indicates failure by returning a null pointer value. Any other allocation 15156 // function never returns a null pointer value and indicates failure only by 15157 // throwing an exception [...] 15158 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15159 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15160 15161 // C++2a [basic.stc.dynamic.allocation]p2: 15162 // An allocation function attempts to allocate the requested amount of 15163 // storage. [...] If the request succeeds, the value returned by a 15164 // replaceable allocation function is a [...] pointer value p0 different 15165 // from any previously returned value p1 [...] 15166 // 15167 // However, this particular information is being added in codegen, 15168 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15169 15170 // C++2a [basic.stc.dynamic.allocation]p2: 15171 // An allocation function attempts to allocate the requested amount of 15172 // storage. If it is successful, it returns the address of the start of a 15173 // block of storage whose length in bytes is at least as large as the 15174 // requested size. 15175 if (!FD->hasAttr<AllocSizeAttr>()) { 15176 FD->addAttr(AllocSizeAttr::CreateImplicit( 15177 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15178 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15179 } 15180 15181 // C++2a [basic.stc.dynamic.allocation]p3: 15182 // For an allocation function [...], the pointer returned on a successful 15183 // call shall represent the address of storage that is aligned as follows: 15184 // (3.1) If the allocation function takes an argument of type 15185 // std::align_val_t, the storage will have the alignment 15186 // specified by the value of this argument. 15187 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15188 FD->addAttr(AllocAlignAttr::CreateImplicit( 15189 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15190 } 15191 15192 // FIXME: 15193 // C++2a [basic.stc.dynamic.allocation]p3: 15194 // For an allocation function [...], the pointer returned on a successful 15195 // call shall represent the address of storage that is aligned as follows: 15196 // (3.2) Otherwise, if the allocation function is named operator new[], 15197 // the storage is aligned for any object that does not have 15198 // new-extended alignment ([basic.align]) and is no larger than the 15199 // requested size. 15200 // (3.3) Otherwise, the storage is aligned for any object that does not 15201 // have new-extended alignment and is of the requested size. 15202 } 15203 15204 /// Adds any function attributes that we know a priori based on 15205 /// the declaration of this function. 15206 /// 15207 /// These attributes can apply both to implicitly-declared builtins 15208 /// (like __builtin___printf_chk) or to library-declared functions 15209 /// like NSLog or printf. 15210 /// 15211 /// We need to check for duplicate attributes both here and where user-written 15212 /// attributes are applied to declarations. 15213 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15214 if (FD->isInvalidDecl()) 15215 return; 15216 15217 // If this is a built-in function, map its builtin attributes to 15218 // actual attributes. 15219 if (unsigned BuiltinID = FD->getBuiltinID()) { 15220 // Handle printf-formatting attributes. 15221 unsigned FormatIdx; 15222 bool HasVAListArg; 15223 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15224 if (!FD->hasAttr<FormatAttr>()) { 15225 const char *fmt = "printf"; 15226 unsigned int NumParams = FD->getNumParams(); 15227 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15228 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15229 fmt = "NSString"; 15230 FD->addAttr(FormatAttr::CreateImplicit(Context, 15231 &Context.Idents.get(fmt), 15232 FormatIdx+1, 15233 HasVAListArg ? 0 : FormatIdx+2, 15234 FD->getLocation())); 15235 } 15236 } 15237 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15238 HasVAListArg)) { 15239 if (!FD->hasAttr<FormatAttr>()) 15240 FD->addAttr(FormatAttr::CreateImplicit(Context, 15241 &Context.Idents.get("scanf"), 15242 FormatIdx+1, 15243 HasVAListArg ? 0 : FormatIdx+2, 15244 FD->getLocation())); 15245 } 15246 15247 // Handle automatically recognized callbacks. 15248 SmallVector<int, 4> Encoding; 15249 if (!FD->hasAttr<CallbackAttr>() && 15250 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15251 FD->addAttr(CallbackAttr::CreateImplicit( 15252 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15253 15254 // Mark const if we don't care about errno and that is the only thing 15255 // preventing the function from being const. This allows IRgen to use LLVM 15256 // intrinsics for such functions. 15257 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15258 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15259 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15260 15261 // We make "fma" on GNU or Windows const because we know it does not set 15262 // errno in those environments even though it could set errno based on the 15263 // C standard. 15264 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15265 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 15266 !FD->hasAttr<ConstAttr>()) { 15267 switch (BuiltinID) { 15268 case Builtin::BI__builtin_fma: 15269 case Builtin::BI__builtin_fmaf: 15270 case Builtin::BI__builtin_fmal: 15271 case Builtin::BIfma: 15272 case Builtin::BIfmaf: 15273 case Builtin::BIfmal: 15274 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15275 break; 15276 default: 15277 break; 15278 } 15279 } 15280 15281 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15282 !FD->hasAttr<ReturnsTwiceAttr>()) 15283 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15284 FD->getLocation())); 15285 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15286 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15287 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15288 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15289 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15290 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15291 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15292 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15293 // Add the appropriate attribute, depending on the CUDA compilation mode 15294 // and which target the builtin belongs to. For example, during host 15295 // compilation, aux builtins are __device__, while the rest are __host__. 15296 if (getLangOpts().CUDAIsDevice != 15297 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15298 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15299 else 15300 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15301 } 15302 15303 // Add known guaranteed alignment for allocation functions. 15304 switch (BuiltinID) { 15305 case Builtin::BIaligned_alloc: 15306 if (!FD->hasAttr<AllocAlignAttr>()) 15307 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15308 FD->getLocation())); 15309 LLVM_FALLTHROUGH; 15310 case Builtin::BIcalloc: 15311 case Builtin::BImalloc: 15312 case Builtin::BImemalign: 15313 case Builtin::BIrealloc: 15314 case Builtin::BIstrdup: 15315 case Builtin::BIstrndup: { 15316 if (!FD->hasAttr<AssumeAlignedAttr>()) { 15317 unsigned NewAlign = Context.getTargetInfo().getNewAlign() / 15318 Context.getTargetInfo().getCharWidth(); 15319 IntegerLiteral *Alignment = IntegerLiteral::Create( 15320 Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy), 15321 Context.UnsignedIntTy, FD->getLocation()); 15322 FD->addAttr(AssumeAlignedAttr::CreateImplicit( 15323 Context, Alignment, /*Offset=*/nullptr, FD->getLocation())); 15324 } 15325 break; 15326 } 15327 default: 15328 break; 15329 } 15330 } 15331 15332 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15333 15334 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15335 // throw, add an implicit nothrow attribute to any extern "C" function we come 15336 // across. 15337 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15338 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15339 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15340 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15341 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15342 } 15343 15344 IdentifierInfo *Name = FD->getIdentifier(); 15345 if (!Name) 15346 return; 15347 if ((!getLangOpts().CPlusPlus && 15348 FD->getDeclContext()->isTranslationUnit()) || 15349 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15350 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15351 LinkageSpecDecl::lang_c)) { 15352 // Okay: this could be a libc/libm/Objective-C function we know 15353 // about. 15354 } else 15355 return; 15356 15357 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15358 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15359 // target-specific builtins, perhaps? 15360 if (!FD->hasAttr<FormatAttr>()) 15361 FD->addAttr(FormatAttr::CreateImplicit(Context, 15362 &Context.Idents.get("printf"), 2, 15363 Name->isStr("vasprintf") ? 0 : 3, 15364 FD->getLocation())); 15365 } 15366 15367 if (Name->isStr("__CFStringMakeConstantString")) { 15368 // We already have a __builtin___CFStringMakeConstantString, 15369 // but builds that use -fno-constant-cfstrings don't go through that. 15370 if (!FD->hasAttr<FormatArgAttr>()) 15371 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15372 FD->getLocation())); 15373 } 15374 } 15375 15376 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15377 TypeSourceInfo *TInfo) { 15378 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15379 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15380 15381 if (!TInfo) { 15382 assert(D.isInvalidType() && "no declarator info for valid type"); 15383 TInfo = Context.getTrivialTypeSourceInfo(T); 15384 } 15385 15386 // Scope manipulation handled by caller. 15387 TypedefDecl *NewTD = 15388 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15389 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15390 15391 // Bail out immediately if we have an invalid declaration. 15392 if (D.isInvalidType()) { 15393 NewTD->setInvalidDecl(); 15394 return NewTD; 15395 } 15396 15397 if (D.getDeclSpec().isModulePrivateSpecified()) { 15398 if (CurContext->isFunctionOrMethod()) 15399 Diag(NewTD->getLocation(), diag::err_module_private_local) 15400 << 2 << NewTD 15401 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15402 << FixItHint::CreateRemoval( 15403 D.getDeclSpec().getModulePrivateSpecLoc()); 15404 else 15405 NewTD->setModulePrivate(); 15406 } 15407 15408 // C++ [dcl.typedef]p8: 15409 // If the typedef declaration defines an unnamed class (or 15410 // enum), the first typedef-name declared by the declaration 15411 // to be that class type (or enum type) is used to denote the 15412 // class type (or enum type) for linkage purposes only. 15413 // We need to check whether the type was declared in the declaration. 15414 switch (D.getDeclSpec().getTypeSpecType()) { 15415 case TST_enum: 15416 case TST_struct: 15417 case TST_interface: 15418 case TST_union: 15419 case TST_class: { 15420 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15421 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15422 break; 15423 } 15424 15425 default: 15426 break; 15427 } 15428 15429 return NewTD; 15430 } 15431 15432 /// Check that this is a valid underlying type for an enum declaration. 15433 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15434 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15435 QualType T = TI->getType(); 15436 15437 if (T->isDependentType()) 15438 return false; 15439 15440 // This doesn't use 'isIntegralType' despite the error message mentioning 15441 // integral type because isIntegralType would also allow enum types in C. 15442 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15443 if (BT->isInteger()) 15444 return false; 15445 15446 if (T->isBitIntType()) 15447 return false; 15448 15449 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15450 } 15451 15452 /// Check whether this is a valid redeclaration of a previous enumeration. 15453 /// \return true if the redeclaration was invalid. 15454 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15455 QualType EnumUnderlyingTy, bool IsFixed, 15456 const EnumDecl *Prev) { 15457 if (IsScoped != Prev->isScoped()) { 15458 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15459 << Prev->isScoped(); 15460 Diag(Prev->getLocation(), diag::note_previous_declaration); 15461 return true; 15462 } 15463 15464 if (IsFixed && Prev->isFixed()) { 15465 if (!EnumUnderlyingTy->isDependentType() && 15466 !Prev->getIntegerType()->isDependentType() && 15467 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15468 Prev->getIntegerType())) { 15469 // TODO: Highlight the underlying type of the redeclaration. 15470 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15471 << EnumUnderlyingTy << Prev->getIntegerType(); 15472 Diag(Prev->getLocation(), diag::note_previous_declaration) 15473 << Prev->getIntegerTypeRange(); 15474 return true; 15475 } 15476 } else if (IsFixed != Prev->isFixed()) { 15477 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15478 << Prev->isFixed(); 15479 Diag(Prev->getLocation(), diag::note_previous_declaration); 15480 return true; 15481 } 15482 15483 return false; 15484 } 15485 15486 /// Get diagnostic %select index for tag kind for 15487 /// redeclaration diagnostic message. 15488 /// WARNING: Indexes apply to particular diagnostics only! 15489 /// 15490 /// \returns diagnostic %select index. 15491 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15492 switch (Tag) { 15493 case TTK_Struct: return 0; 15494 case TTK_Interface: return 1; 15495 case TTK_Class: return 2; 15496 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15497 } 15498 } 15499 15500 /// Determine if tag kind is a class-key compatible with 15501 /// class for redeclaration (class, struct, or __interface). 15502 /// 15503 /// \returns true iff the tag kind is compatible. 15504 static bool isClassCompatTagKind(TagTypeKind Tag) 15505 { 15506 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15507 } 15508 15509 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15510 TagTypeKind TTK) { 15511 if (isa<TypedefDecl>(PrevDecl)) 15512 return NTK_Typedef; 15513 else if (isa<TypeAliasDecl>(PrevDecl)) 15514 return NTK_TypeAlias; 15515 else if (isa<ClassTemplateDecl>(PrevDecl)) 15516 return NTK_Template; 15517 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15518 return NTK_TypeAliasTemplate; 15519 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15520 return NTK_TemplateTemplateArgument; 15521 switch (TTK) { 15522 case TTK_Struct: 15523 case TTK_Interface: 15524 case TTK_Class: 15525 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15526 case TTK_Union: 15527 return NTK_NonUnion; 15528 case TTK_Enum: 15529 return NTK_NonEnum; 15530 } 15531 llvm_unreachable("invalid TTK"); 15532 } 15533 15534 /// Determine whether a tag with a given kind is acceptable 15535 /// as a redeclaration of the given tag declaration. 15536 /// 15537 /// \returns true if the new tag kind is acceptable, false otherwise. 15538 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15539 TagTypeKind NewTag, bool isDefinition, 15540 SourceLocation NewTagLoc, 15541 const IdentifierInfo *Name) { 15542 // C++ [dcl.type.elab]p3: 15543 // The class-key or enum keyword present in the 15544 // elaborated-type-specifier shall agree in kind with the 15545 // declaration to which the name in the elaborated-type-specifier 15546 // refers. This rule also applies to the form of 15547 // elaborated-type-specifier that declares a class-name or 15548 // friend class since it can be construed as referring to the 15549 // definition of the class. Thus, in any 15550 // elaborated-type-specifier, the enum keyword shall be used to 15551 // refer to an enumeration (7.2), the union class-key shall be 15552 // used to refer to a union (clause 9), and either the class or 15553 // struct class-key shall be used to refer to a class (clause 9) 15554 // declared using the class or struct class-key. 15555 TagTypeKind OldTag = Previous->getTagKind(); 15556 if (OldTag != NewTag && 15557 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15558 return false; 15559 15560 // Tags are compatible, but we might still want to warn on mismatched tags. 15561 // Non-class tags can't be mismatched at this point. 15562 if (!isClassCompatTagKind(NewTag)) 15563 return true; 15564 15565 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15566 // by our warning analysis. We don't want to warn about mismatches with (eg) 15567 // declarations in system headers that are designed to be specialized, but if 15568 // a user asks us to warn, we should warn if their code contains mismatched 15569 // declarations. 15570 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15571 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15572 Loc); 15573 }; 15574 if (IsIgnoredLoc(NewTagLoc)) 15575 return true; 15576 15577 auto IsIgnored = [&](const TagDecl *Tag) { 15578 return IsIgnoredLoc(Tag->getLocation()); 15579 }; 15580 while (IsIgnored(Previous)) { 15581 Previous = Previous->getPreviousDecl(); 15582 if (!Previous) 15583 return true; 15584 OldTag = Previous->getTagKind(); 15585 } 15586 15587 bool isTemplate = false; 15588 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15589 isTemplate = Record->getDescribedClassTemplate(); 15590 15591 if (inTemplateInstantiation()) { 15592 if (OldTag != NewTag) { 15593 // In a template instantiation, do not offer fix-its for tag mismatches 15594 // since they usually mess up the template instead of fixing the problem. 15595 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15596 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15597 << getRedeclDiagFromTagKind(OldTag); 15598 // FIXME: Note previous location? 15599 } 15600 return true; 15601 } 15602 15603 if (isDefinition) { 15604 // On definitions, check all previous tags and issue a fix-it for each 15605 // one that doesn't match the current tag. 15606 if (Previous->getDefinition()) { 15607 // Don't suggest fix-its for redefinitions. 15608 return true; 15609 } 15610 15611 bool previousMismatch = false; 15612 for (const TagDecl *I : Previous->redecls()) { 15613 if (I->getTagKind() != NewTag) { 15614 // Ignore previous declarations for which the warning was disabled. 15615 if (IsIgnored(I)) 15616 continue; 15617 15618 if (!previousMismatch) { 15619 previousMismatch = true; 15620 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15621 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15622 << getRedeclDiagFromTagKind(I->getTagKind()); 15623 } 15624 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15625 << getRedeclDiagFromTagKind(NewTag) 15626 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15627 TypeWithKeyword::getTagTypeKindName(NewTag)); 15628 } 15629 } 15630 return true; 15631 } 15632 15633 // Identify the prevailing tag kind: this is the kind of the definition (if 15634 // there is a non-ignored definition), or otherwise the kind of the prior 15635 // (non-ignored) declaration. 15636 const TagDecl *PrevDef = Previous->getDefinition(); 15637 if (PrevDef && IsIgnored(PrevDef)) 15638 PrevDef = nullptr; 15639 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15640 if (Redecl->getTagKind() != NewTag) { 15641 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15642 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15643 << getRedeclDiagFromTagKind(OldTag); 15644 Diag(Redecl->getLocation(), diag::note_previous_use); 15645 15646 // If there is a previous definition, suggest a fix-it. 15647 if (PrevDef) { 15648 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15649 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15650 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15651 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15652 } 15653 } 15654 15655 return true; 15656 } 15657 15658 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15659 /// from an outer enclosing namespace or file scope inside a friend declaration. 15660 /// This should provide the commented out code in the following snippet: 15661 /// namespace N { 15662 /// struct X; 15663 /// namespace M { 15664 /// struct Y { friend struct /*N::*/ X; }; 15665 /// } 15666 /// } 15667 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15668 SourceLocation NameLoc) { 15669 // While the decl is in a namespace, do repeated lookup of that name and see 15670 // if we get the same namespace back. If we do not, continue until 15671 // translation unit scope, at which point we have a fully qualified NNS. 15672 SmallVector<IdentifierInfo *, 4> Namespaces; 15673 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15674 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15675 // This tag should be declared in a namespace, which can only be enclosed by 15676 // other namespaces. Bail if there's an anonymous namespace in the chain. 15677 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15678 if (!Namespace || Namespace->isAnonymousNamespace()) 15679 return FixItHint(); 15680 IdentifierInfo *II = Namespace->getIdentifier(); 15681 Namespaces.push_back(II); 15682 NamedDecl *Lookup = SemaRef.LookupSingleName( 15683 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15684 if (Lookup == Namespace) 15685 break; 15686 } 15687 15688 // Once we have all the namespaces, reverse them to go outermost first, and 15689 // build an NNS. 15690 SmallString<64> Insertion; 15691 llvm::raw_svector_ostream OS(Insertion); 15692 if (DC->isTranslationUnit()) 15693 OS << "::"; 15694 std::reverse(Namespaces.begin(), Namespaces.end()); 15695 for (auto *II : Namespaces) 15696 OS << II->getName() << "::"; 15697 return FixItHint::CreateInsertion(NameLoc, Insertion); 15698 } 15699 15700 /// Determine whether a tag originally declared in context \p OldDC can 15701 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15702 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15703 /// using-declaration). 15704 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15705 DeclContext *NewDC) { 15706 OldDC = OldDC->getRedeclContext(); 15707 NewDC = NewDC->getRedeclContext(); 15708 15709 if (OldDC->Equals(NewDC)) 15710 return true; 15711 15712 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15713 // encloses the other). 15714 if (S.getLangOpts().MSVCCompat && 15715 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15716 return true; 15717 15718 return false; 15719 } 15720 15721 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15722 /// former case, Name will be non-null. In the later case, Name will be null. 15723 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15724 /// reference/declaration/definition of a tag. 15725 /// 15726 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15727 /// trailing-type-specifier) other than one in an alias-declaration. 15728 /// 15729 /// \param SkipBody If non-null, will be set to indicate if the caller should 15730 /// skip the definition of this tag and treat it as if it were a declaration. 15731 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15732 SourceLocation KWLoc, CXXScopeSpec &SS, 15733 IdentifierInfo *Name, SourceLocation NameLoc, 15734 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15735 SourceLocation ModulePrivateLoc, 15736 MultiTemplateParamsArg TemplateParameterLists, 15737 bool &OwnedDecl, bool &IsDependent, 15738 SourceLocation ScopedEnumKWLoc, 15739 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15740 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15741 SkipBodyInfo *SkipBody) { 15742 // If this is not a definition, it must have a name. 15743 IdentifierInfo *OrigName = Name; 15744 assert((Name != nullptr || TUK == TUK_Definition) && 15745 "Nameless record must be a definition!"); 15746 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15747 15748 OwnedDecl = false; 15749 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15750 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15751 15752 // FIXME: Check member specializations more carefully. 15753 bool isMemberSpecialization = false; 15754 bool Invalid = false; 15755 15756 // We only need to do this matching if we have template parameters 15757 // or a scope specifier, which also conveniently avoids this work 15758 // for non-C++ cases. 15759 if (TemplateParameterLists.size() > 0 || 15760 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15761 if (TemplateParameterList *TemplateParams = 15762 MatchTemplateParametersToScopeSpecifier( 15763 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15764 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15765 if (Kind == TTK_Enum) { 15766 Diag(KWLoc, diag::err_enum_template); 15767 return nullptr; 15768 } 15769 15770 if (TemplateParams->size() > 0) { 15771 // This is a declaration or definition of a class template (which may 15772 // be a member of another template). 15773 15774 if (Invalid) 15775 return nullptr; 15776 15777 OwnedDecl = false; 15778 DeclResult Result = CheckClassTemplate( 15779 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15780 AS, ModulePrivateLoc, 15781 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15782 TemplateParameterLists.data(), SkipBody); 15783 return Result.get(); 15784 } else { 15785 // The "template<>" header is extraneous. 15786 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15787 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15788 isMemberSpecialization = true; 15789 } 15790 } 15791 15792 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15793 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15794 return nullptr; 15795 } 15796 15797 // Figure out the underlying type if this a enum declaration. We need to do 15798 // this early, because it's needed to detect if this is an incompatible 15799 // redeclaration. 15800 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15801 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15802 15803 if (Kind == TTK_Enum) { 15804 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15805 // No underlying type explicitly specified, or we failed to parse the 15806 // type, default to int. 15807 EnumUnderlying = Context.IntTy.getTypePtr(); 15808 } else if (UnderlyingType.get()) { 15809 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15810 // integral type; any cv-qualification is ignored. 15811 TypeSourceInfo *TI = nullptr; 15812 GetTypeFromParser(UnderlyingType.get(), &TI); 15813 EnumUnderlying = TI; 15814 15815 if (CheckEnumUnderlyingType(TI)) 15816 // Recover by falling back to int. 15817 EnumUnderlying = Context.IntTy.getTypePtr(); 15818 15819 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15820 UPPC_FixedUnderlyingType)) 15821 EnumUnderlying = Context.IntTy.getTypePtr(); 15822 15823 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15824 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15825 // of 'int'. However, if this is an unfixed forward declaration, don't set 15826 // the underlying type unless the user enables -fms-compatibility. This 15827 // makes unfixed forward declared enums incomplete and is more conforming. 15828 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15829 EnumUnderlying = Context.IntTy.getTypePtr(); 15830 } 15831 } 15832 15833 DeclContext *SearchDC = CurContext; 15834 DeclContext *DC = CurContext; 15835 bool isStdBadAlloc = false; 15836 bool isStdAlignValT = false; 15837 15838 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15839 if (TUK == TUK_Friend || TUK == TUK_Reference) 15840 Redecl = NotForRedeclaration; 15841 15842 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15843 /// implemented asks for structural equivalence checking, the returned decl 15844 /// here is passed back to the parser, allowing the tag body to be parsed. 15845 auto createTagFromNewDecl = [&]() -> TagDecl * { 15846 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15847 // If there is an identifier, use the location of the identifier as the 15848 // location of the decl, otherwise use the location of the struct/union 15849 // keyword. 15850 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15851 TagDecl *New = nullptr; 15852 15853 if (Kind == TTK_Enum) { 15854 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15855 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15856 // If this is an undefined enum, bail. 15857 if (TUK != TUK_Definition && !Invalid) 15858 return nullptr; 15859 if (EnumUnderlying) { 15860 EnumDecl *ED = cast<EnumDecl>(New); 15861 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15862 ED->setIntegerTypeSourceInfo(TI); 15863 else 15864 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15865 ED->setPromotionType(ED->getIntegerType()); 15866 } 15867 } else { // struct/union 15868 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15869 nullptr); 15870 } 15871 15872 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15873 // Add alignment attributes if necessary; these attributes are checked 15874 // when the ASTContext lays out the structure. 15875 // 15876 // It is important for implementing the correct semantics that this 15877 // happen here (in ActOnTag). The #pragma pack stack is 15878 // maintained as a result of parser callbacks which can occur at 15879 // many points during the parsing of a struct declaration (because 15880 // the #pragma tokens are effectively skipped over during the 15881 // parsing of the struct). 15882 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15883 AddAlignmentAttributesForRecord(RD); 15884 AddMsStructLayoutForRecord(RD); 15885 } 15886 } 15887 New->setLexicalDeclContext(CurContext); 15888 return New; 15889 }; 15890 15891 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15892 if (Name && SS.isNotEmpty()) { 15893 // We have a nested-name tag ('struct foo::bar'). 15894 15895 // Check for invalid 'foo::'. 15896 if (SS.isInvalid()) { 15897 Name = nullptr; 15898 goto CreateNewDecl; 15899 } 15900 15901 // If this is a friend or a reference to a class in a dependent 15902 // context, don't try to make a decl for it. 15903 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15904 DC = computeDeclContext(SS, false); 15905 if (!DC) { 15906 IsDependent = true; 15907 return nullptr; 15908 } 15909 } else { 15910 DC = computeDeclContext(SS, true); 15911 if (!DC) { 15912 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15913 << SS.getRange(); 15914 return nullptr; 15915 } 15916 } 15917 15918 if (RequireCompleteDeclContext(SS, DC)) 15919 return nullptr; 15920 15921 SearchDC = DC; 15922 // Look-up name inside 'foo::'. 15923 LookupQualifiedName(Previous, DC); 15924 15925 if (Previous.isAmbiguous()) 15926 return nullptr; 15927 15928 if (Previous.empty()) { 15929 // Name lookup did not find anything. However, if the 15930 // nested-name-specifier refers to the current instantiation, 15931 // and that current instantiation has any dependent base 15932 // classes, we might find something at instantiation time: treat 15933 // this as a dependent elaborated-type-specifier. 15934 // But this only makes any sense for reference-like lookups. 15935 if (Previous.wasNotFoundInCurrentInstantiation() && 15936 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15937 IsDependent = true; 15938 return nullptr; 15939 } 15940 15941 // A tag 'foo::bar' must already exist. 15942 Diag(NameLoc, diag::err_not_tag_in_scope) 15943 << Kind << Name << DC << SS.getRange(); 15944 Name = nullptr; 15945 Invalid = true; 15946 goto CreateNewDecl; 15947 } 15948 } else if (Name) { 15949 // C++14 [class.mem]p14: 15950 // If T is the name of a class, then each of the following shall have a 15951 // name different from T: 15952 // -- every member of class T that is itself a type 15953 if (TUK != TUK_Reference && TUK != TUK_Friend && 15954 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15955 return nullptr; 15956 15957 // If this is a named struct, check to see if there was a previous forward 15958 // declaration or definition. 15959 // FIXME: We're looking into outer scopes here, even when we 15960 // shouldn't be. Doing so can result in ambiguities that we 15961 // shouldn't be diagnosing. 15962 LookupName(Previous, S); 15963 15964 // When declaring or defining a tag, ignore ambiguities introduced 15965 // by types using'ed into this scope. 15966 if (Previous.isAmbiguous() && 15967 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15968 LookupResult::Filter F = Previous.makeFilter(); 15969 while (F.hasNext()) { 15970 NamedDecl *ND = F.next(); 15971 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15972 SearchDC->getRedeclContext())) 15973 F.erase(); 15974 } 15975 F.done(); 15976 } 15977 15978 // C++11 [namespace.memdef]p3: 15979 // If the name in a friend declaration is neither qualified nor 15980 // a template-id and the declaration is a function or an 15981 // elaborated-type-specifier, the lookup to determine whether 15982 // the entity has been previously declared shall not consider 15983 // any scopes outside the innermost enclosing namespace. 15984 // 15985 // MSVC doesn't implement the above rule for types, so a friend tag 15986 // declaration may be a redeclaration of a type declared in an enclosing 15987 // scope. They do implement this rule for friend functions. 15988 // 15989 // Does it matter that this should be by scope instead of by 15990 // semantic context? 15991 if (!Previous.empty() && TUK == TUK_Friend) { 15992 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15993 LookupResult::Filter F = Previous.makeFilter(); 15994 bool FriendSawTagOutsideEnclosingNamespace = false; 15995 while (F.hasNext()) { 15996 NamedDecl *ND = F.next(); 15997 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15998 if (DC->isFileContext() && 15999 !EnclosingNS->Encloses(ND->getDeclContext())) { 16000 if (getLangOpts().MSVCCompat) 16001 FriendSawTagOutsideEnclosingNamespace = true; 16002 else 16003 F.erase(); 16004 } 16005 } 16006 F.done(); 16007 16008 // Diagnose this MSVC extension in the easy case where lookup would have 16009 // unambiguously found something outside the enclosing namespace. 16010 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 16011 NamedDecl *ND = Previous.getFoundDecl(); 16012 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 16013 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 16014 } 16015 } 16016 16017 // Note: there used to be some attempt at recovery here. 16018 if (Previous.isAmbiguous()) 16019 return nullptr; 16020 16021 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 16022 // FIXME: This makes sure that we ignore the contexts associated 16023 // with C structs, unions, and enums when looking for a matching 16024 // tag declaration or definition. See the similar lookup tweak 16025 // in Sema::LookupName; is there a better way to deal with this? 16026 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 16027 SearchDC = SearchDC->getParent(); 16028 } 16029 } 16030 16031 if (Previous.isSingleResult() && 16032 Previous.getFoundDecl()->isTemplateParameter()) { 16033 // Maybe we will complain about the shadowed template parameter. 16034 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 16035 // Just pretend that we didn't see the previous declaration. 16036 Previous.clear(); 16037 } 16038 16039 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 16040 DC->Equals(getStdNamespace())) { 16041 if (Name->isStr("bad_alloc")) { 16042 // This is a declaration of or a reference to "std::bad_alloc". 16043 isStdBadAlloc = true; 16044 16045 // If std::bad_alloc has been implicitly declared (but made invisible to 16046 // name lookup), fill in this implicit declaration as the previous 16047 // declaration, so that the declarations get chained appropriately. 16048 if (Previous.empty() && StdBadAlloc) 16049 Previous.addDecl(getStdBadAlloc()); 16050 } else if (Name->isStr("align_val_t")) { 16051 isStdAlignValT = true; 16052 if (Previous.empty() && StdAlignValT) 16053 Previous.addDecl(getStdAlignValT()); 16054 } 16055 } 16056 16057 // If we didn't find a previous declaration, and this is a reference 16058 // (or friend reference), move to the correct scope. In C++, we 16059 // also need to do a redeclaration lookup there, just in case 16060 // there's a shadow friend decl. 16061 if (Name && Previous.empty() && 16062 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 16063 if (Invalid) goto CreateNewDecl; 16064 assert(SS.isEmpty()); 16065 16066 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 16067 // C++ [basic.scope.pdecl]p5: 16068 // -- for an elaborated-type-specifier of the form 16069 // 16070 // class-key identifier 16071 // 16072 // if the elaborated-type-specifier is used in the 16073 // decl-specifier-seq or parameter-declaration-clause of a 16074 // function defined in namespace scope, the identifier is 16075 // declared as a class-name in the namespace that contains 16076 // the declaration; otherwise, except as a friend 16077 // declaration, the identifier is declared in the smallest 16078 // non-class, non-function-prototype scope that contains the 16079 // declaration. 16080 // 16081 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 16082 // C structs and unions. 16083 // 16084 // It is an error in C++ to declare (rather than define) an enum 16085 // type, including via an elaborated type specifier. We'll 16086 // diagnose that later; for now, declare the enum in the same 16087 // scope as we would have picked for any other tag type. 16088 // 16089 // GNU C also supports this behavior as part of its incomplete 16090 // enum types extension, while GNU C++ does not. 16091 // 16092 // Find the context where we'll be declaring the tag. 16093 // FIXME: We would like to maintain the current DeclContext as the 16094 // lexical context, 16095 SearchDC = getTagInjectionContext(SearchDC); 16096 16097 // Find the scope where we'll be declaring the tag. 16098 S = getTagInjectionScope(S, getLangOpts()); 16099 } else { 16100 assert(TUK == TUK_Friend); 16101 // C++ [namespace.memdef]p3: 16102 // If a friend declaration in a non-local class first declares a 16103 // class or function, the friend class or function is a member of 16104 // the innermost enclosing namespace. 16105 SearchDC = SearchDC->getEnclosingNamespaceContext(); 16106 } 16107 16108 // In C++, we need to do a redeclaration lookup to properly 16109 // diagnose some problems. 16110 // FIXME: redeclaration lookup is also used (with and without C++) to find a 16111 // hidden declaration so that we don't get ambiguity errors when using a 16112 // type declared by an elaborated-type-specifier. In C that is not correct 16113 // and we should instead merge compatible types found by lookup. 16114 if (getLangOpts().CPlusPlus) { 16115 // FIXME: This can perform qualified lookups into function contexts, 16116 // which are meaningless. 16117 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16118 LookupQualifiedName(Previous, SearchDC); 16119 } else { 16120 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16121 LookupName(Previous, S); 16122 } 16123 } 16124 16125 // If we have a known previous declaration to use, then use it. 16126 if (Previous.empty() && SkipBody && SkipBody->Previous) 16127 Previous.addDecl(SkipBody->Previous); 16128 16129 if (!Previous.empty()) { 16130 NamedDecl *PrevDecl = Previous.getFoundDecl(); 16131 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 16132 16133 // It's okay to have a tag decl in the same scope as a typedef 16134 // which hides a tag decl in the same scope. Finding this 16135 // with a redeclaration lookup can only actually happen in C++. 16136 // 16137 // This is also okay for elaborated-type-specifiers, which is 16138 // technically forbidden by the current standard but which is 16139 // okay according to the likely resolution of an open issue; 16140 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16141 if (getLangOpts().CPlusPlus) { 16142 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16143 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16144 TagDecl *Tag = TT->getDecl(); 16145 if (Tag->getDeclName() == Name && 16146 Tag->getDeclContext()->getRedeclContext() 16147 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16148 PrevDecl = Tag; 16149 Previous.clear(); 16150 Previous.addDecl(Tag); 16151 Previous.resolveKind(); 16152 } 16153 } 16154 } 16155 } 16156 16157 // If this is a redeclaration of a using shadow declaration, it must 16158 // declare a tag in the same context. In MSVC mode, we allow a 16159 // redefinition if either context is within the other. 16160 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16161 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16162 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16163 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16164 !(OldTag && isAcceptableTagRedeclContext( 16165 *this, OldTag->getDeclContext(), SearchDC))) { 16166 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16167 Diag(Shadow->getTargetDecl()->getLocation(), 16168 diag::note_using_decl_target); 16169 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16170 << 0; 16171 // Recover by ignoring the old declaration. 16172 Previous.clear(); 16173 goto CreateNewDecl; 16174 } 16175 } 16176 16177 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16178 // If this is a use of a previous tag, or if the tag is already declared 16179 // in the same scope (so that the definition/declaration completes or 16180 // rementions the tag), reuse the decl. 16181 if (TUK == TUK_Reference || TUK == TUK_Friend || 16182 isDeclInScope(DirectPrevDecl, SearchDC, S, 16183 SS.isNotEmpty() || isMemberSpecialization)) { 16184 // Make sure that this wasn't declared as an enum and now used as a 16185 // struct or something similar. 16186 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16187 TUK == TUK_Definition, KWLoc, 16188 Name)) { 16189 bool SafeToContinue 16190 = (PrevTagDecl->getTagKind() != TTK_Enum && 16191 Kind != TTK_Enum); 16192 if (SafeToContinue) 16193 Diag(KWLoc, diag::err_use_with_wrong_tag) 16194 << Name 16195 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16196 PrevTagDecl->getKindName()); 16197 else 16198 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16199 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16200 16201 if (SafeToContinue) 16202 Kind = PrevTagDecl->getTagKind(); 16203 else { 16204 // Recover by making this an anonymous redefinition. 16205 Name = nullptr; 16206 Previous.clear(); 16207 Invalid = true; 16208 } 16209 } 16210 16211 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16212 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16213 if (TUK == TUK_Reference || TUK == TUK_Friend) 16214 return PrevTagDecl; 16215 16216 QualType EnumUnderlyingTy; 16217 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16218 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16219 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16220 EnumUnderlyingTy = QualType(T, 0); 16221 16222 // All conflicts with previous declarations are recovered by 16223 // returning the previous declaration, unless this is a definition, 16224 // in which case we want the caller to bail out. 16225 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16226 ScopedEnum, EnumUnderlyingTy, 16227 IsFixed, PrevEnum)) 16228 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16229 } 16230 16231 // C++11 [class.mem]p1: 16232 // A member shall not be declared twice in the member-specification, 16233 // except that a nested class or member class template can be declared 16234 // and then later defined. 16235 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16236 S->isDeclScope(PrevDecl)) { 16237 Diag(NameLoc, diag::ext_member_redeclared); 16238 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16239 } 16240 16241 if (!Invalid) { 16242 // If this is a use, just return the declaration we found, unless 16243 // we have attributes. 16244 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16245 if (!Attrs.empty()) { 16246 // FIXME: Diagnose these attributes. For now, we create a new 16247 // declaration to hold them. 16248 } else if (TUK == TUK_Reference && 16249 (PrevTagDecl->getFriendObjectKind() == 16250 Decl::FOK_Undeclared || 16251 PrevDecl->getOwningModule() != getCurrentModule()) && 16252 SS.isEmpty()) { 16253 // This declaration is a reference to an existing entity, but 16254 // has different visibility from that entity: it either makes 16255 // a friend visible or it makes a type visible in a new module. 16256 // In either case, create a new declaration. We only do this if 16257 // the declaration would have meant the same thing if no prior 16258 // declaration were found, that is, if it was found in the same 16259 // scope where we would have injected a declaration. 16260 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16261 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16262 return PrevTagDecl; 16263 // This is in the injected scope, create a new declaration in 16264 // that scope. 16265 S = getTagInjectionScope(S, getLangOpts()); 16266 } else { 16267 return PrevTagDecl; 16268 } 16269 } 16270 16271 // Diagnose attempts to redefine a tag. 16272 if (TUK == TUK_Definition) { 16273 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16274 // If we're defining a specialization and the previous definition 16275 // is from an implicit instantiation, don't emit an error 16276 // here; we'll catch this in the general case below. 16277 bool IsExplicitSpecializationAfterInstantiation = false; 16278 if (isMemberSpecialization) { 16279 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16280 IsExplicitSpecializationAfterInstantiation = 16281 RD->getTemplateSpecializationKind() != 16282 TSK_ExplicitSpecialization; 16283 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16284 IsExplicitSpecializationAfterInstantiation = 16285 ED->getTemplateSpecializationKind() != 16286 TSK_ExplicitSpecialization; 16287 } 16288 16289 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16290 // not keep more that one definition around (merge them). However, 16291 // ensure the decl passes the structural compatibility check in 16292 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16293 NamedDecl *Hidden = nullptr; 16294 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16295 // There is a definition of this tag, but it is not visible. We 16296 // explicitly make use of C++'s one definition rule here, and 16297 // assume that this definition is identical to the hidden one 16298 // we already have. Make the existing definition visible and 16299 // use it in place of this one. 16300 if (!getLangOpts().CPlusPlus) { 16301 // Postpone making the old definition visible until after we 16302 // complete parsing the new one and do the structural 16303 // comparison. 16304 SkipBody->CheckSameAsPrevious = true; 16305 SkipBody->New = createTagFromNewDecl(); 16306 SkipBody->Previous = Def; 16307 return Def; 16308 } else { 16309 SkipBody->ShouldSkip = true; 16310 SkipBody->Previous = Def; 16311 makeMergedDefinitionVisible(Hidden); 16312 // Carry on and handle it like a normal definition. We'll 16313 // skip starting the definitiion later. 16314 } 16315 } else if (!IsExplicitSpecializationAfterInstantiation) { 16316 // A redeclaration in function prototype scope in C isn't 16317 // visible elsewhere, so merely issue a warning. 16318 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16319 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16320 else 16321 Diag(NameLoc, diag::err_redefinition) << Name; 16322 notePreviousDefinition(Def, 16323 NameLoc.isValid() ? NameLoc : KWLoc); 16324 // If this is a redefinition, recover by making this 16325 // struct be anonymous, which will make any later 16326 // references get the previous definition. 16327 Name = nullptr; 16328 Previous.clear(); 16329 Invalid = true; 16330 } 16331 } else { 16332 // If the type is currently being defined, complain 16333 // about a nested redefinition. 16334 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16335 if (TD->isBeingDefined()) { 16336 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16337 Diag(PrevTagDecl->getLocation(), 16338 diag::note_previous_definition); 16339 Name = nullptr; 16340 Previous.clear(); 16341 Invalid = true; 16342 } 16343 } 16344 16345 // Okay, this is definition of a previously declared or referenced 16346 // tag. We're going to create a new Decl for it. 16347 } 16348 16349 // Okay, we're going to make a redeclaration. If this is some kind 16350 // of reference, make sure we build the redeclaration in the same DC 16351 // as the original, and ignore the current access specifier. 16352 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16353 SearchDC = PrevTagDecl->getDeclContext(); 16354 AS = AS_none; 16355 } 16356 } 16357 // If we get here we have (another) forward declaration or we 16358 // have a definition. Just create a new decl. 16359 16360 } else { 16361 // If we get here, this is a definition of a new tag type in a nested 16362 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16363 // new decl/type. We set PrevDecl to NULL so that the entities 16364 // have distinct types. 16365 Previous.clear(); 16366 } 16367 // If we get here, we're going to create a new Decl. If PrevDecl 16368 // is non-NULL, it's a definition of the tag declared by 16369 // PrevDecl. If it's NULL, we have a new definition. 16370 16371 // Otherwise, PrevDecl is not a tag, but was found with tag 16372 // lookup. This is only actually possible in C++, where a few 16373 // things like templates still live in the tag namespace. 16374 } else { 16375 // Use a better diagnostic if an elaborated-type-specifier 16376 // found the wrong kind of type on the first 16377 // (non-redeclaration) lookup. 16378 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16379 !Previous.isForRedeclaration()) { 16380 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16381 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16382 << Kind; 16383 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16384 Invalid = true; 16385 16386 // Otherwise, only diagnose if the declaration is in scope. 16387 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16388 SS.isNotEmpty() || isMemberSpecialization)) { 16389 // do nothing 16390 16391 // Diagnose implicit declarations introduced by elaborated types. 16392 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16393 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16394 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16395 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16396 Invalid = true; 16397 16398 // Otherwise it's a declaration. Call out a particularly common 16399 // case here. 16400 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16401 unsigned Kind = 0; 16402 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16403 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16404 << Name << Kind << TND->getUnderlyingType(); 16405 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16406 Invalid = true; 16407 16408 // Otherwise, diagnose. 16409 } else { 16410 // The tag name clashes with something else in the target scope, 16411 // issue an error and recover by making this tag be anonymous. 16412 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16413 notePreviousDefinition(PrevDecl, NameLoc); 16414 Name = nullptr; 16415 Invalid = true; 16416 } 16417 16418 // The existing declaration isn't relevant to us; we're in a 16419 // new scope, so clear out the previous declaration. 16420 Previous.clear(); 16421 } 16422 } 16423 16424 CreateNewDecl: 16425 16426 TagDecl *PrevDecl = nullptr; 16427 if (Previous.isSingleResult()) 16428 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16429 16430 // If there is an identifier, use the location of the identifier as the 16431 // location of the decl, otherwise use the location of the struct/union 16432 // keyword. 16433 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16434 16435 // Otherwise, create a new declaration. If there is a previous 16436 // declaration of the same entity, the two will be linked via 16437 // PrevDecl. 16438 TagDecl *New; 16439 16440 if (Kind == TTK_Enum) { 16441 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16442 // enum X { A, B, C } D; D should chain to X. 16443 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16444 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16445 ScopedEnumUsesClassTag, IsFixed); 16446 16447 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16448 StdAlignValT = cast<EnumDecl>(New); 16449 16450 // If this is an undefined enum, warn. 16451 if (TUK != TUK_Definition && !Invalid) { 16452 TagDecl *Def; 16453 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16454 // C++0x: 7.2p2: opaque-enum-declaration. 16455 // Conflicts are diagnosed above. Do nothing. 16456 } 16457 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16458 Diag(Loc, diag::ext_forward_ref_enum_def) 16459 << New; 16460 Diag(Def->getLocation(), diag::note_previous_definition); 16461 } else { 16462 unsigned DiagID = diag::ext_forward_ref_enum; 16463 if (getLangOpts().MSVCCompat) 16464 DiagID = diag::ext_ms_forward_ref_enum; 16465 else if (getLangOpts().CPlusPlus) 16466 DiagID = diag::err_forward_ref_enum; 16467 Diag(Loc, DiagID); 16468 } 16469 } 16470 16471 if (EnumUnderlying) { 16472 EnumDecl *ED = cast<EnumDecl>(New); 16473 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16474 ED->setIntegerTypeSourceInfo(TI); 16475 else 16476 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16477 ED->setPromotionType(ED->getIntegerType()); 16478 assert(ED->isComplete() && "enum with type should be complete"); 16479 } 16480 } else { 16481 // struct/union/class 16482 16483 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16484 // struct X { int A; } D; D should chain to X. 16485 if (getLangOpts().CPlusPlus) { 16486 // FIXME: Look for a way to use RecordDecl for simple structs. 16487 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16488 cast_or_null<CXXRecordDecl>(PrevDecl)); 16489 16490 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16491 StdBadAlloc = cast<CXXRecordDecl>(New); 16492 } else 16493 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16494 cast_or_null<RecordDecl>(PrevDecl)); 16495 } 16496 16497 // C++11 [dcl.type]p3: 16498 // A type-specifier-seq shall not define a class or enumeration [...]. 16499 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16500 TUK == TUK_Definition) { 16501 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16502 << Context.getTagDeclType(New); 16503 Invalid = true; 16504 } 16505 16506 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16507 DC->getDeclKind() == Decl::Enum) { 16508 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16509 << Context.getTagDeclType(New); 16510 Invalid = true; 16511 } 16512 16513 // Maybe add qualifier info. 16514 if (SS.isNotEmpty()) { 16515 if (SS.isSet()) { 16516 // If this is either a declaration or a definition, check the 16517 // nested-name-specifier against the current context. 16518 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16519 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16520 isMemberSpecialization)) 16521 Invalid = true; 16522 16523 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16524 if (TemplateParameterLists.size() > 0) { 16525 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16526 } 16527 } 16528 else 16529 Invalid = true; 16530 } 16531 16532 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16533 // Add alignment attributes if necessary; these attributes are checked when 16534 // the ASTContext lays out the structure. 16535 // 16536 // It is important for implementing the correct semantics that this 16537 // happen here (in ActOnTag). The #pragma pack stack is 16538 // maintained as a result of parser callbacks which can occur at 16539 // many points during the parsing of a struct declaration (because 16540 // the #pragma tokens are effectively skipped over during the 16541 // parsing of the struct). 16542 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16543 AddAlignmentAttributesForRecord(RD); 16544 AddMsStructLayoutForRecord(RD); 16545 } 16546 } 16547 16548 if (ModulePrivateLoc.isValid()) { 16549 if (isMemberSpecialization) 16550 Diag(New->getLocation(), diag::err_module_private_specialization) 16551 << 2 16552 << FixItHint::CreateRemoval(ModulePrivateLoc); 16553 // __module_private__ does not apply to local classes. However, we only 16554 // diagnose this as an error when the declaration specifiers are 16555 // freestanding. Here, we just ignore the __module_private__. 16556 else if (!SearchDC->isFunctionOrMethod()) 16557 New->setModulePrivate(); 16558 } 16559 16560 // If this is a specialization of a member class (of a class template), 16561 // check the specialization. 16562 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16563 Invalid = true; 16564 16565 // If we're declaring or defining a tag in function prototype scope in C, 16566 // note that this type can only be used within the function and add it to 16567 // the list of decls to inject into the function definition scope. 16568 if ((Name || Kind == TTK_Enum) && 16569 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16570 if (getLangOpts().CPlusPlus) { 16571 // C++ [dcl.fct]p6: 16572 // Types shall not be defined in return or parameter types. 16573 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16574 Diag(Loc, diag::err_type_defined_in_param_type) 16575 << Name; 16576 Invalid = true; 16577 } 16578 } else if (!PrevDecl) { 16579 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16580 } 16581 } 16582 16583 if (Invalid) 16584 New->setInvalidDecl(); 16585 16586 // Set the lexical context. If the tag has a C++ scope specifier, the 16587 // lexical context will be different from the semantic context. 16588 New->setLexicalDeclContext(CurContext); 16589 16590 // Mark this as a friend decl if applicable. 16591 // In Microsoft mode, a friend declaration also acts as a forward 16592 // declaration so we always pass true to setObjectOfFriendDecl to make 16593 // the tag name visible. 16594 if (TUK == TUK_Friend) 16595 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16596 16597 // Set the access specifier. 16598 if (!Invalid && SearchDC->isRecord()) 16599 SetMemberAccessSpecifier(New, PrevDecl, AS); 16600 16601 if (PrevDecl) 16602 CheckRedeclarationInModule(New, PrevDecl); 16603 16604 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16605 New->startDefinition(); 16606 16607 ProcessDeclAttributeList(S, New, Attrs); 16608 AddPragmaAttributes(S, New); 16609 16610 // If this has an identifier, add it to the scope stack. 16611 if (TUK == TUK_Friend) { 16612 // We might be replacing an existing declaration in the lookup tables; 16613 // if so, borrow its access specifier. 16614 if (PrevDecl) 16615 New->setAccess(PrevDecl->getAccess()); 16616 16617 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16618 DC->makeDeclVisibleInContext(New); 16619 if (Name) // can be null along some error paths 16620 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16621 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16622 } else if (Name) { 16623 S = getNonFieldDeclScope(S); 16624 PushOnScopeChains(New, S, true); 16625 } else { 16626 CurContext->addDecl(New); 16627 } 16628 16629 // If this is the C FILE type, notify the AST context. 16630 if (IdentifierInfo *II = New->getIdentifier()) 16631 if (!New->isInvalidDecl() && 16632 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16633 II->isStr("FILE")) 16634 Context.setFILEDecl(New); 16635 16636 if (PrevDecl) 16637 mergeDeclAttributes(New, PrevDecl); 16638 16639 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16640 inferGslOwnerPointerAttribute(CXXRD); 16641 16642 // If there's a #pragma GCC visibility in scope, set the visibility of this 16643 // record. 16644 AddPushedVisibilityAttribute(New); 16645 16646 if (isMemberSpecialization && !New->isInvalidDecl()) 16647 CompleteMemberSpecialization(New, Previous); 16648 16649 OwnedDecl = true; 16650 // In C++, don't return an invalid declaration. We can't recover well from 16651 // the cases where we make the type anonymous. 16652 if (Invalid && getLangOpts().CPlusPlus) { 16653 if (New->isBeingDefined()) 16654 if (auto RD = dyn_cast<RecordDecl>(New)) 16655 RD->completeDefinition(); 16656 return nullptr; 16657 } else if (SkipBody && SkipBody->ShouldSkip) { 16658 return SkipBody->Previous; 16659 } else { 16660 return New; 16661 } 16662 } 16663 16664 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16665 AdjustDeclIfTemplate(TagD); 16666 TagDecl *Tag = cast<TagDecl>(TagD); 16667 16668 // Enter the tag context. 16669 PushDeclContext(S, Tag); 16670 16671 ActOnDocumentableDecl(TagD); 16672 16673 // If there's a #pragma GCC visibility in scope, set the visibility of this 16674 // record. 16675 AddPushedVisibilityAttribute(Tag); 16676 } 16677 16678 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16679 SkipBodyInfo &SkipBody) { 16680 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16681 return false; 16682 16683 // Make the previous decl visible. 16684 makeMergedDefinitionVisible(SkipBody.Previous); 16685 return true; 16686 } 16687 16688 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16689 assert(isa<ObjCContainerDecl>(IDecl) && 16690 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16691 DeclContext *OCD = cast<DeclContext>(IDecl); 16692 assert(OCD->getLexicalParent() == CurContext && 16693 "The next DeclContext should be lexically contained in the current one."); 16694 CurContext = OCD; 16695 return IDecl; 16696 } 16697 16698 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16699 SourceLocation FinalLoc, 16700 bool IsFinalSpelledSealed, 16701 bool IsAbstract, 16702 SourceLocation LBraceLoc) { 16703 AdjustDeclIfTemplate(TagD); 16704 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16705 16706 FieldCollector->StartClass(); 16707 16708 if (!Record->getIdentifier()) 16709 return; 16710 16711 if (IsAbstract) 16712 Record->markAbstract(); 16713 16714 if (FinalLoc.isValid()) { 16715 Record->addAttr(FinalAttr::Create( 16716 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16717 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16718 } 16719 // C++ [class]p2: 16720 // [...] The class-name is also inserted into the scope of the 16721 // class itself; this is known as the injected-class-name. For 16722 // purposes of access checking, the injected-class-name is treated 16723 // as if it were a public member name. 16724 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16725 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16726 Record->getLocation(), Record->getIdentifier(), 16727 /*PrevDecl=*/nullptr, 16728 /*DelayTypeCreation=*/true); 16729 Context.getTypeDeclType(InjectedClassName, Record); 16730 InjectedClassName->setImplicit(); 16731 InjectedClassName->setAccess(AS_public); 16732 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16733 InjectedClassName->setDescribedClassTemplate(Template); 16734 PushOnScopeChains(InjectedClassName, S); 16735 assert(InjectedClassName->isInjectedClassName() && 16736 "Broken injected-class-name"); 16737 } 16738 16739 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16740 SourceRange BraceRange) { 16741 AdjustDeclIfTemplate(TagD); 16742 TagDecl *Tag = cast<TagDecl>(TagD); 16743 Tag->setBraceRange(BraceRange); 16744 16745 // Make sure we "complete" the definition even it is invalid. 16746 if (Tag->isBeingDefined()) { 16747 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16748 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16749 RD->completeDefinition(); 16750 } 16751 16752 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 16753 FieldCollector->FinishClass(); 16754 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 16755 auto *Def = RD->getDefinition(); 16756 assert(Def && "The record is expected to have a completed definition"); 16757 unsigned NumInitMethods = 0; 16758 for (auto *Method : Def->methods()) { 16759 if (!Method->getIdentifier()) 16760 continue; 16761 if (Method->getName() == "__init") 16762 NumInitMethods++; 16763 } 16764 if (NumInitMethods > 1 || !Def->hasInitMethod()) 16765 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 16766 } 16767 } 16768 16769 // Exit this scope of this tag's definition. 16770 PopDeclContext(); 16771 16772 if (getCurLexicalContext()->isObjCContainer() && 16773 Tag->getDeclContext()->isFileContext()) 16774 Tag->setTopLevelDeclInObjCContainer(); 16775 16776 // Notify the consumer that we've defined a tag. 16777 if (!Tag->isInvalidDecl()) 16778 Consumer.HandleTagDeclDefinition(Tag); 16779 16780 // Clangs implementation of #pragma align(packed) differs in bitfield layout 16781 // from XLs and instead matches the XL #pragma pack(1) behavior. 16782 if (Context.getTargetInfo().getTriple().isOSAIX() && 16783 AlignPackStack.hasValue()) { 16784 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 16785 // Only diagnose #pragma align(packed). 16786 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 16787 return; 16788 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 16789 if (!RD) 16790 return; 16791 // Only warn if there is at least 1 bitfield member. 16792 if (llvm::any_of(RD->fields(), 16793 [](const FieldDecl *FD) { return FD->isBitField(); })) 16794 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 16795 } 16796 } 16797 16798 void Sema::ActOnObjCContainerFinishDefinition() { 16799 // Exit this scope of this interface definition. 16800 PopDeclContext(); 16801 } 16802 16803 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16804 assert(DC == CurContext && "Mismatch of container contexts"); 16805 OriginalLexicalContext = DC; 16806 ActOnObjCContainerFinishDefinition(); 16807 } 16808 16809 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16810 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16811 OriginalLexicalContext = nullptr; 16812 } 16813 16814 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16815 AdjustDeclIfTemplate(TagD); 16816 TagDecl *Tag = cast<TagDecl>(TagD); 16817 Tag->setInvalidDecl(); 16818 16819 // Make sure we "complete" the definition even it is invalid. 16820 if (Tag->isBeingDefined()) { 16821 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16822 RD->completeDefinition(); 16823 } 16824 16825 // We're undoing ActOnTagStartDefinition here, not 16826 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16827 // the FieldCollector. 16828 16829 PopDeclContext(); 16830 } 16831 16832 // Note that FieldName may be null for anonymous bitfields. 16833 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16834 IdentifierInfo *FieldName, 16835 QualType FieldTy, bool IsMsStruct, 16836 Expr *BitWidth, bool *ZeroWidth) { 16837 assert(BitWidth); 16838 if (BitWidth->containsErrors()) 16839 return ExprError(); 16840 16841 // Default to true; that shouldn't confuse checks for emptiness 16842 if (ZeroWidth) 16843 *ZeroWidth = true; 16844 16845 // C99 6.7.2.1p4 - verify the field type. 16846 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16847 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16848 // Handle incomplete and sizeless types with a specific error. 16849 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16850 diag::err_field_incomplete_or_sizeless)) 16851 return ExprError(); 16852 if (FieldName) 16853 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16854 << FieldName << FieldTy << BitWidth->getSourceRange(); 16855 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16856 << FieldTy << BitWidth->getSourceRange(); 16857 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16858 UPPC_BitFieldWidth)) 16859 return ExprError(); 16860 16861 // If the bit-width is type- or value-dependent, don't try to check 16862 // it now. 16863 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16864 return BitWidth; 16865 16866 llvm::APSInt Value; 16867 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16868 if (ICE.isInvalid()) 16869 return ICE; 16870 BitWidth = ICE.get(); 16871 16872 if (Value != 0 && ZeroWidth) 16873 *ZeroWidth = false; 16874 16875 // Zero-width bitfield is ok for anonymous field. 16876 if (Value == 0 && FieldName) 16877 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16878 16879 if (Value.isSigned() && Value.isNegative()) { 16880 if (FieldName) 16881 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16882 << FieldName << toString(Value, 10); 16883 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16884 << toString(Value, 10); 16885 } 16886 16887 // The size of the bit-field must not exceed our maximum permitted object 16888 // size. 16889 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16890 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16891 << !FieldName << FieldName << toString(Value, 10); 16892 } 16893 16894 if (!FieldTy->isDependentType()) { 16895 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16896 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16897 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16898 16899 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16900 // ABI. 16901 bool CStdConstraintViolation = 16902 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16903 bool MSBitfieldViolation = 16904 Value.ugt(TypeStorageSize) && 16905 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16906 if (CStdConstraintViolation || MSBitfieldViolation) { 16907 unsigned DiagWidth = 16908 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16909 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16910 << (bool)FieldName << FieldName << toString(Value, 10) 16911 << !CStdConstraintViolation << DiagWidth; 16912 } 16913 16914 // Warn on types where the user might conceivably expect to get all 16915 // specified bits as value bits: that's all integral types other than 16916 // 'bool'. 16917 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16918 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16919 << FieldName << toString(Value, 10) 16920 << (unsigned)TypeWidth; 16921 } 16922 } 16923 16924 return BitWidth; 16925 } 16926 16927 /// ActOnField - Each field of a C struct/union is passed into this in order 16928 /// to create a FieldDecl object for it. 16929 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16930 Declarator &D, Expr *BitfieldWidth) { 16931 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16932 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16933 /*InitStyle=*/ICIS_NoInit, AS_public); 16934 return Res; 16935 } 16936 16937 /// HandleField - Analyze a field of a C struct or a C++ data member. 16938 /// 16939 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16940 SourceLocation DeclStart, 16941 Declarator &D, Expr *BitWidth, 16942 InClassInitStyle InitStyle, 16943 AccessSpecifier AS) { 16944 if (D.isDecompositionDeclarator()) { 16945 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16946 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16947 << Decomp.getSourceRange(); 16948 return nullptr; 16949 } 16950 16951 IdentifierInfo *II = D.getIdentifier(); 16952 SourceLocation Loc = DeclStart; 16953 if (II) Loc = D.getIdentifierLoc(); 16954 16955 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16956 QualType T = TInfo->getType(); 16957 if (getLangOpts().CPlusPlus) { 16958 CheckExtraCXXDefaultArguments(D); 16959 16960 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16961 UPPC_DataMemberType)) { 16962 D.setInvalidType(); 16963 T = Context.IntTy; 16964 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16965 } 16966 } 16967 16968 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16969 16970 if (D.getDeclSpec().isInlineSpecified()) 16971 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16972 << getLangOpts().CPlusPlus17; 16973 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16974 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16975 diag::err_invalid_thread) 16976 << DeclSpec::getSpecifierName(TSCS); 16977 16978 // Check to see if this name was declared as a member previously 16979 NamedDecl *PrevDecl = nullptr; 16980 LookupResult Previous(*this, II, Loc, LookupMemberName, 16981 ForVisibleRedeclaration); 16982 LookupName(Previous, S); 16983 switch (Previous.getResultKind()) { 16984 case LookupResult::Found: 16985 case LookupResult::FoundUnresolvedValue: 16986 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16987 break; 16988 16989 case LookupResult::FoundOverloaded: 16990 PrevDecl = Previous.getRepresentativeDecl(); 16991 break; 16992 16993 case LookupResult::NotFound: 16994 case LookupResult::NotFoundInCurrentInstantiation: 16995 case LookupResult::Ambiguous: 16996 break; 16997 } 16998 Previous.suppressDiagnostics(); 16999 17000 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17001 // Maybe we will complain about the shadowed template parameter. 17002 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17003 // Just pretend that we didn't see the previous declaration. 17004 PrevDecl = nullptr; 17005 } 17006 17007 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17008 PrevDecl = nullptr; 17009 17010 bool Mutable 17011 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 17012 SourceLocation TSSL = D.getBeginLoc(); 17013 FieldDecl *NewFD 17014 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 17015 TSSL, AS, PrevDecl, &D); 17016 17017 if (NewFD->isInvalidDecl()) 17018 Record->setInvalidDecl(); 17019 17020 if (D.getDeclSpec().isModulePrivateSpecified()) 17021 NewFD->setModulePrivate(); 17022 17023 if (NewFD->isInvalidDecl() && PrevDecl) { 17024 // Don't introduce NewFD into scope; there's already something 17025 // with the same name in the same scope. 17026 } else if (II) { 17027 PushOnScopeChains(NewFD, S); 17028 } else 17029 Record->addDecl(NewFD); 17030 17031 return NewFD; 17032 } 17033 17034 /// Build a new FieldDecl and check its well-formedness. 17035 /// 17036 /// This routine builds a new FieldDecl given the fields name, type, 17037 /// record, etc. \p PrevDecl should refer to any previous declaration 17038 /// with the same name and in the same scope as the field to be 17039 /// created. 17040 /// 17041 /// \returns a new FieldDecl. 17042 /// 17043 /// \todo The Declarator argument is a hack. It will be removed once 17044 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 17045 TypeSourceInfo *TInfo, 17046 RecordDecl *Record, SourceLocation Loc, 17047 bool Mutable, Expr *BitWidth, 17048 InClassInitStyle InitStyle, 17049 SourceLocation TSSL, 17050 AccessSpecifier AS, NamedDecl *PrevDecl, 17051 Declarator *D) { 17052 IdentifierInfo *II = Name.getAsIdentifierInfo(); 17053 bool InvalidDecl = false; 17054 if (D) InvalidDecl = D->isInvalidType(); 17055 17056 // If we receive a broken type, recover by assuming 'int' and 17057 // marking this declaration as invalid. 17058 if (T.isNull() || T->containsErrors()) { 17059 InvalidDecl = true; 17060 T = Context.IntTy; 17061 } 17062 17063 QualType EltTy = Context.getBaseElementType(T); 17064 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 17065 if (RequireCompleteSizedType(Loc, EltTy, 17066 diag::err_field_incomplete_or_sizeless)) { 17067 // Fields of incomplete type force their record to be invalid. 17068 Record->setInvalidDecl(); 17069 InvalidDecl = true; 17070 } else { 17071 NamedDecl *Def; 17072 EltTy->isIncompleteType(&Def); 17073 if (Def && Def->isInvalidDecl()) { 17074 Record->setInvalidDecl(); 17075 InvalidDecl = true; 17076 } 17077 } 17078 } 17079 17080 // TR 18037 does not allow fields to be declared with address space 17081 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 17082 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 17083 Diag(Loc, diag::err_field_with_address_space); 17084 Record->setInvalidDecl(); 17085 InvalidDecl = true; 17086 } 17087 17088 if (LangOpts.OpenCL) { 17089 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 17090 // used as structure or union field: image, sampler, event or block types. 17091 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 17092 T->isBlockPointerType()) { 17093 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 17094 Record->setInvalidDecl(); 17095 InvalidDecl = true; 17096 } 17097 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 17098 // is enabled. 17099 if (BitWidth && !getOpenCLOptions().isAvailableOption( 17100 "__cl_clang_bitfields", LangOpts)) { 17101 Diag(Loc, diag::err_opencl_bitfields); 17102 InvalidDecl = true; 17103 } 17104 } 17105 17106 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 17107 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 17108 T.hasQualifiers()) { 17109 InvalidDecl = true; 17110 Diag(Loc, diag::err_anon_bitfield_qualifiers); 17111 } 17112 17113 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17114 // than a variably modified type. 17115 if (!InvalidDecl && T->isVariablyModifiedType()) { 17116 if (!tryToFixVariablyModifiedVarType( 17117 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 17118 InvalidDecl = true; 17119 } 17120 17121 // Fields can not have abstract class types 17122 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 17123 diag::err_abstract_type_in_decl, 17124 AbstractFieldType)) 17125 InvalidDecl = true; 17126 17127 bool ZeroWidth = false; 17128 if (InvalidDecl) 17129 BitWidth = nullptr; 17130 // If this is declared as a bit-field, check the bit-field. 17131 if (BitWidth) { 17132 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 17133 &ZeroWidth).get(); 17134 if (!BitWidth) { 17135 InvalidDecl = true; 17136 BitWidth = nullptr; 17137 ZeroWidth = false; 17138 } 17139 } 17140 17141 // Check that 'mutable' is consistent with the type of the declaration. 17142 if (!InvalidDecl && Mutable) { 17143 unsigned DiagID = 0; 17144 if (T->isReferenceType()) 17145 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 17146 : diag::err_mutable_reference; 17147 else if (T.isConstQualified()) 17148 DiagID = diag::err_mutable_const; 17149 17150 if (DiagID) { 17151 SourceLocation ErrLoc = Loc; 17152 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17153 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17154 Diag(ErrLoc, DiagID); 17155 if (DiagID != diag::ext_mutable_reference) { 17156 Mutable = false; 17157 InvalidDecl = true; 17158 } 17159 } 17160 } 17161 17162 // C++11 [class.union]p8 (DR1460): 17163 // At most one variant member of a union may have a 17164 // brace-or-equal-initializer. 17165 if (InitStyle != ICIS_NoInit) 17166 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17167 17168 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17169 BitWidth, Mutable, InitStyle); 17170 if (InvalidDecl) 17171 NewFD->setInvalidDecl(); 17172 17173 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17174 Diag(Loc, diag::err_duplicate_member) << II; 17175 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17176 NewFD->setInvalidDecl(); 17177 } 17178 17179 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17180 if (Record->isUnion()) { 17181 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17182 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17183 if (RDecl->getDefinition()) { 17184 // C++ [class.union]p1: An object of a class with a non-trivial 17185 // constructor, a non-trivial copy constructor, a non-trivial 17186 // destructor, or a non-trivial copy assignment operator 17187 // cannot be a member of a union, nor can an array of such 17188 // objects. 17189 if (CheckNontrivialField(NewFD)) 17190 NewFD->setInvalidDecl(); 17191 } 17192 } 17193 17194 // C++ [class.union]p1: If a union contains a member of reference type, 17195 // the program is ill-formed, except when compiling with MSVC extensions 17196 // enabled. 17197 if (EltTy->isReferenceType()) { 17198 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17199 diag::ext_union_member_of_reference_type : 17200 diag::err_union_member_of_reference_type) 17201 << NewFD->getDeclName() << EltTy; 17202 if (!getLangOpts().MicrosoftExt) 17203 NewFD->setInvalidDecl(); 17204 } 17205 } 17206 } 17207 17208 // FIXME: We need to pass in the attributes given an AST 17209 // representation, not a parser representation. 17210 if (D) { 17211 // FIXME: The current scope is almost... but not entirely... correct here. 17212 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17213 17214 if (NewFD->hasAttrs()) 17215 CheckAlignasUnderalignment(NewFD); 17216 } 17217 17218 // In auto-retain/release, infer strong retension for fields of 17219 // retainable type. 17220 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17221 NewFD->setInvalidDecl(); 17222 17223 if (T.isObjCGCWeak()) 17224 Diag(Loc, diag::warn_attribute_weak_on_field); 17225 17226 // PPC MMA non-pointer types are not allowed as field types. 17227 if (Context.getTargetInfo().getTriple().isPPC64() && 17228 CheckPPCMMAType(T, NewFD->getLocation())) 17229 NewFD->setInvalidDecl(); 17230 17231 NewFD->setAccess(AS); 17232 return NewFD; 17233 } 17234 17235 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17236 assert(FD); 17237 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17238 17239 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17240 return false; 17241 17242 QualType EltTy = Context.getBaseElementType(FD->getType()); 17243 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17244 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17245 if (RDecl->getDefinition()) { 17246 // We check for copy constructors before constructors 17247 // because otherwise we'll never get complaints about 17248 // copy constructors. 17249 17250 CXXSpecialMember member = CXXInvalid; 17251 // We're required to check for any non-trivial constructors. Since the 17252 // implicit default constructor is suppressed if there are any 17253 // user-declared constructors, we just need to check that there is a 17254 // trivial default constructor and a trivial copy constructor. (We don't 17255 // worry about move constructors here, since this is a C++98 check.) 17256 if (RDecl->hasNonTrivialCopyConstructor()) 17257 member = CXXCopyConstructor; 17258 else if (!RDecl->hasTrivialDefaultConstructor()) 17259 member = CXXDefaultConstructor; 17260 else if (RDecl->hasNonTrivialCopyAssignment()) 17261 member = CXXCopyAssignment; 17262 else if (RDecl->hasNonTrivialDestructor()) 17263 member = CXXDestructor; 17264 17265 if (member != CXXInvalid) { 17266 if (!getLangOpts().CPlusPlus11 && 17267 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17268 // Objective-C++ ARC: it is an error to have a non-trivial field of 17269 // a union. However, system headers in Objective-C programs 17270 // occasionally have Objective-C lifetime objects within unions, 17271 // and rather than cause the program to fail, we make those 17272 // members unavailable. 17273 SourceLocation Loc = FD->getLocation(); 17274 if (getSourceManager().isInSystemHeader(Loc)) { 17275 if (!FD->hasAttr<UnavailableAttr>()) 17276 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17277 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17278 return false; 17279 } 17280 } 17281 17282 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17283 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17284 diag::err_illegal_union_or_anon_struct_member) 17285 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17286 DiagnoseNontrivial(RDecl, member); 17287 return !getLangOpts().CPlusPlus11; 17288 } 17289 } 17290 } 17291 17292 return false; 17293 } 17294 17295 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17296 /// AST enum value. 17297 static ObjCIvarDecl::AccessControl 17298 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17299 switch (ivarVisibility) { 17300 default: llvm_unreachable("Unknown visitibility kind"); 17301 case tok::objc_private: return ObjCIvarDecl::Private; 17302 case tok::objc_public: return ObjCIvarDecl::Public; 17303 case tok::objc_protected: return ObjCIvarDecl::Protected; 17304 case tok::objc_package: return ObjCIvarDecl::Package; 17305 } 17306 } 17307 17308 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17309 /// in order to create an IvarDecl object for it. 17310 Decl *Sema::ActOnIvar(Scope *S, 17311 SourceLocation DeclStart, 17312 Declarator &D, Expr *BitfieldWidth, 17313 tok::ObjCKeywordKind Visibility) { 17314 17315 IdentifierInfo *II = D.getIdentifier(); 17316 Expr *BitWidth = (Expr*)BitfieldWidth; 17317 SourceLocation Loc = DeclStart; 17318 if (II) Loc = D.getIdentifierLoc(); 17319 17320 // FIXME: Unnamed fields can be handled in various different ways, for 17321 // example, unnamed unions inject all members into the struct namespace! 17322 17323 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17324 QualType T = TInfo->getType(); 17325 17326 if (BitWidth) { 17327 // 6.7.2.1p3, 6.7.2.1p4 17328 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17329 if (!BitWidth) 17330 D.setInvalidType(); 17331 } else { 17332 // Not a bitfield. 17333 17334 // validate II. 17335 17336 } 17337 if (T->isReferenceType()) { 17338 Diag(Loc, diag::err_ivar_reference_type); 17339 D.setInvalidType(); 17340 } 17341 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17342 // than a variably modified type. 17343 else if (T->isVariablyModifiedType()) { 17344 if (!tryToFixVariablyModifiedVarType( 17345 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17346 D.setInvalidType(); 17347 } 17348 17349 // Get the visibility (access control) for this ivar. 17350 ObjCIvarDecl::AccessControl ac = 17351 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17352 : ObjCIvarDecl::None; 17353 // Must set ivar's DeclContext to its enclosing interface. 17354 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17355 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17356 return nullptr; 17357 ObjCContainerDecl *EnclosingContext; 17358 if (ObjCImplementationDecl *IMPDecl = 17359 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17360 if (LangOpts.ObjCRuntime.isFragile()) { 17361 // Case of ivar declared in an implementation. Context is that of its class. 17362 EnclosingContext = IMPDecl->getClassInterface(); 17363 assert(EnclosingContext && "Implementation has no class interface!"); 17364 } 17365 else 17366 EnclosingContext = EnclosingDecl; 17367 } else { 17368 if (ObjCCategoryDecl *CDecl = 17369 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17370 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17371 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17372 return nullptr; 17373 } 17374 } 17375 EnclosingContext = EnclosingDecl; 17376 } 17377 17378 // Construct the decl. 17379 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17380 DeclStart, Loc, II, T, 17381 TInfo, ac, (Expr *)BitfieldWidth); 17382 17383 if (II) { 17384 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17385 ForVisibleRedeclaration); 17386 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17387 && !isa<TagDecl>(PrevDecl)) { 17388 Diag(Loc, diag::err_duplicate_member) << II; 17389 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17390 NewID->setInvalidDecl(); 17391 } 17392 } 17393 17394 // Process attributes attached to the ivar. 17395 ProcessDeclAttributes(S, NewID, D); 17396 17397 if (D.isInvalidType()) 17398 NewID->setInvalidDecl(); 17399 17400 // In ARC, infer 'retaining' for ivars of retainable type. 17401 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17402 NewID->setInvalidDecl(); 17403 17404 if (D.getDeclSpec().isModulePrivateSpecified()) 17405 NewID->setModulePrivate(); 17406 17407 if (II) { 17408 // FIXME: When interfaces are DeclContexts, we'll need to add 17409 // these to the interface. 17410 S->AddDecl(NewID); 17411 IdResolver.AddDecl(NewID); 17412 } 17413 17414 if (LangOpts.ObjCRuntime.isNonFragile() && 17415 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17416 Diag(Loc, diag::warn_ivars_in_interface); 17417 17418 return NewID; 17419 } 17420 17421 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17422 /// class and class extensions. For every class \@interface and class 17423 /// extension \@interface, if the last ivar is a bitfield of any type, 17424 /// then add an implicit `char :0` ivar to the end of that interface. 17425 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17426 SmallVectorImpl<Decl *> &AllIvarDecls) { 17427 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17428 return; 17429 17430 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17431 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17432 17433 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17434 return; 17435 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17436 if (!ID) { 17437 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17438 if (!CD->IsClassExtension()) 17439 return; 17440 } 17441 // No need to add this to end of @implementation. 17442 else 17443 return; 17444 } 17445 // All conditions are met. Add a new bitfield to the tail end of ivars. 17446 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17447 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17448 17449 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17450 DeclLoc, DeclLoc, nullptr, 17451 Context.CharTy, 17452 Context.getTrivialTypeSourceInfo(Context.CharTy, 17453 DeclLoc), 17454 ObjCIvarDecl::Private, BW, 17455 true); 17456 AllIvarDecls.push_back(Ivar); 17457 } 17458 17459 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17460 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17461 SourceLocation RBrac, 17462 const ParsedAttributesView &Attrs) { 17463 assert(EnclosingDecl && "missing record or interface decl"); 17464 17465 // If this is an Objective-C @implementation or category and we have 17466 // new fields here we should reset the layout of the interface since 17467 // it will now change. 17468 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17469 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17470 switch (DC->getKind()) { 17471 default: break; 17472 case Decl::ObjCCategory: 17473 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17474 break; 17475 case Decl::ObjCImplementation: 17476 Context. 17477 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17478 break; 17479 } 17480 } 17481 17482 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17483 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17484 17485 // Start counting up the number of named members; make sure to include 17486 // members of anonymous structs and unions in the total. 17487 unsigned NumNamedMembers = 0; 17488 if (Record) { 17489 for (const auto *I : Record->decls()) { 17490 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17491 if (IFD->getDeclName()) 17492 ++NumNamedMembers; 17493 } 17494 } 17495 17496 // Verify that all the fields are okay. 17497 SmallVector<FieldDecl*, 32> RecFields; 17498 17499 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17500 i != end; ++i) { 17501 FieldDecl *FD = cast<FieldDecl>(*i); 17502 17503 // Get the type for the field. 17504 const Type *FDTy = FD->getType().getTypePtr(); 17505 17506 if (!FD->isAnonymousStructOrUnion()) { 17507 // Remember all fields written by the user. 17508 RecFields.push_back(FD); 17509 } 17510 17511 // If the field is already invalid for some reason, don't emit more 17512 // diagnostics about it. 17513 if (FD->isInvalidDecl()) { 17514 EnclosingDecl->setInvalidDecl(); 17515 continue; 17516 } 17517 17518 // C99 6.7.2.1p2: 17519 // A structure or union shall not contain a member with 17520 // incomplete or function type (hence, a structure shall not 17521 // contain an instance of itself, but may contain a pointer to 17522 // an instance of itself), except that the last member of a 17523 // structure with more than one named member may have incomplete 17524 // array type; such a structure (and any union containing, 17525 // possibly recursively, a member that is such a structure) 17526 // shall not be a member of a structure or an element of an 17527 // array. 17528 bool IsLastField = (i + 1 == Fields.end()); 17529 if (FDTy->isFunctionType()) { 17530 // Field declared as a function. 17531 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17532 << FD->getDeclName(); 17533 FD->setInvalidDecl(); 17534 EnclosingDecl->setInvalidDecl(); 17535 continue; 17536 } else if (FDTy->isIncompleteArrayType() && 17537 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17538 if (Record) { 17539 // Flexible array member. 17540 // Microsoft and g++ is more permissive regarding flexible array. 17541 // It will accept flexible array in union and also 17542 // as the sole element of a struct/class. 17543 unsigned DiagID = 0; 17544 if (!Record->isUnion() && !IsLastField) { 17545 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17546 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17547 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17548 FD->setInvalidDecl(); 17549 EnclosingDecl->setInvalidDecl(); 17550 continue; 17551 } else if (Record->isUnion()) 17552 DiagID = getLangOpts().MicrosoftExt 17553 ? diag::ext_flexible_array_union_ms 17554 : getLangOpts().CPlusPlus 17555 ? diag::ext_flexible_array_union_gnu 17556 : diag::err_flexible_array_union; 17557 else if (NumNamedMembers < 1) 17558 DiagID = getLangOpts().MicrosoftExt 17559 ? diag::ext_flexible_array_empty_aggregate_ms 17560 : getLangOpts().CPlusPlus 17561 ? diag::ext_flexible_array_empty_aggregate_gnu 17562 : diag::err_flexible_array_empty_aggregate; 17563 17564 if (DiagID) 17565 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17566 << Record->getTagKind(); 17567 // While the layout of types that contain virtual bases is not specified 17568 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17569 // virtual bases after the derived members. This would make a flexible 17570 // array member declared at the end of an object not adjacent to the end 17571 // of the type. 17572 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17573 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17574 << FD->getDeclName() << Record->getTagKind(); 17575 if (!getLangOpts().C99) 17576 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17577 << FD->getDeclName() << Record->getTagKind(); 17578 17579 // If the element type has a non-trivial destructor, we would not 17580 // implicitly destroy the elements, so disallow it for now. 17581 // 17582 // FIXME: GCC allows this. We should probably either implicitly delete 17583 // the destructor of the containing class, or just allow this. 17584 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17585 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17586 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17587 << FD->getDeclName() << FD->getType(); 17588 FD->setInvalidDecl(); 17589 EnclosingDecl->setInvalidDecl(); 17590 continue; 17591 } 17592 // Okay, we have a legal flexible array member at the end of the struct. 17593 Record->setHasFlexibleArrayMember(true); 17594 } else { 17595 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17596 // unless they are followed by another ivar. That check is done 17597 // elsewhere, after synthesized ivars are known. 17598 } 17599 } else if (!FDTy->isDependentType() && 17600 RequireCompleteSizedType( 17601 FD->getLocation(), FD->getType(), 17602 diag::err_field_incomplete_or_sizeless)) { 17603 // Incomplete type 17604 FD->setInvalidDecl(); 17605 EnclosingDecl->setInvalidDecl(); 17606 continue; 17607 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17608 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17609 // A type which contains a flexible array member is considered to be a 17610 // flexible array member. 17611 Record->setHasFlexibleArrayMember(true); 17612 if (!Record->isUnion()) { 17613 // If this is a struct/class and this is not the last element, reject 17614 // it. Note that GCC supports variable sized arrays in the middle of 17615 // structures. 17616 if (!IsLastField) 17617 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17618 << FD->getDeclName() << FD->getType(); 17619 else { 17620 // We support flexible arrays at the end of structs in 17621 // other structs as an extension. 17622 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17623 << FD->getDeclName(); 17624 } 17625 } 17626 } 17627 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17628 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17629 diag::err_abstract_type_in_decl, 17630 AbstractIvarType)) { 17631 // Ivars can not have abstract class types 17632 FD->setInvalidDecl(); 17633 } 17634 if (Record && FDTTy->getDecl()->hasObjectMember()) 17635 Record->setHasObjectMember(true); 17636 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17637 Record->setHasVolatileMember(true); 17638 } else if (FDTy->isObjCObjectType()) { 17639 /// A field cannot be an Objective-c object 17640 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17641 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17642 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17643 FD->setType(T); 17644 } else if (Record && Record->isUnion() && 17645 FD->getType().hasNonTrivialObjCLifetime() && 17646 getSourceManager().isInSystemHeader(FD->getLocation()) && 17647 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17648 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17649 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17650 // For backward compatibility, fields of C unions declared in system 17651 // headers that have non-trivial ObjC ownership qualifications are marked 17652 // as unavailable unless the qualifier is explicit and __strong. This can 17653 // break ABI compatibility between programs compiled with ARC and MRR, but 17654 // is a better option than rejecting programs using those unions under 17655 // ARC. 17656 FD->addAttr(UnavailableAttr::CreateImplicit( 17657 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17658 FD->getLocation())); 17659 } else if (getLangOpts().ObjC && 17660 getLangOpts().getGC() != LangOptions::NonGC && Record && 17661 !Record->hasObjectMember()) { 17662 if (FD->getType()->isObjCObjectPointerType() || 17663 FD->getType().isObjCGCStrong()) 17664 Record->setHasObjectMember(true); 17665 else if (Context.getAsArrayType(FD->getType())) { 17666 QualType BaseType = Context.getBaseElementType(FD->getType()); 17667 if (BaseType->isRecordType() && 17668 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17669 Record->setHasObjectMember(true); 17670 else if (BaseType->isObjCObjectPointerType() || 17671 BaseType.isObjCGCStrong()) 17672 Record->setHasObjectMember(true); 17673 } 17674 } 17675 17676 if (Record && !getLangOpts().CPlusPlus && 17677 !shouldIgnoreForRecordTriviality(FD)) { 17678 QualType FT = FD->getType(); 17679 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17680 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17681 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17682 Record->isUnion()) 17683 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17684 } 17685 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17686 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17687 Record->setNonTrivialToPrimitiveCopy(true); 17688 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17689 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17690 } 17691 if (FT.isDestructedType()) { 17692 Record->setNonTrivialToPrimitiveDestroy(true); 17693 Record->setParamDestroyedInCallee(true); 17694 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17695 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17696 } 17697 17698 if (const auto *RT = FT->getAs<RecordType>()) { 17699 if (RT->getDecl()->getArgPassingRestrictions() == 17700 RecordDecl::APK_CanNeverPassInRegs) 17701 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17702 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17703 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17704 } 17705 17706 if (Record && FD->getType().isVolatileQualified()) 17707 Record->setHasVolatileMember(true); 17708 // Keep track of the number of named members. 17709 if (FD->getIdentifier()) 17710 ++NumNamedMembers; 17711 } 17712 17713 // Okay, we successfully defined 'Record'. 17714 if (Record) { 17715 bool Completed = false; 17716 if (CXXRecord) { 17717 if (!CXXRecord->isInvalidDecl()) { 17718 // Set access bits correctly on the directly-declared conversions. 17719 for (CXXRecordDecl::conversion_iterator 17720 I = CXXRecord->conversion_begin(), 17721 E = CXXRecord->conversion_end(); I != E; ++I) 17722 I.setAccess((*I)->getAccess()); 17723 } 17724 17725 // Add any implicitly-declared members to this class. 17726 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17727 17728 if (!CXXRecord->isDependentType()) { 17729 if (!CXXRecord->isInvalidDecl()) { 17730 // If we have virtual base classes, we may end up finding multiple 17731 // final overriders for a given virtual function. Check for this 17732 // problem now. 17733 if (CXXRecord->getNumVBases()) { 17734 CXXFinalOverriderMap FinalOverriders; 17735 CXXRecord->getFinalOverriders(FinalOverriders); 17736 17737 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17738 MEnd = FinalOverriders.end(); 17739 M != MEnd; ++M) { 17740 for (OverridingMethods::iterator SO = M->second.begin(), 17741 SOEnd = M->second.end(); 17742 SO != SOEnd; ++SO) { 17743 assert(SO->second.size() > 0 && 17744 "Virtual function without overriding functions?"); 17745 if (SO->second.size() == 1) 17746 continue; 17747 17748 // C++ [class.virtual]p2: 17749 // In a derived class, if a virtual member function of a base 17750 // class subobject has more than one final overrider the 17751 // program is ill-formed. 17752 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17753 << (const NamedDecl *)M->first << Record; 17754 Diag(M->first->getLocation(), 17755 diag::note_overridden_virtual_function); 17756 for (OverridingMethods::overriding_iterator 17757 OM = SO->second.begin(), 17758 OMEnd = SO->second.end(); 17759 OM != OMEnd; ++OM) 17760 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17761 << (const NamedDecl *)M->first << OM->Method->getParent(); 17762 17763 Record->setInvalidDecl(); 17764 } 17765 } 17766 CXXRecord->completeDefinition(&FinalOverriders); 17767 Completed = true; 17768 } 17769 } 17770 } 17771 } 17772 17773 if (!Completed) 17774 Record->completeDefinition(); 17775 17776 // Handle attributes before checking the layout. 17777 ProcessDeclAttributeList(S, Record, Attrs); 17778 17779 // We may have deferred checking for a deleted destructor. Check now. 17780 if (CXXRecord) { 17781 auto *Dtor = CXXRecord->getDestructor(); 17782 if (Dtor && Dtor->isImplicit() && 17783 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17784 CXXRecord->setImplicitDestructorIsDeleted(); 17785 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17786 } 17787 } 17788 17789 if (Record->hasAttrs()) { 17790 CheckAlignasUnderalignment(Record); 17791 17792 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17793 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17794 IA->getRange(), IA->getBestCase(), 17795 IA->getInheritanceModel()); 17796 } 17797 17798 // Check if the structure/union declaration is a type that can have zero 17799 // size in C. For C this is a language extension, for C++ it may cause 17800 // compatibility problems. 17801 bool CheckForZeroSize; 17802 if (!getLangOpts().CPlusPlus) { 17803 CheckForZeroSize = true; 17804 } else { 17805 // For C++ filter out types that cannot be referenced in C code. 17806 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17807 CheckForZeroSize = 17808 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17809 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17810 CXXRecord->isCLike(); 17811 } 17812 if (CheckForZeroSize) { 17813 bool ZeroSize = true; 17814 bool IsEmpty = true; 17815 unsigned NonBitFields = 0; 17816 for (RecordDecl::field_iterator I = Record->field_begin(), 17817 E = Record->field_end(); 17818 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17819 IsEmpty = false; 17820 if (I->isUnnamedBitfield()) { 17821 if (!I->isZeroLengthBitField(Context)) 17822 ZeroSize = false; 17823 } else { 17824 ++NonBitFields; 17825 QualType FieldType = I->getType(); 17826 if (FieldType->isIncompleteType() || 17827 !Context.getTypeSizeInChars(FieldType).isZero()) 17828 ZeroSize = false; 17829 } 17830 } 17831 17832 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17833 // allowed in C++, but warn if its declaration is inside 17834 // extern "C" block. 17835 if (ZeroSize) { 17836 Diag(RecLoc, getLangOpts().CPlusPlus ? 17837 diag::warn_zero_size_struct_union_in_extern_c : 17838 diag::warn_zero_size_struct_union_compat) 17839 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17840 } 17841 17842 // Structs without named members are extension in C (C99 6.7.2.1p7), 17843 // but are accepted by GCC. 17844 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17845 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17846 diag::ext_no_named_members_in_struct_union) 17847 << Record->isUnion(); 17848 } 17849 } 17850 } else { 17851 ObjCIvarDecl **ClsFields = 17852 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17853 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17854 ID->setEndOfDefinitionLoc(RBrac); 17855 // Add ivar's to class's DeclContext. 17856 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17857 ClsFields[i]->setLexicalDeclContext(ID); 17858 ID->addDecl(ClsFields[i]); 17859 } 17860 // Must enforce the rule that ivars in the base classes may not be 17861 // duplicates. 17862 if (ID->getSuperClass()) 17863 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17864 } else if (ObjCImplementationDecl *IMPDecl = 17865 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17866 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17867 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17868 // Ivar declared in @implementation never belongs to the implementation. 17869 // Only it is in implementation's lexical context. 17870 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17871 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17872 IMPDecl->setIvarLBraceLoc(LBrac); 17873 IMPDecl->setIvarRBraceLoc(RBrac); 17874 } else if (ObjCCategoryDecl *CDecl = 17875 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17876 // case of ivars in class extension; all other cases have been 17877 // reported as errors elsewhere. 17878 // FIXME. Class extension does not have a LocEnd field. 17879 // CDecl->setLocEnd(RBrac); 17880 // Add ivar's to class extension's DeclContext. 17881 // Diagnose redeclaration of private ivars. 17882 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17883 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17884 if (IDecl) { 17885 if (const ObjCIvarDecl *ClsIvar = 17886 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17887 Diag(ClsFields[i]->getLocation(), 17888 diag::err_duplicate_ivar_declaration); 17889 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17890 continue; 17891 } 17892 for (const auto *Ext : IDecl->known_extensions()) { 17893 if (const ObjCIvarDecl *ClsExtIvar 17894 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17895 Diag(ClsFields[i]->getLocation(), 17896 diag::err_duplicate_ivar_declaration); 17897 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17898 continue; 17899 } 17900 } 17901 } 17902 ClsFields[i]->setLexicalDeclContext(CDecl); 17903 CDecl->addDecl(ClsFields[i]); 17904 } 17905 CDecl->setIvarLBraceLoc(LBrac); 17906 CDecl->setIvarRBraceLoc(RBrac); 17907 } 17908 } 17909 } 17910 17911 /// Determine whether the given integral value is representable within 17912 /// the given type T. 17913 static bool isRepresentableIntegerValue(ASTContext &Context, 17914 llvm::APSInt &Value, 17915 QualType T) { 17916 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17917 "Integral type required!"); 17918 unsigned BitWidth = Context.getIntWidth(T); 17919 17920 if (Value.isUnsigned() || Value.isNonNegative()) { 17921 if (T->isSignedIntegerOrEnumerationType()) 17922 --BitWidth; 17923 return Value.getActiveBits() <= BitWidth; 17924 } 17925 return Value.getMinSignedBits() <= BitWidth; 17926 } 17927 17928 // Given an integral type, return the next larger integral type 17929 // (or a NULL type of no such type exists). 17930 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17931 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17932 // enum checking below. 17933 assert((T->isIntegralType(Context) || 17934 T->isEnumeralType()) && "Integral type required!"); 17935 const unsigned NumTypes = 4; 17936 QualType SignedIntegralTypes[NumTypes] = { 17937 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17938 }; 17939 QualType UnsignedIntegralTypes[NumTypes] = { 17940 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17941 Context.UnsignedLongLongTy 17942 }; 17943 17944 unsigned BitWidth = Context.getTypeSize(T); 17945 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17946 : UnsignedIntegralTypes; 17947 for (unsigned I = 0; I != NumTypes; ++I) 17948 if (Context.getTypeSize(Types[I]) > BitWidth) 17949 return Types[I]; 17950 17951 return QualType(); 17952 } 17953 17954 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17955 EnumConstantDecl *LastEnumConst, 17956 SourceLocation IdLoc, 17957 IdentifierInfo *Id, 17958 Expr *Val) { 17959 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17960 llvm::APSInt EnumVal(IntWidth); 17961 QualType EltTy; 17962 17963 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17964 Val = nullptr; 17965 17966 if (Val) 17967 Val = DefaultLvalueConversion(Val).get(); 17968 17969 if (Val) { 17970 if (Enum->isDependentType() || Val->isTypeDependent() || 17971 Val->containsErrors()) 17972 EltTy = Context.DependentTy; 17973 else { 17974 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17975 // underlying type, but do allow it in all other contexts. 17976 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17977 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17978 // constant-expression in the enumerator-definition shall be a converted 17979 // constant expression of the underlying type. 17980 EltTy = Enum->getIntegerType(); 17981 ExprResult Converted = 17982 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17983 CCEK_Enumerator); 17984 if (Converted.isInvalid()) 17985 Val = nullptr; 17986 else 17987 Val = Converted.get(); 17988 } else if (!Val->isValueDependent() && 17989 !(Val = 17990 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17991 .get())) { 17992 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17993 } else { 17994 if (Enum->isComplete()) { 17995 EltTy = Enum->getIntegerType(); 17996 17997 // In Obj-C and Microsoft mode, require the enumeration value to be 17998 // representable in the underlying type of the enumeration. In C++11, 17999 // we perform a non-narrowing conversion as part of converted constant 18000 // expression checking. 18001 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18002 if (Context.getTargetInfo() 18003 .getTriple() 18004 .isWindowsMSVCEnvironment()) { 18005 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 18006 } else { 18007 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 18008 } 18009 } 18010 18011 // Cast to the underlying type. 18012 Val = ImpCastExprToType(Val, EltTy, 18013 EltTy->isBooleanType() ? CK_IntegralToBoolean 18014 : CK_IntegralCast) 18015 .get(); 18016 } else if (getLangOpts().CPlusPlus) { 18017 // C++11 [dcl.enum]p5: 18018 // If the underlying type is not fixed, the type of each enumerator 18019 // is the type of its initializing value: 18020 // - If an initializer is specified for an enumerator, the 18021 // initializing value has the same type as the expression. 18022 EltTy = Val->getType(); 18023 } else { 18024 // C99 6.7.2.2p2: 18025 // The expression that defines the value of an enumeration constant 18026 // shall be an integer constant expression that has a value 18027 // representable as an int. 18028 18029 // Complain if the value is not representable in an int. 18030 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 18031 Diag(IdLoc, diag::ext_enum_value_not_int) 18032 << toString(EnumVal, 10) << Val->getSourceRange() 18033 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 18034 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 18035 // Force the type of the expression to 'int'. 18036 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 18037 } 18038 EltTy = Val->getType(); 18039 } 18040 } 18041 } 18042 } 18043 18044 if (!Val) { 18045 if (Enum->isDependentType()) 18046 EltTy = Context.DependentTy; 18047 else if (!LastEnumConst) { 18048 // C++0x [dcl.enum]p5: 18049 // If the underlying type is not fixed, the type of each enumerator 18050 // is the type of its initializing value: 18051 // - If no initializer is specified for the first enumerator, the 18052 // initializing value has an unspecified integral type. 18053 // 18054 // GCC uses 'int' for its unspecified integral type, as does 18055 // C99 6.7.2.2p3. 18056 if (Enum->isFixed()) { 18057 EltTy = Enum->getIntegerType(); 18058 } 18059 else { 18060 EltTy = Context.IntTy; 18061 } 18062 } else { 18063 // Assign the last value + 1. 18064 EnumVal = LastEnumConst->getInitVal(); 18065 ++EnumVal; 18066 EltTy = LastEnumConst->getType(); 18067 18068 // Check for overflow on increment. 18069 if (EnumVal < LastEnumConst->getInitVal()) { 18070 // C++0x [dcl.enum]p5: 18071 // If the underlying type is not fixed, the type of each enumerator 18072 // is the type of its initializing value: 18073 // 18074 // - Otherwise the type of the initializing value is the same as 18075 // the type of the initializing value of the preceding enumerator 18076 // unless the incremented value is not representable in that type, 18077 // in which case the type is an unspecified integral type 18078 // sufficient to contain the incremented value. If no such type 18079 // exists, the program is ill-formed. 18080 QualType T = getNextLargerIntegralType(Context, EltTy); 18081 if (T.isNull() || Enum->isFixed()) { 18082 // There is no integral type larger enough to represent this 18083 // value. Complain, then allow the value to wrap around. 18084 EnumVal = LastEnumConst->getInitVal(); 18085 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 18086 ++EnumVal; 18087 if (Enum->isFixed()) 18088 // When the underlying type is fixed, this is ill-formed. 18089 Diag(IdLoc, diag::err_enumerator_wrapped) 18090 << toString(EnumVal, 10) 18091 << EltTy; 18092 else 18093 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 18094 << toString(EnumVal, 10); 18095 } else { 18096 EltTy = T; 18097 } 18098 18099 // Retrieve the last enumerator's value, extent that type to the 18100 // type that is supposed to be large enough to represent the incremented 18101 // value, then increment. 18102 EnumVal = LastEnumConst->getInitVal(); 18103 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18104 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 18105 ++EnumVal; 18106 18107 // If we're not in C++, diagnose the overflow of enumerator values, 18108 // which in C99 means that the enumerator value is not representable in 18109 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 18110 // permits enumerator values that are representable in some larger 18111 // integral type. 18112 if (!getLangOpts().CPlusPlus && !T.isNull()) 18113 Diag(IdLoc, diag::warn_enum_value_overflow); 18114 } else if (!getLangOpts().CPlusPlus && 18115 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18116 // Enforce C99 6.7.2.2p2 even when we compute the next value. 18117 Diag(IdLoc, diag::ext_enum_value_not_int) 18118 << toString(EnumVal, 10) << 1; 18119 } 18120 } 18121 } 18122 18123 if (!EltTy->isDependentType()) { 18124 // Make the enumerator value match the signedness and size of the 18125 // enumerator's type. 18126 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 18127 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18128 } 18129 18130 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 18131 Val, EnumVal); 18132 } 18133 18134 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 18135 SourceLocation IILoc) { 18136 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 18137 !getLangOpts().CPlusPlus) 18138 return SkipBodyInfo(); 18139 18140 // We have an anonymous enum definition. Look up the first enumerator to 18141 // determine if we should merge the definition with an existing one and 18142 // skip the body. 18143 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 18144 forRedeclarationInCurContext()); 18145 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 18146 if (!PrevECD) 18147 return SkipBodyInfo(); 18148 18149 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18150 NamedDecl *Hidden; 18151 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18152 SkipBodyInfo Skip; 18153 Skip.Previous = Hidden; 18154 return Skip; 18155 } 18156 18157 return SkipBodyInfo(); 18158 } 18159 18160 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18161 SourceLocation IdLoc, IdentifierInfo *Id, 18162 const ParsedAttributesView &Attrs, 18163 SourceLocation EqualLoc, Expr *Val) { 18164 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18165 EnumConstantDecl *LastEnumConst = 18166 cast_or_null<EnumConstantDecl>(lastEnumConst); 18167 18168 // The scope passed in may not be a decl scope. Zip up the scope tree until 18169 // we find one that is. 18170 S = getNonFieldDeclScope(S); 18171 18172 // Verify that there isn't already something declared with this name in this 18173 // scope. 18174 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18175 LookupName(R, S); 18176 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18177 18178 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18179 // Maybe we will complain about the shadowed template parameter. 18180 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18181 // Just pretend that we didn't see the previous declaration. 18182 PrevDecl = nullptr; 18183 } 18184 18185 // C++ [class.mem]p15: 18186 // If T is the name of a class, then each of the following shall have a name 18187 // different from T: 18188 // - every enumerator of every member of class T that is an unscoped 18189 // enumerated type 18190 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18191 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18192 DeclarationNameInfo(Id, IdLoc)); 18193 18194 EnumConstantDecl *New = 18195 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18196 if (!New) 18197 return nullptr; 18198 18199 if (PrevDecl) { 18200 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18201 // Check for other kinds of shadowing not already handled. 18202 CheckShadow(New, PrevDecl, R); 18203 } 18204 18205 // When in C++, we may get a TagDecl with the same name; in this case the 18206 // enum constant will 'hide' the tag. 18207 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18208 "Received TagDecl when not in C++!"); 18209 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18210 if (isa<EnumConstantDecl>(PrevDecl)) 18211 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18212 else 18213 Diag(IdLoc, diag::err_redefinition) << Id; 18214 notePreviousDefinition(PrevDecl, IdLoc); 18215 return nullptr; 18216 } 18217 } 18218 18219 // Process attributes. 18220 ProcessDeclAttributeList(S, New, Attrs); 18221 AddPragmaAttributes(S, New); 18222 18223 // Register this decl in the current scope stack. 18224 New->setAccess(TheEnumDecl->getAccess()); 18225 PushOnScopeChains(New, S); 18226 18227 ActOnDocumentableDecl(New); 18228 18229 return New; 18230 } 18231 18232 // Returns true when the enum initial expression does not trigger the 18233 // duplicate enum warning. A few common cases are exempted as follows: 18234 // Element2 = Element1 18235 // Element2 = Element1 + 1 18236 // Element2 = Element1 - 1 18237 // Where Element2 and Element1 are from the same enum. 18238 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18239 Expr *InitExpr = ECD->getInitExpr(); 18240 if (!InitExpr) 18241 return true; 18242 InitExpr = InitExpr->IgnoreImpCasts(); 18243 18244 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18245 if (!BO->isAdditiveOp()) 18246 return true; 18247 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18248 if (!IL) 18249 return true; 18250 if (IL->getValue() != 1) 18251 return true; 18252 18253 InitExpr = BO->getLHS(); 18254 } 18255 18256 // This checks if the elements are from the same enum. 18257 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18258 if (!DRE) 18259 return true; 18260 18261 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18262 if (!EnumConstant) 18263 return true; 18264 18265 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18266 Enum) 18267 return true; 18268 18269 return false; 18270 } 18271 18272 // Emits a warning when an element is implicitly set a value that 18273 // a previous element has already been set to. 18274 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18275 EnumDecl *Enum, QualType EnumType) { 18276 // Avoid anonymous enums 18277 if (!Enum->getIdentifier()) 18278 return; 18279 18280 // Only check for small enums. 18281 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18282 return; 18283 18284 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18285 return; 18286 18287 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18288 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18289 18290 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18291 18292 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18293 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18294 18295 // Use int64_t as a key to avoid needing special handling for map keys. 18296 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18297 llvm::APSInt Val = D->getInitVal(); 18298 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18299 }; 18300 18301 DuplicatesVector DupVector; 18302 ValueToVectorMap EnumMap; 18303 18304 // Populate the EnumMap with all values represented by enum constants without 18305 // an initializer. 18306 for (auto *Element : Elements) { 18307 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18308 18309 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18310 // this constant. Skip this enum since it may be ill-formed. 18311 if (!ECD) { 18312 return; 18313 } 18314 18315 // Constants with initalizers are handled in the next loop. 18316 if (ECD->getInitExpr()) 18317 continue; 18318 18319 // Duplicate values are handled in the next loop. 18320 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18321 } 18322 18323 if (EnumMap.size() == 0) 18324 return; 18325 18326 // Create vectors for any values that has duplicates. 18327 for (auto *Element : Elements) { 18328 // The last loop returned if any constant was null. 18329 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18330 if (!ValidDuplicateEnum(ECD, Enum)) 18331 continue; 18332 18333 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18334 if (Iter == EnumMap.end()) 18335 continue; 18336 18337 DeclOrVector& Entry = Iter->second; 18338 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18339 // Ensure constants are different. 18340 if (D == ECD) 18341 continue; 18342 18343 // Create new vector and push values onto it. 18344 auto Vec = std::make_unique<ECDVector>(); 18345 Vec->push_back(D); 18346 Vec->push_back(ECD); 18347 18348 // Update entry to point to the duplicates vector. 18349 Entry = Vec.get(); 18350 18351 // Store the vector somewhere we can consult later for quick emission of 18352 // diagnostics. 18353 DupVector.emplace_back(std::move(Vec)); 18354 continue; 18355 } 18356 18357 ECDVector *Vec = Entry.get<ECDVector*>(); 18358 // Make sure constants are not added more than once. 18359 if (*Vec->begin() == ECD) 18360 continue; 18361 18362 Vec->push_back(ECD); 18363 } 18364 18365 // Emit diagnostics. 18366 for (const auto &Vec : DupVector) { 18367 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18368 18369 // Emit warning for one enum constant. 18370 auto *FirstECD = Vec->front(); 18371 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18372 << FirstECD << toString(FirstECD->getInitVal(), 10) 18373 << FirstECD->getSourceRange(); 18374 18375 // Emit one note for each of the remaining enum constants with 18376 // the same value. 18377 for (auto *ECD : llvm::drop_begin(*Vec)) 18378 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18379 << ECD << toString(ECD->getInitVal(), 10) 18380 << ECD->getSourceRange(); 18381 } 18382 } 18383 18384 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18385 bool AllowMask) const { 18386 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18387 assert(ED->isCompleteDefinition() && "expected enum definition"); 18388 18389 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18390 llvm::APInt &FlagBits = R.first->second; 18391 18392 if (R.second) { 18393 for (auto *E : ED->enumerators()) { 18394 const auto &EVal = E->getInitVal(); 18395 // Only single-bit enumerators introduce new flag values. 18396 if (EVal.isPowerOf2()) 18397 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18398 } 18399 } 18400 18401 // A value is in a flag enum if either its bits are a subset of the enum's 18402 // flag bits (the first condition) or we are allowing masks and the same is 18403 // true of its complement (the second condition). When masks are allowed, we 18404 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18405 // 18406 // While it's true that any value could be used as a mask, the assumption is 18407 // that a mask will have all of the insignificant bits set. Anything else is 18408 // likely a logic error. 18409 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18410 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18411 } 18412 18413 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18414 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18415 const ParsedAttributesView &Attrs) { 18416 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18417 QualType EnumType = Context.getTypeDeclType(Enum); 18418 18419 ProcessDeclAttributeList(S, Enum, Attrs); 18420 18421 if (Enum->isDependentType()) { 18422 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18423 EnumConstantDecl *ECD = 18424 cast_or_null<EnumConstantDecl>(Elements[i]); 18425 if (!ECD) continue; 18426 18427 ECD->setType(EnumType); 18428 } 18429 18430 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18431 return; 18432 } 18433 18434 // TODO: If the result value doesn't fit in an int, it must be a long or long 18435 // long value. ISO C does not support this, but GCC does as an extension, 18436 // emit a warning. 18437 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18438 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18439 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18440 18441 // Verify that all the values are okay, compute the size of the values, and 18442 // reverse the list. 18443 unsigned NumNegativeBits = 0; 18444 unsigned NumPositiveBits = 0; 18445 18446 // Keep track of whether all elements have type int. 18447 bool AllElementsInt = true; 18448 18449 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18450 EnumConstantDecl *ECD = 18451 cast_or_null<EnumConstantDecl>(Elements[i]); 18452 if (!ECD) continue; // Already issued a diagnostic. 18453 18454 const llvm::APSInt &InitVal = ECD->getInitVal(); 18455 18456 // Keep track of the size of positive and negative values. 18457 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18458 NumPositiveBits = std::max(NumPositiveBits, 18459 (unsigned)InitVal.getActiveBits()); 18460 else 18461 NumNegativeBits = std::max(NumNegativeBits, 18462 (unsigned)InitVal.getMinSignedBits()); 18463 18464 // Keep track of whether every enum element has type int (very common). 18465 if (AllElementsInt) 18466 AllElementsInt = ECD->getType() == Context.IntTy; 18467 } 18468 18469 // Figure out the type that should be used for this enum. 18470 QualType BestType; 18471 unsigned BestWidth; 18472 18473 // C++0x N3000 [conv.prom]p3: 18474 // An rvalue of an unscoped enumeration type whose underlying 18475 // type is not fixed can be converted to an rvalue of the first 18476 // of the following types that can represent all the values of 18477 // the enumeration: int, unsigned int, long int, unsigned long 18478 // int, long long int, or unsigned long long int. 18479 // C99 6.4.4.3p2: 18480 // An identifier declared as an enumeration constant has type int. 18481 // The C99 rule is modified by a gcc extension 18482 QualType BestPromotionType; 18483 18484 bool Packed = Enum->hasAttr<PackedAttr>(); 18485 // -fshort-enums is the equivalent to specifying the packed attribute on all 18486 // enum definitions. 18487 if (LangOpts.ShortEnums) 18488 Packed = true; 18489 18490 // If the enum already has a type because it is fixed or dictated by the 18491 // target, promote that type instead of analyzing the enumerators. 18492 if (Enum->isComplete()) { 18493 BestType = Enum->getIntegerType(); 18494 if (BestType->isPromotableIntegerType()) 18495 BestPromotionType = Context.getPromotedIntegerType(BestType); 18496 else 18497 BestPromotionType = BestType; 18498 18499 BestWidth = Context.getIntWidth(BestType); 18500 } 18501 else if (NumNegativeBits) { 18502 // If there is a negative value, figure out the smallest integer type (of 18503 // int/long/longlong) that fits. 18504 // If it's packed, check also if it fits a char or a short. 18505 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18506 BestType = Context.SignedCharTy; 18507 BestWidth = CharWidth; 18508 } else if (Packed && NumNegativeBits <= ShortWidth && 18509 NumPositiveBits < ShortWidth) { 18510 BestType = Context.ShortTy; 18511 BestWidth = ShortWidth; 18512 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18513 BestType = Context.IntTy; 18514 BestWidth = IntWidth; 18515 } else { 18516 BestWidth = Context.getTargetInfo().getLongWidth(); 18517 18518 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18519 BestType = Context.LongTy; 18520 } else { 18521 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18522 18523 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18524 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18525 BestType = Context.LongLongTy; 18526 } 18527 } 18528 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18529 } else { 18530 // If there is no negative value, figure out the smallest type that fits 18531 // all of the enumerator values. 18532 // If it's packed, check also if it fits a char or a short. 18533 if (Packed && NumPositiveBits <= CharWidth) { 18534 BestType = Context.UnsignedCharTy; 18535 BestPromotionType = Context.IntTy; 18536 BestWidth = CharWidth; 18537 } else if (Packed && NumPositiveBits <= ShortWidth) { 18538 BestType = Context.UnsignedShortTy; 18539 BestPromotionType = Context.IntTy; 18540 BestWidth = ShortWidth; 18541 } else if (NumPositiveBits <= IntWidth) { 18542 BestType = Context.UnsignedIntTy; 18543 BestWidth = IntWidth; 18544 BestPromotionType 18545 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18546 ? Context.UnsignedIntTy : Context.IntTy; 18547 } else if (NumPositiveBits <= 18548 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18549 BestType = Context.UnsignedLongTy; 18550 BestPromotionType 18551 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18552 ? Context.UnsignedLongTy : Context.LongTy; 18553 } else { 18554 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18555 assert(NumPositiveBits <= BestWidth && 18556 "How could an initializer get larger than ULL?"); 18557 BestType = Context.UnsignedLongLongTy; 18558 BestPromotionType 18559 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18560 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18561 } 18562 } 18563 18564 // Loop over all of the enumerator constants, changing their types to match 18565 // the type of the enum if needed. 18566 for (auto *D : Elements) { 18567 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18568 if (!ECD) continue; // Already issued a diagnostic. 18569 18570 // Standard C says the enumerators have int type, but we allow, as an 18571 // extension, the enumerators to be larger than int size. If each 18572 // enumerator value fits in an int, type it as an int, otherwise type it the 18573 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18574 // that X has type 'int', not 'unsigned'. 18575 18576 // Determine whether the value fits into an int. 18577 llvm::APSInt InitVal = ECD->getInitVal(); 18578 18579 // If it fits into an integer type, force it. Otherwise force it to match 18580 // the enum decl type. 18581 QualType NewTy; 18582 unsigned NewWidth; 18583 bool NewSign; 18584 if (!getLangOpts().CPlusPlus && 18585 !Enum->isFixed() && 18586 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18587 NewTy = Context.IntTy; 18588 NewWidth = IntWidth; 18589 NewSign = true; 18590 } else if (ECD->getType() == BestType) { 18591 // Already the right type! 18592 if (getLangOpts().CPlusPlus) 18593 // C++ [dcl.enum]p4: Following the closing brace of an 18594 // enum-specifier, each enumerator has the type of its 18595 // enumeration. 18596 ECD->setType(EnumType); 18597 continue; 18598 } else { 18599 NewTy = BestType; 18600 NewWidth = BestWidth; 18601 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18602 } 18603 18604 // Adjust the APSInt value. 18605 InitVal = InitVal.extOrTrunc(NewWidth); 18606 InitVal.setIsSigned(NewSign); 18607 ECD->setInitVal(InitVal); 18608 18609 // Adjust the Expr initializer and type. 18610 if (ECD->getInitExpr() && 18611 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18612 ECD->setInitExpr(ImplicitCastExpr::Create( 18613 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18614 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18615 if (getLangOpts().CPlusPlus) 18616 // C++ [dcl.enum]p4: Following the closing brace of an 18617 // enum-specifier, each enumerator has the type of its 18618 // enumeration. 18619 ECD->setType(EnumType); 18620 else 18621 ECD->setType(NewTy); 18622 } 18623 18624 Enum->completeDefinition(BestType, BestPromotionType, 18625 NumPositiveBits, NumNegativeBits); 18626 18627 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18628 18629 if (Enum->isClosedFlag()) { 18630 for (Decl *D : Elements) { 18631 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18632 if (!ECD) continue; // Already issued a diagnostic. 18633 18634 llvm::APSInt InitVal = ECD->getInitVal(); 18635 if (InitVal != 0 && !InitVal.isPowerOf2() && 18636 !IsValueInFlagEnum(Enum, InitVal, true)) 18637 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18638 << ECD << Enum; 18639 } 18640 } 18641 18642 // Now that the enum type is defined, ensure it's not been underaligned. 18643 if (Enum->hasAttrs()) 18644 CheckAlignasUnderalignment(Enum); 18645 } 18646 18647 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18648 SourceLocation StartLoc, 18649 SourceLocation EndLoc) { 18650 StringLiteral *AsmString = cast<StringLiteral>(expr); 18651 18652 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18653 AsmString, StartLoc, 18654 EndLoc); 18655 CurContext->addDecl(New); 18656 return New; 18657 } 18658 18659 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18660 IdentifierInfo* AliasName, 18661 SourceLocation PragmaLoc, 18662 SourceLocation NameLoc, 18663 SourceLocation AliasNameLoc) { 18664 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18665 LookupOrdinaryName); 18666 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18667 AttributeCommonInfo::AS_Pragma); 18668 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18669 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 18670 18671 // If a declaration that: 18672 // 1) declares a function or a variable 18673 // 2) has external linkage 18674 // already exists, add a label attribute to it. 18675 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18676 if (isDeclExternC(PrevDecl)) 18677 PrevDecl->addAttr(Attr); 18678 else 18679 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18680 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18681 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18682 } else 18683 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18684 } 18685 18686 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18687 SourceLocation PragmaLoc, 18688 SourceLocation NameLoc) { 18689 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18690 18691 if (PrevDecl) { 18692 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18693 } else { 18694 (void)WeakUndeclaredIdentifiers.insert( 18695 std::pair<IdentifierInfo*,WeakInfo> 18696 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18697 } 18698 } 18699 18700 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18701 IdentifierInfo* AliasName, 18702 SourceLocation PragmaLoc, 18703 SourceLocation NameLoc, 18704 SourceLocation AliasNameLoc) { 18705 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18706 LookupOrdinaryName); 18707 WeakInfo W = WeakInfo(Name, NameLoc); 18708 18709 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18710 if (!PrevDecl->hasAttr<AliasAttr>()) 18711 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18712 DeclApplyPragmaWeak(TUScope, ND, W); 18713 } else { 18714 (void)WeakUndeclaredIdentifiers.insert( 18715 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18716 } 18717 } 18718 18719 Decl *Sema::getObjCDeclContext() const { 18720 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18721 } 18722 18723 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18724 bool Final) { 18725 assert(FD && "Expected non-null FunctionDecl"); 18726 18727 // SYCL functions can be template, so we check if they have appropriate 18728 // attribute prior to checking if it is a template. 18729 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18730 return FunctionEmissionStatus::Emitted; 18731 18732 // Templates are emitted when they're instantiated. 18733 if (FD->isDependentContext()) 18734 return FunctionEmissionStatus::TemplateDiscarded; 18735 18736 // Check whether this function is an externally visible definition. 18737 auto IsEmittedForExternalSymbol = [this, FD]() { 18738 // We have to check the GVA linkage of the function's *definition* -- if we 18739 // only have a declaration, we don't know whether or not the function will 18740 // be emitted, because (say) the definition could include "inline". 18741 FunctionDecl *Def = FD->getDefinition(); 18742 18743 return Def && !isDiscardableGVALinkage( 18744 getASTContext().GetGVALinkageForFunction(Def)); 18745 }; 18746 18747 if (LangOpts.OpenMPIsDevice) { 18748 // In OpenMP device mode we will not emit host only functions, or functions 18749 // we don't need due to their linkage. 18750 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18751 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18752 // DevTy may be changed later by 18753 // #pragma omp declare target to(*) device_type(*). 18754 // Therefore DevTy having no value does not imply host. The emission status 18755 // will be checked again at the end of compilation unit with Final = true. 18756 if (DevTy.hasValue()) 18757 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18758 return FunctionEmissionStatus::OMPDiscarded; 18759 // If we have an explicit value for the device type, or we are in a target 18760 // declare context, we need to emit all extern and used symbols. 18761 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18762 if (IsEmittedForExternalSymbol()) 18763 return FunctionEmissionStatus::Emitted; 18764 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18765 // we'll omit it. 18766 if (Final) 18767 return FunctionEmissionStatus::OMPDiscarded; 18768 } else if (LangOpts.OpenMP > 45) { 18769 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18770 // function. In 5.0, no_host was introduced which might cause a function to 18771 // be ommitted. 18772 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18773 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18774 if (DevTy.hasValue()) 18775 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18776 return FunctionEmissionStatus::OMPDiscarded; 18777 } 18778 18779 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18780 return FunctionEmissionStatus::Emitted; 18781 18782 if (LangOpts.CUDA) { 18783 // When compiling for device, host functions are never emitted. Similarly, 18784 // when compiling for host, device and global functions are never emitted. 18785 // (Technically, we do emit a host-side stub for global functions, but this 18786 // doesn't count for our purposes here.) 18787 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18788 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18789 return FunctionEmissionStatus::CUDADiscarded; 18790 if (!LangOpts.CUDAIsDevice && 18791 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18792 return FunctionEmissionStatus::CUDADiscarded; 18793 18794 if (IsEmittedForExternalSymbol()) 18795 return FunctionEmissionStatus::Emitted; 18796 } 18797 18798 // Otherwise, the function is known-emitted if it's in our set of 18799 // known-emitted functions. 18800 return FunctionEmissionStatus::Unknown; 18801 } 18802 18803 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18804 // Host-side references to a __global__ function refer to the stub, so the 18805 // function itself is never emitted and therefore should not be marked. 18806 // If we have host fn calls kernel fn calls host+device, the HD function 18807 // does not get instantiated on the host. We model this by omitting at the 18808 // call to the kernel from the callgraph. This ensures that, when compiling 18809 // for host, only HD functions actually called from the host get marked as 18810 // known-emitted. 18811 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18812 IdentifyCUDATarget(Callee) == CFT_Global; 18813 } 18814