1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/Randstruct.h" 28 #include "clang/AST/StmtCXX.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 37 #include "clang/Sema/CXXFieldCollector.h" 38 #include "clang/Sema/DeclSpec.h" 39 #include "clang/Sema/DelayedDiagnostic.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaInternal.h" 46 #include "clang/Sema/Template.h" 47 #include "llvm/ADT/SmallString.h" 48 #include "llvm/ADT/Triple.h" 49 #include <algorithm> 50 #include <cstring> 51 #include <functional> 52 #include <unordered_map> 53 54 using namespace clang; 55 using namespace sema; 56 57 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 58 if (OwnedType) { 59 Decl *Group[2] = { OwnedType, Ptr }; 60 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 61 } 62 63 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 64 } 65 66 namespace { 67 68 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 69 public: 70 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 71 bool AllowTemplates = false, 72 bool AllowNonTemplates = true) 73 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 74 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 75 WantExpressionKeywords = false; 76 WantCXXNamedCasts = false; 77 WantRemainingKeywords = false; 78 } 79 80 bool ValidateCandidate(const TypoCorrection &candidate) override { 81 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 82 if (!AllowInvalidDecl && ND->isInvalidDecl()) 83 return false; 84 85 if (getAsTypeTemplateDecl(ND)) 86 return AllowTemplates; 87 88 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 89 if (!IsType) 90 return false; 91 92 if (AllowNonTemplates) 93 return true; 94 95 // An injected-class-name of a class template (specialization) is valid 96 // as a template or as a non-template. 97 if (AllowTemplates) { 98 auto *RD = dyn_cast<CXXRecordDecl>(ND); 99 if (!RD || !RD->isInjectedClassName()) 100 return false; 101 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 102 return RD->getDescribedClassTemplate() || 103 isa<ClassTemplateSpecializationDecl>(RD); 104 } 105 106 return false; 107 } 108 109 return !WantClassName && candidate.isKeyword(); 110 } 111 112 std::unique_ptr<CorrectionCandidateCallback> clone() override { 113 return std::make_unique<TypeNameValidatorCCC>(*this); 114 } 115 116 private: 117 bool AllowInvalidDecl; 118 bool WantClassName; 119 bool AllowTemplates; 120 bool AllowNonTemplates; 121 }; 122 123 } // end anonymous namespace 124 125 /// Determine whether the token kind starts a simple-type-specifier. 126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 127 switch (Kind) { 128 // FIXME: Take into account the current language when deciding whether a 129 // token kind is a valid type specifier 130 case tok::kw_short: 131 case tok::kw_long: 132 case tok::kw___int64: 133 case tok::kw___int128: 134 case tok::kw_signed: 135 case tok::kw_unsigned: 136 case tok::kw_void: 137 case tok::kw_char: 138 case tok::kw_int: 139 case tok::kw_half: 140 case tok::kw_float: 141 case tok::kw_double: 142 case tok::kw___bf16: 143 case tok::kw__Float16: 144 case tok::kw___float128: 145 case tok::kw___ibm128: 146 case tok::kw_wchar_t: 147 case tok::kw_bool: 148 case tok::kw___underlying_type: 149 case tok::kw___auto_type: 150 return true; 151 152 case tok::annot_typename: 153 case tok::kw_char16_t: 154 case tok::kw_char32_t: 155 case tok::kw_typeof: 156 case tok::annot_decltype: 157 case tok::kw_decltype: 158 return getLangOpts().CPlusPlus; 159 160 case tok::kw_char8_t: 161 return getLangOpts().Char8; 162 163 default: 164 break; 165 } 166 167 return false; 168 } 169 170 namespace { 171 enum class UnqualifiedTypeNameLookupResult { 172 NotFound, 173 FoundNonType, 174 FoundType 175 }; 176 } // end anonymous namespace 177 178 /// Tries to perform unqualified lookup of the type decls in bases for 179 /// dependent class. 180 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 181 /// type decl, \a FoundType if only type decls are found. 182 static UnqualifiedTypeNameLookupResult 183 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 184 SourceLocation NameLoc, 185 const CXXRecordDecl *RD) { 186 if (!RD->hasDefinition()) 187 return UnqualifiedTypeNameLookupResult::NotFound; 188 // Look for type decls in base classes. 189 UnqualifiedTypeNameLookupResult FoundTypeDecl = 190 UnqualifiedTypeNameLookupResult::NotFound; 191 for (const auto &Base : RD->bases()) { 192 const CXXRecordDecl *BaseRD = nullptr; 193 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 194 BaseRD = BaseTT->getAsCXXRecordDecl(); 195 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 196 // Look for type decls in dependent base classes that have known primary 197 // templates. 198 if (!TST || !TST->isDependentType()) 199 continue; 200 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 201 if (!TD) 202 continue; 203 if (auto *BasePrimaryTemplate = 204 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 205 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 206 BaseRD = BasePrimaryTemplate; 207 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 208 if (const ClassTemplatePartialSpecializationDecl *PS = 209 CTD->findPartialSpecialization(Base.getType())) 210 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 211 BaseRD = PS; 212 } 213 } 214 } 215 if (BaseRD) { 216 for (NamedDecl *ND : BaseRD->lookup(&II)) { 217 if (!isa<TypeDecl>(ND)) 218 return UnqualifiedTypeNameLookupResult::FoundNonType; 219 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 220 } 221 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 222 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 223 case UnqualifiedTypeNameLookupResult::FoundNonType: 224 return UnqualifiedTypeNameLookupResult::FoundNonType; 225 case UnqualifiedTypeNameLookupResult::FoundType: 226 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 227 break; 228 case UnqualifiedTypeNameLookupResult::NotFound: 229 break; 230 } 231 } 232 } 233 } 234 235 return FoundTypeDecl; 236 } 237 238 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 239 const IdentifierInfo &II, 240 SourceLocation NameLoc) { 241 // Lookup in the parent class template context, if any. 242 const CXXRecordDecl *RD = nullptr; 243 UnqualifiedTypeNameLookupResult FoundTypeDecl = 244 UnqualifiedTypeNameLookupResult::NotFound; 245 for (DeclContext *DC = S.CurContext; 246 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 247 DC = DC->getParent()) { 248 // Look for type decls in dependent base classes that have known primary 249 // templates. 250 RD = dyn_cast<CXXRecordDecl>(DC); 251 if (RD && RD->getDescribedClassTemplate()) 252 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 253 } 254 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 255 return nullptr; 256 257 // We found some types in dependent base classes. Recover as if the user 258 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 259 // lookup during template instantiation. 260 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 261 262 ASTContext &Context = S.Context; 263 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 264 cast<Type>(Context.getRecordType(RD))); 265 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 266 267 CXXScopeSpec SS; 268 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 269 270 TypeLocBuilder Builder; 271 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 272 DepTL.setNameLoc(NameLoc); 273 DepTL.setElaboratedKeywordLoc(SourceLocation()); 274 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 275 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 276 } 277 278 /// If the identifier refers to a type name within this scope, 279 /// return the declaration of that type. 280 /// 281 /// This routine performs ordinary name lookup of the identifier II 282 /// within the given scope, with optional C++ scope specifier SS, to 283 /// determine whether the name refers to a type. If so, returns an 284 /// opaque pointer (actually a QualType) corresponding to that 285 /// type. Otherwise, returns NULL. 286 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 287 Scope *S, CXXScopeSpec *SS, 288 bool isClassName, bool HasTrailingDot, 289 ParsedType ObjectTypePtr, 290 bool IsCtorOrDtorName, 291 bool WantNontrivialTypeSourceInfo, 292 bool IsClassTemplateDeductionContext, 293 IdentifierInfo **CorrectedII) { 294 // FIXME: Consider allowing this outside C++1z mode as an extension. 295 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 296 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 297 !isClassName && !HasTrailingDot; 298 299 // Determine where we will perform name lookup. 300 DeclContext *LookupCtx = nullptr; 301 if (ObjectTypePtr) { 302 QualType ObjectType = ObjectTypePtr.get(); 303 if (ObjectType->isRecordType()) 304 LookupCtx = computeDeclContext(ObjectType); 305 } else if (SS && SS->isNotEmpty()) { 306 LookupCtx = computeDeclContext(*SS, false); 307 308 if (!LookupCtx) { 309 if (isDependentScopeSpecifier(*SS)) { 310 // C++ [temp.res]p3: 311 // A qualified-id that refers to a type and in which the 312 // nested-name-specifier depends on a template-parameter (14.6.2) 313 // shall be prefixed by the keyword typename to indicate that the 314 // qualified-id denotes a type, forming an 315 // elaborated-type-specifier (7.1.5.3). 316 // 317 // We therefore do not perform any name lookup if the result would 318 // refer to a member of an unknown specialization. 319 if (!isClassName && !IsCtorOrDtorName) 320 return nullptr; 321 322 // We know from the grammar that this name refers to a type, 323 // so build a dependent node to describe the type. 324 if (WantNontrivialTypeSourceInfo) 325 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 326 327 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 328 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 329 II, NameLoc); 330 return ParsedType::make(T); 331 } 332 333 return nullptr; 334 } 335 336 if (!LookupCtx->isDependentContext() && 337 RequireCompleteDeclContext(*SS, LookupCtx)) 338 return nullptr; 339 } 340 341 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 342 // lookup for class-names. 343 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 344 LookupOrdinaryName; 345 LookupResult Result(*this, &II, NameLoc, Kind); 346 if (LookupCtx) { 347 // Perform "qualified" name lookup into the declaration context we 348 // computed, which is either the type of the base of a member access 349 // expression or the declaration context associated with a prior 350 // nested-name-specifier. 351 LookupQualifiedName(Result, LookupCtx); 352 353 if (ObjectTypePtr && Result.empty()) { 354 // C++ [basic.lookup.classref]p3: 355 // If the unqualified-id is ~type-name, the type-name is looked up 356 // in the context of the entire postfix-expression. If the type T of 357 // the object expression is of a class type C, the type-name is also 358 // looked up in the scope of class C. At least one of the lookups shall 359 // find a name that refers to (possibly cv-qualified) T. 360 LookupName(Result, S); 361 } 362 } else { 363 // Perform unqualified name lookup. 364 LookupName(Result, S); 365 366 // For unqualified lookup in a class template in MSVC mode, look into 367 // dependent base classes where the primary class template is known. 368 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 369 if (ParsedType TypeInBase = 370 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 371 return TypeInBase; 372 } 373 } 374 375 NamedDecl *IIDecl = nullptr; 376 UsingShadowDecl *FoundUsingShadow = nullptr; 377 switch (Result.getResultKind()) { 378 case LookupResult::NotFound: 379 case LookupResult::NotFoundInCurrentInstantiation: 380 if (CorrectedII) { 381 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 382 AllowDeducedTemplate); 383 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 384 S, SS, CCC, CTK_ErrorRecovery); 385 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 386 TemplateTy Template; 387 bool MemberOfUnknownSpecialization; 388 UnqualifiedId TemplateName; 389 TemplateName.setIdentifier(NewII, NameLoc); 390 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 391 CXXScopeSpec NewSS, *NewSSPtr = SS; 392 if (SS && NNS) { 393 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 394 NewSSPtr = &NewSS; 395 } 396 if (Correction && (NNS || NewII != &II) && 397 // Ignore a correction to a template type as the to-be-corrected 398 // identifier is not a template (typo correction for template names 399 // is handled elsewhere). 400 !(getLangOpts().CPlusPlus && NewSSPtr && 401 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 402 Template, MemberOfUnknownSpecialization))) { 403 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 404 isClassName, HasTrailingDot, ObjectTypePtr, 405 IsCtorOrDtorName, 406 WantNontrivialTypeSourceInfo, 407 IsClassTemplateDeductionContext); 408 if (Ty) { 409 diagnoseTypo(Correction, 410 PDiag(diag::err_unknown_type_or_class_name_suggest) 411 << Result.getLookupName() << isClassName); 412 if (SS && NNS) 413 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 414 *CorrectedII = NewII; 415 return Ty; 416 } 417 } 418 } 419 // If typo correction failed or was not performed, fall through 420 LLVM_FALLTHROUGH; 421 case LookupResult::FoundOverloaded: 422 case LookupResult::FoundUnresolvedValue: 423 Result.suppressDiagnostics(); 424 return nullptr; 425 426 case LookupResult::Ambiguous: 427 // Recover from type-hiding ambiguities by hiding the type. We'll 428 // do the lookup again when looking for an object, and we can 429 // diagnose the error then. If we don't do this, then the error 430 // about hiding the type will be immediately followed by an error 431 // that only makes sense if the identifier was treated like a type. 432 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 433 Result.suppressDiagnostics(); 434 return nullptr; 435 } 436 437 // Look to see if we have a type anywhere in the list of results. 438 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 439 Res != ResEnd; ++Res) { 440 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 441 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 442 RealRes) || 443 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 444 if (!IIDecl || 445 // Make the selection of the recovery decl deterministic. 446 RealRes->getLocation() < IIDecl->getLocation()) { 447 IIDecl = RealRes; 448 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); 449 } 450 } 451 } 452 453 if (!IIDecl) { 454 // None of the entities we found is a type, so there is no way 455 // to even assume that the result is a type. In this case, don't 456 // complain about the ambiguity. The parser will either try to 457 // perform this lookup again (e.g., as an object name), which 458 // will produce the ambiguity, or will complain that it expected 459 // a type name. 460 Result.suppressDiagnostics(); 461 return nullptr; 462 } 463 464 // We found a type within the ambiguous lookup; diagnose the 465 // ambiguity and then return that type. This might be the right 466 // answer, or it might not be, but it suppresses any attempt to 467 // perform the name lookup again. 468 break; 469 470 case LookupResult::Found: 471 IIDecl = Result.getFoundDecl(); 472 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); 473 break; 474 } 475 476 assert(IIDecl && "Didn't find decl"); 477 478 QualType T; 479 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 480 // C++ [class.qual]p2: A lookup that would find the injected-class-name 481 // instead names the constructors of the class, except when naming a class. 482 // This is ill-formed when we're not actually forming a ctor or dtor name. 483 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 484 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 485 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 486 FoundRD->isInjectedClassName() && 487 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 488 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 489 << &II << /*Type*/1; 490 491 DiagnoseUseOfDecl(IIDecl, NameLoc); 492 493 T = Context.getTypeDeclType(TD); 494 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 495 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 496 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 497 if (!HasTrailingDot) 498 T = Context.getObjCInterfaceType(IDecl); 499 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. 500 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 501 (void)DiagnoseUseOfDecl(UD, NameLoc); 502 // Recover with 'int' 503 T = Context.IntTy; 504 FoundUsingShadow = nullptr; 505 } else if (AllowDeducedTemplate) { 506 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { 507 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); 508 TemplateName Template = 509 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 510 T = Context.getDeducedTemplateSpecializationType(Template, QualType(), 511 false); 512 // Don't wrap in a further UsingType. 513 FoundUsingShadow = nullptr; 514 } 515 } 516 517 if (T.isNull()) { 518 // If it's not plausibly a type, suppress diagnostics. 519 Result.suppressDiagnostics(); 520 return nullptr; 521 } 522 523 if (FoundUsingShadow) 524 T = Context.getUsingType(FoundUsingShadow, T); 525 526 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 527 // constructor or destructor name (in such a case, the scope specifier 528 // will be attached to the enclosing Expr or Decl node). 529 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 530 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { 531 if (WantNontrivialTypeSourceInfo) { 532 // Construct a type with type-source information. 533 TypeLocBuilder Builder; 534 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 535 536 T = getElaboratedType(ETK_None, *SS, T); 537 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 538 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 539 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 540 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 541 } else { 542 T = getElaboratedType(ETK_None, *SS, T); 543 } 544 } 545 546 return ParsedType::make(T); 547 } 548 549 // Builds a fake NNS for the given decl context. 550 static NestedNameSpecifier * 551 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 552 for (;; DC = DC->getLookupParent()) { 553 DC = DC->getPrimaryContext(); 554 auto *ND = dyn_cast<NamespaceDecl>(DC); 555 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 556 return NestedNameSpecifier::Create(Context, nullptr, ND); 557 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 558 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 559 RD->getTypeForDecl()); 560 else if (isa<TranslationUnitDecl>(DC)) 561 return NestedNameSpecifier::GlobalSpecifier(Context); 562 } 563 llvm_unreachable("something isn't in TU scope?"); 564 } 565 566 /// Find the parent class with dependent bases of the innermost enclosing method 567 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 568 /// up allowing unqualified dependent type names at class-level, which MSVC 569 /// correctly rejects. 570 static const CXXRecordDecl * 571 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 572 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 573 DC = DC->getPrimaryContext(); 574 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 575 if (MD->getParent()->hasAnyDependentBases()) 576 return MD->getParent(); 577 } 578 return nullptr; 579 } 580 581 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 582 SourceLocation NameLoc, 583 bool IsTemplateTypeArg) { 584 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 585 586 NestedNameSpecifier *NNS = nullptr; 587 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 588 // If we weren't able to parse a default template argument, delay lookup 589 // until instantiation time by making a non-dependent DependentTypeName. We 590 // pretend we saw a NestedNameSpecifier referring to the current scope, and 591 // lookup is retried. 592 // FIXME: This hurts our diagnostic quality, since we get errors like "no 593 // type named 'Foo' in 'current_namespace'" when the user didn't write any 594 // name specifiers. 595 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 596 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 597 } else if (const CXXRecordDecl *RD = 598 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 599 // Build a DependentNameType that will perform lookup into RD at 600 // instantiation time. 601 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 602 RD->getTypeForDecl()); 603 604 // Diagnose that this identifier was undeclared, and retry the lookup during 605 // template instantiation. 606 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 607 << RD; 608 } else { 609 // This is not a situation that we should recover from. 610 return ParsedType(); 611 } 612 613 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 614 615 // Build type location information. We synthesized the qualifier, so we have 616 // to build a fake NestedNameSpecifierLoc. 617 NestedNameSpecifierLocBuilder NNSLocBuilder; 618 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 619 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 620 621 TypeLocBuilder Builder; 622 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 623 DepTL.setNameLoc(NameLoc); 624 DepTL.setElaboratedKeywordLoc(SourceLocation()); 625 DepTL.setQualifierLoc(QualifierLoc); 626 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 627 } 628 629 /// isTagName() - This method is called *for error recovery purposes only* 630 /// to determine if the specified name is a valid tag name ("struct foo"). If 631 /// so, this returns the TST for the tag corresponding to it (TST_enum, 632 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 633 /// cases in C where the user forgot to specify the tag. 634 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 635 // Do a tag name lookup in this scope. 636 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 637 LookupName(R, S, false); 638 R.suppressDiagnostics(); 639 if (R.getResultKind() == LookupResult::Found) 640 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 641 switch (TD->getTagKind()) { 642 case TTK_Struct: return DeclSpec::TST_struct; 643 case TTK_Interface: return DeclSpec::TST_interface; 644 case TTK_Union: return DeclSpec::TST_union; 645 case TTK_Class: return DeclSpec::TST_class; 646 case TTK_Enum: return DeclSpec::TST_enum; 647 } 648 } 649 650 return DeclSpec::TST_unspecified; 651 } 652 653 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 654 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 655 /// then downgrade the missing typename error to a warning. 656 /// This is needed for MSVC compatibility; Example: 657 /// @code 658 /// template<class T> class A { 659 /// public: 660 /// typedef int TYPE; 661 /// }; 662 /// template<class T> class B : public A<T> { 663 /// public: 664 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 665 /// }; 666 /// @endcode 667 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 668 if (CurContext->isRecord()) { 669 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 670 return true; 671 672 const Type *Ty = SS->getScopeRep()->getAsType(); 673 674 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 675 for (const auto &Base : RD->bases()) 676 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 677 return true; 678 return S->isFunctionPrototypeScope(); 679 } 680 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 681 } 682 683 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 684 SourceLocation IILoc, 685 Scope *S, 686 CXXScopeSpec *SS, 687 ParsedType &SuggestedType, 688 bool IsTemplateName) { 689 // Don't report typename errors for editor placeholders. 690 if (II->isEditorPlaceholder()) 691 return; 692 // We don't have anything to suggest (yet). 693 SuggestedType = nullptr; 694 695 // There may have been a typo in the name of the type. Look up typo 696 // results, in case we have something that we can suggest. 697 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 698 /*AllowTemplates=*/IsTemplateName, 699 /*AllowNonTemplates=*/!IsTemplateName); 700 if (TypoCorrection Corrected = 701 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 702 CCC, CTK_ErrorRecovery)) { 703 // FIXME: Support error recovery for the template-name case. 704 bool CanRecover = !IsTemplateName; 705 if (Corrected.isKeyword()) { 706 // We corrected to a keyword. 707 diagnoseTypo(Corrected, 708 PDiag(IsTemplateName ? diag::err_no_template_suggest 709 : diag::err_unknown_typename_suggest) 710 << II); 711 II = Corrected.getCorrectionAsIdentifierInfo(); 712 } else { 713 // We found a similarly-named type or interface; suggest that. 714 if (!SS || !SS->isSet()) { 715 diagnoseTypo(Corrected, 716 PDiag(IsTemplateName ? diag::err_no_template_suggest 717 : diag::err_unknown_typename_suggest) 718 << II, CanRecover); 719 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 720 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 721 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 722 II->getName().equals(CorrectedStr); 723 diagnoseTypo(Corrected, 724 PDiag(IsTemplateName 725 ? diag::err_no_member_template_suggest 726 : diag::err_unknown_nested_typename_suggest) 727 << II << DC << DroppedSpecifier << SS->getRange(), 728 CanRecover); 729 } else { 730 llvm_unreachable("could not have corrected a typo here"); 731 } 732 733 if (!CanRecover) 734 return; 735 736 CXXScopeSpec tmpSS; 737 if (Corrected.getCorrectionSpecifier()) 738 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 739 SourceRange(IILoc)); 740 // FIXME: Support class template argument deduction here. 741 SuggestedType = 742 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 743 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 744 /*IsCtorOrDtorName=*/false, 745 /*WantNontrivialTypeSourceInfo=*/true); 746 } 747 return; 748 } 749 750 if (getLangOpts().CPlusPlus && !IsTemplateName) { 751 // See if II is a class template that the user forgot to pass arguments to. 752 UnqualifiedId Name; 753 Name.setIdentifier(II, IILoc); 754 CXXScopeSpec EmptySS; 755 TemplateTy TemplateResult; 756 bool MemberOfUnknownSpecialization; 757 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 758 Name, nullptr, true, TemplateResult, 759 MemberOfUnknownSpecialization) == TNK_Type_template) { 760 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 761 return; 762 } 763 } 764 765 // FIXME: Should we move the logic that tries to recover from a missing tag 766 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 767 768 if (!SS || (!SS->isSet() && !SS->isInvalid())) 769 Diag(IILoc, IsTemplateName ? diag::err_no_template 770 : diag::err_unknown_typename) 771 << II; 772 else if (DeclContext *DC = computeDeclContext(*SS, false)) 773 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 774 : diag::err_typename_nested_not_found) 775 << II << DC << SS->getRange(); 776 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 777 SuggestedType = 778 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 779 } else if (isDependentScopeSpecifier(*SS)) { 780 unsigned DiagID = diag::err_typename_missing; 781 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 782 DiagID = diag::ext_typename_missing; 783 784 Diag(SS->getRange().getBegin(), DiagID) 785 << SS->getScopeRep() << II->getName() 786 << SourceRange(SS->getRange().getBegin(), IILoc) 787 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 788 SuggestedType = ActOnTypenameType(S, SourceLocation(), 789 *SS, *II, IILoc).get(); 790 } else { 791 assert(SS && SS->isInvalid() && 792 "Invalid scope specifier has already been diagnosed"); 793 } 794 } 795 796 /// Determine whether the given result set contains either a type name 797 /// or 798 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 799 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 800 NextToken.is(tok::less); 801 802 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 803 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 804 return true; 805 806 if (CheckTemplate && isa<TemplateDecl>(*I)) 807 return true; 808 } 809 810 return false; 811 } 812 813 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 814 Scope *S, CXXScopeSpec &SS, 815 IdentifierInfo *&Name, 816 SourceLocation NameLoc) { 817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 818 SemaRef.LookupParsedName(R, S, &SS); 819 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 820 StringRef FixItTagName; 821 switch (Tag->getTagKind()) { 822 case TTK_Class: 823 FixItTagName = "class "; 824 break; 825 826 case TTK_Enum: 827 FixItTagName = "enum "; 828 break; 829 830 case TTK_Struct: 831 FixItTagName = "struct "; 832 break; 833 834 case TTK_Interface: 835 FixItTagName = "__interface "; 836 break; 837 838 case TTK_Union: 839 FixItTagName = "union "; 840 break; 841 } 842 843 StringRef TagName = FixItTagName.drop_back(); 844 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 845 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 846 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 847 848 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 849 I != IEnd; ++I) 850 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 851 << Name << TagName; 852 853 // Replace lookup results with just the tag decl. 854 Result.clear(Sema::LookupTagName); 855 SemaRef.LookupParsedName(Result, S, &SS); 856 return true; 857 } 858 859 return false; 860 } 861 862 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 863 IdentifierInfo *&Name, 864 SourceLocation NameLoc, 865 const Token &NextToken, 866 CorrectionCandidateCallback *CCC) { 867 DeclarationNameInfo NameInfo(Name, NameLoc); 868 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 869 870 assert(NextToken.isNot(tok::coloncolon) && 871 "parse nested name specifiers before calling ClassifyName"); 872 if (getLangOpts().CPlusPlus && SS.isSet() && 873 isCurrentClassName(*Name, S, &SS)) { 874 // Per [class.qual]p2, this names the constructors of SS, not the 875 // injected-class-name. We don't have a classification for that. 876 // There's not much point caching this result, since the parser 877 // will reject it later. 878 return NameClassification::Unknown(); 879 } 880 881 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 882 LookupParsedName(Result, S, &SS, !CurMethod); 883 884 if (SS.isInvalid()) 885 return NameClassification::Error(); 886 887 // For unqualified lookup in a class template in MSVC mode, look into 888 // dependent base classes where the primary class template is known. 889 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 890 if (ParsedType TypeInBase = 891 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 892 return TypeInBase; 893 } 894 895 // Perform lookup for Objective-C instance variables (including automatically 896 // synthesized instance variables), if we're in an Objective-C method. 897 // FIXME: This lookup really, really needs to be folded in to the normal 898 // unqualified lookup mechanism. 899 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 900 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 901 if (Ivar.isInvalid()) 902 return NameClassification::Error(); 903 if (Ivar.isUsable()) 904 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 905 906 // We defer builtin creation until after ivar lookup inside ObjC methods. 907 if (Result.empty()) 908 LookupBuiltin(Result); 909 } 910 911 bool SecondTry = false; 912 bool IsFilteredTemplateName = false; 913 914 Corrected: 915 switch (Result.getResultKind()) { 916 case LookupResult::NotFound: 917 // If an unqualified-id is followed by a '(', then we have a function 918 // call. 919 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 920 // In C++, this is an ADL-only call. 921 // FIXME: Reference? 922 if (getLangOpts().CPlusPlus) 923 return NameClassification::UndeclaredNonType(); 924 925 // C90 6.3.2.2: 926 // If the expression that precedes the parenthesized argument list in a 927 // function call consists solely of an identifier, and if no 928 // declaration is visible for this identifier, the identifier is 929 // implicitly declared exactly as if, in the innermost block containing 930 // the function call, the declaration 931 // 932 // extern int identifier (); 933 // 934 // appeared. 935 // 936 // We also allow this in C99 as an extension. However, this is not 937 // allowed in C2x as there are no functions without prototypes there. 938 if (!getLangOpts().C2x) { 939 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 940 return NameClassification::NonType(D); 941 } 942 } 943 944 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 945 // In C++20 onwards, this could be an ADL-only call to a function 946 // template, and we're required to assume that this is a template name. 947 // 948 // FIXME: Find a way to still do typo correction in this case. 949 TemplateName Template = 950 Context.getAssumedTemplateName(NameInfo.getName()); 951 return NameClassification::UndeclaredTemplate(Template); 952 } 953 954 // In C, we first see whether there is a tag type by the same name, in 955 // which case it's likely that the user just forgot to write "enum", 956 // "struct", or "union". 957 if (!getLangOpts().CPlusPlus && !SecondTry && 958 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 959 break; 960 } 961 962 // Perform typo correction to determine if there is another name that is 963 // close to this name. 964 if (!SecondTry && CCC) { 965 SecondTry = true; 966 if (TypoCorrection Corrected = 967 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 968 &SS, *CCC, CTK_ErrorRecovery)) { 969 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 970 unsigned QualifiedDiag = diag::err_no_member_suggest; 971 972 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 973 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 974 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 975 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 976 UnqualifiedDiag = diag::err_no_template_suggest; 977 QualifiedDiag = diag::err_no_member_template_suggest; 978 } else if (UnderlyingFirstDecl && 979 (isa<TypeDecl>(UnderlyingFirstDecl) || 980 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 981 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 982 UnqualifiedDiag = diag::err_unknown_typename_suggest; 983 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 984 } 985 986 if (SS.isEmpty()) { 987 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 988 } else {// FIXME: is this even reachable? Test it. 989 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 990 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 991 Name->getName().equals(CorrectedStr); 992 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 993 << Name << computeDeclContext(SS, false) 994 << DroppedSpecifier << SS.getRange()); 995 } 996 997 // Update the name, so that the caller has the new name. 998 Name = Corrected.getCorrectionAsIdentifierInfo(); 999 1000 // Typo correction corrected to a keyword. 1001 if (Corrected.isKeyword()) 1002 return Name; 1003 1004 // Also update the LookupResult... 1005 // FIXME: This should probably go away at some point 1006 Result.clear(); 1007 Result.setLookupName(Corrected.getCorrection()); 1008 if (FirstDecl) 1009 Result.addDecl(FirstDecl); 1010 1011 // If we found an Objective-C instance variable, let 1012 // LookupInObjCMethod build the appropriate expression to 1013 // reference the ivar. 1014 // FIXME: This is a gross hack. 1015 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1016 DeclResult R = 1017 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1018 if (R.isInvalid()) 1019 return NameClassification::Error(); 1020 if (R.isUsable()) 1021 return NameClassification::NonType(Ivar); 1022 } 1023 1024 goto Corrected; 1025 } 1026 } 1027 1028 // We failed to correct; just fall through and let the parser deal with it. 1029 Result.suppressDiagnostics(); 1030 return NameClassification::Unknown(); 1031 1032 case LookupResult::NotFoundInCurrentInstantiation: { 1033 // We performed name lookup into the current instantiation, and there were 1034 // dependent bases, so we treat this result the same way as any other 1035 // dependent nested-name-specifier. 1036 1037 // C++ [temp.res]p2: 1038 // A name used in a template declaration or definition and that is 1039 // dependent on a template-parameter is assumed not to name a type 1040 // unless the applicable name lookup finds a type name or the name is 1041 // qualified by the keyword typename. 1042 // 1043 // FIXME: If the next token is '<', we might want to ask the parser to 1044 // perform some heroics to see if we actually have a 1045 // template-argument-list, which would indicate a missing 'template' 1046 // keyword here. 1047 return NameClassification::DependentNonType(); 1048 } 1049 1050 case LookupResult::Found: 1051 case LookupResult::FoundOverloaded: 1052 case LookupResult::FoundUnresolvedValue: 1053 break; 1054 1055 case LookupResult::Ambiguous: 1056 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1057 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1058 /*AllowDependent=*/false)) { 1059 // C++ [temp.local]p3: 1060 // A lookup that finds an injected-class-name (10.2) can result in an 1061 // ambiguity in certain cases (for example, if it is found in more than 1062 // one base class). If all of the injected-class-names that are found 1063 // refer to specializations of the same class template, and if the name 1064 // is followed by a template-argument-list, the reference refers to the 1065 // class template itself and not a specialization thereof, and is not 1066 // ambiguous. 1067 // 1068 // This filtering can make an ambiguous result into an unambiguous one, 1069 // so try again after filtering out template names. 1070 FilterAcceptableTemplateNames(Result); 1071 if (!Result.isAmbiguous()) { 1072 IsFilteredTemplateName = true; 1073 break; 1074 } 1075 } 1076 1077 // Diagnose the ambiguity and return an error. 1078 return NameClassification::Error(); 1079 } 1080 1081 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1082 (IsFilteredTemplateName || 1083 hasAnyAcceptableTemplateNames( 1084 Result, /*AllowFunctionTemplates=*/true, 1085 /*AllowDependent=*/false, 1086 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1087 getLangOpts().CPlusPlus20))) { 1088 // C++ [temp.names]p3: 1089 // After name lookup (3.4) finds that a name is a template-name or that 1090 // an operator-function-id or a literal- operator-id refers to a set of 1091 // overloaded functions any member of which is a function template if 1092 // this is followed by a <, the < is always taken as the delimiter of a 1093 // template-argument-list and never as the less-than operator. 1094 // C++2a [temp.names]p2: 1095 // A name is also considered to refer to a template if it is an 1096 // unqualified-id followed by a < and name lookup finds either one 1097 // or more functions or finds nothing. 1098 if (!IsFilteredTemplateName) 1099 FilterAcceptableTemplateNames(Result); 1100 1101 bool IsFunctionTemplate; 1102 bool IsVarTemplate; 1103 TemplateName Template; 1104 if (Result.end() - Result.begin() > 1) { 1105 IsFunctionTemplate = true; 1106 Template = Context.getOverloadedTemplateName(Result.begin(), 1107 Result.end()); 1108 } else if (!Result.empty()) { 1109 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1110 *Result.begin(), /*AllowFunctionTemplates=*/true, 1111 /*AllowDependent=*/false)); 1112 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1113 IsVarTemplate = isa<VarTemplateDecl>(TD); 1114 1115 UsingShadowDecl *FoundUsingShadow = 1116 dyn_cast<UsingShadowDecl>(*Result.begin()); 1117 1118 if (SS.isNotEmpty()) { 1119 // FIXME: support using shadow-declaration in qualified template name. 1120 Template = 1121 Context.getQualifiedTemplateName(SS.getScopeRep(), 1122 /*TemplateKeyword=*/false, TD); 1123 } else { 1124 assert(!FoundUsingShadow || 1125 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())); 1126 Template = FoundUsingShadow ? TemplateName(FoundUsingShadow) 1127 : TemplateName(TD); 1128 } 1129 } else { 1130 // All results were non-template functions. This is a function template 1131 // name. 1132 IsFunctionTemplate = true; 1133 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1134 } 1135 1136 if (IsFunctionTemplate) { 1137 // Function templates always go through overload resolution, at which 1138 // point we'll perform the various checks (e.g., accessibility) we need 1139 // to based on which function we selected. 1140 Result.suppressDiagnostics(); 1141 1142 return NameClassification::FunctionTemplate(Template); 1143 } 1144 1145 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1146 : NameClassification::TypeTemplate(Template); 1147 } 1148 1149 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { 1150 QualType T = Context.getTypeDeclType(Type); 1151 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) 1152 T = Context.getUsingType(USD, T); 1153 1154 if (SS.isEmpty()) // No elaborated type, trivial location info 1155 return ParsedType::make(T); 1156 1157 TypeLocBuilder Builder; 1158 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 1159 T = getElaboratedType(ETK_None, SS, T); 1160 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 1161 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 1162 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 1163 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 1164 }; 1165 1166 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1167 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1168 DiagnoseUseOfDecl(Type, NameLoc); 1169 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1170 return BuildTypeFor(Type, *Result.begin()); 1171 } 1172 1173 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1174 if (!Class) { 1175 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1176 if (ObjCCompatibleAliasDecl *Alias = 1177 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1178 Class = Alias->getClassInterface(); 1179 } 1180 1181 if (Class) { 1182 DiagnoseUseOfDecl(Class, NameLoc); 1183 1184 if (NextToken.is(tok::period)) { 1185 // Interface. <something> is parsed as a property reference expression. 1186 // Just return "unknown" as a fall-through for now. 1187 Result.suppressDiagnostics(); 1188 return NameClassification::Unknown(); 1189 } 1190 1191 QualType T = Context.getObjCInterfaceType(Class); 1192 return ParsedType::make(T); 1193 } 1194 1195 if (isa<ConceptDecl>(FirstDecl)) 1196 return NameClassification::Concept( 1197 TemplateName(cast<TemplateDecl>(FirstDecl))); 1198 1199 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1200 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1201 return NameClassification::Error(); 1202 } 1203 1204 // We can have a type template here if we're classifying a template argument. 1205 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1206 !isa<VarTemplateDecl>(FirstDecl)) 1207 return NameClassification::TypeTemplate( 1208 TemplateName(cast<TemplateDecl>(FirstDecl))); 1209 1210 // Check for a tag type hidden by a non-type decl in a few cases where it 1211 // seems likely a type is wanted instead of the non-type that was found. 1212 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1213 if ((NextToken.is(tok::identifier) || 1214 (NextIsOp && 1215 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1216 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1217 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1218 DiagnoseUseOfDecl(Type, NameLoc); 1219 return BuildTypeFor(Type, *Result.begin()); 1220 } 1221 1222 // If we already know which single declaration is referenced, just annotate 1223 // that declaration directly. Defer resolving even non-overloaded class 1224 // member accesses, as we need to defer certain access checks until we know 1225 // the context. 1226 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1227 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1228 return NameClassification::NonType(Result.getRepresentativeDecl()); 1229 1230 // Otherwise, this is an overload set that we will need to resolve later. 1231 Result.suppressDiagnostics(); 1232 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1233 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1234 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1235 Result.begin(), Result.end())); 1236 } 1237 1238 ExprResult 1239 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1240 SourceLocation NameLoc) { 1241 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1242 CXXScopeSpec SS; 1243 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1244 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1245 } 1246 1247 ExprResult 1248 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1249 IdentifierInfo *Name, 1250 SourceLocation NameLoc, 1251 bool IsAddressOfOperand) { 1252 DeclarationNameInfo NameInfo(Name, NameLoc); 1253 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1254 NameInfo, IsAddressOfOperand, 1255 /*TemplateArgs=*/nullptr); 1256 } 1257 1258 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1259 NamedDecl *Found, 1260 SourceLocation NameLoc, 1261 const Token &NextToken) { 1262 if (getCurMethodDecl() && SS.isEmpty()) 1263 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1264 return BuildIvarRefExpr(S, NameLoc, Ivar); 1265 1266 // Reconstruct the lookup result. 1267 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1268 Result.addDecl(Found); 1269 Result.resolveKind(); 1270 1271 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1272 return BuildDeclarationNameExpr(SS, Result, ADL); 1273 } 1274 1275 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1276 // For an implicit class member access, transform the result into a member 1277 // access expression if necessary. 1278 auto *ULE = cast<UnresolvedLookupExpr>(E); 1279 if ((*ULE->decls_begin())->isCXXClassMember()) { 1280 CXXScopeSpec SS; 1281 SS.Adopt(ULE->getQualifierLoc()); 1282 1283 // Reconstruct the lookup result. 1284 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1285 LookupOrdinaryName); 1286 Result.setNamingClass(ULE->getNamingClass()); 1287 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1288 Result.addDecl(*I, I.getAccess()); 1289 Result.resolveKind(); 1290 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1291 nullptr, S); 1292 } 1293 1294 // Otherwise, this is already in the form we needed, and no further checks 1295 // are necessary. 1296 return ULE; 1297 } 1298 1299 Sema::TemplateNameKindForDiagnostics 1300 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1301 auto *TD = Name.getAsTemplateDecl(); 1302 if (!TD) 1303 return TemplateNameKindForDiagnostics::DependentTemplate; 1304 if (isa<ClassTemplateDecl>(TD)) 1305 return TemplateNameKindForDiagnostics::ClassTemplate; 1306 if (isa<FunctionTemplateDecl>(TD)) 1307 return TemplateNameKindForDiagnostics::FunctionTemplate; 1308 if (isa<VarTemplateDecl>(TD)) 1309 return TemplateNameKindForDiagnostics::VarTemplate; 1310 if (isa<TypeAliasTemplateDecl>(TD)) 1311 return TemplateNameKindForDiagnostics::AliasTemplate; 1312 if (isa<TemplateTemplateParmDecl>(TD)) 1313 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1314 if (isa<ConceptDecl>(TD)) 1315 return TemplateNameKindForDiagnostics::Concept; 1316 return TemplateNameKindForDiagnostics::DependentTemplate; 1317 } 1318 1319 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1320 assert(DC->getLexicalParent() == CurContext && 1321 "The next DeclContext should be lexically contained in the current one."); 1322 CurContext = DC; 1323 S->setEntity(DC); 1324 } 1325 1326 void Sema::PopDeclContext() { 1327 assert(CurContext && "DeclContext imbalance!"); 1328 1329 CurContext = CurContext->getLexicalParent(); 1330 assert(CurContext && "Popped translation unit!"); 1331 } 1332 1333 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1334 Decl *D) { 1335 // Unlike PushDeclContext, the context to which we return is not necessarily 1336 // the containing DC of TD, because the new context will be some pre-existing 1337 // TagDecl definition instead of a fresh one. 1338 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1339 CurContext = cast<TagDecl>(D)->getDefinition(); 1340 assert(CurContext && "skipping definition of undefined tag"); 1341 // Start lookups from the parent of the current context; we don't want to look 1342 // into the pre-existing complete definition. 1343 S->setEntity(CurContext->getLookupParent()); 1344 return Result; 1345 } 1346 1347 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1348 CurContext = static_cast<decltype(CurContext)>(Context); 1349 } 1350 1351 /// EnterDeclaratorContext - Used when we must lookup names in the context 1352 /// of a declarator's nested name specifier. 1353 /// 1354 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1355 // C++0x [basic.lookup.unqual]p13: 1356 // A name used in the definition of a static data member of class 1357 // X (after the qualified-id of the static member) is looked up as 1358 // if the name was used in a member function of X. 1359 // C++0x [basic.lookup.unqual]p14: 1360 // If a variable member of a namespace is defined outside of the 1361 // scope of its namespace then any name used in the definition of 1362 // the variable member (after the declarator-id) is looked up as 1363 // if the definition of the variable member occurred in its 1364 // namespace. 1365 // Both of these imply that we should push a scope whose context 1366 // is the semantic context of the declaration. We can't use 1367 // PushDeclContext here because that context is not necessarily 1368 // lexically contained in the current context. Fortunately, 1369 // the containing scope should have the appropriate information. 1370 1371 assert(!S->getEntity() && "scope already has entity"); 1372 1373 #ifndef NDEBUG 1374 Scope *Ancestor = S->getParent(); 1375 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1376 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1377 #endif 1378 1379 CurContext = DC; 1380 S->setEntity(DC); 1381 1382 if (S->getParent()->isTemplateParamScope()) { 1383 // Also set the corresponding entities for all immediately-enclosing 1384 // template parameter scopes. 1385 EnterTemplatedContext(S->getParent(), DC); 1386 } 1387 } 1388 1389 void Sema::ExitDeclaratorContext(Scope *S) { 1390 assert(S->getEntity() == CurContext && "Context imbalance!"); 1391 1392 // Switch back to the lexical context. The safety of this is 1393 // enforced by an assert in EnterDeclaratorContext. 1394 Scope *Ancestor = S->getParent(); 1395 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1396 CurContext = Ancestor->getEntity(); 1397 1398 // We don't need to do anything with the scope, which is going to 1399 // disappear. 1400 } 1401 1402 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1403 assert(S->isTemplateParamScope() && 1404 "expected to be initializing a template parameter scope"); 1405 1406 // C++20 [temp.local]p7: 1407 // In the definition of a member of a class template that appears outside 1408 // of the class template definition, the name of a member of the class 1409 // template hides the name of a template-parameter of any enclosing class 1410 // templates (but not a template-parameter of the member if the member is a 1411 // class or function template). 1412 // C++20 [temp.local]p9: 1413 // In the definition of a class template or in the definition of a member 1414 // of such a template that appears outside of the template definition, for 1415 // each non-dependent base class (13.8.2.1), if the name of the base class 1416 // or the name of a member of the base class is the same as the name of a 1417 // template-parameter, the base class name or member name hides the 1418 // template-parameter name (6.4.10). 1419 // 1420 // This means that a template parameter scope should be searched immediately 1421 // after searching the DeclContext for which it is a template parameter 1422 // scope. For example, for 1423 // template<typename T> template<typename U> template<typename V> 1424 // void N::A<T>::B<U>::f(...) 1425 // we search V then B<U> (and base classes) then U then A<T> (and base 1426 // classes) then T then N then ::. 1427 unsigned ScopeDepth = getTemplateDepth(S); 1428 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1429 DeclContext *SearchDCAfterScope = DC; 1430 for (; DC; DC = DC->getLookupParent()) { 1431 if (const TemplateParameterList *TPL = 1432 cast<Decl>(DC)->getDescribedTemplateParams()) { 1433 unsigned DCDepth = TPL->getDepth() + 1; 1434 if (DCDepth > ScopeDepth) 1435 continue; 1436 if (ScopeDepth == DCDepth) 1437 SearchDCAfterScope = DC = DC->getLookupParent(); 1438 break; 1439 } 1440 } 1441 S->setLookupEntity(SearchDCAfterScope); 1442 } 1443 } 1444 1445 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1446 // We assume that the caller has already called 1447 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1448 FunctionDecl *FD = D->getAsFunction(); 1449 if (!FD) 1450 return; 1451 1452 // Same implementation as PushDeclContext, but enters the context 1453 // from the lexical parent, rather than the top-level class. 1454 assert(CurContext == FD->getLexicalParent() && 1455 "The next DeclContext should be lexically contained in the current one."); 1456 CurContext = FD; 1457 S->setEntity(CurContext); 1458 1459 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1460 ParmVarDecl *Param = FD->getParamDecl(P); 1461 // If the parameter has an identifier, then add it to the scope 1462 if (Param->getIdentifier()) { 1463 S->AddDecl(Param); 1464 IdResolver.AddDecl(Param); 1465 } 1466 } 1467 } 1468 1469 void Sema::ActOnExitFunctionContext() { 1470 // Same implementation as PopDeclContext, but returns to the lexical parent, 1471 // rather than the top-level class. 1472 assert(CurContext && "DeclContext imbalance!"); 1473 CurContext = CurContext->getLexicalParent(); 1474 assert(CurContext && "Popped translation unit!"); 1475 } 1476 1477 /// Determine whether overloading is allowed for a new function 1478 /// declaration considering prior declarations of the same name. 1479 /// 1480 /// This routine determines whether overloading is possible, not 1481 /// whether a new declaration actually overloads a previous one. 1482 /// It will return true in C++ (where overloads are alway permitted) 1483 /// or, as a C extension, when either the new declaration or a 1484 /// previous one is declared with the 'overloadable' attribute. 1485 static bool AllowOverloadingOfFunction(const LookupResult &Previous, 1486 ASTContext &Context, 1487 const FunctionDecl *New) { 1488 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>()) 1489 return true; 1490 1491 // Multiversion function declarations are not overloads in the 1492 // usual sense of that term, but lookup will report that an 1493 // overload set was found if more than one multiversion function 1494 // declaration is present for the same name. It is therefore 1495 // inadequate to assume that some prior declaration(s) had 1496 // the overloadable attribute; checking is required. Since one 1497 // declaration is permitted to omit the attribute, it is necessary 1498 // to check at least two; hence the 'any_of' check below. Note that 1499 // the overloadable attribute is implicitly added to declarations 1500 // that were required to have it but did not. 1501 if (Previous.getResultKind() == LookupResult::FoundOverloaded) { 1502 return llvm::any_of(Previous, [](const NamedDecl *ND) { 1503 return ND->hasAttr<OverloadableAttr>(); 1504 }); 1505 } else if (Previous.getResultKind() == LookupResult::Found) 1506 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>(); 1507 1508 return false; 1509 } 1510 1511 /// Add this decl to the scope shadowed decl chains. 1512 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1513 // Move up the scope chain until we find the nearest enclosing 1514 // non-transparent context. The declaration will be introduced into this 1515 // scope. 1516 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1517 S = S->getParent(); 1518 1519 // Add scoped declarations into their context, so that they can be 1520 // found later. Declarations without a context won't be inserted 1521 // into any context. 1522 if (AddToContext) 1523 CurContext->addDecl(D); 1524 1525 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1526 // are function-local declarations. 1527 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1528 return; 1529 1530 // Template instantiations should also not be pushed into scope. 1531 if (isa<FunctionDecl>(D) && 1532 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1533 return; 1534 1535 // If this replaces anything in the current scope, 1536 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1537 IEnd = IdResolver.end(); 1538 for (; I != IEnd; ++I) { 1539 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1540 S->RemoveDecl(*I); 1541 IdResolver.RemoveDecl(*I); 1542 1543 // Should only need to replace one decl. 1544 break; 1545 } 1546 } 1547 1548 S->AddDecl(D); 1549 1550 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1551 // Implicitly-generated labels may end up getting generated in an order that 1552 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1553 // the label at the appropriate place in the identifier chain. 1554 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1555 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1556 if (IDC == CurContext) { 1557 if (!S->isDeclScope(*I)) 1558 continue; 1559 } else if (IDC->Encloses(CurContext)) 1560 break; 1561 } 1562 1563 IdResolver.InsertDeclAfter(I, D); 1564 } else { 1565 IdResolver.AddDecl(D); 1566 } 1567 warnOnReservedIdentifier(D); 1568 } 1569 1570 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1571 bool AllowInlineNamespace) { 1572 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1573 } 1574 1575 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1576 DeclContext *TargetDC = DC->getPrimaryContext(); 1577 do { 1578 if (DeclContext *ScopeDC = S->getEntity()) 1579 if (ScopeDC->getPrimaryContext() == TargetDC) 1580 return S; 1581 } while ((S = S->getParent())); 1582 1583 return nullptr; 1584 } 1585 1586 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1587 DeclContext*, 1588 ASTContext&); 1589 1590 /// Filters out lookup results that don't fall within the given scope 1591 /// as determined by isDeclInScope. 1592 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1593 bool ConsiderLinkage, 1594 bool AllowInlineNamespace) { 1595 LookupResult::Filter F = R.makeFilter(); 1596 while (F.hasNext()) { 1597 NamedDecl *D = F.next(); 1598 1599 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1600 continue; 1601 1602 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1603 continue; 1604 1605 F.erase(); 1606 } 1607 1608 F.done(); 1609 } 1610 1611 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1612 /// have compatible owning modules. 1613 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1614 // [module.interface]p7: 1615 // A declaration is attached to a module as follows: 1616 // - If the declaration is a non-dependent friend declaration that nominates a 1617 // function with a declarator-id that is a qualified-id or template-id or that 1618 // nominates a class other than with an elaborated-type-specifier with neither 1619 // a nested-name-specifier nor a simple-template-id, it is attached to the 1620 // module to which the friend is attached ([basic.link]). 1621 if (New->getFriendObjectKind() && 1622 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1623 New->setLocalOwningModule(Old->getOwningModule()); 1624 makeMergedDefinitionVisible(New); 1625 return false; 1626 } 1627 1628 Module *NewM = New->getOwningModule(); 1629 Module *OldM = Old->getOwningModule(); 1630 1631 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1632 NewM = NewM->Parent; 1633 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1634 OldM = OldM->Parent; 1635 1636 // If we have a decl in a module partition, it is part of the containing 1637 // module (which is the only thing that can be importing it). 1638 if (NewM && OldM && 1639 (OldM->Kind == Module::ModulePartitionInterface || 1640 OldM->Kind == Module::ModulePartitionImplementation)) { 1641 return false; 1642 } 1643 1644 if (NewM == OldM) 1645 return false; 1646 1647 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1648 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1649 if (NewIsModuleInterface || OldIsModuleInterface) { 1650 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1651 // if a declaration of D [...] appears in the purview of a module, all 1652 // other such declarations shall appear in the purview of the same module 1653 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1654 << New 1655 << NewIsModuleInterface 1656 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1657 << OldIsModuleInterface 1658 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1659 Diag(Old->getLocation(), diag::note_previous_declaration); 1660 New->setInvalidDecl(); 1661 return true; 1662 } 1663 1664 return false; 1665 } 1666 1667 // [module.interface]p6: 1668 // A redeclaration of an entity X is implicitly exported if X was introduced by 1669 // an exported declaration; otherwise it shall not be exported. 1670 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { 1671 // [module.interface]p1: 1672 // An export-declaration shall inhabit a namespace scope. 1673 // 1674 // So it is meaningless to talk about redeclaration which is not at namespace 1675 // scope. 1676 if (!New->getLexicalDeclContext() 1677 ->getNonTransparentContext() 1678 ->isFileContext() || 1679 !Old->getLexicalDeclContext() 1680 ->getNonTransparentContext() 1681 ->isFileContext()) 1682 return false; 1683 1684 bool IsNewExported = New->isInExportDeclContext(); 1685 bool IsOldExported = Old->isInExportDeclContext(); 1686 1687 // It should be irrevelant if both of them are not exported. 1688 if (!IsNewExported && !IsOldExported) 1689 return false; 1690 1691 if (IsOldExported) 1692 return false; 1693 1694 assert(IsNewExported); 1695 1696 auto Lk = Old->getFormalLinkage(); 1697 int S = 0; 1698 if (Lk == Linkage::InternalLinkage) 1699 S = 1; 1700 else if (Lk == Linkage::ModuleLinkage) 1701 S = 2; 1702 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S; 1703 Diag(Old->getLocation(), diag::note_previous_declaration); 1704 return true; 1705 } 1706 1707 // A wrapper function for checking the semantic restrictions of 1708 // a redeclaration within a module. 1709 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1710 if (CheckRedeclarationModuleOwnership(New, Old)) 1711 return true; 1712 1713 if (CheckRedeclarationExported(New, Old)) 1714 return true; 1715 1716 return false; 1717 } 1718 1719 static bool isUsingDecl(NamedDecl *D) { 1720 return isa<UsingShadowDecl>(D) || 1721 isa<UnresolvedUsingTypenameDecl>(D) || 1722 isa<UnresolvedUsingValueDecl>(D); 1723 } 1724 1725 /// Removes using shadow declarations from the lookup results. 1726 static void RemoveUsingDecls(LookupResult &R) { 1727 LookupResult::Filter F = R.makeFilter(); 1728 while (F.hasNext()) 1729 if (isUsingDecl(F.next())) 1730 F.erase(); 1731 1732 F.done(); 1733 } 1734 1735 /// Check for this common pattern: 1736 /// @code 1737 /// class S { 1738 /// S(const S&); // DO NOT IMPLEMENT 1739 /// void operator=(const S&); // DO NOT IMPLEMENT 1740 /// }; 1741 /// @endcode 1742 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1743 // FIXME: Should check for private access too but access is set after we get 1744 // the decl here. 1745 if (D->doesThisDeclarationHaveABody()) 1746 return false; 1747 1748 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1749 return CD->isCopyConstructor(); 1750 return D->isCopyAssignmentOperator(); 1751 } 1752 1753 // We need this to handle 1754 // 1755 // typedef struct { 1756 // void *foo() { return 0; } 1757 // } A; 1758 // 1759 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1760 // for example. If 'A', foo will have external linkage. If we have '*A', 1761 // foo will have no linkage. Since we can't know until we get to the end 1762 // of the typedef, this function finds out if D might have non-external linkage. 1763 // Callers should verify at the end of the TU if it D has external linkage or 1764 // not. 1765 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1766 const DeclContext *DC = D->getDeclContext(); 1767 while (!DC->isTranslationUnit()) { 1768 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1769 if (!RD->hasNameForLinkage()) 1770 return true; 1771 } 1772 DC = DC->getParent(); 1773 } 1774 1775 return !D->isExternallyVisible(); 1776 } 1777 1778 // FIXME: This needs to be refactored; some other isInMainFile users want 1779 // these semantics. 1780 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1781 if (S.TUKind != TU_Complete) 1782 return false; 1783 return S.SourceMgr.isInMainFile(Loc); 1784 } 1785 1786 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1787 assert(D); 1788 1789 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1790 return false; 1791 1792 // Ignore all entities declared within templates, and out-of-line definitions 1793 // of members of class templates. 1794 if (D->getDeclContext()->isDependentContext() || 1795 D->getLexicalDeclContext()->isDependentContext()) 1796 return false; 1797 1798 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1799 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1800 return false; 1801 // A non-out-of-line declaration of a member specialization was implicitly 1802 // instantiated; it's the out-of-line declaration that we're interested in. 1803 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1804 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1805 return false; 1806 1807 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1808 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1809 return false; 1810 } else { 1811 // 'static inline' functions are defined in headers; don't warn. 1812 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1813 return false; 1814 } 1815 1816 if (FD->doesThisDeclarationHaveABody() && 1817 Context.DeclMustBeEmitted(FD)) 1818 return false; 1819 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1820 // Constants and utility variables are defined in headers with internal 1821 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1822 // like "inline".) 1823 if (!isMainFileLoc(*this, VD->getLocation())) 1824 return false; 1825 1826 if (Context.DeclMustBeEmitted(VD)) 1827 return false; 1828 1829 if (VD->isStaticDataMember() && 1830 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1831 return false; 1832 if (VD->isStaticDataMember() && 1833 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1834 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1835 return false; 1836 1837 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1838 return false; 1839 } else { 1840 return false; 1841 } 1842 1843 // Only warn for unused decls internal to the translation unit. 1844 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1845 // for inline functions defined in the main source file, for instance. 1846 return mightHaveNonExternalLinkage(D); 1847 } 1848 1849 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1850 if (!D) 1851 return; 1852 1853 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1854 const FunctionDecl *First = FD->getFirstDecl(); 1855 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1856 return; // First should already be in the vector. 1857 } 1858 1859 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1860 const VarDecl *First = VD->getFirstDecl(); 1861 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1862 return; // First should already be in the vector. 1863 } 1864 1865 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1866 UnusedFileScopedDecls.push_back(D); 1867 } 1868 1869 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1870 if (D->isInvalidDecl()) 1871 return false; 1872 1873 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1874 // For a decomposition declaration, warn if none of the bindings are 1875 // referenced, instead of if the variable itself is referenced (which 1876 // it is, by the bindings' expressions). 1877 for (auto *BD : DD->bindings()) 1878 if (BD->isReferenced()) 1879 return false; 1880 } else if (!D->getDeclName()) { 1881 return false; 1882 } else if (D->isReferenced() || D->isUsed()) { 1883 return false; 1884 } 1885 1886 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1887 return false; 1888 1889 if (isa<LabelDecl>(D)) 1890 return true; 1891 1892 // Except for labels, we only care about unused decls that are local to 1893 // functions. 1894 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1895 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1896 // For dependent types, the diagnostic is deferred. 1897 WithinFunction = 1898 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1899 if (!WithinFunction) 1900 return false; 1901 1902 if (isa<TypedefNameDecl>(D)) 1903 return true; 1904 1905 // White-list anything that isn't a local variable. 1906 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1907 return false; 1908 1909 // Types of valid local variables should be complete, so this should succeed. 1910 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1911 1912 const Expr *Init = VD->getInit(); 1913 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init)) 1914 Init = Cleanups->getSubExpr(); 1915 1916 const auto *Ty = VD->getType().getTypePtr(); 1917 1918 // Only look at the outermost level of typedef. 1919 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1920 // Allow anything marked with __attribute__((unused)). 1921 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1922 return false; 1923 } 1924 1925 // Warn for reference variables whose initializtion performs lifetime 1926 // extension. 1927 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) { 1928 if (MTE->getExtendingDecl()) { 1929 Ty = VD->getType().getNonReferenceType().getTypePtr(); 1930 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten(); 1931 } 1932 } 1933 1934 // If we failed to complete the type for some reason, or if the type is 1935 // dependent, don't diagnose the variable. 1936 if (Ty->isIncompleteType() || Ty->isDependentType()) 1937 return false; 1938 1939 // Look at the element type to ensure that the warning behaviour is 1940 // consistent for both scalars and arrays. 1941 Ty = Ty->getBaseElementTypeUnsafe(); 1942 1943 if (const TagType *TT = Ty->getAs<TagType>()) { 1944 const TagDecl *Tag = TT->getDecl(); 1945 if (Tag->hasAttr<UnusedAttr>()) 1946 return false; 1947 1948 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1949 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1950 return false; 1951 1952 if (Init) { 1953 const CXXConstructExpr *Construct = 1954 dyn_cast<CXXConstructExpr>(Init); 1955 if (Construct && !Construct->isElidable()) { 1956 CXXConstructorDecl *CD = Construct->getConstructor(); 1957 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1958 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1959 return false; 1960 } 1961 1962 // Suppress the warning if we don't know how this is constructed, and 1963 // it could possibly be non-trivial constructor. 1964 if (Init->isTypeDependent()) { 1965 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1966 if (!Ctor->isTrivial()) 1967 return false; 1968 } 1969 1970 // Suppress the warning if the constructor is unresolved because 1971 // its arguments are dependent. 1972 if (isa<CXXUnresolvedConstructExpr>(Init)) 1973 return false; 1974 } 1975 } 1976 } 1977 1978 // TODO: __attribute__((unused)) templates? 1979 } 1980 1981 return true; 1982 } 1983 1984 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1985 FixItHint &Hint) { 1986 if (isa<LabelDecl>(D)) { 1987 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1988 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1989 true); 1990 if (AfterColon.isInvalid()) 1991 return; 1992 Hint = FixItHint::CreateRemoval( 1993 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1994 } 1995 } 1996 1997 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1998 if (D->getTypeForDecl()->isDependentType()) 1999 return; 2000 2001 for (auto *TmpD : D->decls()) { 2002 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 2003 DiagnoseUnusedDecl(T); 2004 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 2005 DiagnoseUnusedNestedTypedefs(R); 2006 } 2007 } 2008 2009 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 2010 /// unless they are marked attr(unused). 2011 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 2012 if (!ShouldDiagnoseUnusedDecl(D)) 2013 return; 2014 2015 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2016 // typedefs can be referenced later on, so the diagnostics are emitted 2017 // at end-of-translation-unit. 2018 UnusedLocalTypedefNameCandidates.insert(TD); 2019 return; 2020 } 2021 2022 FixItHint Hint; 2023 GenerateFixForUnusedDecl(D, Context, Hint); 2024 2025 unsigned DiagID; 2026 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 2027 DiagID = diag::warn_unused_exception_param; 2028 else if (isa<LabelDecl>(D)) 2029 DiagID = diag::warn_unused_label; 2030 else 2031 DiagID = diag::warn_unused_variable; 2032 2033 Diag(D->getLocation(), DiagID) << D << Hint; 2034 } 2035 2036 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 2037 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 2038 // it's not really unused. 2039 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 2040 VD->hasAttr<CleanupAttr>()) 2041 return; 2042 2043 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 2044 2045 if (Ty->isReferenceType() || Ty->isDependentType()) 2046 return; 2047 2048 if (const TagType *TT = Ty->getAs<TagType>()) { 2049 const TagDecl *Tag = TT->getDecl(); 2050 if (Tag->hasAttr<UnusedAttr>()) 2051 return; 2052 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 2053 // mimic gcc's behavior. 2054 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 2055 if (!RD->hasAttr<WarnUnusedAttr>()) 2056 return; 2057 } 2058 } 2059 2060 // Don't warn about __block Objective-C pointer variables, as they might 2061 // be assigned in the block but not used elsewhere for the purpose of lifetime 2062 // extension. 2063 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 2064 return; 2065 2066 // Don't warn about Objective-C pointer variables with precise lifetime 2067 // semantics; they can be used to ensure ARC releases the object at a known 2068 // time, which may mean assignment but no other references. 2069 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) 2070 return; 2071 2072 auto iter = RefsMinusAssignments.find(VD); 2073 if (iter == RefsMinusAssignments.end()) 2074 return; 2075 2076 assert(iter->getSecond() >= 0 && 2077 "Found a negative number of references to a VarDecl"); 2078 if (iter->getSecond() != 0) 2079 return; 2080 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2081 : diag::warn_unused_but_set_variable; 2082 Diag(VD->getLocation(), DiagID) << VD; 2083 } 2084 2085 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 2086 // Verify that we have no forward references left. If so, there was a goto 2087 // or address of a label taken, but no definition of it. Label fwd 2088 // definitions are indicated with a null substmt which is also not a resolved 2089 // MS inline assembly label name. 2090 bool Diagnose = false; 2091 if (L->isMSAsmLabel()) 2092 Diagnose = !L->isResolvedMSAsmLabel(); 2093 else 2094 Diagnose = L->getStmt() == nullptr; 2095 if (Diagnose) 2096 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 2097 } 2098 2099 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2100 S->mergeNRVOIntoParent(); 2101 2102 if (S->decl_empty()) return; 2103 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2104 "Scope shouldn't contain decls!"); 2105 2106 for (auto *TmpD : S->decls()) { 2107 assert(TmpD && "This decl didn't get pushed??"); 2108 2109 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2110 NamedDecl *D = cast<NamedDecl>(TmpD); 2111 2112 // Diagnose unused variables in this scope. 2113 if (!S->hasUnrecoverableErrorOccurred()) { 2114 DiagnoseUnusedDecl(D); 2115 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2116 DiagnoseUnusedNestedTypedefs(RD); 2117 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2118 DiagnoseUnusedButSetDecl(VD); 2119 RefsMinusAssignments.erase(VD); 2120 } 2121 } 2122 2123 if (!D->getDeclName()) continue; 2124 2125 // If this was a forward reference to a label, verify it was defined. 2126 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2127 CheckPoppedLabel(LD, *this); 2128 2129 // Remove this name from our lexical scope, and warn on it if we haven't 2130 // already. 2131 IdResolver.RemoveDecl(D); 2132 auto ShadowI = ShadowingDecls.find(D); 2133 if (ShadowI != ShadowingDecls.end()) { 2134 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2135 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2136 << D << FD << FD->getParent(); 2137 Diag(FD->getLocation(), diag::note_previous_declaration); 2138 } 2139 ShadowingDecls.erase(ShadowI); 2140 } 2141 } 2142 } 2143 2144 /// Look for an Objective-C class in the translation unit. 2145 /// 2146 /// \param Id The name of the Objective-C class we're looking for. If 2147 /// typo-correction fixes this name, the Id will be updated 2148 /// to the fixed name. 2149 /// 2150 /// \param IdLoc The location of the name in the translation unit. 2151 /// 2152 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2153 /// if there is no class with the given name. 2154 /// 2155 /// \returns The declaration of the named Objective-C class, or NULL if the 2156 /// class could not be found. 2157 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2158 SourceLocation IdLoc, 2159 bool DoTypoCorrection) { 2160 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2161 // creation from this context. 2162 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2163 2164 if (!IDecl && DoTypoCorrection) { 2165 // Perform typo correction at the given location, but only if we 2166 // find an Objective-C class name. 2167 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2168 if (TypoCorrection C = 2169 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2170 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2171 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2172 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2173 Id = IDecl->getIdentifier(); 2174 } 2175 } 2176 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2177 // This routine must always return a class definition, if any. 2178 if (Def && Def->getDefinition()) 2179 Def = Def->getDefinition(); 2180 return Def; 2181 } 2182 2183 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2184 /// from S, where a non-field would be declared. This routine copes 2185 /// with the difference between C and C++ scoping rules in structs and 2186 /// unions. For example, the following code is well-formed in C but 2187 /// ill-formed in C++: 2188 /// @code 2189 /// struct S6 { 2190 /// enum { BAR } e; 2191 /// }; 2192 /// 2193 /// void test_S6() { 2194 /// struct S6 a; 2195 /// a.e = BAR; 2196 /// } 2197 /// @endcode 2198 /// For the declaration of BAR, this routine will return a different 2199 /// scope. The scope S will be the scope of the unnamed enumeration 2200 /// within S6. In C++, this routine will return the scope associated 2201 /// with S6, because the enumeration's scope is a transparent 2202 /// context but structures can contain non-field names. In C, this 2203 /// routine will return the translation unit scope, since the 2204 /// enumeration's scope is a transparent context and structures cannot 2205 /// contain non-field names. 2206 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2207 while (((S->getFlags() & Scope::DeclScope) == 0) || 2208 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2209 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2210 S = S->getParent(); 2211 return S; 2212 } 2213 2214 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2215 ASTContext::GetBuiltinTypeError Error) { 2216 switch (Error) { 2217 case ASTContext::GE_None: 2218 return ""; 2219 case ASTContext::GE_Missing_type: 2220 return BuiltinInfo.getHeaderName(ID); 2221 case ASTContext::GE_Missing_stdio: 2222 return "stdio.h"; 2223 case ASTContext::GE_Missing_setjmp: 2224 return "setjmp.h"; 2225 case ASTContext::GE_Missing_ucontext: 2226 return "ucontext.h"; 2227 } 2228 llvm_unreachable("unhandled error kind"); 2229 } 2230 2231 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2232 unsigned ID, SourceLocation Loc) { 2233 DeclContext *Parent = Context.getTranslationUnitDecl(); 2234 2235 if (getLangOpts().CPlusPlus) { 2236 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2237 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2238 CLinkageDecl->setImplicit(); 2239 Parent->addDecl(CLinkageDecl); 2240 Parent = CLinkageDecl; 2241 } 2242 2243 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2244 /*TInfo=*/nullptr, SC_Extern, 2245 getCurFPFeatures().isFPConstrained(), 2246 false, Type->isFunctionProtoType()); 2247 New->setImplicit(); 2248 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2249 2250 // Create Decl objects for each parameter, adding them to the 2251 // FunctionDecl. 2252 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2253 SmallVector<ParmVarDecl *, 16> Params; 2254 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2255 ParmVarDecl *parm = ParmVarDecl::Create( 2256 Context, New, SourceLocation(), SourceLocation(), nullptr, 2257 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2258 parm->setScopeInfo(0, i); 2259 Params.push_back(parm); 2260 } 2261 New->setParams(Params); 2262 } 2263 2264 AddKnownFunctionAttributes(New); 2265 return New; 2266 } 2267 2268 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2269 /// file scope. lazily create a decl for it. ForRedeclaration is true 2270 /// if we're creating this built-in in anticipation of redeclaring the 2271 /// built-in. 2272 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2273 Scope *S, bool ForRedeclaration, 2274 SourceLocation Loc) { 2275 LookupNecessaryTypesForBuiltin(S, ID); 2276 2277 ASTContext::GetBuiltinTypeError Error; 2278 QualType R = Context.GetBuiltinType(ID, Error); 2279 if (Error) { 2280 if (!ForRedeclaration) 2281 return nullptr; 2282 2283 // If we have a builtin without an associated type we should not emit a 2284 // warning when we were not able to find a type for it. 2285 if (Error == ASTContext::GE_Missing_type || 2286 Context.BuiltinInfo.allowTypeMismatch(ID)) 2287 return nullptr; 2288 2289 // If we could not find a type for setjmp it is because the jmp_buf type was 2290 // not defined prior to the setjmp declaration. 2291 if (Error == ASTContext::GE_Missing_setjmp) { 2292 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2293 << Context.BuiltinInfo.getName(ID); 2294 return nullptr; 2295 } 2296 2297 // Generally, we emit a warning that the declaration requires the 2298 // appropriate header. 2299 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2300 << getHeaderName(Context.BuiltinInfo, ID, Error) 2301 << Context.BuiltinInfo.getName(ID); 2302 return nullptr; 2303 } 2304 2305 if (!ForRedeclaration && 2306 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2307 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2308 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99 2309 : diag::ext_implicit_lib_function_decl) 2310 << Context.BuiltinInfo.getName(ID) << R; 2311 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2312 Diag(Loc, diag::note_include_header_or_declare) 2313 << Header << Context.BuiltinInfo.getName(ID); 2314 } 2315 2316 if (R.isNull()) 2317 return nullptr; 2318 2319 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2320 RegisterLocallyScopedExternCDecl(New, S); 2321 2322 // TUScope is the translation-unit scope to insert this function into. 2323 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2324 // relate Scopes to DeclContexts, and probably eliminate CurContext 2325 // entirely, but we're not there yet. 2326 DeclContext *SavedContext = CurContext; 2327 CurContext = New->getDeclContext(); 2328 PushOnScopeChains(New, TUScope); 2329 CurContext = SavedContext; 2330 return New; 2331 } 2332 2333 /// Typedef declarations don't have linkage, but they still denote the same 2334 /// entity if their types are the same. 2335 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2336 /// isSameEntity. 2337 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2338 TypedefNameDecl *Decl, 2339 LookupResult &Previous) { 2340 // This is only interesting when modules are enabled. 2341 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2342 return; 2343 2344 // Empty sets are uninteresting. 2345 if (Previous.empty()) 2346 return; 2347 2348 LookupResult::Filter Filter = Previous.makeFilter(); 2349 while (Filter.hasNext()) { 2350 NamedDecl *Old = Filter.next(); 2351 2352 // Non-hidden declarations are never ignored. 2353 if (S.isVisible(Old)) 2354 continue; 2355 2356 // Declarations of the same entity are not ignored, even if they have 2357 // different linkages. 2358 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2359 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2360 Decl->getUnderlyingType())) 2361 continue; 2362 2363 // If both declarations give a tag declaration a typedef name for linkage 2364 // purposes, then they declare the same entity. 2365 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2366 Decl->getAnonDeclWithTypedefName()) 2367 continue; 2368 } 2369 2370 Filter.erase(); 2371 } 2372 2373 Filter.done(); 2374 } 2375 2376 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2377 QualType OldType; 2378 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2379 OldType = OldTypedef->getUnderlyingType(); 2380 else 2381 OldType = Context.getTypeDeclType(Old); 2382 QualType NewType = New->getUnderlyingType(); 2383 2384 if (NewType->isVariablyModifiedType()) { 2385 // Must not redefine a typedef with a variably-modified type. 2386 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2387 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2388 << Kind << NewType; 2389 if (Old->getLocation().isValid()) 2390 notePreviousDefinition(Old, New->getLocation()); 2391 New->setInvalidDecl(); 2392 return true; 2393 } 2394 2395 if (OldType != NewType && 2396 !OldType->isDependentType() && 2397 !NewType->isDependentType() && 2398 !Context.hasSameType(OldType, NewType)) { 2399 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2400 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2401 << Kind << NewType << OldType; 2402 if (Old->getLocation().isValid()) 2403 notePreviousDefinition(Old, New->getLocation()); 2404 New->setInvalidDecl(); 2405 return true; 2406 } 2407 return false; 2408 } 2409 2410 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2411 /// same name and scope as a previous declaration 'Old'. Figure out 2412 /// how to resolve this situation, merging decls or emitting 2413 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2414 /// 2415 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2416 LookupResult &OldDecls) { 2417 // If the new decl is known invalid already, don't bother doing any 2418 // merging checks. 2419 if (New->isInvalidDecl()) return; 2420 2421 // Allow multiple definitions for ObjC built-in typedefs. 2422 // FIXME: Verify the underlying types are equivalent! 2423 if (getLangOpts().ObjC) { 2424 const IdentifierInfo *TypeID = New->getIdentifier(); 2425 switch (TypeID->getLength()) { 2426 default: break; 2427 case 2: 2428 { 2429 if (!TypeID->isStr("id")) 2430 break; 2431 QualType T = New->getUnderlyingType(); 2432 if (!T->isPointerType()) 2433 break; 2434 if (!T->isVoidPointerType()) { 2435 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2436 if (!PT->isStructureType()) 2437 break; 2438 } 2439 Context.setObjCIdRedefinitionType(T); 2440 // Install the built-in type for 'id', ignoring the current definition. 2441 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2442 return; 2443 } 2444 case 5: 2445 if (!TypeID->isStr("Class")) 2446 break; 2447 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2448 // Install the built-in type for 'Class', ignoring the current definition. 2449 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2450 return; 2451 case 3: 2452 if (!TypeID->isStr("SEL")) 2453 break; 2454 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2455 // Install the built-in type for 'SEL', ignoring the current definition. 2456 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2457 return; 2458 } 2459 // Fall through - the typedef name was not a builtin type. 2460 } 2461 2462 // Verify the old decl was also a type. 2463 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2464 if (!Old) { 2465 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2466 << New->getDeclName(); 2467 2468 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2469 if (OldD->getLocation().isValid()) 2470 notePreviousDefinition(OldD, New->getLocation()); 2471 2472 return New->setInvalidDecl(); 2473 } 2474 2475 // If the old declaration is invalid, just give up here. 2476 if (Old->isInvalidDecl()) 2477 return New->setInvalidDecl(); 2478 2479 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2480 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2481 auto *NewTag = New->getAnonDeclWithTypedefName(); 2482 NamedDecl *Hidden = nullptr; 2483 if (OldTag && NewTag && 2484 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2485 !hasVisibleDefinition(OldTag, &Hidden)) { 2486 // There is a definition of this tag, but it is not visible. Use it 2487 // instead of our tag. 2488 New->setTypeForDecl(OldTD->getTypeForDecl()); 2489 if (OldTD->isModed()) 2490 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2491 OldTD->getUnderlyingType()); 2492 else 2493 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2494 2495 // Make the old tag definition visible. 2496 makeMergedDefinitionVisible(Hidden); 2497 2498 // If this was an unscoped enumeration, yank all of its enumerators 2499 // out of the scope. 2500 if (isa<EnumDecl>(NewTag)) { 2501 Scope *EnumScope = getNonFieldDeclScope(S); 2502 for (auto *D : NewTag->decls()) { 2503 auto *ED = cast<EnumConstantDecl>(D); 2504 assert(EnumScope->isDeclScope(ED)); 2505 EnumScope->RemoveDecl(ED); 2506 IdResolver.RemoveDecl(ED); 2507 ED->getLexicalDeclContext()->removeDecl(ED); 2508 } 2509 } 2510 } 2511 } 2512 2513 // If the typedef types are not identical, reject them in all languages and 2514 // with any extensions enabled. 2515 if (isIncompatibleTypedef(Old, New)) 2516 return; 2517 2518 // The types match. Link up the redeclaration chain and merge attributes if 2519 // the old declaration was a typedef. 2520 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2521 New->setPreviousDecl(Typedef); 2522 mergeDeclAttributes(New, Old); 2523 } 2524 2525 if (getLangOpts().MicrosoftExt) 2526 return; 2527 2528 if (getLangOpts().CPlusPlus) { 2529 // C++ [dcl.typedef]p2: 2530 // In a given non-class scope, a typedef specifier can be used to 2531 // redefine the name of any type declared in that scope to refer 2532 // to the type to which it already refers. 2533 if (!isa<CXXRecordDecl>(CurContext)) 2534 return; 2535 2536 // C++0x [dcl.typedef]p4: 2537 // In a given class scope, a typedef specifier can be used to redefine 2538 // any class-name declared in that scope that is not also a typedef-name 2539 // to refer to the type to which it already refers. 2540 // 2541 // This wording came in via DR424, which was a correction to the 2542 // wording in DR56, which accidentally banned code like: 2543 // 2544 // struct S { 2545 // typedef struct A { } A; 2546 // }; 2547 // 2548 // in the C++03 standard. We implement the C++0x semantics, which 2549 // allow the above but disallow 2550 // 2551 // struct S { 2552 // typedef int I; 2553 // typedef int I; 2554 // }; 2555 // 2556 // since that was the intent of DR56. 2557 if (!isa<TypedefNameDecl>(Old)) 2558 return; 2559 2560 Diag(New->getLocation(), diag::err_redefinition) 2561 << New->getDeclName(); 2562 notePreviousDefinition(Old, New->getLocation()); 2563 return New->setInvalidDecl(); 2564 } 2565 2566 // Modules always permit redefinition of typedefs, as does C11. 2567 if (getLangOpts().Modules || getLangOpts().C11) 2568 return; 2569 2570 // If we have a redefinition of a typedef in C, emit a warning. This warning 2571 // is normally mapped to an error, but can be controlled with 2572 // -Wtypedef-redefinition. If either the original or the redefinition is 2573 // in a system header, don't emit this for compatibility with GCC. 2574 if (getDiagnostics().getSuppressSystemWarnings() && 2575 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2576 (Old->isImplicit() || 2577 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2578 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2579 return; 2580 2581 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2582 << New->getDeclName(); 2583 notePreviousDefinition(Old, New->getLocation()); 2584 } 2585 2586 /// DeclhasAttr - returns true if decl Declaration already has the target 2587 /// attribute. 2588 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2589 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2590 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2591 for (const auto *i : D->attrs()) 2592 if (i->getKind() == A->getKind()) { 2593 if (Ann) { 2594 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2595 return true; 2596 continue; 2597 } 2598 // FIXME: Don't hardcode this check 2599 if (OA && isa<OwnershipAttr>(i)) 2600 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2601 return true; 2602 } 2603 2604 return false; 2605 } 2606 2607 static bool isAttributeTargetADefinition(Decl *D) { 2608 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2609 return VD->isThisDeclarationADefinition(); 2610 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2611 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2612 return true; 2613 } 2614 2615 /// Merge alignment attributes from \p Old to \p New, taking into account the 2616 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2617 /// 2618 /// \return \c true if any attributes were added to \p New. 2619 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2620 // Look for alignas attributes on Old, and pick out whichever attribute 2621 // specifies the strictest alignment requirement. 2622 AlignedAttr *OldAlignasAttr = nullptr; 2623 AlignedAttr *OldStrictestAlignAttr = nullptr; 2624 unsigned OldAlign = 0; 2625 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2626 // FIXME: We have no way of representing inherited dependent alignments 2627 // in a case like: 2628 // template<int A, int B> struct alignas(A) X; 2629 // template<int A, int B> struct alignas(B) X {}; 2630 // For now, we just ignore any alignas attributes which are not on the 2631 // definition in such a case. 2632 if (I->isAlignmentDependent()) 2633 return false; 2634 2635 if (I->isAlignas()) 2636 OldAlignasAttr = I; 2637 2638 unsigned Align = I->getAlignment(S.Context); 2639 if (Align > OldAlign) { 2640 OldAlign = Align; 2641 OldStrictestAlignAttr = I; 2642 } 2643 } 2644 2645 // Look for alignas attributes on New. 2646 AlignedAttr *NewAlignasAttr = nullptr; 2647 unsigned NewAlign = 0; 2648 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2649 if (I->isAlignmentDependent()) 2650 return false; 2651 2652 if (I->isAlignas()) 2653 NewAlignasAttr = I; 2654 2655 unsigned Align = I->getAlignment(S.Context); 2656 if (Align > NewAlign) 2657 NewAlign = Align; 2658 } 2659 2660 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2661 // Both declarations have 'alignas' attributes. We require them to match. 2662 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2663 // fall short. (If two declarations both have alignas, they must both match 2664 // every definition, and so must match each other if there is a definition.) 2665 2666 // If either declaration only contains 'alignas(0)' specifiers, then it 2667 // specifies the natural alignment for the type. 2668 if (OldAlign == 0 || NewAlign == 0) { 2669 QualType Ty; 2670 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2671 Ty = VD->getType(); 2672 else 2673 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2674 2675 if (OldAlign == 0) 2676 OldAlign = S.Context.getTypeAlign(Ty); 2677 if (NewAlign == 0) 2678 NewAlign = S.Context.getTypeAlign(Ty); 2679 } 2680 2681 if (OldAlign != NewAlign) { 2682 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2683 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2684 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2685 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2686 } 2687 } 2688 2689 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2690 // C++11 [dcl.align]p6: 2691 // if any declaration of an entity has an alignment-specifier, 2692 // every defining declaration of that entity shall specify an 2693 // equivalent alignment. 2694 // C11 6.7.5/7: 2695 // If the definition of an object does not have an alignment 2696 // specifier, any other declaration of that object shall also 2697 // have no alignment specifier. 2698 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2699 << OldAlignasAttr; 2700 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2701 << OldAlignasAttr; 2702 } 2703 2704 bool AnyAdded = false; 2705 2706 // Ensure we have an attribute representing the strictest alignment. 2707 if (OldAlign > NewAlign) { 2708 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2709 Clone->setInherited(true); 2710 New->addAttr(Clone); 2711 AnyAdded = true; 2712 } 2713 2714 // Ensure we have an alignas attribute if the old declaration had one. 2715 if (OldAlignasAttr && !NewAlignasAttr && 2716 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2717 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2718 Clone->setInherited(true); 2719 New->addAttr(Clone); 2720 AnyAdded = true; 2721 } 2722 2723 return AnyAdded; 2724 } 2725 2726 #define WANT_DECL_MERGE_LOGIC 2727 #include "clang/Sema/AttrParsedAttrImpl.inc" 2728 #undef WANT_DECL_MERGE_LOGIC 2729 2730 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2731 const InheritableAttr *Attr, 2732 Sema::AvailabilityMergeKind AMK) { 2733 // Diagnose any mutual exclusions between the attribute that we want to add 2734 // and attributes that already exist on the declaration. 2735 if (!DiagnoseMutualExclusions(S, D, Attr)) 2736 return false; 2737 2738 // This function copies an attribute Attr from a previous declaration to the 2739 // new declaration D if the new declaration doesn't itself have that attribute 2740 // yet or if that attribute allows duplicates. 2741 // If you're adding a new attribute that requires logic different from 2742 // "use explicit attribute on decl if present, else use attribute from 2743 // previous decl", for example if the attribute needs to be consistent 2744 // between redeclarations, you need to call a custom merge function here. 2745 InheritableAttr *NewAttr = nullptr; 2746 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2747 NewAttr = S.mergeAvailabilityAttr( 2748 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2749 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2750 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2751 AA->getPriority()); 2752 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2753 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2754 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2755 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2756 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2757 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2758 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2759 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2760 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2761 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2762 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2763 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2764 FA->getFirstArg()); 2765 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2766 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2767 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2768 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2769 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2770 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2771 IA->getInheritanceModel()); 2772 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2773 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2774 &S.Context.Idents.get(AA->getSpelling())); 2775 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2776 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2777 isa<CUDAGlobalAttr>(Attr))) { 2778 // CUDA target attributes are part of function signature for 2779 // overloading purposes and must not be merged. 2780 return false; 2781 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2782 NewAttr = S.mergeMinSizeAttr(D, *MA); 2783 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2784 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2785 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2786 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2787 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2788 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2789 else if (isa<AlignedAttr>(Attr)) 2790 // AlignedAttrs are handled separately, because we need to handle all 2791 // such attributes on a declaration at the same time. 2792 NewAttr = nullptr; 2793 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2794 (AMK == Sema::AMK_Override || 2795 AMK == Sema::AMK_ProtocolImplementation || 2796 AMK == Sema::AMK_OptionalProtocolImplementation)) 2797 NewAttr = nullptr; 2798 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2799 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2800 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2801 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2802 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2803 NewAttr = S.mergeImportNameAttr(D, *INA); 2804 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2805 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2806 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2807 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2808 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2809 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2810 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr)) 2811 NewAttr = 2812 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ()); 2813 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2814 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2815 2816 if (NewAttr) { 2817 NewAttr->setInherited(true); 2818 D->addAttr(NewAttr); 2819 if (isa<MSInheritanceAttr>(NewAttr)) 2820 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2821 return true; 2822 } 2823 2824 return false; 2825 } 2826 2827 static const NamedDecl *getDefinition(const Decl *D) { 2828 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2829 return TD->getDefinition(); 2830 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2831 const VarDecl *Def = VD->getDefinition(); 2832 if (Def) 2833 return Def; 2834 return VD->getActingDefinition(); 2835 } 2836 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2837 const FunctionDecl *Def = nullptr; 2838 if (FD->isDefined(Def, true)) 2839 return Def; 2840 } 2841 return nullptr; 2842 } 2843 2844 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2845 for (const auto *Attribute : D->attrs()) 2846 if (Attribute->getKind() == Kind) 2847 return true; 2848 return false; 2849 } 2850 2851 /// checkNewAttributesAfterDef - If we already have a definition, check that 2852 /// there are no new attributes in this declaration. 2853 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2854 if (!New->hasAttrs()) 2855 return; 2856 2857 const NamedDecl *Def = getDefinition(Old); 2858 if (!Def || Def == New) 2859 return; 2860 2861 AttrVec &NewAttributes = New->getAttrs(); 2862 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2863 const Attr *NewAttribute = NewAttributes[I]; 2864 2865 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2866 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2867 Sema::SkipBodyInfo SkipBody; 2868 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2869 2870 // If we're skipping this definition, drop the "alias" attribute. 2871 if (SkipBody.ShouldSkip) { 2872 NewAttributes.erase(NewAttributes.begin() + I); 2873 --E; 2874 continue; 2875 } 2876 } else { 2877 VarDecl *VD = cast<VarDecl>(New); 2878 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2879 VarDecl::TentativeDefinition 2880 ? diag::err_alias_after_tentative 2881 : diag::err_redefinition; 2882 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2883 if (Diag == diag::err_redefinition) 2884 S.notePreviousDefinition(Def, VD->getLocation()); 2885 else 2886 S.Diag(Def->getLocation(), diag::note_previous_definition); 2887 VD->setInvalidDecl(); 2888 } 2889 ++I; 2890 continue; 2891 } 2892 2893 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2894 // Tentative definitions are only interesting for the alias check above. 2895 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2896 ++I; 2897 continue; 2898 } 2899 } 2900 2901 if (hasAttribute(Def, NewAttribute->getKind())) { 2902 ++I; 2903 continue; // regular attr merging will take care of validating this. 2904 } 2905 2906 if (isa<C11NoReturnAttr>(NewAttribute)) { 2907 // C's _Noreturn is allowed to be added to a function after it is defined. 2908 ++I; 2909 continue; 2910 } else if (isa<UuidAttr>(NewAttribute)) { 2911 // msvc will allow a subsequent definition to add an uuid to a class 2912 ++I; 2913 continue; 2914 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2915 if (AA->isAlignas()) { 2916 // C++11 [dcl.align]p6: 2917 // if any declaration of an entity has an alignment-specifier, 2918 // every defining declaration of that entity shall specify an 2919 // equivalent alignment. 2920 // C11 6.7.5/7: 2921 // If the definition of an object does not have an alignment 2922 // specifier, any other declaration of that object shall also 2923 // have no alignment specifier. 2924 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2925 << AA; 2926 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2927 << AA; 2928 NewAttributes.erase(NewAttributes.begin() + I); 2929 --E; 2930 continue; 2931 } 2932 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2933 // If there is a C definition followed by a redeclaration with this 2934 // attribute then there are two different definitions. In C++, prefer the 2935 // standard diagnostics. 2936 if (!S.getLangOpts().CPlusPlus) { 2937 S.Diag(NewAttribute->getLocation(), 2938 diag::err_loader_uninitialized_redeclaration); 2939 S.Diag(Def->getLocation(), diag::note_previous_definition); 2940 NewAttributes.erase(NewAttributes.begin() + I); 2941 --E; 2942 continue; 2943 } 2944 } else if (isa<SelectAnyAttr>(NewAttribute) && 2945 cast<VarDecl>(New)->isInline() && 2946 !cast<VarDecl>(New)->isInlineSpecified()) { 2947 // Don't warn about applying selectany to implicitly inline variables. 2948 // Older compilers and language modes would require the use of selectany 2949 // to make such variables inline, and it would have no effect if we 2950 // honored it. 2951 ++I; 2952 continue; 2953 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2954 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2955 // declarations after defintions. 2956 ++I; 2957 continue; 2958 } 2959 2960 S.Diag(NewAttribute->getLocation(), 2961 diag::warn_attribute_precede_definition); 2962 S.Diag(Def->getLocation(), diag::note_previous_definition); 2963 NewAttributes.erase(NewAttributes.begin() + I); 2964 --E; 2965 } 2966 } 2967 2968 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2969 const ConstInitAttr *CIAttr, 2970 bool AttrBeforeInit) { 2971 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2972 2973 // Figure out a good way to write this specifier on the old declaration. 2974 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2975 // enough of the attribute list spelling information to extract that without 2976 // heroics. 2977 std::string SuitableSpelling; 2978 if (S.getLangOpts().CPlusPlus20) 2979 SuitableSpelling = std::string( 2980 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2981 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2982 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2983 InsertLoc, {tok::l_square, tok::l_square, 2984 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2985 S.PP.getIdentifierInfo("require_constant_initialization"), 2986 tok::r_square, tok::r_square})); 2987 if (SuitableSpelling.empty()) 2988 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2989 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2990 S.PP.getIdentifierInfo("require_constant_initialization"), 2991 tok::r_paren, tok::r_paren})); 2992 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2993 SuitableSpelling = "constinit"; 2994 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2995 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2996 if (SuitableSpelling.empty()) 2997 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2998 SuitableSpelling += " "; 2999 3000 if (AttrBeforeInit) { 3001 // extern constinit int a; 3002 // int a = 0; // error (missing 'constinit'), accepted as extension 3003 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 3004 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 3005 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3006 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 3007 } else { 3008 // int a = 0; 3009 // constinit extern int a; // error (missing 'constinit') 3010 S.Diag(CIAttr->getLocation(), 3011 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 3012 : diag::warn_require_const_init_added_too_late) 3013 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 3014 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 3015 << CIAttr->isConstinit() 3016 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3017 } 3018 } 3019 3020 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 3021 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 3022 AvailabilityMergeKind AMK) { 3023 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 3024 UsedAttr *NewAttr = OldAttr->clone(Context); 3025 NewAttr->setInherited(true); 3026 New->addAttr(NewAttr); 3027 } 3028 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 3029 RetainAttr *NewAttr = OldAttr->clone(Context); 3030 NewAttr->setInherited(true); 3031 New->addAttr(NewAttr); 3032 } 3033 3034 if (!Old->hasAttrs() && !New->hasAttrs()) 3035 return; 3036 3037 // [dcl.constinit]p1: 3038 // If the [constinit] specifier is applied to any declaration of a 3039 // variable, it shall be applied to the initializing declaration. 3040 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 3041 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 3042 if (bool(OldConstInit) != bool(NewConstInit)) { 3043 const auto *OldVD = cast<VarDecl>(Old); 3044 auto *NewVD = cast<VarDecl>(New); 3045 3046 // Find the initializing declaration. Note that we might not have linked 3047 // the new declaration into the redeclaration chain yet. 3048 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 3049 if (!InitDecl && 3050 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 3051 InitDecl = NewVD; 3052 3053 if (InitDecl == NewVD) { 3054 // This is the initializing declaration. If it would inherit 'constinit', 3055 // that's ill-formed. (Note that we do not apply this to the attribute 3056 // form). 3057 if (OldConstInit && OldConstInit->isConstinit()) 3058 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 3059 /*AttrBeforeInit=*/true); 3060 } else if (NewConstInit) { 3061 // This is the first time we've been told that this declaration should 3062 // have a constant initializer. If we already saw the initializing 3063 // declaration, this is too late. 3064 if (InitDecl && InitDecl != NewVD) { 3065 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3066 /*AttrBeforeInit=*/false); 3067 NewVD->dropAttr<ConstInitAttr>(); 3068 } 3069 } 3070 } 3071 3072 // Attributes declared post-definition are currently ignored. 3073 checkNewAttributesAfterDef(*this, New, Old); 3074 3075 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3076 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3077 if (!OldA->isEquivalent(NewA)) { 3078 // This redeclaration changes __asm__ label. 3079 Diag(New->getLocation(), diag::err_different_asm_label); 3080 Diag(OldA->getLocation(), diag::note_previous_declaration); 3081 } 3082 } else if (Old->isUsed()) { 3083 // This redeclaration adds an __asm__ label to a declaration that has 3084 // already been ODR-used. 3085 Diag(New->getLocation(), diag::err_late_asm_label_name) 3086 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3087 } 3088 } 3089 3090 // Re-declaration cannot add abi_tag's. 3091 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3092 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3093 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3094 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3095 Diag(NewAbiTagAttr->getLocation(), 3096 diag::err_new_abi_tag_on_redeclaration) 3097 << NewTag; 3098 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3099 } 3100 } 3101 } else { 3102 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3103 Diag(Old->getLocation(), diag::note_previous_declaration); 3104 } 3105 } 3106 3107 // This redeclaration adds a section attribute. 3108 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3109 if (auto *VD = dyn_cast<VarDecl>(New)) { 3110 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3111 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3112 Diag(Old->getLocation(), diag::note_previous_declaration); 3113 } 3114 } 3115 } 3116 3117 // Redeclaration adds code-seg attribute. 3118 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3119 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3120 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3121 Diag(New->getLocation(), diag::warn_mismatched_section) 3122 << 0 /*codeseg*/; 3123 Diag(Old->getLocation(), diag::note_previous_declaration); 3124 } 3125 3126 if (!Old->hasAttrs()) 3127 return; 3128 3129 bool foundAny = New->hasAttrs(); 3130 3131 // Ensure that any moving of objects within the allocated map is done before 3132 // we process them. 3133 if (!foundAny) New->setAttrs(AttrVec()); 3134 3135 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3136 // Ignore deprecated/unavailable/availability attributes if requested. 3137 AvailabilityMergeKind LocalAMK = AMK_None; 3138 if (isa<DeprecatedAttr>(I) || 3139 isa<UnavailableAttr>(I) || 3140 isa<AvailabilityAttr>(I)) { 3141 switch (AMK) { 3142 case AMK_None: 3143 continue; 3144 3145 case AMK_Redeclaration: 3146 case AMK_Override: 3147 case AMK_ProtocolImplementation: 3148 case AMK_OptionalProtocolImplementation: 3149 LocalAMK = AMK; 3150 break; 3151 } 3152 } 3153 3154 // Already handled. 3155 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3156 continue; 3157 3158 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3159 foundAny = true; 3160 } 3161 3162 if (mergeAlignedAttrs(*this, New, Old)) 3163 foundAny = true; 3164 3165 if (!foundAny) New->dropAttrs(); 3166 } 3167 3168 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3169 /// to the new one. 3170 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3171 const ParmVarDecl *oldDecl, 3172 Sema &S) { 3173 // C++11 [dcl.attr.depend]p2: 3174 // The first declaration of a function shall specify the 3175 // carries_dependency attribute for its declarator-id if any declaration 3176 // of the function specifies the carries_dependency attribute. 3177 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3178 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3179 S.Diag(CDA->getLocation(), 3180 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3181 // Find the first declaration of the parameter. 3182 // FIXME: Should we build redeclaration chains for function parameters? 3183 const FunctionDecl *FirstFD = 3184 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3185 const ParmVarDecl *FirstVD = 3186 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3187 S.Diag(FirstVD->getLocation(), 3188 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3189 } 3190 3191 if (!oldDecl->hasAttrs()) 3192 return; 3193 3194 bool foundAny = newDecl->hasAttrs(); 3195 3196 // Ensure that any moving of objects within the allocated map is 3197 // done before we process them. 3198 if (!foundAny) newDecl->setAttrs(AttrVec()); 3199 3200 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3201 if (!DeclHasAttr(newDecl, I)) { 3202 InheritableAttr *newAttr = 3203 cast<InheritableParamAttr>(I->clone(S.Context)); 3204 newAttr->setInherited(true); 3205 newDecl->addAttr(newAttr); 3206 foundAny = true; 3207 } 3208 } 3209 3210 if (!foundAny) newDecl->dropAttrs(); 3211 } 3212 3213 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3214 const ParmVarDecl *OldParam, 3215 Sema &S) { 3216 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3217 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3218 if (*Oldnullability != *Newnullability) { 3219 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3220 << DiagNullabilityKind( 3221 *Newnullability, 3222 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3223 != 0)) 3224 << DiagNullabilityKind( 3225 *Oldnullability, 3226 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3227 != 0)); 3228 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3229 } 3230 } else { 3231 QualType NewT = NewParam->getType(); 3232 NewT = S.Context.getAttributedType( 3233 AttributedType::getNullabilityAttrKind(*Oldnullability), 3234 NewT, NewT); 3235 NewParam->setType(NewT); 3236 } 3237 } 3238 } 3239 3240 namespace { 3241 3242 /// Used in MergeFunctionDecl to keep track of function parameters in 3243 /// C. 3244 struct GNUCompatibleParamWarning { 3245 ParmVarDecl *OldParm; 3246 ParmVarDecl *NewParm; 3247 QualType PromotedType; 3248 }; 3249 3250 } // end anonymous namespace 3251 3252 // Determine whether the previous declaration was a definition, implicit 3253 // declaration, or a declaration. 3254 template <typename T> 3255 static std::pair<diag::kind, SourceLocation> 3256 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3257 diag::kind PrevDiag; 3258 SourceLocation OldLocation = Old->getLocation(); 3259 if (Old->isThisDeclarationADefinition()) 3260 PrevDiag = diag::note_previous_definition; 3261 else if (Old->isImplicit()) { 3262 PrevDiag = diag::note_previous_implicit_declaration; 3263 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) { 3264 if (FD->getBuiltinID()) 3265 PrevDiag = diag::note_previous_builtin_declaration; 3266 } 3267 if (OldLocation.isInvalid()) 3268 OldLocation = New->getLocation(); 3269 } else 3270 PrevDiag = diag::note_previous_declaration; 3271 return std::make_pair(PrevDiag, OldLocation); 3272 } 3273 3274 /// canRedefineFunction - checks if a function can be redefined. Currently, 3275 /// only extern inline functions can be redefined, and even then only in 3276 /// GNU89 mode. 3277 static bool canRedefineFunction(const FunctionDecl *FD, 3278 const LangOptions& LangOpts) { 3279 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3280 !LangOpts.CPlusPlus && 3281 FD->isInlineSpecified() && 3282 FD->getStorageClass() == SC_Extern); 3283 } 3284 3285 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3286 const AttributedType *AT = T->getAs<AttributedType>(); 3287 while (AT && !AT->isCallingConv()) 3288 AT = AT->getModifiedType()->getAs<AttributedType>(); 3289 return AT; 3290 } 3291 3292 template <typename T> 3293 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3294 const DeclContext *DC = Old->getDeclContext(); 3295 if (DC->isRecord()) 3296 return false; 3297 3298 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3299 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3300 return true; 3301 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3302 return true; 3303 return false; 3304 } 3305 3306 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3307 static bool isExternC(VarTemplateDecl *) { return false; } 3308 static bool isExternC(FunctionTemplateDecl *) { return false; } 3309 3310 /// Check whether a redeclaration of an entity introduced by a 3311 /// using-declaration is valid, given that we know it's not an overload 3312 /// (nor a hidden tag declaration). 3313 template<typename ExpectedDecl> 3314 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3315 ExpectedDecl *New) { 3316 // C++11 [basic.scope.declarative]p4: 3317 // Given a set of declarations in a single declarative region, each of 3318 // which specifies the same unqualified name, 3319 // -- they shall all refer to the same entity, or all refer to functions 3320 // and function templates; or 3321 // -- exactly one declaration shall declare a class name or enumeration 3322 // name that is not a typedef name and the other declarations shall all 3323 // refer to the same variable or enumerator, or all refer to functions 3324 // and function templates; in this case the class name or enumeration 3325 // name is hidden (3.3.10). 3326 3327 // C++11 [namespace.udecl]p14: 3328 // If a function declaration in namespace scope or block scope has the 3329 // same name and the same parameter-type-list as a function introduced 3330 // by a using-declaration, and the declarations do not declare the same 3331 // function, the program is ill-formed. 3332 3333 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3334 if (Old && 3335 !Old->getDeclContext()->getRedeclContext()->Equals( 3336 New->getDeclContext()->getRedeclContext()) && 3337 !(isExternC(Old) && isExternC(New))) 3338 Old = nullptr; 3339 3340 if (!Old) { 3341 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3342 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3343 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3344 return true; 3345 } 3346 return false; 3347 } 3348 3349 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3350 const FunctionDecl *B) { 3351 assert(A->getNumParams() == B->getNumParams()); 3352 3353 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3354 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3355 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3356 if (AttrA == AttrB) 3357 return true; 3358 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3359 AttrA->isDynamic() == AttrB->isDynamic(); 3360 }; 3361 3362 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3363 } 3364 3365 /// If necessary, adjust the semantic declaration context for a qualified 3366 /// declaration to name the correct inline namespace within the qualifier. 3367 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3368 DeclaratorDecl *OldD) { 3369 // The only case where we need to update the DeclContext is when 3370 // redeclaration lookup for a qualified name finds a declaration 3371 // in an inline namespace within the context named by the qualifier: 3372 // 3373 // inline namespace N { int f(); } 3374 // int ::f(); // Sema DC needs adjusting from :: to N::. 3375 // 3376 // For unqualified declarations, the semantic context *can* change 3377 // along the redeclaration chain (for local extern declarations, 3378 // extern "C" declarations, and friend declarations in particular). 3379 if (!NewD->getQualifier()) 3380 return; 3381 3382 // NewD is probably already in the right context. 3383 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3384 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3385 if (NamedDC->Equals(SemaDC)) 3386 return; 3387 3388 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3389 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3390 "unexpected context for redeclaration"); 3391 3392 auto *LexDC = NewD->getLexicalDeclContext(); 3393 auto FixSemaDC = [=](NamedDecl *D) { 3394 if (!D) 3395 return; 3396 D->setDeclContext(SemaDC); 3397 D->setLexicalDeclContext(LexDC); 3398 }; 3399 3400 FixSemaDC(NewD); 3401 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3402 FixSemaDC(FD->getDescribedFunctionTemplate()); 3403 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3404 FixSemaDC(VD->getDescribedVarTemplate()); 3405 } 3406 3407 /// MergeFunctionDecl - We just parsed a function 'New' from 3408 /// declarator D which has the same name and scope as a previous 3409 /// declaration 'Old'. Figure out how to resolve this situation, 3410 /// merging decls or emitting diagnostics as appropriate. 3411 /// 3412 /// In C++, New and Old must be declarations that are not 3413 /// overloaded. Use IsOverload to determine whether New and Old are 3414 /// overloaded, and to select the Old declaration that New should be 3415 /// merged with. 3416 /// 3417 /// Returns true if there was an error, false otherwise. 3418 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, 3419 bool MergeTypeWithOld, bool NewDeclIsDefn) { 3420 // Verify the old decl was also a function. 3421 FunctionDecl *Old = OldD->getAsFunction(); 3422 if (!Old) { 3423 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3424 if (New->getFriendObjectKind()) { 3425 Diag(New->getLocation(), diag::err_using_decl_friend); 3426 Diag(Shadow->getTargetDecl()->getLocation(), 3427 diag::note_using_decl_target); 3428 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3429 << 0; 3430 return true; 3431 } 3432 3433 // Check whether the two declarations might declare the same function or 3434 // function template. 3435 if (FunctionTemplateDecl *NewTemplate = 3436 New->getDescribedFunctionTemplate()) { 3437 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3438 NewTemplate)) 3439 return true; 3440 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3441 ->getAsFunction(); 3442 } else { 3443 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3444 return true; 3445 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3446 } 3447 } else { 3448 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3449 << New->getDeclName(); 3450 notePreviousDefinition(OldD, New->getLocation()); 3451 return true; 3452 } 3453 } 3454 3455 // If the old declaration was found in an inline namespace and the new 3456 // declaration was qualified, update the DeclContext to match. 3457 adjustDeclContextForDeclaratorDecl(New, Old); 3458 3459 // If the old declaration is invalid, just give up here. 3460 if (Old->isInvalidDecl()) 3461 return true; 3462 3463 // Disallow redeclaration of some builtins. 3464 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3465 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3466 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3467 << Old << Old->getType(); 3468 return true; 3469 } 3470 3471 diag::kind PrevDiag; 3472 SourceLocation OldLocation; 3473 std::tie(PrevDiag, OldLocation) = 3474 getNoteDiagForInvalidRedeclaration(Old, New); 3475 3476 // Don't complain about this if we're in GNU89 mode and the old function 3477 // is an extern inline function. 3478 // Don't complain about specializations. They are not supposed to have 3479 // storage classes. 3480 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3481 New->getStorageClass() == SC_Static && 3482 Old->hasExternalFormalLinkage() && 3483 !New->getTemplateSpecializationInfo() && 3484 !canRedefineFunction(Old, getLangOpts())) { 3485 if (getLangOpts().MicrosoftExt) { 3486 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3487 Diag(OldLocation, PrevDiag); 3488 } else { 3489 Diag(New->getLocation(), diag::err_static_non_static) << New; 3490 Diag(OldLocation, PrevDiag); 3491 return true; 3492 } 3493 } 3494 3495 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3496 if (!Old->hasAttr<InternalLinkageAttr>()) { 3497 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3498 << ILA; 3499 Diag(Old->getLocation(), diag::note_previous_declaration); 3500 New->dropAttr<InternalLinkageAttr>(); 3501 } 3502 3503 if (auto *EA = New->getAttr<ErrorAttr>()) { 3504 if (!Old->hasAttr<ErrorAttr>()) { 3505 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3506 Diag(Old->getLocation(), diag::note_previous_declaration); 3507 New->dropAttr<ErrorAttr>(); 3508 } 3509 } 3510 3511 if (CheckRedeclarationInModule(New, Old)) 3512 return true; 3513 3514 if (!getLangOpts().CPlusPlus) { 3515 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3516 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3517 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3518 << New << OldOvl; 3519 3520 // Try our best to find a decl that actually has the overloadable 3521 // attribute for the note. In most cases (e.g. programs with only one 3522 // broken declaration/definition), this won't matter. 3523 // 3524 // FIXME: We could do this if we juggled some extra state in 3525 // OverloadableAttr, rather than just removing it. 3526 const Decl *DiagOld = Old; 3527 if (OldOvl) { 3528 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3529 const auto *A = D->getAttr<OverloadableAttr>(); 3530 return A && !A->isImplicit(); 3531 }); 3532 // If we've implicitly added *all* of the overloadable attrs to this 3533 // chain, emitting a "previous redecl" note is pointless. 3534 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3535 } 3536 3537 if (DiagOld) 3538 Diag(DiagOld->getLocation(), 3539 diag::note_attribute_overloadable_prev_overload) 3540 << OldOvl; 3541 3542 if (OldOvl) 3543 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3544 else 3545 New->dropAttr<OverloadableAttr>(); 3546 } 3547 } 3548 3549 // If a function is first declared with a calling convention, but is later 3550 // declared or defined without one, all following decls assume the calling 3551 // convention of the first. 3552 // 3553 // It's OK if a function is first declared without a calling convention, 3554 // but is later declared or defined with the default calling convention. 3555 // 3556 // To test if either decl has an explicit calling convention, we look for 3557 // AttributedType sugar nodes on the type as written. If they are missing or 3558 // were canonicalized away, we assume the calling convention was implicit. 3559 // 3560 // Note also that we DO NOT return at this point, because we still have 3561 // other tests to run. 3562 QualType OldQType = Context.getCanonicalType(Old->getType()); 3563 QualType NewQType = Context.getCanonicalType(New->getType()); 3564 const FunctionType *OldType = cast<FunctionType>(OldQType); 3565 const FunctionType *NewType = cast<FunctionType>(NewQType); 3566 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3567 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3568 bool RequiresAdjustment = false; 3569 3570 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3571 FunctionDecl *First = Old->getFirstDecl(); 3572 const FunctionType *FT = 3573 First->getType().getCanonicalType()->castAs<FunctionType>(); 3574 FunctionType::ExtInfo FI = FT->getExtInfo(); 3575 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3576 if (!NewCCExplicit) { 3577 // Inherit the CC from the previous declaration if it was specified 3578 // there but not here. 3579 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3580 RequiresAdjustment = true; 3581 } else if (Old->getBuiltinID()) { 3582 // Builtin attribute isn't propagated to the new one yet at this point, 3583 // so we check if the old one is a builtin. 3584 3585 // Calling Conventions on a Builtin aren't really useful and setting a 3586 // default calling convention and cdecl'ing some builtin redeclarations is 3587 // common, so warn and ignore the calling convention on the redeclaration. 3588 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3589 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3590 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3591 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3592 RequiresAdjustment = true; 3593 } else { 3594 // Calling conventions aren't compatible, so complain. 3595 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3596 Diag(New->getLocation(), diag::err_cconv_change) 3597 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3598 << !FirstCCExplicit 3599 << (!FirstCCExplicit ? "" : 3600 FunctionType::getNameForCallConv(FI.getCC())); 3601 3602 // Put the note on the first decl, since it is the one that matters. 3603 Diag(First->getLocation(), diag::note_previous_declaration); 3604 return true; 3605 } 3606 } 3607 3608 // FIXME: diagnose the other way around? 3609 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3610 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3611 RequiresAdjustment = true; 3612 } 3613 3614 // Merge regparm attribute. 3615 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3616 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3617 if (NewTypeInfo.getHasRegParm()) { 3618 Diag(New->getLocation(), diag::err_regparm_mismatch) 3619 << NewType->getRegParmType() 3620 << OldType->getRegParmType(); 3621 Diag(OldLocation, diag::note_previous_declaration); 3622 return true; 3623 } 3624 3625 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3626 RequiresAdjustment = true; 3627 } 3628 3629 // Merge ns_returns_retained attribute. 3630 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3631 if (NewTypeInfo.getProducesResult()) { 3632 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3633 << "'ns_returns_retained'"; 3634 Diag(OldLocation, diag::note_previous_declaration); 3635 return true; 3636 } 3637 3638 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3639 RequiresAdjustment = true; 3640 } 3641 3642 if (OldTypeInfo.getNoCallerSavedRegs() != 3643 NewTypeInfo.getNoCallerSavedRegs()) { 3644 if (NewTypeInfo.getNoCallerSavedRegs()) { 3645 AnyX86NoCallerSavedRegistersAttr *Attr = 3646 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3647 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3648 Diag(OldLocation, diag::note_previous_declaration); 3649 return true; 3650 } 3651 3652 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3653 RequiresAdjustment = true; 3654 } 3655 3656 if (RequiresAdjustment) { 3657 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3658 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3659 New->setType(QualType(AdjustedType, 0)); 3660 NewQType = Context.getCanonicalType(New->getType()); 3661 } 3662 3663 // If this redeclaration makes the function inline, we may need to add it to 3664 // UndefinedButUsed. 3665 if (!Old->isInlined() && New->isInlined() && 3666 !New->hasAttr<GNUInlineAttr>() && 3667 !getLangOpts().GNUInline && 3668 Old->isUsed(false) && 3669 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3670 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3671 SourceLocation())); 3672 3673 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3674 // about it. 3675 if (New->hasAttr<GNUInlineAttr>() && 3676 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3677 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3678 } 3679 3680 // If pass_object_size params don't match up perfectly, this isn't a valid 3681 // redeclaration. 3682 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3683 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3684 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3685 << New->getDeclName(); 3686 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3687 return true; 3688 } 3689 3690 if (getLangOpts().CPlusPlus) { 3691 // C++1z [over.load]p2 3692 // Certain function declarations cannot be overloaded: 3693 // -- Function declarations that differ only in the return type, 3694 // the exception specification, or both cannot be overloaded. 3695 3696 // Check the exception specifications match. This may recompute the type of 3697 // both Old and New if it resolved exception specifications, so grab the 3698 // types again after this. Because this updates the type, we do this before 3699 // any of the other checks below, which may update the "de facto" NewQType 3700 // but do not necessarily update the type of New. 3701 if (CheckEquivalentExceptionSpec(Old, New)) 3702 return true; 3703 OldQType = Context.getCanonicalType(Old->getType()); 3704 NewQType = Context.getCanonicalType(New->getType()); 3705 3706 // Go back to the type source info to compare the declared return types, 3707 // per C++1y [dcl.type.auto]p13: 3708 // Redeclarations or specializations of a function or function template 3709 // with a declared return type that uses a placeholder type shall also 3710 // use that placeholder, not a deduced type. 3711 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3712 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3713 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3714 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3715 OldDeclaredReturnType)) { 3716 QualType ResQT; 3717 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3718 OldDeclaredReturnType->isObjCObjectPointerType()) 3719 // FIXME: This does the wrong thing for a deduced return type. 3720 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3721 if (ResQT.isNull()) { 3722 if (New->isCXXClassMember() && New->isOutOfLine()) 3723 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3724 << New << New->getReturnTypeSourceRange(); 3725 else 3726 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3727 << New->getReturnTypeSourceRange(); 3728 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3729 << Old->getReturnTypeSourceRange(); 3730 return true; 3731 } 3732 else 3733 NewQType = ResQT; 3734 } 3735 3736 QualType OldReturnType = OldType->getReturnType(); 3737 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3738 if (OldReturnType != NewReturnType) { 3739 // If this function has a deduced return type and has already been 3740 // defined, copy the deduced value from the old declaration. 3741 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3742 if (OldAT && OldAT->isDeduced()) { 3743 QualType DT = OldAT->getDeducedType(); 3744 if (DT.isNull()) { 3745 New->setType(SubstAutoTypeDependent(New->getType())); 3746 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3747 } else { 3748 New->setType(SubstAutoType(New->getType(), DT)); 3749 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3750 } 3751 } 3752 } 3753 3754 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3755 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3756 if (OldMethod && NewMethod) { 3757 // Preserve triviality. 3758 NewMethod->setTrivial(OldMethod->isTrivial()); 3759 3760 // MSVC allows explicit template specialization at class scope: 3761 // 2 CXXMethodDecls referring to the same function will be injected. 3762 // We don't want a redeclaration error. 3763 bool IsClassScopeExplicitSpecialization = 3764 OldMethod->isFunctionTemplateSpecialization() && 3765 NewMethod->isFunctionTemplateSpecialization(); 3766 bool isFriend = NewMethod->getFriendObjectKind(); 3767 3768 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3769 !IsClassScopeExplicitSpecialization) { 3770 // -- Member function declarations with the same name and the 3771 // same parameter types cannot be overloaded if any of them 3772 // is a static member function declaration. 3773 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3774 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3775 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3776 return true; 3777 } 3778 3779 // C++ [class.mem]p1: 3780 // [...] A member shall not be declared twice in the 3781 // member-specification, except that a nested class or member 3782 // class template can be declared and then later defined. 3783 if (!inTemplateInstantiation()) { 3784 unsigned NewDiag; 3785 if (isa<CXXConstructorDecl>(OldMethod)) 3786 NewDiag = diag::err_constructor_redeclared; 3787 else if (isa<CXXDestructorDecl>(NewMethod)) 3788 NewDiag = diag::err_destructor_redeclared; 3789 else if (isa<CXXConversionDecl>(NewMethod)) 3790 NewDiag = diag::err_conv_function_redeclared; 3791 else 3792 NewDiag = diag::err_member_redeclared; 3793 3794 Diag(New->getLocation(), NewDiag); 3795 } else { 3796 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3797 << New << New->getType(); 3798 } 3799 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3800 return true; 3801 3802 // Complain if this is an explicit declaration of a special 3803 // member that was initially declared implicitly. 3804 // 3805 // As an exception, it's okay to befriend such methods in order 3806 // to permit the implicit constructor/destructor/operator calls. 3807 } else if (OldMethod->isImplicit()) { 3808 if (isFriend) { 3809 NewMethod->setImplicit(); 3810 } else { 3811 Diag(NewMethod->getLocation(), 3812 diag::err_definition_of_implicitly_declared_member) 3813 << New << getSpecialMember(OldMethod); 3814 return true; 3815 } 3816 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3817 Diag(NewMethod->getLocation(), 3818 diag::err_definition_of_explicitly_defaulted_member) 3819 << getSpecialMember(OldMethod); 3820 return true; 3821 } 3822 } 3823 3824 // C++11 [dcl.attr.noreturn]p1: 3825 // The first declaration of a function shall specify the noreturn 3826 // attribute if any declaration of that function specifies the noreturn 3827 // attribute. 3828 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3829 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3830 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3831 << NRA; 3832 Diag(Old->getLocation(), diag::note_previous_declaration); 3833 } 3834 3835 // C++11 [dcl.attr.depend]p2: 3836 // The first declaration of a function shall specify the 3837 // carries_dependency attribute for its declarator-id if any declaration 3838 // of the function specifies the carries_dependency attribute. 3839 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3840 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3841 Diag(CDA->getLocation(), 3842 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3843 Diag(Old->getFirstDecl()->getLocation(), 3844 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3845 } 3846 3847 // (C++98 8.3.5p3): 3848 // All declarations for a function shall agree exactly in both the 3849 // return type and the parameter-type-list. 3850 // We also want to respect all the extended bits except noreturn. 3851 3852 // noreturn should now match unless the old type info didn't have it. 3853 QualType OldQTypeForComparison = OldQType; 3854 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3855 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3856 const FunctionType *OldTypeForComparison 3857 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3858 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3859 assert(OldQTypeForComparison.isCanonical()); 3860 } 3861 3862 if (haveIncompatibleLanguageLinkages(Old, New)) { 3863 // As a special case, retain the language linkage from previous 3864 // declarations of a friend function as an extension. 3865 // 3866 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3867 // and is useful because there's otherwise no way to specify language 3868 // linkage within class scope. 3869 // 3870 // Check cautiously as the friend object kind isn't yet complete. 3871 if (New->getFriendObjectKind() != Decl::FOK_None) { 3872 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3873 Diag(OldLocation, PrevDiag); 3874 } else { 3875 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3876 Diag(OldLocation, PrevDiag); 3877 return true; 3878 } 3879 } 3880 3881 // If the function types are compatible, merge the declarations. Ignore the 3882 // exception specifier because it was already checked above in 3883 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3884 // about incompatible types under -fms-compatibility. 3885 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3886 NewQType)) 3887 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3888 3889 // If the types are imprecise (due to dependent constructs in friends or 3890 // local extern declarations), it's OK if they differ. We'll check again 3891 // during instantiation. 3892 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3893 return false; 3894 3895 // Fall through for conflicting redeclarations and redefinitions. 3896 } 3897 3898 // C: Function types need to be compatible, not identical. This handles 3899 // duplicate function decls like "void f(int); void f(enum X);" properly. 3900 if (!getLangOpts().CPlusPlus) { 3901 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other 3902 // type is specified by a function definition that contains a (possibly 3903 // empty) identifier list, both shall agree in the number of parameters 3904 // and the type of each parameter shall be compatible with the type that 3905 // results from the application of default argument promotions to the 3906 // type of the corresponding identifier. ... 3907 // This cannot be handled by ASTContext::typesAreCompatible() because that 3908 // doesn't know whether the function type is for a definition or not when 3909 // eventually calling ASTContext::mergeFunctionTypes(). The only situation 3910 // we need to cover here is that the number of arguments agree as the 3911 // default argument promotion rules were already checked by 3912 // ASTContext::typesAreCompatible(). 3913 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn && 3914 Old->getNumParams() != New->getNumParams()) { 3915 Diag(New->getLocation(), diag::err_conflicting_types) << New; 3916 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 3917 return true; 3918 } 3919 3920 // If we are merging two functions where only one of them has a prototype, 3921 // we may have enough information to decide to issue a diagnostic that the 3922 // function without a protoype will change behavior in C2x. This handles 3923 // cases like: 3924 // void i(); void i(int j); 3925 // void i(int j); void i(); 3926 // void i(); void i(int j) {} 3927 // See ActOnFinishFunctionBody() for other cases of the behavior change 3928 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 3929 // type without a prototype. 3930 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && 3931 !New->isImplicit() && !Old->isImplicit()) { 3932 const FunctionDecl *WithProto, *WithoutProto; 3933 if (New->hasWrittenPrototype()) { 3934 WithProto = New; 3935 WithoutProto = Old; 3936 } else { 3937 WithProto = Old; 3938 WithoutProto = New; 3939 } 3940 3941 if (WithProto->getNumParams() != 0) { 3942 // The function definition has parameters, so this will change 3943 // behavior in C2x. 3944 // 3945 // If we already warned about about the function without a prototype 3946 // being deprecated, add a note that it also changes behavior. If we 3947 // didn't warn about it being deprecated (because the diagnostic is 3948 // not enabled), warn now that it is deprecated and changes behavior. 3949 bool AddNote = false; 3950 if (Diags.isIgnored(diag::warn_strict_prototypes, 3951 WithoutProto->getLocation())) { 3952 if (WithoutProto->getBuiltinID() == 0 && 3953 !WithoutProto->isImplicit() && 3954 SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(), 3955 WithProto->getLocation())) { 3956 PartialDiagnostic PD = 3957 PDiag(diag::warn_non_prototype_changes_behavior); 3958 if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) { 3959 if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>()) 3960 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 3961 } 3962 Diag(WithoutProto->getLocation(), PD); 3963 } 3964 } else { 3965 AddNote = true; 3966 } 3967 3968 // Because the function with a prototype has parameters but a previous 3969 // declaration had none, the function with the prototype will also 3970 // change behavior in C2x. 3971 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit()) { 3972 if (SourceMgr.isBeforeInTranslationUnit( 3973 WithProto->getLocation(), WithoutProto->getLocation())) { 3974 // If the function with the prototype comes before the function 3975 // without the prototype, we only want to diagnose the one without 3976 // the prototype. 3977 Diag(WithoutProto->getLocation(), 3978 diag::warn_non_prototype_changes_behavior); 3979 } else { 3980 // Otherwise, diagnose the one with the prototype, and potentially 3981 // attach a note to the one without a prototype if needed. 3982 Diag(WithProto->getLocation(), 3983 diag::warn_non_prototype_changes_behavior); 3984 if (AddNote && WithoutProto->getBuiltinID() == 0) 3985 Diag(WithoutProto->getLocation(), 3986 diag::note_func_decl_changes_behavior); 3987 } 3988 } else if (AddNote && WithoutProto->getBuiltinID() == 0 && 3989 !WithoutProto->isImplicit()) { 3990 // If we were supposed to add a note but the function with a 3991 // prototype is a builtin or was implicitly declared, which means we 3992 // have nothing to attach the note to, so we issue a warning instead. 3993 Diag(WithoutProto->getLocation(), 3994 diag::warn_non_prototype_changes_behavior); 3995 } 3996 } 3997 } 3998 3999 if (Context.typesAreCompatible(OldQType, NewQType)) { 4000 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 4001 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 4002 const FunctionProtoType *OldProto = nullptr; 4003 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 4004 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 4005 // The old declaration provided a function prototype, but the 4006 // new declaration does not. Merge in the prototype. 4007 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 4008 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 4009 NewQType = 4010 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 4011 OldProto->getExtProtoInfo()); 4012 New->setType(NewQType); 4013 New->setHasInheritedPrototype(); 4014 4015 // Synthesize parameters with the same types. 4016 SmallVector<ParmVarDecl *, 16> Params; 4017 for (const auto &ParamType : OldProto->param_types()) { 4018 ParmVarDecl *Param = ParmVarDecl::Create( 4019 Context, New, SourceLocation(), SourceLocation(), nullptr, 4020 ParamType, /*TInfo=*/nullptr, SC_None, nullptr); 4021 Param->setScopeInfo(0, Params.size()); 4022 Param->setImplicit(); 4023 Params.push_back(Param); 4024 } 4025 4026 New->setParams(Params); 4027 } 4028 4029 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4030 } 4031 } 4032 4033 // Check if the function types are compatible when pointer size address 4034 // spaces are ignored. 4035 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 4036 return false; 4037 4038 // GNU C permits a K&R definition to follow a prototype declaration 4039 // if the declared types of the parameters in the K&R definition 4040 // match the types in the prototype declaration, even when the 4041 // promoted types of the parameters from the K&R definition differ 4042 // from the types in the prototype. GCC then keeps the types from 4043 // the prototype. 4044 // 4045 // If a variadic prototype is followed by a non-variadic K&R definition, 4046 // the K&R definition becomes variadic. This is sort of an edge case, but 4047 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 4048 // C99 6.9.1p8. 4049 if (!getLangOpts().CPlusPlus && 4050 Old->hasPrototype() && !New->hasPrototype() && 4051 New->getType()->getAs<FunctionProtoType>() && 4052 Old->getNumParams() == New->getNumParams()) { 4053 SmallVector<QualType, 16> ArgTypes; 4054 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 4055 const FunctionProtoType *OldProto 4056 = Old->getType()->getAs<FunctionProtoType>(); 4057 const FunctionProtoType *NewProto 4058 = New->getType()->getAs<FunctionProtoType>(); 4059 4060 // Determine whether this is the GNU C extension. 4061 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 4062 NewProto->getReturnType()); 4063 bool LooseCompatible = !MergedReturn.isNull(); 4064 for (unsigned Idx = 0, End = Old->getNumParams(); 4065 LooseCompatible && Idx != End; ++Idx) { 4066 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 4067 ParmVarDecl *NewParm = New->getParamDecl(Idx); 4068 if (Context.typesAreCompatible(OldParm->getType(), 4069 NewProto->getParamType(Idx))) { 4070 ArgTypes.push_back(NewParm->getType()); 4071 } else if (Context.typesAreCompatible(OldParm->getType(), 4072 NewParm->getType(), 4073 /*CompareUnqualified=*/true)) { 4074 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 4075 NewProto->getParamType(Idx) }; 4076 Warnings.push_back(Warn); 4077 ArgTypes.push_back(NewParm->getType()); 4078 } else 4079 LooseCompatible = false; 4080 } 4081 4082 if (LooseCompatible) { 4083 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 4084 Diag(Warnings[Warn].NewParm->getLocation(), 4085 diag::ext_param_promoted_not_compatible_with_prototype) 4086 << Warnings[Warn].PromotedType 4087 << Warnings[Warn].OldParm->getType(); 4088 if (Warnings[Warn].OldParm->getLocation().isValid()) 4089 Diag(Warnings[Warn].OldParm->getLocation(), 4090 diag::note_previous_declaration); 4091 } 4092 4093 if (MergeTypeWithOld) 4094 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 4095 OldProto->getExtProtoInfo())); 4096 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4097 } 4098 4099 // Fall through to diagnose conflicting types. 4100 } 4101 4102 // A function that has already been declared has been redeclared or 4103 // defined with a different type; show an appropriate diagnostic. 4104 4105 // If the previous declaration was an implicitly-generated builtin 4106 // declaration, then at the very least we should use a specialized note. 4107 unsigned BuiltinID; 4108 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 4109 // If it's actually a library-defined builtin function like 'malloc' 4110 // or 'printf', just warn about the incompatible redeclaration. 4111 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4112 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 4113 Diag(OldLocation, diag::note_previous_builtin_declaration) 4114 << Old << Old->getType(); 4115 return false; 4116 } 4117 4118 PrevDiag = diag::note_previous_builtin_declaration; 4119 } 4120 4121 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 4122 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4123 return true; 4124 } 4125 4126 /// Completes the merge of two function declarations that are 4127 /// known to be compatible. 4128 /// 4129 /// This routine handles the merging of attributes and other 4130 /// properties of function declarations from the old declaration to 4131 /// the new declaration, once we know that New is in fact a 4132 /// redeclaration of Old. 4133 /// 4134 /// \returns false 4135 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 4136 Scope *S, bool MergeTypeWithOld) { 4137 // Merge the attributes 4138 mergeDeclAttributes(New, Old); 4139 4140 // Merge "pure" flag. 4141 if (Old->isPure()) 4142 New->setPure(); 4143 4144 // Merge "used" flag. 4145 if (Old->getMostRecentDecl()->isUsed(false)) 4146 New->setIsUsed(); 4147 4148 // Merge attributes from the parameters. These can mismatch with K&R 4149 // declarations. 4150 if (New->getNumParams() == Old->getNumParams()) 4151 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 4152 ParmVarDecl *NewParam = New->getParamDecl(i); 4153 ParmVarDecl *OldParam = Old->getParamDecl(i); 4154 mergeParamDeclAttributes(NewParam, OldParam, *this); 4155 mergeParamDeclTypes(NewParam, OldParam, *this); 4156 } 4157 4158 if (getLangOpts().CPlusPlus) 4159 return MergeCXXFunctionDecl(New, Old, S); 4160 4161 // Merge the function types so the we get the composite types for the return 4162 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 4163 // was visible. 4164 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 4165 if (!Merged.isNull() && MergeTypeWithOld) 4166 New->setType(Merged); 4167 4168 return false; 4169 } 4170 4171 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4172 ObjCMethodDecl *oldMethod) { 4173 // Merge the attributes, including deprecated/unavailable 4174 AvailabilityMergeKind MergeKind = 4175 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4176 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4177 : AMK_ProtocolImplementation) 4178 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4179 : AMK_Override; 4180 4181 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4182 4183 // Merge attributes from the parameters. 4184 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4185 oe = oldMethod->param_end(); 4186 for (ObjCMethodDecl::param_iterator 4187 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4188 ni != ne && oi != oe; ++ni, ++oi) 4189 mergeParamDeclAttributes(*ni, *oi, *this); 4190 4191 CheckObjCMethodOverride(newMethod, oldMethod); 4192 } 4193 4194 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4195 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4196 4197 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4198 ? diag::err_redefinition_different_type 4199 : diag::err_redeclaration_different_type) 4200 << New->getDeclName() << New->getType() << Old->getType(); 4201 4202 diag::kind PrevDiag; 4203 SourceLocation OldLocation; 4204 std::tie(PrevDiag, OldLocation) 4205 = getNoteDiagForInvalidRedeclaration(Old, New); 4206 S.Diag(OldLocation, PrevDiag); 4207 New->setInvalidDecl(); 4208 } 4209 4210 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4211 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4212 /// emitting diagnostics as appropriate. 4213 /// 4214 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4215 /// to here in AddInitializerToDecl. We can't check them before the initializer 4216 /// is attached. 4217 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4218 bool MergeTypeWithOld) { 4219 if (New->isInvalidDecl() || Old->isInvalidDecl()) 4220 return; 4221 4222 QualType MergedT; 4223 if (getLangOpts().CPlusPlus) { 4224 if (New->getType()->isUndeducedType()) { 4225 // We don't know what the new type is until the initializer is attached. 4226 return; 4227 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4228 // These could still be something that needs exception specs checked. 4229 return MergeVarDeclExceptionSpecs(New, Old); 4230 } 4231 // C++ [basic.link]p10: 4232 // [...] the types specified by all declarations referring to a given 4233 // object or function shall be identical, except that declarations for an 4234 // array object can specify array types that differ by the presence or 4235 // absence of a major array bound (8.3.4). 4236 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4237 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4238 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4239 4240 // We are merging a variable declaration New into Old. If it has an array 4241 // bound, and that bound differs from Old's bound, we should diagnose the 4242 // mismatch. 4243 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4244 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4245 PrevVD = PrevVD->getPreviousDecl()) { 4246 QualType PrevVDTy = PrevVD->getType(); 4247 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4248 continue; 4249 4250 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4251 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4252 } 4253 } 4254 4255 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4256 if (Context.hasSameType(OldArray->getElementType(), 4257 NewArray->getElementType())) 4258 MergedT = New->getType(); 4259 } 4260 // FIXME: Check visibility. New is hidden but has a complete type. If New 4261 // has no array bound, it should not inherit one from Old, if Old is not 4262 // visible. 4263 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4264 if (Context.hasSameType(OldArray->getElementType(), 4265 NewArray->getElementType())) 4266 MergedT = Old->getType(); 4267 } 4268 } 4269 else if (New->getType()->isObjCObjectPointerType() && 4270 Old->getType()->isObjCObjectPointerType()) { 4271 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4272 Old->getType()); 4273 } 4274 } else { 4275 // C 6.2.7p2: 4276 // All declarations that refer to the same object or function shall have 4277 // compatible type. 4278 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4279 } 4280 if (MergedT.isNull()) { 4281 // It's OK if we couldn't merge types if either type is dependent, for a 4282 // block-scope variable. In other cases (static data members of class 4283 // templates, variable templates, ...), we require the types to be 4284 // equivalent. 4285 // FIXME: The C++ standard doesn't say anything about this. 4286 if ((New->getType()->isDependentType() || 4287 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4288 // If the old type was dependent, we can't merge with it, so the new type 4289 // becomes dependent for now. We'll reproduce the original type when we 4290 // instantiate the TypeSourceInfo for the variable. 4291 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4292 New->setType(Context.DependentTy); 4293 return; 4294 } 4295 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4296 } 4297 4298 // Don't actually update the type on the new declaration if the old 4299 // declaration was an extern declaration in a different scope. 4300 if (MergeTypeWithOld) 4301 New->setType(MergedT); 4302 } 4303 4304 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4305 LookupResult &Previous) { 4306 // C11 6.2.7p4: 4307 // For an identifier with internal or external linkage declared 4308 // in a scope in which a prior declaration of that identifier is 4309 // visible, if the prior declaration specifies internal or 4310 // external linkage, the type of the identifier at the later 4311 // declaration becomes the composite type. 4312 // 4313 // If the variable isn't visible, we do not merge with its type. 4314 if (Previous.isShadowed()) 4315 return false; 4316 4317 if (S.getLangOpts().CPlusPlus) { 4318 // C++11 [dcl.array]p3: 4319 // If there is a preceding declaration of the entity in the same 4320 // scope in which the bound was specified, an omitted array bound 4321 // is taken to be the same as in that earlier declaration. 4322 return NewVD->isPreviousDeclInSameBlockScope() || 4323 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4324 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4325 } else { 4326 // If the old declaration was function-local, don't merge with its 4327 // type unless we're in the same function. 4328 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4329 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4330 } 4331 } 4332 4333 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4334 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4335 /// situation, merging decls or emitting diagnostics as appropriate. 4336 /// 4337 /// Tentative definition rules (C99 6.9.2p2) are checked by 4338 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4339 /// definitions here, since the initializer hasn't been attached. 4340 /// 4341 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4342 // If the new decl is already invalid, don't do any other checking. 4343 if (New->isInvalidDecl()) 4344 return; 4345 4346 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4347 return; 4348 4349 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4350 4351 // Verify the old decl was also a variable or variable template. 4352 VarDecl *Old = nullptr; 4353 VarTemplateDecl *OldTemplate = nullptr; 4354 if (Previous.isSingleResult()) { 4355 if (NewTemplate) { 4356 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4357 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4358 4359 if (auto *Shadow = 4360 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4361 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4362 return New->setInvalidDecl(); 4363 } else { 4364 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4365 4366 if (auto *Shadow = 4367 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4368 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4369 return New->setInvalidDecl(); 4370 } 4371 } 4372 if (!Old) { 4373 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4374 << New->getDeclName(); 4375 notePreviousDefinition(Previous.getRepresentativeDecl(), 4376 New->getLocation()); 4377 return New->setInvalidDecl(); 4378 } 4379 4380 // If the old declaration was found in an inline namespace and the new 4381 // declaration was qualified, update the DeclContext to match. 4382 adjustDeclContextForDeclaratorDecl(New, Old); 4383 4384 // Ensure the template parameters are compatible. 4385 if (NewTemplate && 4386 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4387 OldTemplate->getTemplateParameters(), 4388 /*Complain=*/true, TPL_TemplateMatch)) 4389 return New->setInvalidDecl(); 4390 4391 // C++ [class.mem]p1: 4392 // A member shall not be declared twice in the member-specification [...] 4393 // 4394 // Here, we need only consider static data members. 4395 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4396 Diag(New->getLocation(), diag::err_duplicate_member) 4397 << New->getIdentifier(); 4398 Diag(Old->getLocation(), diag::note_previous_declaration); 4399 New->setInvalidDecl(); 4400 } 4401 4402 mergeDeclAttributes(New, Old); 4403 // Warn if an already-declared variable is made a weak_import in a subsequent 4404 // declaration 4405 if (New->hasAttr<WeakImportAttr>() && 4406 Old->getStorageClass() == SC_None && 4407 !Old->hasAttr<WeakImportAttr>()) { 4408 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4409 Diag(Old->getLocation(), diag::note_previous_declaration); 4410 // Remove weak_import attribute on new declaration. 4411 New->dropAttr<WeakImportAttr>(); 4412 } 4413 4414 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4415 if (!Old->hasAttr<InternalLinkageAttr>()) { 4416 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4417 << ILA; 4418 Diag(Old->getLocation(), diag::note_previous_declaration); 4419 New->dropAttr<InternalLinkageAttr>(); 4420 } 4421 4422 // Merge the types. 4423 VarDecl *MostRecent = Old->getMostRecentDecl(); 4424 if (MostRecent != Old) { 4425 MergeVarDeclTypes(New, MostRecent, 4426 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4427 if (New->isInvalidDecl()) 4428 return; 4429 } 4430 4431 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4432 if (New->isInvalidDecl()) 4433 return; 4434 4435 diag::kind PrevDiag; 4436 SourceLocation OldLocation; 4437 std::tie(PrevDiag, OldLocation) = 4438 getNoteDiagForInvalidRedeclaration(Old, New); 4439 4440 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4441 if (New->getStorageClass() == SC_Static && 4442 !New->isStaticDataMember() && 4443 Old->hasExternalFormalLinkage()) { 4444 if (getLangOpts().MicrosoftExt) { 4445 Diag(New->getLocation(), diag::ext_static_non_static) 4446 << New->getDeclName(); 4447 Diag(OldLocation, PrevDiag); 4448 } else { 4449 Diag(New->getLocation(), diag::err_static_non_static) 4450 << New->getDeclName(); 4451 Diag(OldLocation, PrevDiag); 4452 return New->setInvalidDecl(); 4453 } 4454 } 4455 // C99 6.2.2p4: 4456 // For an identifier declared with the storage-class specifier 4457 // extern in a scope in which a prior declaration of that 4458 // identifier is visible,23) if the prior declaration specifies 4459 // internal or external linkage, the linkage of the identifier at 4460 // the later declaration is the same as the linkage specified at 4461 // the prior declaration. If no prior declaration is visible, or 4462 // if the prior declaration specifies no linkage, then the 4463 // identifier has external linkage. 4464 if (New->hasExternalStorage() && Old->hasLinkage()) 4465 /* Okay */; 4466 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4467 !New->isStaticDataMember() && 4468 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4469 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4470 Diag(OldLocation, PrevDiag); 4471 return New->setInvalidDecl(); 4472 } 4473 4474 // Check if extern is followed by non-extern and vice-versa. 4475 if (New->hasExternalStorage() && 4476 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4477 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4478 Diag(OldLocation, PrevDiag); 4479 return New->setInvalidDecl(); 4480 } 4481 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4482 !New->hasExternalStorage()) { 4483 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4484 Diag(OldLocation, PrevDiag); 4485 return New->setInvalidDecl(); 4486 } 4487 4488 if (CheckRedeclarationInModule(New, Old)) 4489 return; 4490 4491 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4492 4493 // FIXME: The test for external storage here seems wrong? We still 4494 // need to check for mismatches. 4495 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4496 // Don't complain about out-of-line definitions of static members. 4497 !(Old->getLexicalDeclContext()->isRecord() && 4498 !New->getLexicalDeclContext()->isRecord())) { 4499 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4500 Diag(OldLocation, PrevDiag); 4501 return New->setInvalidDecl(); 4502 } 4503 4504 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4505 if (VarDecl *Def = Old->getDefinition()) { 4506 // C++1z [dcl.fcn.spec]p4: 4507 // If the definition of a variable appears in a translation unit before 4508 // its first declaration as inline, the program is ill-formed. 4509 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4510 Diag(Def->getLocation(), diag::note_previous_definition); 4511 } 4512 } 4513 4514 // If this redeclaration makes the variable inline, we may need to add it to 4515 // UndefinedButUsed. 4516 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4517 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4518 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4519 SourceLocation())); 4520 4521 if (New->getTLSKind() != Old->getTLSKind()) { 4522 if (!Old->getTLSKind()) { 4523 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4524 Diag(OldLocation, PrevDiag); 4525 } else if (!New->getTLSKind()) { 4526 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4527 Diag(OldLocation, PrevDiag); 4528 } else { 4529 // Do not allow redeclaration to change the variable between requiring 4530 // static and dynamic initialization. 4531 // FIXME: GCC allows this, but uses the TLS keyword on the first 4532 // declaration to determine the kind. Do we need to be compatible here? 4533 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4534 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4535 Diag(OldLocation, PrevDiag); 4536 } 4537 } 4538 4539 // C++ doesn't have tentative definitions, so go right ahead and check here. 4540 if (getLangOpts().CPlusPlus && 4541 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4542 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4543 Old->getCanonicalDecl()->isConstexpr()) { 4544 // This definition won't be a definition any more once it's been merged. 4545 Diag(New->getLocation(), 4546 diag::warn_deprecated_redundant_constexpr_static_def); 4547 } else if (VarDecl *Def = Old->getDefinition()) { 4548 if (checkVarDeclRedefinition(Def, New)) 4549 return; 4550 } 4551 } 4552 4553 if (haveIncompatibleLanguageLinkages(Old, New)) { 4554 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4555 Diag(OldLocation, PrevDiag); 4556 New->setInvalidDecl(); 4557 return; 4558 } 4559 4560 // Merge "used" flag. 4561 if (Old->getMostRecentDecl()->isUsed(false)) 4562 New->setIsUsed(); 4563 4564 // Keep a chain of previous declarations. 4565 New->setPreviousDecl(Old); 4566 if (NewTemplate) 4567 NewTemplate->setPreviousDecl(OldTemplate); 4568 4569 // Inherit access appropriately. 4570 New->setAccess(Old->getAccess()); 4571 if (NewTemplate) 4572 NewTemplate->setAccess(New->getAccess()); 4573 4574 if (Old->isInline()) 4575 New->setImplicitlyInline(); 4576 } 4577 4578 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4579 SourceManager &SrcMgr = getSourceManager(); 4580 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4581 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4582 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4583 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4584 auto &HSI = PP.getHeaderSearchInfo(); 4585 StringRef HdrFilename = 4586 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4587 4588 auto noteFromModuleOrInclude = [&](Module *Mod, 4589 SourceLocation IncLoc) -> bool { 4590 // Redefinition errors with modules are common with non modular mapped 4591 // headers, example: a non-modular header H in module A that also gets 4592 // included directly in a TU. Pointing twice to the same header/definition 4593 // is confusing, try to get better diagnostics when modules is on. 4594 if (IncLoc.isValid()) { 4595 if (Mod) { 4596 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4597 << HdrFilename.str() << Mod->getFullModuleName(); 4598 if (!Mod->DefinitionLoc.isInvalid()) 4599 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4600 << Mod->getFullModuleName(); 4601 } else { 4602 Diag(IncLoc, diag::note_redefinition_include_same_file) 4603 << HdrFilename.str(); 4604 } 4605 return true; 4606 } 4607 4608 return false; 4609 }; 4610 4611 // Is it the same file and same offset? Provide more information on why 4612 // this leads to a redefinition error. 4613 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4614 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4615 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4616 bool EmittedDiag = 4617 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4618 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4619 4620 // If the header has no guards, emit a note suggesting one. 4621 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4622 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4623 4624 if (EmittedDiag) 4625 return; 4626 } 4627 4628 // Redefinition coming from different files or couldn't do better above. 4629 if (Old->getLocation().isValid()) 4630 Diag(Old->getLocation(), diag::note_previous_definition); 4631 } 4632 4633 /// We've just determined that \p Old and \p New both appear to be definitions 4634 /// of the same variable. Either diagnose or fix the problem. 4635 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4636 if (!hasVisibleDefinition(Old) && 4637 (New->getFormalLinkage() == InternalLinkage || 4638 New->isInline() || 4639 New->getDescribedVarTemplate() || 4640 New->getNumTemplateParameterLists() || 4641 New->getDeclContext()->isDependentContext())) { 4642 // The previous definition is hidden, and multiple definitions are 4643 // permitted (in separate TUs). Demote this to a declaration. 4644 New->demoteThisDefinitionToDeclaration(); 4645 4646 // Make the canonical definition visible. 4647 if (auto *OldTD = Old->getDescribedVarTemplate()) 4648 makeMergedDefinitionVisible(OldTD); 4649 makeMergedDefinitionVisible(Old); 4650 return false; 4651 } else { 4652 Diag(New->getLocation(), diag::err_redefinition) << New; 4653 notePreviousDefinition(Old, New->getLocation()); 4654 New->setInvalidDecl(); 4655 return true; 4656 } 4657 } 4658 4659 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4660 /// no declarator (e.g. "struct foo;") is parsed. 4661 Decl * 4662 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4663 RecordDecl *&AnonRecord) { 4664 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4665 AnonRecord); 4666 } 4667 4668 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4669 // disambiguate entities defined in different scopes. 4670 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4671 // compatibility. 4672 // We will pick our mangling number depending on which version of MSVC is being 4673 // targeted. 4674 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4675 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4676 ? S->getMSCurManglingNumber() 4677 : S->getMSLastManglingNumber(); 4678 } 4679 4680 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4681 if (!Context.getLangOpts().CPlusPlus) 4682 return; 4683 4684 if (isa<CXXRecordDecl>(Tag->getParent())) { 4685 // If this tag is the direct child of a class, number it if 4686 // it is anonymous. 4687 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4688 return; 4689 MangleNumberingContext &MCtx = 4690 Context.getManglingNumberContext(Tag->getParent()); 4691 Context.setManglingNumber( 4692 Tag, MCtx.getManglingNumber( 4693 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4694 return; 4695 } 4696 4697 // If this tag isn't a direct child of a class, number it if it is local. 4698 MangleNumberingContext *MCtx; 4699 Decl *ManglingContextDecl; 4700 std::tie(MCtx, ManglingContextDecl) = 4701 getCurrentMangleNumberContext(Tag->getDeclContext()); 4702 if (MCtx) { 4703 Context.setManglingNumber( 4704 Tag, MCtx->getManglingNumber( 4705 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4706 } 4707 } 4708 4709 namespace { 4710 struct NonCLikeKind { 4711 enum { 4712 None, 4713 BaseClass, 4714 DefaultMemberInit, 4715 Lambda, 4716 Friend, 4717 OtherMember, 4718 Invalid, 4719 } Kind = None; 4720 SourceRange Range; 4721 4722 explicit operator bool() { return Kind != None; } 4723 }; 4724 } 4725 4726 /// Determine whether a class is C-like, according to the rules of C++ 4727 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4728 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4729 if (RD->isInvalidDecl()) 4730 return {NonCLikeKind::Invalid, {}}; 4731 4732 // C++ [dcl.typedef]p9: [P1766R1] 4733 // An unnamed class with a typedef name for linkage purposes shall not 4734 // 4735 // -- have any base classes 4736 if (RD->getNumBases()) 4737 return {NonCLikeKind::BaseClass, 4738 SourceRange(RD->bases_begin()->getBeginLoc(), 4739 RD->bases_end()[-1].getEndLoc())}; 4740 bool Invalid = false; 4741 for (Decl *D : RD->decls()) { 4742 // Don't complain about things we already diagnosed. 4743 if (D->isInvalidDecl()) { 4744 Invalid = true; 4745 continue; 4746 } 4747 4748 // -- have any [...] default member initializers 4749 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4750 if (FD->hasInClassInitializer()) { 4751 auto *Init = FD->getInClassInitializer(); 4752 return {NonCLikeKind::DefaultMemberInit, 4753 Init ? Init->getSourceRange() : D->getSourceRange()}; 4754 } 4755 continue; 4756 } 4757 4758 // FIXME: We don't allow friend declarations. This violates the wording of 4759 // P1766, but not the intent. 4760 if (isa<FriendDecl>(D)) 4761 return {NonCLikeKind::Friend, D->getSourceRange()}; 4762 4763 // -- declare any members other than non-static data members, member 4764 // enumerations, or member classes, 4765 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4766 isa<EnumDecl>(D)) 4767 continue; 4768 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4769 if (!MemberRD) { 4770 if (D->isImplicit()) 4771 continue; 4772 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4773 } 4774 4775 // -- contain a lambda-expression, 4776 if (MemberRD->isLambda()) 4777 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4778 4779 // and all member classes shall also satisfy these requirements 4780 // (recursively). 4781 if (MemberRD->isThisDeclarationADefinition()) { 4782 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4783 return Kind; 4784 } 4785 } 4786 4787 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4788 } 4789 4790 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4791 TypedefNameDecl *NewTD) { 4792 if (TagFromDeclSpec->isInvalidDecl()) 4793 return; 4794 4795 // Do nothing if the tag already has a name for linkage purposes. 4796 if (TagFromDeclSpec->hasNameForLinkage()) 4797 return; 4798 4799 // A well-formed anonymous tag must always be a TUK_Definition. 4800 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4801 4802 // The type must match the tag exactly; no qualifiers allowed. 4803 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4804 Context.getTagDeclType(TagFromDeclSpec))) { 4805 if (getLangOpts().CPlusPlus) 4806 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4807 return; 4808 } 4809 4810 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4811 // An unnamed class with a typedef name for linkage purposes shall [be 4812 // C-like]. 4813 // 4814 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4815 // shouldn't happen, but there are constructs that the language rule doesn't 4816 // disallow for which we can't reasonably avoid computing linkage early. 4817 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4818 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4819 : NonCLikeKind(); 4820 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4821 if (NonCLike || ChangesLinkage) { 4822 if (NonCLike.Kind == NonCLikeKind::Invalid) 4823 return; 4824 4825 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4826 if (ChangesLinkage) { 4827 // If the linkage changes, we can't accept this as an extension. 4828 if (NonCLike.Kind == NonCLikeKind::None) 4829 DiagID = diag::err_typedef_changes_linkage; 4830 else 4831 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4832 } 4833 4834 SourceLocation FixitLoc = 4835 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4836 llvm::SmallString<40> TextToInsert; 4837 TextToInsert += ' '; 4838 TextToInsert += NewTD->getIdentifier()->getName(); 4839 4840 Diag(FixitLoc, DiagID) 4841 << isa<TypeAliasDecl>(NewTD) 4842 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4843 if (NonCLike.Kind != NonCLikeKind::None) { 4844 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4845 << NonCLike.Kind - 1 << NonCLike.Range; 4846 } 4847 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4848 << NewTD << isa<TypeAliasDecl>(NewTD); 4849 4850 if (ChangesLinkage) 4851 return; 4852 } 4853 4854 // Otherwise, set this as the anon-decl typedef for the tag. 4855 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4856 } 4857 4858 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4859 switch (T) { 4860 case DeclSpec::TST_class: 4861 return 0; 4862 case DeclSpec::TST_struct: 4863 return 1; 4864 case DeclSpec::TST_interface: 4865 return 2; 4866 case DeclSpec::TST_union: 4867 return 3; 4868 case DeclSpec::TST_enum: 4869 return 4; 4870 default: 4871 llvm_unreachable("unexpected type specifier"); 4872 } 4873 } 4874 4875 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4876 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4877 /// parameters to cope with template friend declarations. 4878 Decl * 4879 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4880 MultiTemplateParamsArg TemplateParams, 4881 bool IsExplicitInstantiation, 4882 RecordDecl *&AnonRecord) { 4883 Decl *TagD = nullptr; 4884 TagDecl *Tag = nullptr; 4885 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4886 DS.getTypeSpecType() == DeclSpec::TST_struct || 4887 DS.getTypeSpecType() == DeclSpec::TST_interface || 4888 DS.getTypeSpecType() == DeclSpec::TST_union || 4889 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4890 TagD = DS.getRepAsDecl(); 4891 4892 if (!TagD) // We probably had an error 4893 return nullptr; 4894 4895 // Note that the above type specs guarantee that the 4896 // type rep is a Decl, whereas in many of the others 4897 // it's a Type. 4898 if (isa<TagDecl>(TagD)) 4899 Tag = cast<TagDecl>(TagD); 4900 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4901 Tag = CTD->getTemplatedDecl(); 4902 } 4903 4904 if (Tag) { 4905 handleTagNumbering(Tag, S); 4906 Tag->setFreeStanding(); 4907 if (Tag->isInvalidDecl()) 4908 return Tag; 4909 } 4910 4911 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4912 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4913 // or incomplete types shall not be restrict-qualified." 4914 if (TypeQuals & DeclSpec::TQ_restrict) 4915 Diag(DS.getRestrictSpecLoc(), 4916 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4917 << DS.getSourceRange(); 4918 } 4919 4920 if (DS.isInlineSpecified()) 4921 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4922 << getLangOpts().CPlusPlus17; 4923 4924 if (DS.hasConstexprSpecifier()) { 4925 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4926 // and definitions of functions and variables. 4927 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4928 // the declaration of a function or function template 4929 if (Tag) 4930 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4931 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4932 << static_cast<int>(DS.getConstexprSpecifier()); 4933 else 4934 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4935 << static_cast<int>(DS.getConstexprSpecifier()); 4936 // Don't emit warnings after this error. 4937 return TagD; 4938 } 4939 4940 DiagnoseFunctionSpecifiers(DS); 4941 4942 if (DS.isFriendSpecified()) { 4943 // If we're dealing with a decl but not a TagDecl, assume that 4944 // whatever routines created it handled the friendship aspect. 4945 if (TagD && !Tag) 4946 return nullptr; 4947 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4948 } 4949 4950 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4951 bool IsExplicitSpecialization = 4952 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4953 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4954 !IsExplicitInstantiation && !IsExplicitSpecialization && 4955 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4956 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4957 // nested-name-specifier unless it is an explicit instantiation 4958 // or an explicit specialization. 4959 // 4960 // FIXME: We allow class template partial specializations here too, per the 4961 // obvious intent of DR1819. 4962 // 4963 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4964 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4965 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4966 return nullptr; 4967 } 4968 4969 // Track whether this decl-specifier declares anything. 4970 bool DeclaresAnything = true; 4971 4972 // Handle anonymous struct definitions. 4973 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4974 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4975 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4976 if (getLangOpts().CPlusPlus || 4977 Record->getDeclContext()->isRecord()) { 4978 // If CurContext is a DeclContext that can contain statements, 4979 // RecursiveASTVisitor won't visit the decls that 4980 // BuildAnonymousStructOrUnion() will put into CurContext. 4981 // Also store them here so that they can be part of the 4982 // DeclStmt that gets created in this case. 4983 // FIXME: Also return the IndirectFieldDecls created by 4984 // BuildAnonymousStructOr union, for the same reason? 4985 if (CurContext->isFunctionOrMethod()) 4986 AnonRecord = Record; 4987 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4988 Context.getPrintingPolicy()); 4989 } 4990 4991 DeclaresAnything = false; 4992 } 4993 } 4994 4995 // C11 6.7.2.1p2: 4996 // A struct-declaration that does not declare an anonymous structure or 4997 // anonymous union shall contain a struct-declarator-list. 4998 // 4999 // This rule also existed in C89 and C99; the grammar for struct-declaration 5000 // did not permit a struct-declaration without a struct-declarator-list. 5001 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 5002 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 5003 // Check for Microsoft C extension: anonymous struct/union member. 5004 // Handle 2 kinds of anonymous struct/union: 5005 // struct STRUCT; 5006 // union UNION; 5007 // and 5008 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 5009 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 5010 if ((Tag && Tag->getDeclName()) || 5011 DS.getTypeSpecType() == DeclSpec::TST_typename) { 5012 RecordDecl *Record = nullptr; 5013 if (Tag) 5014 Record = dyn_cast<RecordDecl>(Tag); 5015 else if (const RecordType *RT = 5016 DS.getRepAsType().get()->getAsStructureType()) 5017 Record = RT->getDecl(); 5018 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 5019 Record = UT->getDecl(); 5020 5021 if (Record && getLangOpts().MicrosoftExt) { 5022 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 5023 << Record->isUnion() << DS.getSourceRange(); 5024 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 5025 } 5026 5027 DeclaresAnything = false; 5028 } 5029 } 5030 5031 // Skip all the checks below if we have a type error. 5032 if (DS.getTypeSpecType() == DeclSpec::TST_error || 5033 (TagD && TagD->isInvalidDecl())) 5034 return TagD; 5035 5036 if (getLangOpts().CPlusPlus && 5037 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 5038 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 5039 if (Enum->enumerator_begin() == Enum->enumerator_end() && 5040 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 5041 DeclaresAnything = false; 5042 5043 if (!DS.isMissingDeclaratorOk()) { 5044 // Customize diagnostic for a typedef missing a name. 5045 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 5046 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 5047 << DS.getSourceRange(); 5048 else 5049 DeclaresAnything = false; 5050 } 5051 5052 if (DS.isModulePrivateSpecified() && 5053 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 5054 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 5055 << Tag->getTagKind() 5056 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 5057 5058 ActOnDocumentableDecl(TagD); 5059 5060 // C 6.7/2: 5061 // A declaration [...] shall declare at least a declarator [...], a tag, 5062 // or the members of an enumeration. 5063 // C++ [dcl.dcl]p3: 5064 // [If there are no declarators], and except for the declaration of an 5065 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5066 // names into the program, or shall redeclare a name introduced by a 5067 // previous declaration. 5068 if (!DeclaresAnything) { 5069 // In C, we allow this as a (popular) extension / bug. Don't bother 5070 // producing further diagnostics for redundant qualifiers after this. 5071 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 5072 ? diag::err_no_declarators 5073 : diag::ext_no_declarators) 5074 << DS.getSourceRange(); 5075 return TagD; 5076 } 5077 5078 // C++ [dcl.stc]p1: 5079 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 5080 // init-declarator-list of the declaration shall not be empty. 5081 // C++ [dcl.fct.spec]p1: 5082 // If a cv-qualifier appears in a decl-specifier-seq, the 5083 // init-declarator-list of the declaration shall not be empty. 5084 // 5085 // Spurious qualifiers here appear to be valid in C. 5086 unsigned DiagID = diag::warn_standalone_specifier; 5087 if (getLangOpts().CPlusPlus) 5088 DiagID = diag::ext_standalone_specifier; 5089 5090 // Note that a linkage-specification sets a storage class, but 5091 // 'extern "C" struct foo;' is actually valid and not theoretically 5092 // useless. 5093 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5094 if (SCS == DeclSpec::SCS_mutable) 5095 // Since mutable is not a viable storage class specifier in C, there is 5096 // no reason to treat it as an extension. Instead, diagnose as an error. 5097 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 5098 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 5099 Diag(DS.getStorageClassSpecLoc(), DiagID) 5100 << DeclSpec::getSpecifierName(SCS); 5101 } 5102 5103 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 5104 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 5105 << DeclSpec::getSpecifierName(TSCS); 5106 if (DS.getTypeQualifiers()) { 5107 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5108 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 5109 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5110 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 5111 // Restrict is covered above. 5112 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5113 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 5114 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5115 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 5116 } 5117 5118 // Warn about ignored type attributes, for example: 5119 // __attribute__((aligned)) struct A; 5120 // Attributes should be placed after tag to apply to type declaration. 5121 if (!DS.getAttributes().empty()) { 5122 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 5123 if (TypeSpecType == DeclSpec::TST_class || 5124 TypeSpecType == DeclSpec::TST_struct || 5125 TypeSpecType == DeclSpec::TST_interface || 5126 TypeSpecType == DeclSpec::TST_union || 5127 TypeSpecType == DeclSpec::TST_enum) { 5128 for (const ParsedAttr &AL : DS.getAttributes()) 5129 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 5130 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 5131 } 5132 } 5133 5134 return TagD; 5135 } 5136 5137 /// We are trying to inject an anonymous member into the given scope; 5138 /// check if there's an existing declaration that can't be overloaded. 5139 /// 5140 /// \return true if this is a forbidden redeclaration 5141 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 5142 Scope *S, 5143 DeclContext *Owner, 5144 DeclarationName Name, 5145 SourceLocation NameLoc, 5146 bool IsUnion) { 5147 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 5148 Sema::ForVisibleRedeclaration); 5149 if (!SemaRef.LookupName(R, S)) return false; 5150 5151 // Pick a representative declaration. 5152 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 5153 assert(PrevDecl && "Expected a non-null Decl"); 5154 5155 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 5156 return false; 5157 5158 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 5159 << IsUnion << Name; 5160 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5161 5162 return true; 5163 } 5164 5165 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 5166 /// anonymous struct or union AnonRecord into the owning context Owner 5167 /// and scope S. This routine will be invoked just after we realize 5168 /// that an unnamed union or struct is actually an anonymous union or 5169 /// struct, e.g., 5170 /// 5171 /// @code 5172 /// union { 5173 /// int i; 5174 /// float f; 5175 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5176 /// // f into the surrounding scope.x 5177 /// @endcode 5178 /// 5179 /// This routine is recursive, injecting the names of nested anonymous 5180 /// structs/unions into the owning context and scope as well. 5181 static bool 5182 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5183 RecordDecl *AnonRecord, AccessSpecifier AS, 5184 SmallVectorImpl<NamedDecl *> &Chaining) { 5185 bool Invalid = false; 5186 5187 // Look every FieldDecl and IndirectFieldDecl with a name. 5188 for (auto *D : AnonRecord->decls()) { 5189 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5190 cast<NamedDecl>(D)->getDeclName()) { 5191 ValueDecl *VD = cast<ValueDecl>(D); 5192 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5193 VD->getLocation(), 5194 AnonRecord->isUnion())) { 5195 // C++ [class.union]p2: 5196 // The names of the members of an anonymous union shall be 5197 // distinct from the names of any other entity in the 5198 // scope in which the anonymous union is declared. 5199 Invalid = true; 5200 } else { 5201 // C++ [class.union]p2: 5202 // For the purpose of name lookup, after the anonymous union 5203 // definition, the members of the anonymous union are 5204 // considered to have been defined in the scope in which the 5205 // anonymous union is declared. 5206 unsigned OldChainingSize = Chaining.size(); 5207 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5208 Chaining.append(IF->chain_begin(), IF->chain_end()); 5209 else 5210 Chaining.push_back(VD); 5211 5212 assert(Chaining.size() >= 2); 5213 NamedDecl **NamedChain = 5214 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5215 for (unsigned i = 0; i < Chaining.size(); i++) 5216 NamedChain[i] = Chaining[i]; 5217 5218 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5219 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5220 VD->getType(), {NamedChain, Chaining.size()}); 5221 5222 for (const auto *Attr : VD->attrs()) 5223 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5224 5225 IndirectField->setAccess(AS); 5226 IndirectField->setImplicit(); 5227 SemaRef.PushOnScopeChains(IndirectField, S); 5228 5229 // That includes picking up the appropriate access specifier. 5230 if (AS != AS_none) IndirectField->setAccess(AS); 5231 5232 Chaining.resize(OldChainingSize); 5233 } 5234 } 5235 } 5236 5237 return Invalid; 5238 } 5239 5240 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5241 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5242 /// illegal input values are mapped to SC_None. 5243 static StorageClass 5244 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5245 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5246 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5247 "Parser allowed 'typedef' as storage class VarDecl."); 5248 switch (StorageClassSpec) { 5249 case DeclSpec::SCS_unspecified: return SC_None; 5250 case DeclSpec::SCS_extern: 5251 if (DS.isExternInLinkageSpec()) 5252 return SC_None; 5253 return SC_Extern; 5254 case DeclSpec::SCS_static: return SC_Static; 5255 case DeclSpec::SCS_auto: return SC_Auto; 5256 case DeclSpec::SCS_register: return SC_Register; 5257 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5258 // Illegal SCSs map to None: error reporting is up to the caller. 5259 case DeclSpec::SCS_mutable: // Fall through. 5260 case DeclSpec::SCS_typedef: return SC_None; 5261 } 5262 llvm_unreachable("unknown storage class specifier"); 5263 } 5264 5265 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5266 assert(Record->hasInClassInitializer()); 5267 5268 for (const auto *I : Record->decls()) { 5269 const auto *FD = dyn_cast<FieldDecl>(I); 5270 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5271 FD = IFD->getAnonField(); 5272 if (FD && FD->hasInClassInitializer()) 5273 return FD->getLocation(); 5274 } 5275 5276 llvm_unreachable("couldn't find in-class initializer"); 5277 } 5278 5279 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5280 SourceLocation DefaultInitLoc) { 5281 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5282 return; 5283 5284 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5285 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5286 } 5287 5288 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5289 CXXRecordDecl *AnonUnion) { 5290 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5291 return; 5292 5293 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5294 } 5295 5296 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5297 /// anonymous structure or union. Anonymous unions are a C++ feature 5298 /// (C++ [class.union]) and a C11 feature; anonymous structures 5299 /// are a C11 feature and GNU C++ extension. 5300 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5301 AccessSpecifier AS, 5302 RecordDecl *Record, 5303 const PrintingPolicy &Policy) { 5304 DeclContext *Owner = Record->getDeclContext(); 5305 5306 // Diagnose whether this anonymous struct/union is an extension. 5307 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5308 Diag(Record->getLocation(), diag::ext_anonymous_union); 5309 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5310 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5311 else if (!Record->isUnion() && !getLangOpts().C11) 5312 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5313 5314 // C and C++ require different kinds of checks for anonymous 5315 // structs/unions. 5316 bool Invalid = false; 5317 if (getLangOpts().CPlusPlus) { 5318 const char *PrevSpec = nullptr; 5319 if (Record->isUnion()) { 5320 // C++ [class.union]p6: 5321 // C++17 [class.union.anon]p2: 5322 // Anonymous unions declared in a named namespace or in the 5323 // global namespace shall be declared static. 5324 unsigned DiagID; 5325 DeclContext *OwnerScope = Owner->getRedeclContext(); 5326 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5327 (OwnerScope->isTranslationUnit() || 5328 (OwnerScope->isNamespace() && 5329 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5330 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5331 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5332 5333 // Recover by adding 'static'. 5334 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5335 PrevSpec, DiagID, Policy); 5336 } 5337 // C++ [class.union]p6: 5338 // A storage class is not allowed in a declaration of an 5339 // anonymous union in a class scope. 5340 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5341 isa<RecordDecl>(Owner)) { 5342 Diag(DS.getStorageClassSpecLoc(), 5343 diag::err_anonymous_union_with_storage_spec) 5344 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5345 5346 // Recover by removing the storage specifier. 5347 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5348 SourceLocation(), 5349 PrevSpec, DiagID, Context.getPrintingPolicy()); 5350 } 5351 } 5352 5353 // Ignore const/volatile/restrict qualifiers. 5354 if (DS.getTypeQualifiers()) { 5355 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5356 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5357 << Record->isUnion() << "const" 5358 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5359 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5360 Diag(DS.getVolatileSpecLoc(), 5361 diag::ext_anonymous_struct_union_qualified) 5362 << Record->isUnion() << "volatile" 5363 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5364 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5365 Diag(DS.getRestrictSpecLoc(), 5366 diag::ext_anonymous_struct_union_qualified) 5367 << Record->isUnion() << "restrict" 5368 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5369 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5370 Diag(DS.getAtomicSpecLoc(), 5371 diag::ext_anonymous_struct_union_qualified) 5372 << Record->isUnion() << "_Atomic" 5373 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5374 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5375 Diag(DS.getUnalignedSpecLoc(), 5376 diag::ext_anonymous_struct_union_qualified) 5377 << Record->isUnion() << "__unaligned" 5378 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5379 5380 DS.ClearTypeQualifiers(); 5381 } 5382 5383 // C++ [class.union]p2: 5384 // The member-specification of an anonymous union shall only 5385 // define non-static data members. [Note: nested types and 5386 // functions cannot be declared within an anonymous union. ] 5387 for (auto *Mem : Record->decls()) { 5388 // Ignore invalid declarations; we already diagnosed them. 5389 if (Mem->isInvalidDecl()) 5390 continue; 5391 5392 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5393 // C++ [class.union]p3: 5394 // An anonymous union shall not have private or protected 5395 // members (clause 11). 5396 assert(FD->getAccess() != AS_none); 5397 if (FD->getAccess() != AS_public) { 5398 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5399 << Record->isUnion() << (FD->getAccess() == AS_protected); 5400 Invalid = true; 5401 } 5402 5403 // C++ [class.union]p1 5404 // An object of a class with a non-trivial constructor, a non-trivial 5405 // copy constructor, a non-trivial destructor, or a non-trivial copy 5406 // assignment operator cannot be a member of a union, nor can an 5407 // array of such objects. 5408 if (CheckNontrivialField(FD)) 5409 Invalid = true; 5410 } else if (Mem->isImplicit()) { 5411 // Any implicit members are fine. 5412 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5413 // This is a type that showed up in an 5414 // elaborated-type-specifier inside the anonymous struct or 5415 // union, but which actually declares a type outside of the 5416 // anonymous struct or union. It's okay. 5417 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5418 if (!MemRecord->isAnonymousStructOrUnion() && 5419 MemRecord->getDeclName()) { 5420 // Visual C++ allows type definition in anonymous struct or union. 5421 if (getLangOpts().MicrosoftExt) 5422 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5423 << Record->isUnion(); 5424 else { 5425 // This is a nested type declaration. 5426 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5427 << Record->isUnion(); 5428 Invalid = true; 5429 } 5430 } else { 5431 // This is an anonymous type definition within another anonymous type. 5432 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5433 // not part of standard C++. 5434 Diag(MemRecord->getLocation(), 5435 diag::ext_anonymous_record_with_anonymous_type) 5436 << Record->isUnion(); 5437 } 5438 } else if (isa<AccessSpecDecl>(Mem)) { 5439 // Any access specifier is fine. 5440 } else if (isa<StaticAssertDecl>(Mem)) { 5441 // In C++1z, static_assert declarations are also fine. 5442 } else { 5443 // We have something that isn't a non-static data 5444 // member. Complain about it. 5445 unsigned DK = diag::err_anonymous_record_bad_member; 5446 if (isa<TypeDecl>(Mem)) 5447 DK = diag::err_anonymous_record_with_type; 5448 else if (isa<FunctionDecl>(Mem)) 5449 DK = diag::err_anonymous_record_with_function; 5450 else if (isa<VarDecl>(Mem)) 5451 DK = diag::err_anonymous_record_with_static; 5452 5453 // Visual C++ allows type definition in anonymous struct or union. 5454 if (getLangOpts().MicrosoftExt && 5455 DK == diag::err_anonymous_record_with_type) 5456 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5457 << Record->isUnion(); 5458 else { 5459 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5460 Invalid = true; 5461 } 5462 } 5463 } 5464 5465 // C++11 [class.union]p8 (DR1460): 5466 // At most one variant member of a union may have a 5467 // brace-or-equal-initializer. 5468 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5469 Owner->isRecord()) 5470 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5471 cast<CXXRecordDecl>(Record)); 5472 } 5473 5474 if (!Record->isUnion() && !Owner->isRecord()) { 5475 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5476 << getLangOpts().CPlusPlus; 5477 Invalid = true; 5478 } 5479 5480 // C++ [dcl.dcl]p3: 5481 // [If there are no declarators], and except for the declaration of an 5482 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5483 // names into the program 5484 // C++ [class.mem]p2: 5485 // each such member-declaration shall either declare at least one member 5486 // name of the class or declare at least one unnamed bit-field 5487 // 5488 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5489 if (getLangOpts().CPlusPlus && Record->field_empty()) 5490 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5491 5492 // Mock up a declarator. 5493 Declarator Dc(DS, DeclaratorContext::Member); 5494 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5495 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5496 5497 // Create a declaration for this anonymous struct/union. 5498 NamedDecl *Anon = nullptr; 5499 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5500 Anon = FieldDecl::Create( 5501 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5502 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5503 /*BitWidth=*/nullptr, /*Mutable=*/false, 5504 /*InitStyle=*/ICIS_NoInit); 5505 Anon->setAccess(AS); 5506 ProcessDeclAttributes(S, Anon, Dc); 5507 5508 if (getLangOpts().CPlusPlus) 5509 FieldCollector->Add(cast<FieldDecl>(Anon)); 5510 } else { 5511 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5512 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5513 if (SCSpec == DeclSpec::SCS_mutable) { 5514 // mutable can only appear on non-static class members, so it's always 5515 // an error here 5516 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5517 Invalid = true; 5518 SC = SC_None; 5519 } 5520 5521 assert(DS.getAttributes().empty() && "No attribute expected"); 5522 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5523 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5524 Context.getTypeDeclType(Record), TInfo, SC); 5525 5526 // Default-initialize the implicit variable. This initialization will be 5527 // trivial in almost all cases, except if a union member has an in-class 5528 // initializer: 5529 // union { int n = 0; }; 5530 ActOnUninitializedDecl(Anon); 5531 } 5532 Anon->setImplicit(); 5533 5534 // Mark this as an anonymous struct/union type. 5535 Record->setAnonymousStructOrUnion(true); 5536 5537 // Add the anonymous struct/union object to the current 5538 // context. We'll be referencing this object when we refer to one of 5539 // its members. 5540 Owner->addDecl(Anon); 5541 5542 // Inject the members of the anonymous struct/union into the owning 5543 // context and into the identifier resolver chain for name lookup 5544 // purposes. 5545 SmallVector<NamedDecl*, 2> Chain; 5546 Chain.push_back(Anon); 5547 5548 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5549 Invalid = true; 5550 5551 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5552 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5553 MangleNumberingContext *MCtx; 5554 Decl *ManglingContextDecl; 5555 std::tie(MCtx, ManglingContextDecl) = 5556 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5557 if (MCtx) { 5558 Context.setManglingNumber( 5559 NewVD, MCtx->getManglingNumber( 5560 NewVD, getMSManglingNumber(getLangOpts(), S))); 5561 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5562 } 5563 } 5564 } 5565 5566 if (Invalid) 5567 Anon->setInvalidDecl(); 5568 5569 return Anon; 5570 } 5571 5572 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5573 /// Microsoft C anonymous structure. 5574 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5575 /// Example: 5576 /// 5577 /// struct A { int a; }; 5578 /// struct B { struct A; int b; }; 5579 /// 5580 /// void foo() { 5581 /// B var; 5582 /// var.a = 3; 5583 /// } 5584 /// 5585 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5586 RecordDecl *Record) { 5587 assert(Record && "expected a record!"); 5588 5589 // Mock up a declarator. 5590 Declarator Dc(DS, DeclaratorContext::TypeName); 5591 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5592 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5593 5594 auto *ParentDecl = cast<RecordDecl>(CurContext); 5595 QualType RecTy = Context.getTypeDeclType(Record); 5596 5597 // Create a declaration for this anonymous struct. 5598 NamedDecl *Anon = 5599 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5600 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5601 /*BitWidth=*/nullptr, /*Mutable=*/false, 5602 /*InitStyle=*/ICIS_NoInit); 5603 Anon->setImplicit(); 5604 5605 // Add the anonymous struct object to the current context. 5606 CurContext->addDecl(Anon); 5607 5608 // Inject the members of the anonymous struct into the current 5609 // context and into the identifier resolver chain for name lookup 5610 // purposes. 5611 SmallVector<NamedDecl*, 2> Chain; 5612 Chain.push_back(Anon); 5613 5614 RecordDecl *RecordDef = Record->getDefinition(); 5615 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5616 diag::err_field_incomplete_or_sizeless) || 5617 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5618 AS_none, Chain)) { 5619 Anon->setInvalidDecl(); 5620 ParentDecl->setInvalidDecl(); 5621 } 5622 5623 return Anon; 5624 } 5625 5626 /// GetNameForDeclarator - Determine the full declaration name for the 5627 /// given Declarator. 5628 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5629 return GetNameFromUnqualifiedId(D.getName()); 5630 } 5631 5632 /// Retrieves the declaration name from a parsed unqualified-id. 5633 DeclarationNameInfo 5634 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5635 DeclarationNameInfo NameInfo; 5636 NameInfo.setLoc(Name.StartLocation); 5637 5638 switch (Name.getKind()) { 5639 5640 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5641 case UnqualifiedIdKind::IK_Identifier: 5642 NameInfo.setName(Name.Identifier); 5643 return NameInfo; 5644 5645 case UnqualifiedIdKind::IK_DeductionGuideName: { 5646 // C++ [temp.deduct.guide]p3: 5647 // The simple-template-id shall name a class template specialization. 5648 // The template-name shall be the same identifier as the template-name 5649 // of the simple-template-id. 5650 // These together intend to imply that the template-name shall name a 5651 // class template. 5652 // FIXME: template<typename T> struct X {}; 5653 // template<typename T> using Y = X<T>; 5654 // Y(int) -> Y<int>; 5655 // satisfies these rules but does not name a class template. 5656 TemplateName TN = Name.TemplateName.get().get(); 5657 auto *Template = TN.getAsTemplateDecl(); 5658 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5659 Diag(Name.StartLocation, 5660 diag::err_deduction_guide_name_not_class_template) 5661 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5662 if (Template) 5663 Diag(Template->getLocation(), diag::note_template_decl_here); 5664 return DeclarationNameInfo(); 5665 } 5666 5667 NameInfo.setName( 5668 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5669 return NameInfo; 5670 } 5671 5672 case UnqualifiedIdKind::IK_OperatorFunctionId: 5673 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5674 Name.OperatorFunctionId.Operator)); 5675 NameInfo.setCXXOperatorNameRange(SourceRange( 5676 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5677 return NameInfo; 5678 5679 case UnqualifiedIdKind::IK_LiteralOperatorId: 5680 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5681 Name.Identifier)); 5682 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5683 return NameInfo; 5684 5685 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5686 TypeSourceInfo *TInfo; 5687 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5688 if (Ty.isNull()) 5689 return DeclarationNameInfo(); 5690 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5691 Context.getCanonicalType(Ty))); 5692 NameInfo.setNamedTypeInfo(TInfo); 5693 return NameInfo; 5694 } 5695 5696 case UnqualifiedIdKind::IK_ConstructorName: { 5697 TypeSourceInfo *TInfo; 5698 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5699 if (Ty.isNull()) 5700 return DeclarationNameInfo(); 5701 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5702 Context.getCanonicalType(Ty))); 5703 NameInfo.setNamedTypeInfo(TInfo); 5704 return NameInfo; 5705 } 5706 5707 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5708 // In well-formed code, we can only have a constructor 5709 // template-id that refers to the current context, so go there 5710 // to find the actual type being constructed. 5711 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5712 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5713 return DeclarationNameInfo(); 5714 5715 // Determine the type of the class being constructed. 5716 QualType CurClassType = Context.getTypeDeclType(CurClass); 5717 5718 // FIXME: Check two things: that the template-id names the same type as 5719 // CurClassType, and that the template-id does not occur when the name 5720 // was qualified. 5721 5722 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5723 Context.getCanonicalType(CurClassType))); 5724 // FIXME: should we retrieve TypeSourceInfo? 5725 NameInfo.setNamedTypeInfo(nullptr); 5726 return NameInfo; 5727 } 5728 5729 case UnqualifiedIdKind::IK_DestructorName: { 5730 TypeSourceInfo *TInfo; 5731 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5732 if (Ty.isNull()) 5733 return DeclarationNameInfo(); 5734 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5735 Context.getCanonicalType(Ty))); 5736 NameInfo.setNamedTypeInfo(TInfo); 5737 return NameInfo; 5738 } 5739 5740 case UnqualifiedIdKind::IK_TemplateId: { 5741 TemplateName TName = Name.TemplateId->Template.get(); 5742 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5743 return Context.getNameForTemplate(TName, TNameLoc); 5744 } 5745 5746 } // switch (Name.getKind()) 5747 5748 llvm_unreachable("Unknown name kind"); 5749 } 5750 5751 static QualType getCoreType(QualType Ty) { 5752 do { 5753 if (Ty->isPointerType() || Ty->isReferenceType()) 5754 Ty = Ty->getPointeeType(); 5755 else if (Ty->isArrayType()) 5756 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5757 else 5758 return Ty.withoutLocalFastQualifiers(); 5759 } while (true); 5760 } 5761 5762 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5763 /// and Definition have "nearly" matching parameters. This heuristic is 5764 /// used to improve diagnostics in the case where an out-of-line function 5765 /// definition doesn't match any declaration within the class or namespace. 5766 /// Also sets Params to the list of indices to the parameters that differ 5767 /// between the declaration and the definition. If hasSimilarParameters 5768 /// returns true and Params is empty, then all of the parameters match. 5769 static bool hasSimilarParameters(ASTContext &Context, 5770 FunctionDecl *Declaration, 5771 FunctionDecl *Definition, 5772 SmallVectorImpl<unsigned> &Params) { 5773 Params.clear(); 5774 if (Declaration->param_size() != Definition->param_size()) 5775 return false; 5776 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5777 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5778 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5779 5780 // The parameter types are identical 5781 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5782 continue; 5783 5784 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5785 QualType DefParamBaseTy = getCoreType(DefParamTy); 5786 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5787 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5788 5789 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5790 (DeclTyName && DeclTyName == DefTyName)) 5791 Params.push_back(Idx); 5792 else // The two parameters aren't even close 5793 return false; 5794 } 5795 5796 return true; 5797 } 5798 5799 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5800 /// declarator needs to be rebuilt in the current instantiation. 5801 /// Any bits of declarator which appear before the name are valid for 5802 /// consideration here. That's specifically the type in the decl spec 5803 /// and the base type in any member-pointer chunks. 5804 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5805 DeclarationName Name) { 5806 // The types we specifically need to rebuild are: 5807 // - typenames, typeofs, and decltypes 5808 // - types which will become injected class names 5809 // Of course, we also need to rebuild any type referencing such a 5810 // type. It's safest to just say "dependent", but we call out a 5811 // few cases here. 5812 5813 DeclSpec &DS = D.getMutableDeclSpec(); 5814 switch (DS.getTypeSpecType()) { 5815 case DeclSpec::TST_typename: 5816 case DeclSpec::TST_typeofType: 5817 case DeclSpec::TST_underlyingType: 5818 case DeclSpec::TST_atomic: { 5819 // Grab the type from the parser. 5820 TypeSourceInfo *TSI = nullptr; 5821 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5822 if (T.isNull() || !T->isInstantiationDependentType()) break; 5823 5824 // Make sure there's a type source info. This isn't really much 5825 // of a waste; most dependent types should have type source info 5826 // attached already. 5827 if (!TSI) 5828 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5829 5830 // Rebuild the type in the current instantiation. 5831 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5832 if (!TSI) return true; 5833 5834 // Store the new type back in the decl spec. 5835 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5836 DS.UpdateTypeRep(LocType); 5837 break; 5838 } 5839 5840 case DeclSpec::TST_decltype: 5841 case DeclSpec::TST_typeofExpr: { 5842 Expr *E = DS.getRepAsExpr(); 5843 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5844 if (Result.isInvalid()) return true; 5845 DS.UpdateExprRep(Result.get()); 5846 break; 5847 } 5848 5849 default: 5850 // Nothing to do for these decl specs. 5851 break; 5852 } 5853 5854 // It doesn't matter what order we do this in. 5855 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5856 DeclaratorChunk &Chunk = D.getTypeObject(I); 5857 5858 // The only type information in the declarator which can come 5859 // before the declaration name is the base type of a member 5860 // pointer. 5861 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5862 continue; 5863 5864 // Rebuild the scope specifier in-place. 5865 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5866 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5867 return true; 5868 } 5869 5870 return false; 5871 } 5872 5873 /// Returns true if the declaration is declared in a system header or from a 5874 /// system macro. 5875 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { 5876 return SM.isInSystemHeader(D->getLocation()) || 5877 SM.isInSystemMacro(D->getLocation()); 5878 } 5879 5880 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5881 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5882 // of system decl. 5883 if (D->getPreviousDecl() || D->isImplicit()) 5884 return; 5885 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5886 if (Status != ReservedIdentifierStatus::NotReserved && 5887 !isFromSystemHeader(Context.getSourceManager(), D)) { 5888 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5889 << D << static_cast<int>(Status); 5890 } 5891 } 5892 5893 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5894 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5895 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5896 5897 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5898 Dcl && Dcl->getDeclContext()->isFileContext()) 5899 Dcl->setTopLevelDeclInObjCContainer(); 5900 5901 return Dcl; 5902 } 5903 5904 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5905 /// If T is the name of a class, then each of the following shall have a 5906 /// name different from T: 5907 /// - every static data member of class T; 5908 /// - every member function of class T 5909 /// - every member of class T that is itself a type; 5910 /// \returns true if the declaration name violates these rules. 5911 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5912 DeclarationNameInfo NameInfo) { 5913 DeclarationName Name = NameInfo.getName(); 5914 5915 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5916 while (Record && Record->isAnonymousStructOrUnion()) 5917 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5918 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5919 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5920 return true; 5921 } 5922 5923 return false; 5924 } 5925 5926 /// Diagnose a declaration whose declarator-id has the given 5927 /// nested-name-specifier. 5928 /// 5929 /// \param SS The nested-name-specifier of the declarator-id. 5930 /// 5931 /// \param DC The declaration context to which the nested-name-specifier 5932 /// resolves. 5933 /// 5934 /// \param Name The name of the entity being declared. 5935 /// 5936 /// \param Loc The location of the name of the entity being declared. 5937 /// 5938 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5939 /// we're declaring an explicit / partial specialization / instantiation. 5940 /// 5941 /// \returns true if we cannot safely recover from this error, false otherwise. 5942 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5943 DeclarationName Name, 5944 SourceLocation Loc, bool IsTemplateId) { 5945 DeclContext *Cur = CurContext; 5946 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5947 Cur = Cur->getParent(); 5948 5949 // If the user provided a superfluous scope specifier that refers back to the 5950 // class in which the entity is already declared, diagnose and ignore it. 5951 // 5952 // class X { 5953 // void X::f(); 5954 // }; 5955 // 5956 // Note, it was once ill-formed to give redundant qualification in all 5957 // contexts, but that rule was removed by DR482. 5958 if (Cur->Equals(DC)) { 5959 if (Cur->isRecord()) { 5960 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5961 : diag::err_member_extra_qualification) 5962 << Name << FixItHint::CreateRemoval(SS.getRange()); 5963 SS.clear(); 5964 } else { 5965 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5966 } 5967 return false; 5968 } 5969 5970 // Check whether the qualifying scope encloses the scope of the original 5971 // declaration. For a template-id, we perform the checks in 5972 // CheckTemplateSpecializationScope. 5973 if (!Cur->Encloses(DC) && !IsTemplateId) { 5974 if (Cur->isRecord()) 5975 Diag(Loc, diag::err_member_qualification) 5976 << Name << SS.getRange(); 5977 else if (isa<TranslationUnitDecl>(DC)) 5978 Diag(Loc, diag::err_invalid_declarator_global_scope) 5979 << Name << SS.getRange(); 5980 else if (isa<FunctionDecl>(Cur)) 5981 Diag(Loc, diag::err_invalid_declarator_in_function) 5982 << Name << SS.getRange(); 5983 else if (isa<BlockDecl>(Cur)) 5984 Diag(Loc, diag::err_invalid_declarator_in_block) 5985 << Name << SS.getRange(); 5986 else if (isa<ExportDecl>(Cur)) { 5987 if (!isa<NamespaceDecl>(DC)) 5988 Diag(Loc, diag::err_export_non_namespace_scope_name) 5989 << Name << SS.getRange(); 5990 else 5991 // The cases that DC is not NamespaceDecl should be handled in 5992 // CheckRedeclarationExported. 5993 return false; 5994 } else 5995 Diag(Loc, diag::err_invalid_declarator_scope) 5996 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5997 5998 return true; 5999 } 6000 6001 if (Cur->isRecord()) { 6002 // Cannot qualify members within a class. 6003 Diag(Loc, diag::err_member_qualification) 6004 << Name << SS.getRange(); 6005 SS.clear(); 6006 6007 // C++ constructors and destructors with incorrect scopes can break 6008 // our AST invariants by having the wrong underlying types. If 6009 // that's the case, then drop this declaration entirely. 6010 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 6011 Name.getNameKind() == DeclarationName::CXXDestructorName) && 6012 !Context.hasSameType(Name.getCXXNameType(), 6013 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 6014 return true; 6015 6016 return false; 6017 } 6018 6019 // C++11 [dcl.meaning]p1: 6020 // [...] "The nested-name-specifier of the qualified declarator-id shall 6021 // not begin with a decltype-specifer" 6022 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 6023 while (SpecLoc.getPrefix()) 6024 SpecLoc = SpecLoc.getPrefix(); 6025 if (isa_and_nonnull<DecltypeType>( 6026 SpecLoc.getNestedNameSpecifier()->getAsType())) 6027 Diag(Loc, diag::err_decltype_in_declarator) 6028 << SpecLoc.getTypeLoc().getSourceRange(); 6029 6030 return false; 6031 } 6032 6033 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 6034 MultiTemplateParamsArg TemplateParamLists) { 6035 // TODO: consider using NameInfo for diagnostic. 6036 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6037 DeclarationName Name = NameInfo.getName(); 6038 6039 // All of these full declarators require an identifier. If it doesn't have 6040 // one, the ParsedFreeStandingDeclSpec action should be used. 6041 if (D.isDecompositionDeclarator()) { 6042 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 6043 } else if (!Name) { 6044 if (!D.isInvalidType()) // Reject this if we think it is valid. 6045 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 6046 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 6047 return nullptr; 6048 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 6049 return nullptr; 6050 6051 // The scope passed in may not be a decl scope. Zip up the scope tree until 6052 // we find one that is. 6053 while ((S->getFlags() & Scope::DeclScope) == 0 || 6054 (S->getFlags() & Scope::TemplateParamScope) != 0) 6055 S = S->getParent(); 6056 6057 DeclContext *DC = CurContext; 6058 if (D.getCXXScopeSpec().isInvalid()) 6059 D.setInvalidType(); 6060 else if (D.getCXXScopeSpec().isSet()) { 6061 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 6062 UPPC_DeclarationQualifier)) 6063 return nullptr; 6064 6065 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 6066 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 6067 if (!DC || isa<EnumDecl>(DC)) { 6068 // If we could not compute the declaration context, it's because the 6069 // declaration context is dependent but does not refer to a class, 6070 // class template, or class template partial specialization. Complain 6071 // and return early, to avoid the coming semantic disaster. 6072 Diag(D.getIdentifierLoc(), 6073 diag::err_template_qualified_declarator_no_match) 6074 << D.getCXXScopeSpec().getScopeRep() 6075 << D.getCXXScopeSpec().getRange(); 6076 return nullptr; 6077 } 6078 bool IsDependentContext = DC->isDependentContext(); 6079 6080 if (!IsDependentContext && 6081 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 6082 return nullptr; 6083 6084 // If a class is incomplete, do not parse entities inside it. 6085 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 6086 Diag(D.getIdentifierLoc(), 6087 diag::err_member_def_undefined_record) 6088 << Name << DC << D.getCXXScopeSpec().getRange(); 6089 return nullptr; 6090 } 6091 if (!D.getDeclSpec().isFriendSpecified()) { 6092 if (diagnoseQualifiedDeclaration( 6093 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 6094 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 6095 if (DC->isRecord()) 6096 return nullptr; 6097 6098 D.setInvalidType(); 6099 } 6100 } 6101 6102 // Check whether we need to rebuild the type of the given 6103 // declaration in the current instantiation. 6104 if (EnteringContext && IsDependentContext && 6105 TemplateParamLists.size() != 0) { 6106 ContextRAII SavedContext(*this, DC); 6107 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 6108 D.setInvalidType(); 6109 } 6110 } 6111 6112 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6113 QualType R = TInfo->getType(); 6114 6115 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6116 UPPC_DeclarationType)) 6117 D.setInvalidType(); 6118 6119 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6120 forRedeclarationInCurContext()); 6121 6122 // See if this is a redefinition of a variable in the same scope. 6123 if (!D.getCXXScopeSpec().isSet()) { 6124 bool IsLinkageLookup = false; 6125 bool CreateBuiltins = false; 6126 6127 // If the declaration we're planning to build will be a function 6128 // or object with linkage, then look for another declaration with 6129 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 6130 // 6131 // If the declaration we're planning to build will be declared with 6132 // external linkage in the translation unit, create any builtin with 6133 // the same name. 6134 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 6135 /* Do nothing*/; 6136 else if (CurContext->isFunctionOrMethod() && 6137 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 6138 R->isFunctionType())) { 6139 IsLinkageLookup = true; 6140 CreateBuiltins = 6141 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 6142 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 6143 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 6144 CreateBuiltins = true; 6145 6146 if (IsLinkageLookup) { 6147 Previous.clear(LookupRedeclarationWithLinkage); 6148 Previous.setRedeclarationKind(ForExternalRedeclaration); 6149 } 6150 6151 LookupName(Previous, S, CreateBuiltins); 6152 } else { // Something like "int foo::x;" 6153 LookupQualifiedName(Previous, DC); 6154 6155 // C++ [dcl.meaning]p1: 6156 // When the declarator-id is qualified, the declaration shall refer to a 6157 // previously declared member of the class or namespace to which the 6158 // qualifier refers (or, in the case of a namespace, of an element of the 6159 // inline namespace set of that namespace (7.3.1)) or to a specialization 6160 // thereof; [...] 6161 // 6162 // Note that we already checked the context above, and that we do not have 6163 // enough information to make sure that Previous contains the declaration 6164 // we want to match. For example, given: 6165 // 6166 // class X { 6167 // void f(); 6168 // void f(float); 6169 // }; 6170 // 6171 // void X::f(int) { } // ill-formed 6172 // 6173 // In this case, Previous will point to the overload set 6174 // containing the two f's declared in X, but neither of them 6175 // matches. 6176 6177 // C++ [dcl.meaning]p1: 6178 // [...] the member shall not merely have been introduced by a 6179 // using-declaration in the scope of the class or namespace nominated by 6180 // the nested-name-specifier of the declarator-id. 6181 RemoveUsingDecls(Previous); 6182 } 6183 6184 if (Previous.isSingleResult() && 6185 Previous.getFoundDecl()->isTemplateParameter()) { 6186 // Maybe we will complain about the shadowed template parameter. 6187 if (!D.isInvalidType()) 6188 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 6189 Previous.getFoundDecl()); 6190 6191 // Just pretend that we didn't see the previous declaration. 6192 Previous.clear(); 6193 } 6194 6195 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6196 // Forget that the previous declaration is the injected-class-name. 6197 Previous.clear(); 6198 6199 // In C++, the previous declaration we find might be a tag type 6200 // (class or enum). In this case, the new declaration will hide the 6201 // tag type. Note that this applies to functions, function templates, and 6202 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6203 if (Previous.isSingleTagDecl() && 6204 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6205 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6206 Previous.clear(); 6207 6208 // Check that there are no default arguments other than in the parameters 6209 // of a function declaration (C++ only). 6210 if (getLangOpts().CPlusPlus) 6211 CheckExtraCXXDefaultArguments(D); 6212 6213 NamedDecl *New; 6214 6215 bool AddToScope = true; 6216 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6217 if (TemplateParamLists.size()) { 6218 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6219 return nullptr; 6220 } 6221 6222 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6223 } else if (R->isFunctionType()) { 6224 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6225 TemplateParamLists, 6226 AddToScope); 6227 } else { 6228 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6229 AddToScope); 6230 } 6231 6232 if (!New) 6233 return nullptr; 6234 6235 // If this has an identifier and is not a function template specialization, 6236 // add it to the scope stack. 6237 if (New->getDeclName() && AddToScope) 6238 PushOnScopeChains(New, S); 6239 6240 if (isInOpenMPDeclareTargetContext()) 6241 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6242 6243 return New; 6244 } 6245 6246 /// Helper method to turn variable array types into constant array 6247 /// types in certain situations which would otherwise be errors (for 6248 /// GCC compatibility). 6249 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6250 ASTContext &Context, 6251 bool &SizeIsNegative, 6252 llvm::APSInt &Oversized) { 6253 // This method tries to turn a variable array into a constant 6254 // array even when the size isn't an ICE. This is necessary 6255 // for compatibility with code that depends on gcc's buggy 6256 // constant expression folding, like struct {char x[(int)(char*)2];} 6257 SizeIsNegative = false; 6258 Oversized = 0; 6259 6260 if (T->isDependentType()) 6261 return QualType(); 6262 6263 QualifierCollector Qs; 6264 const Type *Ty = Qs.strip(T); 6265 6266 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6267 QualType Pointee = PTy->getPointeeType(); 6268 QualType FixedType = 6269 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6270 Oversized); 6271 if (FixedType.isNull()) return FixedType; 6272 FixedType = Context.getPointerType(FixedType); 6273 return Qs.apply(Context, FixedType); 6274 } 6275 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6276 QualType Inner = PTy->getInnerType(); 6277 QualType FixedType = 6278 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6279 Oversized); 6280 if (FixedType.isNull()) return FixedType; 6281 FixedType = Context.getParenType(FixedType); 6282 return Qs.apply(Context, FixedType); 6283 } 6284 6285 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6286 if (!VLATy) 6287 return QualType(); 6288 6289 QualType ElemTy = VLATy->getElementType(); 6290 if (ElemTy->isVariablyModifiedType()) { 6291 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6292 SizeIsNegative, Oversized); 6293 if (ElemTy.isNull()) 6294 return QualType(); 6295 } 6296 6297 Expr::EvalResult Result; 6298 if (!VLATy->getSizeExpr() || 6299 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6300 return QualType(); 6301 6302 llvm::APSInt Res = Result.Val.getInt(); 6303 6304 // Check whether the array size is negative. 6305 if (Res.isSigned() && Res.isNegative()) { 6306 SizeIsNegative = true; 6307 return QualType(); 6308 } 6309 6310 // Check whether the array is too large to be addressed. 6311 unsigned ActiveSizeBits = 6312 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6313 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6314 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6315 : Res.getActiveBits(); 6316 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6317 Oversized = Res; 6318 return QualType(); 6319 } 6320 6321 QualType FoldedArrayType = Context.getConstantArrayType( 6322 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6323 return Qs.apply(Context, FoldedArrayType); 6324 } 6325 6326 static void 6327 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6328 SrcTL = SrcTL.getUnqualifiedLoc(); 6329 DstTL = DstTL.getUnqualifiedLoc(); 6330 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6331 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6332 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6333 DstPTL.getPointeeLoc()); 6334 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6335 return; 6336 } 6337 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6338 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6339 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6340 DstPTL.getInnerLoc()); 6341 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6342 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6343 return; 6344 } 6345 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6346 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6347 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6348 TypeLoc DstElemTL = DstATL.getElementLoc(); 6349 if (VariableArrayTypeLoc SrcElemATL = 6350 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6351 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6352 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6353 } else { 6354 DstElemTL.initializeFullCopy(SrcElemTL); 6355 } 6356 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6357 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6358 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6359 } 6360 6361 /// Helper method to turn variable array types into constant array 6362 /// types in certain situations which would otherwise be errors (for 6363 /// GCC compatibility). 6364 static TypeSourceInfo* 6365 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6366 ASTContext &Context, 6367 bool &SizeIsNegative, 6368 llvm::APSInt &Oversized) { 6369 QualType FixedTy 6370 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6371 SizeIsNegative, Oversized); 6372 if (FixedTy.isNull()) 6373 return nullptr; 6374 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6375 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6376 FixedTInfo->getTypeLoc()); 6377 return FixedTInfo; 6378 } 6379 6380 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6381 /// true if we were successful. 6382 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6383 QualType &T, SourceLocation Loc, 6384 unsigned FailedFoldDiagID) { 6385 bool SizeIsNegative; 6386 llvm::APSInt Oversized; 6387 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6388 TInfo, Context, SizeIsNegative, Oversized); 6389 if (FixedTInfo) { 6390 Diag(Loc, diag::ext_vla_folded_to_constant); 6391 TInfo = FixedTInfo; 6392 T = FixedTInfo->getType(); 6393 return true; 6394 } 6395 6396 if (SizeIsNegative) 6397 Diag(Loc, diag::err_typecheck_negative_array_size); 6398 else if (Oversized.getBoolValue()) 6399 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6400 else if (FailedFoldDiagID) 6401 Diag(Loc, FailedFoldDiagID); 6402 return false; 6403 } 6404 6405 /// Register the given locally-scoped extern "C" declaration so 6406 /// that it can be found later for redeclarations. We include any extern "C" 6407 /// declaration that is not visible in the translation unit here, not just 6408 /// function-scope declarations. 6409 void 6410 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6411 if (!getLangOpts().CPlusPlus && 6412 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6413 // Don't need to track declarations in the TU in C. 6414 return; 6415 6416 // Note that we have a locally-scoped external with this name. 6417 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6418 } 6419 6420 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6421 // FIXME: We can have multiple results via __attribute__((overloadable)). 6422 auto Result = Context.getExternCContextDecl()->lookup(Name); 6423 return Result.empty() ? nullptr : *Result.begin(); 6424 } 6425 6426 /// Diagnose function specifiers on a declaration of an identifier that 6427 /// does not identify a function. 6428 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6429 // FIXME: We should probably indicate the identifier in question to avoid 6430 // confusion for constructs like "virtual int a(), b;" 6431 if (DS.isVirtualSpecified()) 6432 Diag(DS.getVirtualSpecLoc(), 6433 diag::err_virtual_non_function); 6434 6435 if (DS.hasExplicitSpecifier()) 6436 Diag(DS.getExplicitSpecLoc(), 6437 diag::err_explicit_non_function); 6438 6439 if (DS.isNoreturnSpecified()) 6440 Diag(DS.getNoreturnSpecLoc(), 6441 diag::err_noreturn_non_function); 6442 } 6443 6444 NamedDecl* 6445 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6446 TypeSourceInfo *TInfo, LookupResult &Previous) { 6447 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6448 if (D.getCXXScopeSpec().isSet()) { 6449 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6450 << D.getCXXScopeSpec().getRange(); 6451 D.setInvalidType(); 6452 // Pretend we didn't see the scope specifier. 6453 DC = CurContext; 6454 Previous.clear(); 6455 } 6456 6457 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6458 6459 if (D.getDeclSpec().isInlineSpecified()) 6460 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6461 << getLangOpts().CPlusPlus17; 6462 if (D.getDeclSpec().hasConstexprSpecifier()) 6463 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6464 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6465 6466 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6467 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6468 Diag(D.getName().StartLocation, 6469 diag::err_deduction_guide_invalid_specifier) 6470 << "typedef"; 6471 else 6472 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6473 << D.getName().getSourceRange(); 6474 return nullptr; 6475 } 6476 6477 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6478 if (!NewTD) return nullptr; 6479 6480 // Handle attributes prior to checking for duplicates in MergeVarDecl 6481 ProcessDeclAttributes(S, NewTD, D); 6482 6483 CheckTypedefForVariablyModifiedType(S, NewTD); 6484 6485 bool Redeclaration = D.isRedeclaration(); 6486 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6487 D.setRedeclaration(Redeclaration); 6488 return ND; 6489 } 6490 6491 void 6492 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6493 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6494 // then it shall have block scope. 6495 // Note that variably modified types must be fixed before merging the decl so 6496 // that redeclarations will match. 6497 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6498 QualType T = TInfo->getType(); 6499 if (T->isVariablyModifiedType()) { 6500 setFunctionHasBranchProtectedScope(); 6501 6502 if (S->getFnParent() == nullptr) { 6503 bool SizeIsNegative; 6504 llvm::APSInt Oversized; 6505 TypeSourceInfo *FixedTInfo = 6506 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6507 SizeIsNegative, 6508 Oversized); 6509 if (FixedTInfo) { 6510 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6511 NewTD->setTypeSourceInfo(FixedTInfo); 6512 } else { 6513 if (SizeIsNegative) 6514 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6515 else if (T->isVariableArrayType()) 6516 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6517 else if (Oversized.getBoolValue()) 6518 Diag(NewTD->getLocation(), diag::err_array_too_large) 6519 << toString(Oversized, 10); 6520 else 6521 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6522 NewTD->setInvalidDecl(); 6523 } 6524 } 6525 } 6526 } 6527 6528 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6529 /// declares a typedef-name, either using the 'typedef' type specifier or via 6530 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6531 NamedDecl* 6532 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6533 LookupResult &Previous, bool &Redeclaration) { 6534 6535 // Find the shadowed declaration before filtering for scope. 6536 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6537 6538 // Merge the decl with the existing one if appropriate. If the decl is 6539 // in an outer scope, it isn't the same thing. 6540 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6541 /*AllowInlineNamespace*/false); 6542 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6543 if (!Previous.empty()) { 6544 Redeclaration = true; 6545 MergeTypedefNameDecl(S, NewTD, Previous); 6546 } else { 6547 inferGslPointerAttribute(NewTD); 6548 } 6549 6550 if (ShadowedDecl && !Redeclaration) 6551 CheckShadow(NewTD, ShadowedDecl, Previous); 6552 6553 // If this is the C FILE type, notify the AST context. 6554 if (IdentifierInfo *II = NewTD->getIdentifier()) 6555 if (!NewTD->isInvalidDecl() && 6556 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6557 if (II->isStr("FILE")) 6558 Context.setFILEDecl(NewTD); 6559 else if (II->isStr("jmp_buf")) 6560 Context.setjmp_bufDecl(NewTD); 6561 else if (II->isStr("sigjmp_buf")) 6562 Context.setsigjmp_bufDecl(NewTD); 6563 else if (II->isStr("ucontext_t")) 6564 Context.setucontext_tDecl(NewTD); 6565 } 6566 6567 return NewTD; 6568 } 6569 6570 /// Determines whether the given declaration is an out-of-scope 6571 /// previous declaration. 6572 /// 6573 /// This routine should be invoked when name lookup has found a 6574 /// previous declaration (PrevDecl) that is not in the scope where a 6575 /// new declaration by the same name is being introduced. If the new 6576 /// declaration occurs in a local scope, previous declarations with 6577 /// linkage may still be considered previous declarations (C99 6578 /// 6.2.2p4-5, C++ [basic.link]p6). 6579 /// 6580 /// \param PrevDecl the previous declaration found by name 6581 /// lookup 6582 /// 6583 /// \param DC the context in which the new declaration is being 6584 /// declared. 6585 /// 6586 /// \returns true if PrevDecl is an out-of-scope previous declaration 6587 /// for a new delcaration with the same name. 6588 static bool 6589 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6590 ASTContext &Context) { 6591 if (!PrevDecl) 6592 return false; 6593 6594 if (!PrevDecl->hasLinkage()) 6595 return false; 6596 6597 if (Context.getLangOpts().CPlusPlus) { 6598 // C++ [basic.link]p6: 6599 // If there is a visible declaration of an entity with linkage 6600 // having the same name and type, ignoring entities declared 6601 // outside the innermost enclosing namespace scope, the block 6602 // scope declaration declares that same entity and receives the 6603 // linkage of the previous declaration. 6604 DeclContext *OuterContext = DC->getRedeclContext(); 6605 if (!OuterContext->isFunctionOrMethod()) 6606 // This rule only applies to block-scope declarations. 6607 return false; 6608 6609 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6610 if (PrevOuterContext->isRecord()) 6611 // We found a member function: ignore it. 6612 return false; 6613 6614 // Find the innermost enclosing namespace for the new and 6615 // previous declarations. 6616 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6617 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6618 6619 // The previous declaration is in a different namespace, so it 6620 // isn't the same function. 6621 if (!OuterContext->Equals(PrevOuterContext)) 6622 return false; 6623 } 6624 6625 return true; 6626 } 6627 6628 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6629 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6630 if (!SS.isSet()) return; 6631 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6632 } 6633 6634 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6635 QualType type = decl->getType(); 6636 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6637 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6638 // Various kinds of declaration aren't allowed to be __autoreleasing. 6639 unsigned kind = -1U; 6640 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6641 if (var->hasAttr<BlocksAttr>()) 6642 kind = 0; // __block 6643 else if (!var->hasLocalStorage()) 6644 kind = 1; // global 6645 } else if (isa<ObjCIvarDecl>(decl)) { 6646 kind = 3; // ivar 6647 } else if (isa<FieldDecl>(decl)) { 6648 kind = 2; // field 6649 } 6650 6651 if (kind != -1U) { 6652 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6653 << kind; 6654 } 6655 } else if (lifetime == Qualifiers::OCL_None) { 6656 // Try to infer lifetime. 6657 if (!type->isObjCLifetimeType()) 6658 return false; 6659 6660 lifetime = type->getObjCARCImplicitLifetime(); 6661 type = Context.getLifetimeQualifiedType(type, lifetime); 6662 decl->setType(type); 6663 } 6664 6665 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6666 // Thread-local variables cannot have lifetime. 6667 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6668 var->getTLSKind()) { 6669 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6670 << var->getType(); 6671 return true; 6672 } 6673 } 6674 6675 return false; 6676 } 6677 6678 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6679 if (Decl->getType().hasAddressSpace()) 6680 return; 6681 if (Decl->getType()->isDependentType()) 6682 return; 6683 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6684 QualType Type = Var->getType(); 6685 if (Type->isSamplerT() || Type->isVoidType()) 6686 return; 6687 LangAS ImplAS = LangAS::opencl_private; 6688 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6689 // __opencl_c_program_scope_global_variables feature, the address space 6690 // for a variable at program scope or a static or extern variable inside 6691 // a function are inferred to be __global. 6692 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6693 Var->hasGlobalStorage()) 6694 ImplAS = LangAS::opencl_global; 6695 // If the original type from a decayed type is an array type and that array 6696 // type has no address space yet, deduce it now. 6697 if (auto DT = dyn_cast<DecayedType>(Type)) { 6698 auto OrigTy = DT->getOriginalType(); 6699 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6700 // Add the address space to the original array type and then propagate 6701 // that to the element type through `getAsArrayType`. 6702 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6703 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6704 // Re-generate the decayed type. 6705 Type = Context.getDecayedType(OrigTy); 6706 } 6707 } 6708 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6709 // Apply any qualifiers (including address space) from the array type to 6710 // the element type. This implements C99 6.7.3p8: "If the specification of 6711 // an array type includes any type qualifiers, the element type is so 6712 // qualified, not the array type." 6713 if (Type->isArrayType()) 6714 Type = QualType(Context.getAsArrayType(Type), 0); 6715 Decl->setType(Type); 6716 } 6717 } 6718 6719 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6720 // Ensure that an auto decl is deduced otherwise the checks below might cache 6721 // the wrong linkage. 6722 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6723 6724 // 'weak' only applies to declarations with external linkage. 6725 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6726 if (!ND.isExternallyVisible()) { 6727 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6728 ND.dropAttr<WeakAttr>(); 6729 } 6730 } 6731 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6732 if (ND.isExternallyVisible()) { 6733 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6734 ND.dropAttr<WeakRefAttr>(); 6735 ND.dropAttr<AliasAttr>(); 6736 } 6737 } 6738 6739 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6740 if (VD->hasInit()) { 6741 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6742 assert(VD->isThisDeclarationADefinition() && 6743 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6744 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6745 VD->dropAttr<AliasAttr>(); 6746 } 6747 } 6748 } 6749 6750 // 'selectany' only applies to externally visible variable declarations. 6751 // It does not apply to functions. 6752 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6753 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6754 S.Diag(Attr->getLocation(), 6755 diag::err_attribute_selectany_non_extern_data); 6756 ND.dropAttr<SelectAnyAttr>(); 6757 } 6758 } 6759 6760 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6761 auto *VD = dyn_cast<VarDecl>(&ND); 6762 bool IsAnonymousNS = false; 6763 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6764 if (VD) { 6765 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6766 while (NS && !IsAnonymousNS) { 6767 IsAnonymousNS = NS->isAnonymousNamespace(); 6768 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6769 } 6770 } 6771 // dll attributes require external linkage. Static locals may have external 6772 // linkage but still cannot be explicitly imported or exported. 6773 // In Microsoft mode, a variable defined in anonymous namespace must have 6774 // external linkage in order to be exported. 6775 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6776 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6777 (!AnonNSInMicrosoftMode && 6778 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6779 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6780 << &ND << Attr; 6781 ND.setInvalidDecl(); 6782 } 6783 } 6784 6785 // Check the attributes on the function type, if any. 6786 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6787 // Don't declare this variable in the second operand of the for-statement; 6788 // GCC miscompiles that by ending its lifetime before evaluating the 6789 // third operand. See gcc.gnu.org/PR86769. 6790 AttributedTypeLoc ATL; 6791 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6792 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6793 TL = ATL.getModifiedLoc()) { 6794 // The [[lifetimebound]] attribute can be applied to the implicit object 6795 // parameter of a non-static member function (other than a ctor or dtor) 6796 // by applying it to the function type. 6797 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6798 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6799 if (!MD || MD->isStatic()) { 6800 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6801 << !MD << A->getRange(); 6802 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6803 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6804 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6805 } 6806 } 6807 } 6808 } 6809 } 6810 6811 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6812 NamedDecl *NewDecl, 6813 bool IsSpecialization, 6814 bool IsDefinition) { 6815 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6816 return; 6817 6818 bool IsTemplate = false; 6819 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6820 OldDecl = OldTD->getTemplatedDecl(); 6821 IsTemplate = true; 6822 if (!IsSpecialization) 6823 IsDefinition = false; 6824 } 6825 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6826 NewDecl = NewTD->getTemplatedDecl(); 6827 IsTemplate = true; 6828 } 6829 6830 if (!OldDecl || !NewDecl) 6831 return; 6832 6833 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6834 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6835 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6836 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6837 6838 // dllimport and dllexport are inheritable attributes so we have to exclude 6839 // inherited attribute instances. 6840 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6841 (NewExportAttr && !NewExportAttr->isInherited()); 6842 6843 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6844 // the only exception being explicit specializations. 6845 // Implicitly generated declarations are also excluded for now because there 6846 // is no other way to switch these to use dllimport or dllexport. 6847 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6848 6849 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6850 // Allow with a warning for free functions and global variables. 6851 bool JustWarn = false; 6852 if (!OldDecl->isCXXClassMember()) { 6853 auto *VD = dyn_cast<VarDecl>(OldDecl); 6854 if (VD && !VD->getDescribedVarTemplate()) 6855 JustWarn = true; 6856 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6857 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6858 JustWarn = true; 6859 } 6860 6861 // We cannot change a declaration that's been used because IR has already 6862 // been emitted. Dllimported functions will still work though (modulo 6863 // address equality) as they can use the thunk. 6864 if (OldDecl->isUsed()) 6865 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6866 JustWarn = false; 6867 6868 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6869 : diag::err_attribute_dll_redeclaration; 6870 S.Diag(NewDecl->getLocation(), DiagID) 6871 << NewDecl 6872 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6873 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6874 if (!JustWarn) { 6875 NewDecl->setInvalidDecl(); 6876 return; 6877 } 6878 } 6879 6880 // A redeclaration is not allowed to drop a dllimport attribute, the only 6881 // exceptions being inline function definitions (except for function 6882 // templates), local extern declarations, qualified friend declarations or 6883 // special MSVC extension: in the last case, the declaration is treated as if 6884 // it were marked dllexport. 6885 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6886 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6887 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6888 // Ignore static data because out-of-line definitions are diagnosed 6889 // separately. 6890 IsStaticDataMember = VD->isStaticDataMember(); 6891 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6892 VarDecl::DeclarationOnly; 6893 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6894 IsInline = FD->isInlined(); 6895 IsQualifiedFriend = FD->getQualifier() && 6896 FD->getFriendObjectKind() == Decl::FOK_Declared; 6897 } 6898 6899 if (OldImportAttr && !HasNewAttr && 6900 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6901 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6902 if (IsMicrosoftABI && IsDefinition) { 6903 S.Diag(NewDecl->getLocation(), 6904 diag::warn_redeclaration_without_import_attribute) 6905 << NewDecl; 6906 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6907 NewDecl->dropAttr<DLLImportAttr>(); 6908 NewDecl->addAttr( 6909 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6910 } else { 6911 S.Diag(NewDecl->getLocation(), 6912 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6913 << NewDecl << OldImportAttr; 6914 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6915 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6916 OldDecl->dropAttr<DLLImportAttr>(); 6917 NewDecl->dropAttr<DLLImportAttr>(); 6918 } 6919 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6920 // In MinGW, seeing a function declared inline drops the dllimport 6921 // attribute. 6922 OldDecl->dropAttr<DLLImportAttr>(); 6923 NewDecl->dropAttr<DLLImportAttr>(); 6924 S.Diag(NewDecl->getLocation(), 6925 diag::warn_dllimport_dropped_from_inline_function) 6926 << NewDecl << OldImportAttr; 6927 } 6928 6929 // A specialization of a class template member function is processed here 6930 // since it's a redeclaration. If the parent class is dllexport, the 6931 // specialization inherits that attribute. This doesn't happen automatically 6932 // since the parent class isn't instantiated until later. 6933 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6934 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6935 !NewImportAttr && !NewExportAttr) { 6936 if (const DLLExportAttr *ParentExportAttr = 6937 MD->getParent()->getAttr<DLLExportAttr>()) { 6938 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6939 NewAttr->setInherited(true); 6940 NewDecl->addAttr(NewAttr); 6941 } 6942 } 6943 } 6944 } 6945 6946 /// Given that we are within the definition of the given function, 6947 /// will that definition behave like C99's 'inline', where the 6948 /// definition is discarded except for optimization purposes? 6949 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6950 // Try to avoid calling GetGVALinkageForFunction. 6951 6952 // All cases of this require the 'inline' keyword. 6953 if (!FD->isInlined()) return false; 6954 6955 // This is only possible in C++ with the gnu_inline attribute. 6956 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6957 return false; 6958 6959 // Okay, go ahead and call the relatively-more-expensive function. 6960 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6961 } 6962 6963 /// Determine whether a variable is extern "C" prior to attaching 6964 /// an initializer. We can't just call isExternC() here, because that 6965 /// will also compute and cache whether the declaration is externally 6966 /// visible, which might change when we attach the initializer. 6967 /// 6968 /// This can only be used if the declaration is known to not be a 6969 /// redeclaration of an internal linkage declaration. 6970 /// 6971 /// For instance: 6972 /// 6973 /// auto x = []{}; 6974 /// 6975 /// Attaching the initializer here makes this declaration not externally 6976 /// visible, because its type has internal linkage. 6977 /// 6978 /// FIXME: This is a hack. 6979 template<typename T> 6980 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6981 if (S.getLangOpts().CPlusPlus) { 6982 // In C++, the overloadable attribute negates the effects of extern "C". 6983 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6984 return false; 6985 6986 // So do CUDA's host/device attributes. 6987 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6988 D->template hasAttr<CUDAHostAttr>())) 6989 return false; 6990 } 6991 return D->isExternC(); 6992 } 6993 6994 static bool shouldConsiderLinkage(const VarDecl *VD) { 6995 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6996 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6997 isa<OMPDeclareMapperDecl>(DC)) 6998 return VD->hasExternalStorage(); 6999 if (DC->isFileContext()) 7000 return true; 7001 if (DC->isRecord()) 7002 return false; 7003 if (isa<RequiresExprBodyDecl>(DC)) 7004 return false; 7005 llvm_unreachable("Unexpected context"); 7006 } 7007 7008 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 7009 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 7010 if (DC->isFileContext() || DC->isFunctionOrMethod() || 7011 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 7012 return true; 7013 if (DC->isRecord()) 7014 return false; 7015 llvm_unreachable("Unexpected context"); 7016 } 7017 7018 static bool hasParsedAttr(Scope *S, const Declarator &PD, 7019 ParsedAttr::Kind Kind) { 7020 // Check decl attributes on the DeclSpec. 7021 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 7022 return true; 7023 7024 // Walk the declarator structure, checking decl attributes that were in a type 7025 // position to the decl itself. 7026 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 7027 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 7028 return true; 7029 } 7030 7031 // Finally, check attributes on the decl itself. 7032 return PD.getAttributes().hasAttribute(Kind); 7033 } 7034 7035 /// Adjust the \c DeclContext for a function or variable that might be a 7036 /// function-local external declaration. 7037 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 7038 if (!DC->isFunctionOrMethod()) 7039 return false; 7040 7041 // If this is a local extern function or variable declared within a function 7042 // template, don't add it into the enclosing namespace scope until it is 7043 // instantiated; it might have a dependent type right now. 7044 if (DC->isDependentContext()) 7045 return true; 7046 7047 // C++11 [basic.link]p7: 7048 // When a block scope declaration of an entity with linkage is not found to 7049 // refer to some other declaration, then that entity is a member of the 7050 // innermost enclosing namespace. 7051 // 7052 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 7053 // semantically-enclosing namespace, not a lexically-enclosing one. 7054 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 7055 DC = DC->getParent(); 7056 return true; 7057 } 7058 7059 /// Returns true if given declaration has external C language linkage. 7060 static bool isDeclExternC(const Decl *D) { 7061 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 7062 return FD->isExternC(); 7063 if (const auto *VD = dyn_cast<VarDecl>(D)) 7064 return VD->isExternC(); 7065 7066 llvm_unreachable("Unknown type of decl!"); 7067 } 7068 7069 /// Returns true if there hasn't been any invalid type diagnosed. 7070 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 7071 DeclContext *DC = NewVD->getDeclContext(); 7072 QualType R = NewVD->getType(); 7073 7074 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 7075 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 7076 // argument. 7077 if (R->isImageType() || R->isPipeType()) { 7078 Se.Diag(NewVD->getLocation(), 7079 diag::err_opencl_type_can_only_be_used_as_function_parameter) 7080 << R; 7081 NewVD->setInvalidDecl(); 7082 return false; 7083 } 7084 7085 // OpenCL v1.2 s6.9.r: 7086 // The event type cannot be used to declare a program scope variable. 7087 // OpenCL v2.0 s6.9.q: 7088 // The clk_event_t and reserve_id_t types cannot be declared in program 7089 // scope. 7090 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 7091 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 7092 Se.Diag(NewVD->getLocation(), 7093 diag::err_invalid_type_for_program_scope_var) 7094 << R; 7095 NewVD->setInvalidDecl(); 7096 return false; 7097 } 7098 } 7099 7100 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 7101 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 7102 Se.getLangOpts())) { 7103 QualType NR = R.getCanonicalType(); 7104 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 7105 NR->isReferenceType()) { 7106 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 7107 NR->isFunctionReferenceType()) { 7108 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 7109 << NR->isReferenceType(); 7110 NewVD->setInvalidDecl(); 7111 return false; 7112 } 7113 NR = NR->getPointeeType(); 7114 } 7115 } 7116 7117 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 7118 Se.getLangOpts())) { 7119 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 7120 // half array type (unless the cl_khr_fp16 extension is enabled). 7121 if (Se.Context.getBaseElementType(R)->isHalfType()) { 7122 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 7123 NewVD->setInvalidDecl(); 7124 return false; 7125 } 7126 } 7127 7128 // OpenCL v1.2 s6.9.r: 7129 // The event type cannot be used with the __local, __constant and __global 7130 // address space qualifiers. 7131 if (R->isEventT()) { 7132 if (R.getAddressSpace() != LangAS::opencl_private) { 7133 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 7134 NewVD->setInvalidDecl(); 7135 return false; 7136 } 7137 } 7138 7139 if (R->isSamplerT()) { 7140 // OpenCL v1.2 s6.9.b p4: 7141 // The sampler type cannot be used with the __local and __global address 7142 // space qualifiers. 7143 if (R.getAddressSpace() == LangAS::opencl_local || 7144 R.getAddressSpace() == LangAS::opencl_global) { 7145 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 7146 NewVD->setInvalidDecl(); 7147 } 7148 7149 // OpenCL v1.2 s6.12.14.1: 7150 // A global sampler must be declared with either the constant address 7151 // space qualifier or with the const qualifier. 7152 if (DC->isTranslationUnit() && 7153 !(R.getAddressSpace() == LangAS::opencl_constant || 7154 R.isConstQualified())) { 7155 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 7156 NewVD->setInvalidDecl(); 7157 } 7158 if (NewVD->isInvalidDecl()) 7159 return false; 7160 } 7161 7162 return true; 7163 } 7164 7165 template <typename AttrTy> 7166 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 7167 const TypedefNameDecl *TND = TT->getDecl(); 7168 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 7169 AttrTy *Clone = Attribute->clone(S.Context); 7170 Clone->setInherited(true); 7171 D->addAttr(Clone); 7172 } 7173 } 7174 7175 NamedDecl *Sema::ActOnVariableDeclarator( 7176 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7177 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7178 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7179 QualType R = TInfo->getType(); 7180 DeclarationName Name = GetNameForDeclarator(D).getName(); 7181 7182 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7183 7184 if (D.isDecompositionDeclarator()) { 7185 // Take the name of the first declarator as our name for diagnostic 7186 // purposes. 7187 auto &Decomp = D.getDecompositionDeclarator(); 7188 if (!Decomp.bindings().empty()) { 7189 II = Decomp.bindings()[0].Name; 7190 Name = II; 7191 } 7192 } else if (!II) { 7193 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7194 return nullptr; 7195 } 7196 7197 7198 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7199 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7200 7201 // dllimport globals without explicit storage class are treated as extern. We 7202 // have to change the storage class this early to get the right DeclContext. 7203 if (SC == SC_None && !DC->isRecord() && 7204 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7205 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7206 SC = SC_Extern; 7207 7208 DeclContext *OriginalDC = DC; 7209 bool IsLocalExternDecl = SC == SC_Extern && 7210 adjustContextForLocalExternDecl(DC); 7211 7212 if (SCSpec == DeclSpec::SCS_mutable) { 7213 // mutable can only appear on non-static class members, so it's always 7214 // an error here 7215 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7216 D.setInvalidType(); 7217 SC = SC_None; 7218 } 7219 7220 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7221 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7222 D.getDeclSpec().getStorageClassSpecLoc())) { 7223 // In C++11, the 'register' storage class specifier is deprecated. 7224 // Suppress the warning in system macros, it's used in macros in some 7225 // popular C system headers, such as in glibc's htonl() macro. 7226 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7227 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7228 : diag::warn_deprecated_register) 7229 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7230 } 7231 7232 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7233 7234 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7235 // C99 6.9p2: The storage-class specifiers auto and register shall not 7236 // appear in the declaration specifiers in an external declaration. 7237 // Global Register+Asm is a GNU extension we support. 7238 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7239 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7240 D.setInvalidType(); 7241 } 7242 } 7243 7244 // If this variable has a VLA type and an initializer, try to 7245 // fold to a constant-sized type. This is otherwise invalid. 7246 if (D.hasInitializer() && R->isVariableArrayType()) 7247 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7248 /*DiagID=*/0); 7249 7250 bool IsMemberSpecialization = false; 7251 bool IsVariableTemplateSpecialization = false; 7252 bool IsPartialSpecialization = false; 7253 bool IsVariableTemplate = false; 7254 VarDecl *NewVD = nullptr; 7255 VarTemplateDecl *NewTemplate = nullptr; 7256 TemplateParameterList *TemplateParams = nullptr; 7257 if (!getLangOpts().CPlusPlus) { 7258 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7259 II, R, TInfo, SC); 7260 7261 if (R->getContainedDeducedType()) 7262 ParsingInitForAutoVars.insert(NewVD); 7263 7264 if (D.isInvalidType()) 7265 NewVD->setInvalidDecl(); 7266 7267 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7268 NewVD->hasLocalStorage()) 7269 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7270 NTCUC_AutoVar, NTCUK_Destruct); 7271 } else { 7272 bool Invalid = false; 7273 7274 if (DC->isRecord() && !CurContext->isRecord()) { 7275 // This is an out-of-line definition of a static data member. 7276 switch (SC) { 7277 case SC_None: 7278 break; 7279 case SC_Static: 7280 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7281 diag::err_static_out_of_line) 7282 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7283 break; 7284 case SC_Auto: 7285 case SC_Register: 7286 case SC_Extern: 7287 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7288 // to names of variables declared in a block or to function parameters. 7289 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7290 // of class members 7291 7292 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7293 diag::err_storage_class_for_static_member) 7294 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7295 break; 7296 case SC_PrivateExtern: 7297 llvm_unreachable("C storage class in c++!"); 7298 } 7299 } 7300 7301 if (SC == SC_Static && CurContext->isRecord()) { 7302 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7303 // Walk up the enclosing DeclContexts to check for any that are 7304 // incompatible with static data members. 7305 const DeclContext *FunctionOrMethod = nullptr; 7306 const CXXRecordDecl *AnonStruct = nullptr; 7307 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7308 if (Ctxt->isFunctionOrMethod()) { 7309 FunctionOrMethod = Ctxt; 7310 break; 7311 } 7312 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7313 if (ParentDecl && !ParentDecl->getDeclName()) { 7314 AnonStruct = ParentDecl; 7315 break; 7316 } 7317 } 7318 if (FunctionOrMethod) { 7319 // C++ [class.static.data]p5: A local class shall not have static data 7320 // members. 7321 Diag(D.getIdentifierLoc(), 7322 diag::err_static_data_member_not_allowed_in_local_class) 7323 << Name << RD->getDeclName() << RD->getTagKind(); 7324 } else if (AnonStruct) { 7325 // C++ [class.static.data]p4: Unnamed classes and classes contained 7326 // directly or indirectly within unnamed classes shall not contain 7327 // static data members. 7328 Diag(D.getIdentifierLoc(), 7329 diag::err_static_data_member_not_allowed_in_anon_struct) 7330 << Name << AnonStruct->getTagKind(); 7331 Invalid = true; 7332 } else if (RD->isUnion()) { 7333 // C++98 [class.union]p1: If a union contains a static data member, 7334 // the program is ill-formed. C++11 drops this restriction. 7335 Diag(D.getIdentifierLoc(), 7336 getLangOpts().CPlusPlus11 7337 ? diag::warn_cxx98_compat_static_data_member_in_union 7338 : diag::ext_static_data_member_in_union) << Name; 7339 } 7340 } 7341 } 7342 7343 // Match up the template parameter lists with the scope specifier, then 7344 // determine whether we have a template or a template specialization. 7345 bool InvalidScope = false; 7346 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7347 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7348 D.getCXXScopeSpec(), 7349 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7350 ? D.getName().TemplateId 7351 : nullptr, 7352 TemplateParamLists, 7353 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7354 Invalid |= InvalidScope; 7355 7356 if (TemplateParams) { 7357 if (!TemplateParams->size() && 7358 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7359 // There is an extraneous 'template<>' for this variable. Complain 7360 // about it, but allow the declaration of the variable. 7361 Diag(TemplateParams->getTemplateLoc(), 7362 diag::err_template_variable_noparams) 7363 << II 7364 << SourceRange(TemplateParams->getTemplateLoc(), 7365 TemplateParams->getRAngleLoc()); 7366 TemplateParams = nullptr; 7367 } else { 7368 // Check that we can declare a template here. 7369 if (CheckTemplateDeclScope(S, TemplateParams)) 7370 return nullptr; 7371 7372 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7373 // This is an explicit specialization or a partial specialization. 7374 IsVariableTemplateSpecialization = true; 7375 IsPartialSpecialization = TemplateParams->size() > 0; 7376 } else { // if (TemplateParams->size() > 0) 7377 // This is a template declaration. 7378 IsVariableTemplate = true; 7379 7380 // Only C++1y supports variable templates (N3651). 7381 Diag(D.getIdentifierLoc(), 7382 getLangOpts().CPlusPlus14 7383 ? diag::warn_cxx11_compat_variable_template 7384 : diag::ext_variable_template); 7385 } 7386 } 7387 } else { 7388 // Check that we can declare a member specialization here. 7389 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7390 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7391 return nullptr; 7392 assert((Invalid || 7393 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7394 "should have a 'template<>' for this decl"); 7395 } 7396 7397 if (IsVariableTemplateSpecialization) { 7398 SourceLocation TemplateKWLoc = 7399 TemplateParamLists.size() > 0 7400 ? TemplateParamLists[0]->getTemplateLoc() 7401 : SourceLocation(); 7402 DeclResult Res = ActOnVarTemplateSpecialization( 7403 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7404 IsPartialSpecialization); 7405 if (Res.isInvalid()) 7406 return nullptr; 7407 NewVD = cast<VarDecl>(Res.get()); 7408 AddToScope = false; 7409 } else if (D.isDecompositionDeclarator()) { 7410 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7411 D.getIdentifierLoc(), R, TInfo, SC, 7412 Bindings); 7413 } else 7414 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7415 D.getIdentifierLoc(), II, R, TInfo, SC); 7416 7417 // If this is supposed to be a variable template, create it as such. 7418 if (IsVariableTemplate) { 7419 NewTemplate = 7420 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7421 TemplateParams, NewVD); 7422 NewVD->setDescribedVarTemplate(NewTemplate); 7423 } 7424 7425 // If this decl has an auto type in need of deduction, make a note of the 7426 // Decl so we can diagnose uses of it in its own initializer. 7427 if (R->getContainedDeducedType()) 7428 ParsingInitForAutoVars.insert(NewVD); 7429 7430 if (D.isInvalidType() || Invalid) { 7431 NewVD->setInvalidDecl(); 7432 if (NewTemplate) 7433 NewTemplate->setInvalidDecl(); 7434 } 7435 7436 SetNestedNameSpecifier(*this, NewVD, D); 7437 7438 // If we have any template parameter lists that don't directly belong to 7439 // the variable (matching the scope specifier), store them. 7440 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7441 if (TemplateParamLists.size() > VDTemplateParamLists) 7442 NewVD->setTemplateParameterListsInfo( 7443 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7444 } 7445 7446 if (D.getDeclSpec().isInlineSpecified()) { 7447 if (!getLangOpts().CPlusPlus) { 7448 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7449 << 0; 7450 } else if (CurContext->isFunctionOrMethod()) { 7451 // 'inline' is not allowed on block scope variable declaration. 7452 Diag(D.getDeclSpec().getInlineSpecLoc(), 7453 diag::err_inline_declaration_block_scope) << Name 7454 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7455 } else { 7456 Diag(D.getDeclSpec().getInlineSpecLoc(), 7457 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7458 : diag::ext_inline_variable); 7459 NewVD->setInlineSpecified(); 7460 } 7461 } 7462 7463 // Set the lexical context. If the declarator has a C++ scope specifier, the 7464 // lexical context will be different from the semantic context. 7465 NewVD->setLexicalDeclContext(CurContext); 7466 if (NewTemplate) 7467 NewTemplate->setLexicalDeclContext(CurContext); 7468 7469 if (IsLocalExternDecl) { 7470 if (D.isDecompositionDeclarator()) 7471 for (auto *B : Bindings) 7472 B->setLocalExternDecl(); 7473 else 7474 NewVD->setLocalExternDecl(); 7475 } 7476 7477 bool EmitTLSUnsupportedError = false; 7478 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7479 // C++11 [dcl.stc]p4: 7480 // When thread_local is applied to a variable of block scope the 7481 // storage-class-specifier static is implied if it does not appear 7482 // explicitly. 7483 // Core issue: 'static' is not implied if the variable is declared 7484 // 'extern'. 7485 if (NewVD->hasLocalStorage() && 7486 (SCSpec != DeclSpec::SCS_unspecified || 7487 TSCS != DeclSpec::TSCS_thread_local || 7488 !DC->isFunctionOrMethod())) 7489 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7490 diag::err_thread_non_global) 7491 << DeclSpec::getSpecifierName(TSCS); 7492 else if (!Context.getTargetInfo().isTLSSupported()) { 7493 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7494 getLangOpts().SYCLIsDevice) { 7495 // Postpone error emission until we've collected attributes required to 7496 // figure out whether it's a host or device variable and whether the 7497 // error should be ignored. 7498 EmitTLSUnsupportedError = true; 7499 // We still need to mark the variable as TLS so it shows up in AST with 7500 // proper storage class for other tools to use even if we're not going 7501 // to emit any code for it. 7502 NewVD->setTSCSpec(TSCS); 7503 } else 7504 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7505 diag::err_thread_unsupported); 7506 } else 7507 NewVD->setTSCSpec(TSCS); 7508 } 7509 7510 switch (D.getDeclSpec().getConstexprSpecifier()) { 7511 case ConstexprSpecKind::Unspecified: 7512 break; 7513 7514 case ConstexprSpecKind::Consteval: 7515 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7516 diag::err_constexpr_wrong_decl_kind) 7517 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7518 LLVM_FALLTHROUGH; 7519 7520 case ConstexprSpecKind::Constexpr: 7521 NewVD->setConstexpr(true); 7522 // C++1z [dcl.spec.constexpr]p1: 7523 // A static data member declared with the constexpr specifier is 7524 // implicitly an inline variable. 7525 if (NewVD->isStaticDataMember() && 7526 (getLangOpts().CPlusPlus17 || 7527 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7528 NewVD->setImplicitlyInline(); 7529 break; 7530 7531 case ConstexprSpecKind::Constinit: 7532 if (!NewVD->hasGlobalStorage()) 7533 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7534 diag::err_constinit_local_variable); 7535 else 7536 NewVD->addAttr(ConstInitAttr::Create( 7537 Context, D.getDeclSpec().getConstexprSpecLoc(), 7538 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7539 break; 7540 } 7541 7542 // C99 6.7.4p3 7543 // An inline definition of a function with external linkage shall 7544 // not contain a definition of a modifiable object with static or 7545 // thread storage duration... 7546 // We only apply this when the function is required to be defined 7547 // elsewhere, i.e. when the function is not 'extern inline'. Note 7548 // that a local variable with thread storage duration still has to 7549 // be marked 'static'. Also note that it's possible to get these 7550 // semantics in C++ using __attribute__((gnu_inline)). 7551 if (SC == SC_Static && S->getFnParent() != nullptr && 7552 !NewVD->getType().isConstQualified()) { 7553 FunctionDecl *CurFD = getCurFunctionDecl(); 7554 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7555 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7556 diag::warn_static_local_in_extern_inline); 7557 MaybeSuggestAddingStaticToDecl(CurFD); 7558 } 7559 } 7560 7561 if (D.getDeclSpec().isModulePrivateSpecified()) { 7562 if (IsVariableTemplateSpecialization) 7563 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7564 << (IsPartialSpecialization ? 1 : 0) 7565 << FixItHint::CreateRemoval( 7566 D.getDeclSpec().getModulePrivateSpecLoc()); 7567 else if (IsMemberSpecialization) 7568 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7569 << 2 7570 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7571 else if (NewVD->hasLocalStorage()) 7572 Diag(NewVD->getLocation(), diag::err_module_private_local) 7573 << 0 << NewVD 7574 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7575 << FixItHint::CreateRemoval( 7576 D.getDeclSpec().getModulePrivateSpecLoc()); 7577 else { 7578 NewVD->setModulePrivate(); 7579 if (NewTemplate) 7580 NewTemplate->setModulePrivate(); 7581 for (auto *B : Bindings) 7582 B->setModulePrivate(); 7583 } 7584 } 7585 7586 if (getLangOpts().OpenCL) { 7587 deduceOpenCLAddressSpace(NewVD); 7588 7589 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7590 if (TSC != TSCS_unspecified) { 7591 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7592 diag::err_opencl_unknown_type_specifier) 7593 << getLangOpts().getOpenCLVersionString() 7594 << DeclSpec::getSpecifierName(TSC) << 1; 7595 NewVD->setInvalidDecl(); 7596 } 7597 } 7598 7599 // Handle attributes prior to checking for duplicates in MergeVarDecl 7600 ProcessDeclAttributes(S, NewVD, D); 7601 7602 // FIXME: This is probably the wrong location to be doing this and we should 7603 // probably be doing this for more attributes (especially for function 7604 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7605 // the code to copy attributes would be generated by TableGen. 7606 if (R->isFunctionPointerType()) 7607 if (const auto *TT = R->getAs<TypedefType>()) 7608 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7609 7610 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7611 getLangOpts().SYCLIsDevice) { 7612 if (EmitTLSUnsupportedError && 7613 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7614 (getLangOpts().OpenMPIsDevice && 7615 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7616 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7617 diag::err_thread_unsupported); 7618 7619 if (EmitTLSUnsupportedError && 7620 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7621 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7622 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7623 // storage [duration]." 7624 if (SC == SC_None && S->getFnParent() != nullptr && 7625 (NewVD->hasAttr<CUDASharedAttr>() || 7626 NewVD->hasAttr<CUDAConstantAttr>())) { 7627 NewVD->setStorageClass(SC_Static); 7628 } 7629 } 7630 7631 // Ensure that dllimport globals without explicit storage class are treated as 7632 // extern. The storage class is set above using parsed attributes. Now we can 7633 // check the VarDecl itself. 7634 assert(!NewVD->hasAttr<DLLImportAttr>() || 7635 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7636 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7637 7638 // In auto-retain/release, infer strong retension for variables of 7639 // retainable type. 7640 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7641 NewVD->setInvalidDecl(); 7642 7643 // Handle GNU asm-label extension (encoded as an attribute). 7644 if (Expr *E = (Expr*)D.getAsmLabel()) { 7645 // The parser guarantees this is a string. 7646 StringLiteral *SE = cast<StringLiteral>(E); 7647 StringRef Label = SE->getString(); 7648 if (S->getFnParent() != nullptr) { 7649 switch (SC) { 7650 case SC_None: 7651 case SC_Auto: 7652 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7653 break; 7654 case SC_Register: 7655 // Local Named register 7656 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7657 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7658 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7659 break; 7660 case SC_Static: 7661 case SC_Extern: 7662 case SC_PrivateExtern: 7663 break; 7664 } 7665 } else if (SC == SC_Register) { 7666 // Global Named register 7667 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7668 const auto &TI = Context.getTargetInfo(); 7669 bool HasSizeMismatch; 7670 7671 if (!TI.isValidGCCRegisterName(Label)) 7672 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7673 else if (!TI.validateGlobalRegisterVariable(Label, 7674 Context.getTypeSize(R), 7675 HasSizeMismatch)) 7676 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7677 else if (HasSizeMismatch) 7678 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7679 } 7680 7681 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7682 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7683 NewVD->setInvalidDecl(true); 7684 } 7685 } 7686 7687 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7688 /*IsLiteralLabel=*/true, 7689 SE->getStrTokenLoc(0))); 7690 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7691 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7692 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7693 if (I != ExtnameUndeclaredIdentifiers.end()) { 7694 if (isDeclExternC(NewVD)) { 7695 NewVD->addAttr(I->second); 7696 ExtnameUndeclaredIdentifiers.erase(I); 7697 } else 7698 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7699 << /*Variable*/1 << NewVD; 7700 } 7701 } 7702 7703 // Find the shadowed declaration before filtering for scope. 7704 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7705 ? getShadowedDeclaration(NewVD, Previous) 7706 : nullptr; 7707 7708 // Don't consider existing declarations that are in a different 7709 // scope and are out-of-semantic-context declarations (if the new 7710 // declaration has linkage). 7711 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7712 D.getCXXScopeSpec().isNotEmpty() || 7713 IsMemberSpecialization || 7714 IsVariableTemplateSpecialization); 7715 7716 // Check whether the previous declaration is in the same block scope. This 7717 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7718 if (getLangOpts().CPlusPlus && 7719 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7720 NewVD->setPreviousDeclInSameBlockScope( 7721 Previous.isSingleResult() && !Previous.isShadowed() && 7722 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7723 7724 if (!getLangOpts().CPlusPlus) { 7725 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7726 } else { 7727 // If this is an explicit specialization of a static data member, check it. 7728 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7729 CheckMemberSpecialization(NewVD, Previous)) 7730 NewVD->setInvalidDecl(); 7731 7732 // Merge the decl with the existing one if appropriate. 7733 if (!Previous.empty()) { 7734 if (Previous.isSingleResult() && 7735 isa<FieldDecl>(Previous.getFoundDecl()) && 7736 D.getCXXScopeSpec().isSet()) { 7737 // The user tried to define a non-static data member 7738 // out-of-line (C++ [dcl.meaning]p1). 7739 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7740 << D.getCXXScopeSpec().getRange(); 7741 Previous.clear(); 7742 NewVD->setInvalidDecl(); 7743 } 7744 } else if (D.getCXXScopeSpec().isSet()) { 7745 // No previous declaration in the qualifying scope. 7746 Diag(D.getIdentifierLoc(), diag::err_no_member) 7747 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7748 << D.getCXXScopeSpec().getRange(); 7749 NewVD->setInvalidDecl(); 7750 } 7751 7752 if (!IsVariableTemplateSpecialization) 7753 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7754 7755 if (NewTemplate) { 7756 VarTemplateDecl *PrevVarTemplate = 7757 NewVD->getPreviousDecl() 7758 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7759 : nullptr; 7760 7761 // Check the template parameter list of this declaration, possibly 7762 // merging in the template parameter list from the previous variable 7763 // template declaration. 7764 if (CheckTemplateParameterList( 7765 TemplateParams, 7766 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7767 : nullptr, 7768 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7769 DC->isDependentContext()) 7770 ? TPC_ClassTemplateMember 7771 : TPC_VarTemplate)) 7772 NewVD->setInvalidDecl(); 7773 7774 // If we are providing an explicit specialization of a static variable 7775 // template, make a note of that. 7776 if (PrevVarTemplate && 7777 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7778 PrevVarTemplate->setMemberSpecialization(); 7779 } 7780 } 7781 7782 // Diagnose shadowed variables iff this isn't a redeclaration. 7783 if (ShadowedDecl && !D.isRedeclaration()) 7784 CheckShadow(NewVD, ShadowedDecl, Previous); 7785 7786 ProcessPragmaWeak(S, NewVD); 7787 7788 // If this is the first declaration of an extern C variable, update 7789 // the map of such variables. 7790 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7791 isIncompleteDeclExternC(*this, NewVD)) 7792 RegisterLocallyScopedExternCDecl(NewVD, S); 7793 7794 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7795 MangleNumberingContext *MCtx; 7796 Decl *ManglingContextDecl; 7797 std::tie(MCtx, ManglingContextDecl) = 7798 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7799 if (MCtx) { 7800 Context.setManglingNumber( 7801 NewVD, MCtx->getManglingNumber( 7802 NewVD, getMSManglingNumber(getLangOpts(), S))); 7803 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7804 } 7805 } 7806 7807 // Special handling of variable named 'main'. 7808 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7809 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7810 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7811 7812 // C++ [basic.start.main]p3 7813 // A program that declares a variable main at global scope is ill-formed. 7814 if (getLangOpts().CPlusPlus) 7815 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7816 7817 // In C, and external-linkage variable named main results in undefined 7818 // behavior. 7819 else if (NewVD->hasExternalFormalLinkage()) 7820 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7821 } 7822 7823 if (D.isRedeclaration() && !Previous.empty()) { 7824 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7825 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7826 D.isFunctionDefinition()); 7827 } 7828 7829 if (NewTemplate) { 7830 if (NewVD->isInvalidDecl()) 7831 NewTemplate->setInvalidDecl(); 7832 ActOnDocumentableDecl(NewTemplate); 7833 return NewTemplate; 7834 } 7835 7836 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7837 CompleteMemberSpecialization(NewVD, Previous); 7838 7839 return NewVD; 7840 } 7841 7842 /// Enum describing the %select options in diag::warn_decl_shadow. 7843 enum ShadowedDeclKind { 7844 SDK_Local, 7845 SDK_Global, 7846 SDK_StaticMember, 7847 SDK_Field, 7848 SDK_Typedef, 7849 SDK_Using, 7850 SDK_StructuredBinding 7851 }; 7852 7853 /// Determine what kind of declaration we're shadowing. 7854 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7855 const DeclContext *OldDC) { 7856 if (isa<TypeAliasDecl>(ShadowedDecl)) 7857 return SDK_Using; 7858 else if (isa<TypedefDecl>(ShadowedDecl)) 7859 return SDK_Typedef; 7860 else if (isa<BindingDecl>(ShadowedDecl)) 7861 return SDK_StructuredBinding; 7862 else if (isa<RecordDecl>(OldDC)) 7863 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7864 7865 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7866 } 7867 7868 /// Return the location of the capture if the given lambda captures the given 7869 /// variable \p VD, or an invalid source location otherwise. 7870 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7871 const VarDecl *VD) { 7872 for (const Capture &Capture : LSI->Captures) { 7873 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7874 return Capture.getLocation(); 7875 } 7876 return SourceLocation(); 7877 } 7878 7879 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7880 const LookupResult &R) { 7881 // Only diagnose if we're shadowing an unambiguous field or variable. 7882 if (R.getResultKind() != LookupResult::Found) 7883 return false; 7884 7885 // Return false if warning is ignored. 7886 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7887 } 7888 7889 /// Return the declaration shadowed by the given variable \p D, or null 7890 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7891 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7892 const LookupResult &R) { 7893 if (!shouldWarnIfShadowedDecl(Diags, R)) 7894 return nullptr; 7895 7896 // Don't diagnose declarations at file scope. 7897 if (D->hasGlobalStorage()) 7898 return nullptr; 7899 7900 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7901 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7902 : nullptr; 7903 } 7904 7905 /// Return the declaration shadowed by the given typedef \p D, or null 7906 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7907 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7908 const LookupResult &R) { 7909 // Don't warn if typedef declaration is part of a class 7910 if (D->getDeclContext()->isRecord()) 7911 return nullptr; 7912 7913 if (!shouldWarnIfShadowedDecl(Diags, R)) 7914 return nullptr; 7915 7916 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7917 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7918 } 7919 7920 /// Return the declaration shadowed by the given variable \p D, or null 7921 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7922 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7923 const LookupResult &R) { 7924 if (!shouldWarnIfShadowedDecl(Diags, R)) 7925 return nullptr; 7926 7927 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7928 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7929 : nullptr; 7930 } 7931 7932 /// Diagnose variable or built-in function shadowing. Implements 7933 /// -Wshadow. 7934 /// 7935 /// This method is called whenever a VarDecl is added to a "useful" 7936 /// scope. 7937 /// 7938 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7939 /// \param R the lookup of the name 7940 /// 7941 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7942 const LookupResult &R) { 7943 DeclContext *NewDC = D->getDeclContext(); 7944 7945 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7946 // Fields are not shadowed by variables in C++ static methods. 7947 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7948 if (MD->isStatic()) 7949 return; 7950 7951 // Fields shadowed by constructor parameters are a special case. Usually 7952 // the constructor initializes the field with the parameter. 7953 if (isa<CXXConstructorDecl>(NewDC)) 7954 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7955 // Remember that this was shadowed so we can either warn about its 7956 // modification or its existence depending on warning settings. 7957 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7958 return; 7959 } 7960 } 7961 7962 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7963 if (shadowedVar->isExternC()) { 7964 // For shadowing external vars, make sure that we point to the global 7965 // declaration, not a locally scoped extern declaration. 7966 for (auto I : shadowedVar->redecls()) 7967 if (I->isFileVarDecl()) { 7968 ShadowedDecl = I; 7969 break; 7970 } 7971 } 7972 7973 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7974 7975 unsigned WarningDiag = diag::warn_decl_shadow; 7976 SourceLocation CaptureLoc; 7977 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7978 isa<CXXMethodDecl>(NewDC)) { 7979 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7980 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7981 if (RD->getLambdaCaptureDefault() == LCD_None) { 7982 // Try to avoid warnings for lambdas with an explicit capture list. 7983 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7984 // Warn only when the lambda captures the shadowed decl explicitly. 7985 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7986 if (CaptureLoc.isInvalid()) 7987 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7988 } else { 7989 // Remember that this was shadowed so we can avoid the warning if the 7990 // shadowed decl isn't captured and the warning settings allow it. 7991 cast<LambdaScopeInfo>(getCurFunction()) 7992 ->ShadowingDecls.push_back( 7993 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7994 return; 7995 } 7996 } 7997 7998 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7999 // A variable can't shadow a local variable in an enclosing scope, if 8000 // they are separated by a non-capturing declaration context. 8001 for (DeclContext *ParentDC = NewDC; 8002 ParentDC && !ParentDC->Equals(OldDC); 8003 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 8004 // Only block literals, captured statements, and lambda expressions 8005 // can capture; other scopes don't. 8006 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 8007 !isLambdaCallOperator(ParentDC)) { 8008 return; 8009 } 8010 } 8011 } 8012 } 8013 } 8014 8015 // Only warn about certain kinds of shadowing for class members. 8016 if (NewDC && NewDC->isRecord()) { 8017 // In particular, don't warn about shadowing non-class members. 8018 if (!OldDC->isRecord()) 8019 return; 8020 8021 // TODO: should we warn about static data members shadowing 8022 // static data members from base classes? 8023 8024 // TODO: don't diagnose for inaccessible shadowed members. 8025 // This is hard to do perfectly because we might friend the 8026 // shadowing context, but that's just a false negative. 8027 } 8028 8029 8030 DeclarationName Name = R.getLookupName(); 8031 8032 // Emit warning and note. 8033 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 8034 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 8035 if (!CaptureLoc.isInvalid()) 8036 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8037 << Name << /*explicitly*/ 1; 8038 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8039 } 8040 8041 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 8042 /// when these variables are captured by the lambda. 8043 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 8044 for (const auto &Shadow : LSI->ShadowingDecls) { 8045 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 8046 // Try to avoid the warning when the shadowed decl isn't captured. 8047 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 8048 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8049 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 8050 ? diag::warn_decl_shadow_uncaptured_local 8051 : diag::warn_decl_shadow) 8052 << Shadow.VD->getDeclName() 8053 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8054 if (!CaptureLoc.isInvalid()) 8055 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8056 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 8057 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8058 } 8059 } 8060 8061 /// Check -Wshadow without the advantage of a previous lookup. 8062 void Sema::CheckShadow(Scope *S, VarDecl *D) { 8063 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 8064 return; 8065 8066 LookupResult R(*this, D->getDeclName(), D->getLocation(), 8067 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 8068 LookupName(R, S); 8069 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 8070 CheckShadow(D, ShadowedDecl, R); 8071 } 8072 8073 /// Check if 'E', which is an expression that is about to be modified, refers 8074 /// to a constructor parameter that shadows a field. 8075 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 8076 // Quickly ignore expressions that can't be shadowing ctor parameters. 8077 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 8078 return; 8079 E = E->IgnoreParenImpCasts(); 8080 auto *DRE = dyn_cast<DeclRefExpr>(E); 8081 if (!DRE) 8082 return; 8083 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 8084 auto I = ShadowingDecls.find(D); 8085 if (I == ShadowingDecls.end()) 8086 return; 8087 const NamedDecl *ShadowedDecl = I->second; 8088 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8089 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 8090 Diag(D->getLocation(), diag::note_var_declared_here) << D; 8091 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8092 8093 // Avoid issuing multiple warnings about the same decl. 8094 ShadowingDecls.erase(I); 8095 } 8096 8097 /// Check for conflict between this global or extern "C" declaration and 8098 /// previous global or extern "C" declarations. This is only used in C++. 8099 template<typename T> 8100 static bool checkGlobalOrExternCConflict( 8101 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 8102 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 8103 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 8104 8105 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 8106 // The common case: this global doesn't conflict with any extern "C" 8107 // declaration. 8108 return false; 8109 } 8110 8111 if (Prev) { 8112 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 8113 // Both the old and new declarations have C language linkage. This is a 8114 // redeclaration. 8115 Previous.clear(); 8116 Previous.addDecl(Prev); 8117 return true; 8118 } 8119 8120 // This is a global, non-extern "C" declaration, and there is a previous 8121 // non-global extern "C" declaration. Diagnose if this is a variable 8122 // declaration. 8123 if (!isa<VarDecl>(ND)) 8124 return false; 8125 } else { 8126 // The declaration is extern "C". Check for any declaration in the 8127 // translation unit which might conflict. 8128 if (IsGlobal) { 8129 // We have already performed the lookup into the translation unit. 8130 IsGlobal = false; 8131 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8132 I != E; ++I) { 8133 if (isa<VarDecl>(*I)) { 8134 Prev = *I; 8135 break; 8136 } 8137 } 8138 } else { 8139 DeclContext::lookup_result R = 8140 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 8141 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 8142 I != E; ++I) { 8143 if (isa<VarDecl>(*I)) { 8144 Prev = *I; 8145 break; 8146 } 8147 // FIXME: If we have any other entity with this name in global scope, 8148 // the declaration is ill-formed, but that is a defect: it breaks the 8149 // 'stat' hack, for instance. Only variables can have mangled name 8150 // clashes with extern "C" declarations, so only they deserve a 8151 // diagnostic. 8152 } 8153 } 8154 8155 if (!Prev) 8156 return false; 8157 } 8158 8159 // Use the first declaration's location to ensure we point at something which 8160 // is lexically inside an extern "C" linkage-spec. 8161 assert(Prev && "should have found a previous declaration to diagnose"); 8162 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 8163 Prev = FD->getFirstDecl(); 8164 else 8165 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 8166 8167 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 8168 << IsGlobal << ND; 8169 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 8170 << IsGlobal; 8171 return false; 8172 } 8173 8174 /// Apply special rules for handling extern "C" declarations. Returns \c true 8175 /// if we have found that this is a redeclaration of some prior entity. 8176 /// 8177 /// Per C++ [dcl.link]p6: 8178 /// Two declarations [for a function or variable] with C language linkage 8179 /// with the same name that appear in different scopes refer to the same 8180 /// [entity]. An entity with C language linkage shall not be declared with 8181 /// the same name as an entity in global scope. 8182 template<typename T> 8183 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8184 LookupResult &Previous) { 8185 if (!S.getLangOpts().CPlusPlus) { 8186 // In C, when declaring a global variable, look for a corresponding 'extern' 8187 // variable declared in function scope. We don't need this in C++, because 8188 // we find local extern decls in the surrounding file-scope DeclContext. 8189 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8190 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8191 Previous.clear(); 8192 Previous.addDecl(Prev); 8193 return true; 8194 } 8195 } 8196 return false; 8197 } 8198 8199 // A declaration in the translation unit can conflict with an extern "C" 8200 // declaration. 8201 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8202 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8203 8204 // An extern "C" declaration can conflict with a declaration in the 8205 // translation unit or can be a redeclaration of an extern "C" declaration 8206 // in another scope. 8207 if (isIncompleteDeclExternC(S,ND)) 8208 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8209 8210 // Neither global nor extern "C": nothing to do. 8211 return false; 8212 } 8213 8214 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8215 // If the decl is already known invalid, don't check it. 8216 if (NewVD->isInvalidDecl()) 8217 return; 8218 8219 QualType T = NewVD->getType(); 8220 8221 // Defer checking an 'auto' type until its initializer is attached. 8222 if (T->isUndeducedType()) 8223 return; 8224 8225 if (NewVD->hasAttrs()) 8226 CheckAlignasUnderalignment(NewVD); 8227 8228 if (T->isObjCObjectType()) { 8229 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8230 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8231 T = Context.getObjCObjectPointerType(T); 8232 NewVD->setType(T); 8233 } 8234 8235 // Emit an error if an address space was applied to decl with local storage. 8236 // This includes arrays of objects with address space qualifiers, but not 8237 // automatic variables that point to other address spaces. 8238 // ISO/IEC TR 18037 S5.1.2 8239 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8240 T.getAddressSpace() != LangAS::Default) { 8241 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8242 NewVD->setInvalidDecl(); 8243 return; 8244 } 8245 8246 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8247 // scope. 8248 if (getLangOpts().OpenCLVersion == 120 && 8249 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8250 getLangOpts()) && 8251 NewVD->isStaticLocal()) { 8252 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8253 NewVD->setInvalidDecl(); 8254 return; 8255 } 8256 8257 if (getLangOpts().OpenCL) { 8258 if (!diagnoseOpenCLTypes(*this, NewVD)) 8259 return; 8260 8261 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8262 if (NewVD->hasAttr<BlocksAttr>()) { 8263 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8264 return; 8265 } 8266 8267 if (T->isBlockPointerType()) { 8268 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8269 // can't use 'extern' storage class. 8270 if (!T.isConstQualified()) { 8271 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8272 << 0 /*const*/; 8273 NewVD->setInvalidDecl(); 8274 return; 8275 } 8276 if (NewVD->hasExternalStorage()) { 8277 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8278 NewVD->setInvalidDecl(); 8279 return; 8280 } 8281 } 8282 8283 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8284 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8285 NewVD->hasExternalStorage()) { 8286 if (!T->isSamplerT() && !T->isDependentType() && 8287 !(T.getAddressSpace() == LangAS::opencl_constant || 8288 (T.getAddressSpace() == LangAS::opencl_global && 8289 getOpenCLOptions().areProgramScopeVariablesSupported( 8290 getLangOpts())))) { 8291 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8292 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8293 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8294 << Scope << "global or constant"; 8295 else 8296 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8297 << Scope << "constant"; 8298 NewVD->setInvalidDecl(); 8299 return; 8300 } 8301 } else { 8302 if (T.getAddressSpace() == LangAS::opencl_global) { 8303 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8304 << 1 /*is any function*/ << "global"; 8305 NewVD->setInvalidDecl(); 8306 return; 8307 } 8308 if (T.getAddressSpace() == LangAS::opencl_constant || 8309 T.getAddressSpace() == LangAS::opencl_local) { 8310 FunctionDecl *FD = getCurFunctionDecl(); 8311 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8312 // in functions. 8313 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8314 if (T.getAddressSpace() == LangAS::opencl_constant) 8315 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8316 << 0 /*non-kernel only*/ << "constant"; 8317 else 8318 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8319 << 0 /*non-kernel only*/ << "local"; 8320 NewVD->setInvalidDecl(); 8321 return; 8322 } 8323 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8324 // in the outermost scope of a kernel function. 8325 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8326 if (!getCurScope()->isFunctionScope()) { 8327 if (T.getAddressSpace() == LangAS::opencl_constant) 8328 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8329 << "constant"; 8330 else 8331 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8332 << "local"; 8333 NewVD->setInvalidDecl(); 8334 return; 8335 } 8336 } 8337 } else if (T.getAddressSpace() != LangAS::opencl_private && 8338 // If we are parsing a template we didn't deduce an addr 8339 // space yet. 8340 T.getAddressSpace() != LangAS::Default) { 8341 // Do not allow other address spaces on automatic variable. 8342 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8343 NewVD->setInvalidDecl(); 8344 return; 8345 } 8346 } 8347 } 8348 8349 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8350 && !NewVD->hasAttr<BlocksAttr>()) { 8351 if (getLangOpts().getGC() != LangOptions::NonGC) 8352 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8353 else { 8354 assert(!getLangOpts().ObjCAutoRefCount); 8355 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8356 } 8357 } 8358 8359 bool isVM = T->isVariablyModifiedType(); 8360 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8361 NewVD->hasAttr<BlocksAttr>()) 8362 setFunctionHasBranchProtectedScope(); 8363 8364 if ((isVM && NewVD->hasLinkage()) || 8365 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8366 bool SizeIsNegative; 8367 llvm::APSInt Oversized; 8368 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8369 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8370 QualType FixedT; 8371 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8372 FixedT = FixedTInfo->getType(); 8373 else if (FixedTInfo) { 8374 // Type and type-as-written are canonically different. We need to fix up 8375 // both types separately. 8376 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8377 Oversized); 8378 } 8379 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8380 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8381 // FIXME: This won't give the correct result for 8382 // int a[10][n]; 8383 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8384 8385 if (NewVD->isFileVarDecl()) 8386 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8387 << SizeRange; 8388 else if (NewVD->isStaticLocal()) 8389 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8390 << SizeRange; 8391 else 8392 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8393 << SizeRange; 8394 NewVD->setInvalidDecl(); 8395 return; 8396 } 8397 8398 if (!FixedTInfo) { 8399 if (NewVD->isFileVarDecl()) 8400 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8401 else 8402 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8403 NewVD->setInvalidDecl(); 8404 return; 8405 } 8406 8407 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8408 NewVD->setType(FixedT); 8409 NewVD->setTypeSourceInfo(FixedTInfo); 8410 } 8411 8412 if (T->isVoidType()) { 8413 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8414 // of objects and functions. 8415 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8416 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8417 << T; 8418 NewVD->setInvalidDecl(); 8419 return; 8420 } 8421 } 8422 8423 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8424 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8425 NewVD->setInvalidDecl(); 8426 return; 8427 } 8428 8429 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8430 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8431 NewVD->setInvalidDecl(); 8432 return; 8433 } 8434 8435 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8436 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8437 NewVD->setInvalidDecl(); 8438 return; 8439 } 8440 8441 if (NewVD->isConstexpr() && !T->isDependentType() && 8442 RequireLiteralType(NewVD->getLocation(), T, 8443 diag::err_constexpr_var_non_literal)) { 8444 NewVD->setInvalidDecl(); 8445 return; 8446 } 8447 8448 // PPC MMA non-pointer types are not allowed as non-local variable types. 8449 if (Context.getTargetInfo().getTriple().isPPC64() && 8450 !NewVD->isLocalVarDecl() && 8451 CheckPPCMMAType(T, NewVD->getLocation())) { 8452 NewVD->setInvalidDecl(); 8453 return; 8454 } 8455 } 8456 8457 /// Perform semantic checking on a newly-created variable 8458 /// declaration. 8459 /// 8460 /// This routine performs all of the type-checking required for a 8461 /// variable declaration once it has been built. It is used both to 8462 /// check variables after they have been parsed and their declarators 8463 /// have been translated into a declaration, and to check variables 8464 /// that have been instantiated from a template. 8465 /// 8466 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8467 /// 8468 /// Returns true if the variable declaration is a redeclaration. 8469 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8470 CheckVariableDeclarationType(NewVD); 8471 8472 // If the decl is already known invalid, don't check it. 8473 if (NewVD->isInvalidDecl()) 8474 return false; 8475 8476 // If we did not find anything by this name, look for a non-visible 8477 // extern "C" declaration with the same name. 8478 if (Previous.empty() && 8479 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8480 Previous.setShadowed(); 8481 8482 if (!Previous.empty()) { 8483 MergeVarDecl(NewVD, Previous); 8484 return true; 8485 } 8486 return false; 8487 } 8488 8489 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8490 /// and if so, check that it's a valid override and remember it. 8491 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8492 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8493 8494 // Look for methods in base classes that this method might override. 8495 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8496 /*DetectVirtual=*/false); 8497 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8498 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8499 DeclarationName Name = MD->getDeclName(); 8500 8501 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8502 // We really want to find the base class destructor here. 8503 QualType T = Context.getTypeDeclType(BaseRecord); 8504 CanQualType CT = Context.getCanonicalType(T); 8505 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8506 } 8507 8508 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8509 CXXMethodDecl *BaseMD = 8510 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8511 if (!BaseMD || !BaseMD->isVirtual() || 8512 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8513 /*ConsiderCudaAttrs=*/true, 8514 // C++2a [class.virtual]p2 does not consider requires 8515 // clauses when overriding. 8516 /*ConsiderRequiresClauses=*/false)) 8517 continue; 8518 8519 if (Overridden.insert(BaseMD).second) { 8520 MD->addOverriddenMethod(BaseMD); 8521 CheckOverridingFunctionReturnType(MD, BaseMD); 8522 CheckOverridingFunctionAttributes(MD, BaseMD); 8523 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8524 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8525 } 8526 8527 // A method can only override one function from each base class. We 8528 // don't track indirectly overridden methods from bases of bases. 8529 return true; 8530 } 8531 8532 return false; 8533 }; 8534 8535 DC->lookupInBases(VisitBase, Paths); 8536 return !Overridden.empty(); 8537 } 8538 8539 namespace { 8540 // Struct for holding all of the extra arguments needed by 8541 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8542 struct ActOnFDArgs { 8543 Scope *S; 8544 Declarator &D; 8545 MultiTemplateParamsArg TemplateParamLists; 8546 bool AddToScope; 8547 }; 8548 } // end anonymous namespace 8549 8550 namespace { 8551 8552 // Callback to only accept typo corrections that have a non-zero edit distance. 8553 // Also only accept corrections that have the same parent decl. 8554 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8555 public: 8556 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8557 CXXRecordDecl *Parent) 8558 : Context(Context), OriginalFD(TypoFD), 8559 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8560 8561 bool ValidateCandidate(const TypoCorrection &candidate) override { 8562 if (candidate.getEditDistance() == 0) 8563 return false; 8564 8565 SmallVector<unsigned, 1> MismatchedParams; 8566 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8567 CDeclEnd = candidate.end(); 8568 CDecl != CDeclEnd; ++CDecl) { 8569 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8570 8571 if (FD && !FD->hasBody() && 8572 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8573 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8574 CXXRecordDecl *Parent = MD->getParent(); 8575 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8576 return true; 8577 } else if (!ExpectedParent) { 8578 return true; 8579 } 8580 } 8581 } 8582 8583 return false; 8584 } 8585 8586 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8587 return std::make_unique<DifferentNameValidatorCCC>(*this); 8588 } 8589 8590 private: 8591 ASTContext &Context; 8592 FunctionDecl *OriginalFD; 8593 CXXRecordDecl *ExpectedParent; 8594 }; 8595 8596 } // end anonymous namespace 8597 8598 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8599 TypoCorrectedFunctionDefinitions.insert(F); 8600 } 8601 8602 /// Generate diagnostics for an invalid function redeclaration. 8603 /// 8604 /// This routine handles generating the diagnostic messages for an invalid 8605 /// function redeclaration, including finding possible similar declarations 8606 /// or performing typo correction if there are no previous declarations with 8607 /// the same name. 8608 /// 8609 /// Returns a NamedDecl iff typo correction was performed and substituting in 8610 /// the new declaration name does not cause new errors. 8611 static NamedDecl *DiagnoseInvalidRedeclaration( 8612 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8613 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8614 DeclarationName Name = NewFD->getDeclName(); 8615 DeclContext *NewDC = NewFD->getDeclContext(); 8616 SmallVector<unsigned, 1> MismatchedParams; 8617 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8618 TypoCorrection Correction; 8619 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8620 unsigned DiagMsg = 8621 IsLocalFriend ? diag::err_no_matching_local_friend : 8622 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8623 diag::err_member_decl_does_not_match; 8624 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8625 IsLocalFriend ? Sema::LookupLocalFriendName 8626 : Sema::LookupOrdinaryName, 8627 Sema::ForVisibleRedeclaration); 8628 8629 NewFD->setInvalidDecl(); 8630 if (IsLocalFriend) 8631 SemaRef.LookupName(Prev, S); 8632 else 8633 SemaRef.LookupQualifiedName(Prev, NewDC); 8634 assert(!Prev.isAmbiguous() && 8635 "Cannot have an ambiguity in previous-declaration lookup"); 8636 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8637 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8638 MD ? MD->getParent() : nullptr); 8639 if (!Prev.empty()) { 8640 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8641 Func != FuncEnd; ++Func) { 8642 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8643 if (FD && 8644 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8645 // Add 1 to the index so that 0 can mean the mismatch didn't 8646 // involve a parameter 8647 unsigned ParamNum = 8648 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8649 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8650 } 8651 } 8652 // If the qualified name lookup yielded nothing, try typo correction 8653 } else if ((Correction = SemaRef.CorrectTypo( 8654 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8655 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8656 IsLocalFriend ? nullptr : NewDC))) { 8657 // Set up everything for the call to ActOnFunctionDeclarator 8658 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8659 ExtraArgs.D.getIdentifierLoc()); 8660 Previous.clear(); 8661 Previous.setLookupName(Correction.getCorrection()); 8662 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8663 CDeclEnd = Correction.end(); 8664 CDecl != CDeclEnd; ++CDecl) { 8665 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8666 if (FD && !FD->hasBody() && 8667 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8668 Previous.addDecl(FD); 8669 } 8670 } 8671 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8672 8673 NamedDecl *Result; 8674 // Retry building the function declaration with the new previous 8675 // declarations, and with errors suppressed. 8676 { 8677 // Trap errors. 8678 Sema::SFINAETrap Trap(SemaRef); 8679 8680 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8681 // pieces need to verify the typo-corrected C++ declaration and hopefully 8682 // eliminate the need for the parameter pack ExtraArgs. 8683 Result = SemaRef.ActOnFunctionDeclarator( 8684 ExtraArgs.S, ExtraArgs.D, 8685 Correction.getCorrectionDecl()->getDeclContext(), 8686 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8687 ExtraArgs.AddToScope); 8688 8689 if (Trap.hasErrorOccurred()) 8690 Result = nullptr; 8691 } 8692 8693 if (Result) { 8694 // Determine which correction we picked. 8695 Decl *Canonical = Result->getCanonicalDecl(); 8696 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8697 I != E; ++I) 8698 if ((*I)->getCanonicalDecl() == Canonical) 8699 Correction.setCorrectionDecl(*I); 8700 8701 // Let Sema know about the correction. 8702 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8703 SemaRef.diagnoseTypo( 8704 Correction, 8705 SemaRef.PDiag(IsLocalFriend 8706 ? diag::err_no_matching_local_friend_suggest 8707 : diag::err_member_decl_does_not_match_suggest) 8708 << Name << NewDC << IsDefinition); 8709 return Result; 8710 } 8711 8712 // Pretend the typo correction never occurred 8713 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8714 ExtraArgs.D.getIdentifierLoc()); 8715 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8716 Previous.clear(); 8717 Previous.setLookupName(Name); 8718 } 8719 8720 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8721 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8722 8723 bool NewFDisConst = false; 8724 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8725 NewFDisConst = NewMD->isConst(); 8726 8727 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8728 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8729 NearMatch != NearMatchEnd; ++NearMatch) { 8730 FunctionDecl *FD = NearMatch->first; 8731 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8732 bool FDisConst = MD && MD->isConst(); 8733 bool IsMember = MD || !IsLocalFriend; 8734 8735 // FIXME: These notes are poorly worded for the local friend case. 8736 if (unsigned Idx = NearMatch->second) { 8737 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8738 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8739 if (Loc.isInvalid()) Loc = FD->getLocation(); 8740 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8741 : diag::note_local_decl_close_param_match) 8742 << Idx << FDParam->getType() 8743 << NewFD->getParamDecl(Idx - 1)->getType(); 8744 } else if (FDisConst != NewFDisConst) { 8745 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8746 << NewFDisConst << FD->getSourceRange().getEnd() 8747 << (NewFDisConst 8748 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 8749 .getConstQualifierLoc()) 8750 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 8751 .getRParenLoc() 8752 .getLocWithOffset(1), 8753 " const")); 8754 } else 8755 SemaRef.Diag(FD->getLocation(), 8756 IsMember ? diag::note_member_def_close_match 8757 : diag::note_local_decl_close_match); 8758 } 8759 return nullptr; 8760 } 8761 8762 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8763 switch (D.getDeclSpec().getStorageClassSpec()) { 8764 default: llvm_unreachable("Unknown storage class!"); 8765 case DeclSpec::SCS_auto: 8766 case DeclSpec::SCS_register: 8767 case DeclSpec::SCS_mutable: 8768 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8769 diag::err_typecheck_sclass_func); 8770 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8771 D.setInvalidType(); 8772 break; 8773 case DeclSpec::SCS_unspecified: break; 8774 case DeclSpec::SCS_extern: 8775 if (D.getDeclSpec().isExternInLinkageSpec()) 8776 return SC_None; 8777 return SC_Extern; 8778 case DeclSpec::SCS_static: { 8779 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8780 // C99 6.7.1p5: 8781 // The declaration of an identifier for a function that has 8782 // block scope shall have no explicit storage-class specifier 8783 // other than extern 8784 // See also (C++ [dcl.stc]p4). 8785 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8786 diag::err_static_block_func); 8787 break; 8788 } else 8789 return SC_Static; 8790 } 8791 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8792 } 8793 8794 // No explicit storage class has already been returned 8795 return SC_None; 8796 } 8797 8798 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8799 DeclContext *DC, QualType &R, 8800 TypeSourceInfo *TInfo, 8801 StorageClass SC, 8802 bool &IsVirtualOkay) { 8803 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8804 DeclarationName Name = NameInfo.getName(); 8805 8806 FunctionDecl *NewFD = nullptr; 8807 bool isInline = D.getDeclSpec().isInlineSpecified(); 8808 8809 if (!SemaRef.getLangOpts().CPlusPlus) { 8810 // Determine whether the function was written with a prototype. This is 8811 // true when: 8812 // - there is a prototype in the declarator, or 8813 // - the type R of the function is some kind of typedef or other non- 8814 // attributed reference to a type name (which eventually refers to a 8815 // function type). Note, we can't always look at the adjusted type to 8816 // check this case because attributes may cause a non-function 8817 // declarator to still have a function type. e.g., 8818 // typedef void func(int a); 8819 // __attribute__((noreturn)) func other_func; // This has a prototype 8820 bool HasPrototype = 8821 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8822 (D.getDeclSpec().isTypeRep() && 8823 D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) || 8824 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8825 assert( 8826 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && 8827 "Strict prototypes are required"); 8828 8829 NewFD = FunctionDecl::Create( 8830 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8831 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8832 ConstexprSpecKind::Unspecified, 8833 /*TrailingRequiresClause=*/nullptr); 8834 if (D.isInvalidType()) 8835 NewFD->setInvalidDecl(); 8836 8837 return NewFD; 8838 } 8839 8840 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8841 8842 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8843 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8844 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8845 diag::err_constexpr_wrong_decl_kind) 8846 << static_cast<int>(ConstexprKind); 8847 ConstexprKind = ConstexprSpecKind::Unspecified; 8848 D.getMutableDeclSpec().ClearConstexprSpec(); 8849 } 8850 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8851 8852 // Check that the return type is not an abstract class type. 8853 // For record types, this is done by the AbstractClassUsageDiagnoser once 8854 // the class has been completely parsed. 8855 if (!DC->isRecord() && 8856 SemaRef.RequireNonAbstractType( 8857 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8858 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8859 D.setInvalidType(); 8860 8861 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8862 // This is a C++ constructor declaration. 8863 assert(DC->isRecord() && 8864 "Constructors can only be declared in a member context"); 8865 8866 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8867 return CXXConstructorDecl::Create( 8868 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8869 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8870 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8871 InheritedConstructor(), TrailingRequiresClause); 8872 8873 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8874 // This is a C++ destructor declaration. 8875 if (DC->isRecord()) { 8876 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8877 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8878 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8879 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8880 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8881 /*isImplicitlyDeclared=*/false, ConstexprKind, 8882 TrailingRequiresClause); 8883 8884 // If the destructor needs an implicit exception specification, set it 8885 // now. FIXME: It'd be nice to be able to create the right type to start 8886 // with, but the type needs to reference the destructor declaration. 8887 if (SemaRef.getLangOpts().CPlusPlus11) 8888 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8889 8890 IsVirtualOkay = true; 8891 return NewDD; 8892 8893 } else { 8894 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8895 D.setInvalidType(); 8896 8897 // Create a FunctionDecl to satisfy the function definition parsing 8898 // code path. 8899 return FunctionDecl::Create( 8900 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8901 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8902 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8903 } 8904 8905 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8906 if (!DC->isRecord()) { 8907 SemaRef.Diag(D.getIdentifierLoc(), 8908 diag::err_conv_function_not_member); 8909 return nullptr; 8910 } 8911 8912 SemaRef.CheckConversionDeclarator(D, R, SC); 8913 if (D.isInvalidType()) 8914 return nullptr; 8915 8916 IsVirtualOkay = true; 8917 return CXXConversionDecl::Create( 8918 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8919 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8920 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8921 TrailingRequiresClause); 8922 8923 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8924 if (TrailingRequiresClause) 8925 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8926 diag::err_trailing_requires_clause_on_deduction_guide) 8927 << TrailingRequiresClause->getSourceRange(); 8928 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8929 8930 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8931 ExplicitSpecifier, NameInfo, R, TInfo, 8932 D.getEndLoc()); 8933 } else if (DC->isRecord()) { 8934 // If the name of the function is the same as the name of the record, 8935 // then this must be an invalid constructor that has a return type. 8936 // (The parser checks for a return type and makes the declarator a 8937 // constructor if it has no return type). 8938 if (Name.getAsIdentifierInfo() && 8939 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8940 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8941 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8942 << SourceRange(D.getIdentifierLoc()); 8943 return nullptr; 8944 } 8945 8946 // This is a C++ method declaration. 8947 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8948 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8949 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8950 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8951 IsVirtualOkay = !Ret->isStatic(); 8952 return Ret; 8953 } else { 8954 bool isFriend = 8955 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8956 if (!isFriend && SemaRef.CurContext->isRecord()) 8957 return nullptr; 8958 8959 // Determine whether the function was written with a 8960 // prototype. This true when: 8961 // - we're in C++ (where every function has a prototype), 8962 return FunctionDecl::Create( 8963 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8964 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8965 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8966 } 8967 } 8968 8969 enum OpenCLParamType { 8970 ValidKernelParam, 8971 PtrPtrKernelParam, 8972 PtrKernelParam, 8973 InvalidAddrSpacePtrKernelParam, 8974 InvalidKernelParam, 8975 RecordKernelParam 8976 }; 8977 8978 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8979 // Size dependent types are just typedefs to normal integer types 8980 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8981 // integers other than by their names. 8982 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8983 8984 // Remove typedefs one by one until we reach a typedef 8985 // for a size dependent type. 8986 QualType DesugaredTy = Ty; 8987 do { 8988 ArrayRef<StringRef> Names(SizeTypeNames); 8989 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8990 if (Names.end() != Match) 8991 return true; 8992 8993 Ty = DesugaredTy; 8994 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8995 } while (DesugaredTy != Ty); 8996 8997 return false; 8998 } 8999 9000 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 9001 if (PT->isDependentType()) 9002 return InvalidKernelParam; 9003 9004 if (PT->isPointerType() || PT->isReferenceType()) { 9005 QualType PointeeType = PT->getPointeeType(); 9006 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 9007 PointeeType.getAddressSpace() == LangAS::opencl_private || 9008 PointeeType.getAddressSpace() == LangAS::Default) 9009 return InvalidAddrSpacePtrKernelParam; 9010 9011 if (PointeeType->isPointerType()) { 9012 // This is a pointer to pointer parameter. 9013 // Recursively check inner type. 9014 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 9015 if (ParamKind == InvalidAddrSpacePtrKernelParam || 9016 ParamKind == InvalidKernelParam) 9017 return ParamKind; 9018 9019 return PtrPtrKernelParam; 9020 } 9021 9022 // C++ for OpenCL v1.0 s2.4: 9023 // Moreover the types used in parameters of the kernel functions must be: 9024 // Standard layout types for pointer parameters. The same applies to 9025 // reference if an implementation supports them in kernel parameters. 9026 if (S.getLangOpts().OpenCLCPlusPlus && 9027 !S.getOpenCLOptions().isAvailableOption( 9028 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9029 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 9030 !PointeeType->isStandardLayoutType()) 9031 return InvalidKernelParam; 9032 9033 return PtrKernelParam; 9034 } 9035 9036 // OpenCL v1.2 s6.9.k: 9037 // Arguments to kernel functions in a program cannot be declared with the 9038 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9039 // uintptr_t or a struct and/or union that contain fields declared to be one 9040 // of these built-in scalar types. 9041 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 9042 return InvalidKernelParam; 9043 9044 if (PT->isImageType()) 9045 return PtrKernelParam; 9046 9047 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 9048 return InvalidKernelParam; 9049 9050 // OpenCL extension spec v1.2 s9.5: 9051 // This extension adds support for half scalar and vector types as built-in 9052 // types that can be used for arithmetic operations, conversions etc. 9053 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 9054 PT->isHalfType()) 9055 return InvalidKernelParam; 9056 9057 // Look into an array argument to check if it has a forbidden type. 9058 if (PT->isArrayType()) { 9059 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 9060 // Call ourself to check an underlying type of an array. Since the 9061 // getPointeeOrArrayElementType returns an innermost type which is not an 9062 // array, this recursive call only happens once. 9063 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 9064 } 9065 9066 // C++ for OpenCL v1.0 s2.4: 9067 // Moreover the types used in parameters of the kernel functions must be: 9068 // Trivial and standard-layout types C++17 [basic.types] (plain old data 9069 // types) for parameters passed by value; 9070 if (S.getLangOpts().OpenCLCPlusPlus && 9071 !S.getOpenCLOptions().isAvailableOption( 9072 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9073 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 9074 return InvalidKernelParam; 9075 9076 if (PT->isRecordType()) 9077 return RecordKernelParam; 9078 9079 return ValidKernelParam; 9080 } 9081 9082 static void checkIsValidOpenCLKernelParameter( 9083 Sema &S, 9084 Declarator &D, 9085 ParmVarDecl *Param, 9086 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 9087 QualType PT = Param->getType(); 9088 9089 // Cache the valid types we encounter to avoid rechecking structs that are 9090 // used again 9091 if (ValidTypes.count(PT.getTypePtr())) 9092 return; 9093 9094 switch (getOpenCLKernelParameterType(S, PT)) { 9095 case PtrPtrKernelParam: 9096 // OpenCL v3.0 s6.11.a: 9097 // A kernel function argument cannot be declared as a pointer to a pointer 9098 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 9099 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 9100 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 9101 D.setInvalidType(); 9102 return; 9103 } 9104 9105 ValidTypes.insert(PT.getTypePtr()); 9106 return; 9107 9108 case InvalidAddrSpacePtrKernelParam: 9109 // OpenCL v1.0 s6.5: 9110 // __kernel function arguments declared to be a pointer of a type can point 9111 // to one of the following address spaces only : __global, __local or 9112 // __constant. 9113 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 9114 D.setInvalidType(); 9115 return; 9116 9117 // OpenCL v1.2 s6.9.k: 9118 // Arguments to kernel functions in a program cannot be declared with the 9119 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9120 // uintptr_t or a struct and/or union that contain fields declared to be 9121 // one of these built-in scalar types. 9122 9123 case InvalidKernelParam: 9124 // OpenCL v1.2 s6.8 n: 9125 // A kernel function argument cannot be declared 9126 // of event_t type. 9127 // Do not diagnose half type since it is diagnosed as invalid argument 9128 // type for any function elsewhere. 9129 if (!PT->isHalfType()) { 9130 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9131 9132 // Explain what typedefs are involved. 9133 const TypedefType *Typedef = nullptr; 9134 while ((Typedef = PT->getAs<TypedefType>())) { 9135 SourceLocation Loc = Typedef->getDecl()->getLocation(); 9136 // SourceLocation may be invalid for a built-in type. 9137 if (Loc.isValid()) 9138 S.Diag(Loc, diag::note_entity_declared_at) << PT; 9139 PT = Typedef->desugar(); 9140 } 9141 } 9142 9143 D.setInvalidType(); 9144 return; 9145 9146 case PtrKernelParam: 9147 case ValidKernelParam: 9148 ValidTypes.insert(PT.getTypePtr()); 9149 return; 9150 9151 case RecordKernelParam: 9152 break; 9153 } 9154 9155 // Track nested structs we will inspect 9156 SmallVector<const Decl *, 4> VisitStack; 9157 9158 // Track where we are in the nested structs. Items will migrate from 9159 // VisitStack to HistoryStack as we do the DFS for bad field. 9160 SmallVector<const FieldDecl *, 4> HistoryStack; 9161 HistoryStack.push_back(nullptr); 9162 9163 // At this point we already handled everything except of a RecordType or 9164 // an ArrayType of a RecordType. 9165 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9166 const RecordType *RecTy = 9167 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9168 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9169 9170 VisitStack.push_back(RecTy->getDecl()); 9171 assert(VisitStack.back() && "First decl null?"); 9172 9173 do { 9174 const Decl *Next = VisitStack.pop_back_val(); 9175 if (!Next) { 9176 assert(!HistoryStack.empty()); 9177 // Found a marker, we have gone up a level 9178 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9179 ValidTypes.insert(Hist->getType().getTypePtr()); 9180 9181 continue; 9182 } 9183 9184 // Adds everything except the original parameter declaration (which is not a 9185 // field itself) to the history stack. 9186 const RecordDecl *RD; 9187 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9188 HistoryStack.push_back(Field); 9189 9190 QualType FieldTy = Field->getType(); 9191 // Other field types (known to be valid or invalid) are handled while we 9192 // walk around RecordDecl::fields(). 9193 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9194 "Unexpected type."); 9195 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9196 9197 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9198 } else { 9199 RD = cast<RecordDecl>(Next); 9200 } 9201 9202 // Add a null marker so we know when we've gone back up a level 9203 VisitStack.push_back(nullptr); 9204 9205 for (const auto *FD : RD->fields()) { 9206 QualType QT = FD->getType(); 9207 9208 if (ValidTypes.count(QT.getTypePtr())) 9209 continue; 9210 9211 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9212 if (ParamType == ValidKernelParam) 9213 continue; 9214 9215 if (ParamType == RecordKernelParam) { 9216 VisitStack.push_back(FD); 9217 continue; 9218 } 9219 9220 // OpenCL v1.2 s6.9.p: 9221 // Arguments to kernel functions that are declared to be a struct or union 9222 // do not allow OpenCL objects to be passed as elements of the struct or 9223 // union. 9224 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9225 ParamType == InvalidAddrSpacePtrKernelParam) { 9226 S.Diag(Param->getLocation(), 9227 diag::err_record_with_pointers_kernel_param) 9228 << PT->isUnionType() 9229 << PT; 9230 } else { 9231 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9232 } 9233 9234 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9235 << OrigRecDecl->getDeclName(); 9236 9237 // We have an error, now let's go back up through history and show where 9238 // the offending field came from 9239 for (ArrayRef<const FieldDecl *>::const_iterator 9240 I = HistoryStack.begin() + 1, 9241 E = HistoryStack.end(); 9242 I != E; ++I) { 9243 const FieldDecl *OuterField = *I; 9244 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9245 << OuterField->getType(); 9246 } 9247 9248 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9249 << QT->isPointerType() 9250 << QT; 9251 D.setInvalidType(); 9252 return; 9253 } 9254 } while (!VisitStack.empty()); 9255 } 9256 9257 /// Find the DeclContext in which a tag is implicitly declared if we see an 9258 /// elaborated type specifier in the specified context, and lookup finds 9259 /// nothing. 9260 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9261 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9262 DC = DC->getParent(); 9263 return DC; 9264 } 9265 9266 /// Find the Scope in which a tag is implicitly declared if we see an 9267 /// elaborated type specifier in the specified context, and lookup finds 9268 /// nothing. 9269 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9270 while (S->isClassScope() || 9271 (LangOpts.CPlusPlus && 9272 S->isFunctionPrototypeScope()) || 9273 ((S->getFlags() & Scope::DeclScope) == 0) || 9274 (S->getEntity() && S->getEntity()->isTransparentContext())) 9275 S = S->getParent(); 9276 return S; 9277 } 9278 9279 /// Determine whether a declaration matches a known function in namespace std. 9280 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, 9281 unsigned BuiltinID) { 9282 switch (BuiltinID) { 9283 case Builtin::BI__GetExceptionInfo: 9284 // No type checking whatsoever. 9285 return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); 9286 9287 case Builtin::BIaddressof: 9288 case Builtin::BI__addressof: 9289 case Builtin::BIforward: 9290 case Builtin::BImove: 9291 case Builtin::BImove_if_noexcept: 9292 case Builtin::BIas_const: { 9293 // Ensure that we don't treat the algorithm 9294 // OutputIt std::move(InputIt, InputIt, OutputIt) 9295 // as the builtin std::move. 9296 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 9297 return FPT->getNumParams() == 1 && !FPT->isVariadic(); 9298 } 9299 9300 default: 9301 return false; 9302 } 9303 } 9304 9305 NamedDecl* 9306 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9307 TypeSourceInfo *TInfo, LookupResult &Previous, 9308 MultiTemplateParamsArg TemplateParamListsRef, 9309 bool &AddToScope) { 9310 QualType R = TInfo->getType(); 9311 9312 assert(R->isFunctionType()); 9313 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9314 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9315 9316 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9317 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9318 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9319 if (!TemplateParamLists.empty() && 9320 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9321 TemplateParamLists.back() = Invented; 9322 else 9323 TemplateParamLists.push_back(Invented); 9324 } 9325 9326 // TODO: consider using NameInfo for diagnostic. 9327 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9328 DeclarationName Name = NameInfo.getName(); 9329 StorageClass SC = getFunctionStorageClass(*this, D); 9330 9331 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9332 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9333 diag::err_invalid_thread) 9334 << DeclSpec::getSpecifierName(TSCS); 9335 9336 if (D.isFirstDeclarationOfMember()) 9337 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9338 D.getIdentifierLoc()); 9339 9340 bool isFriend = false; 9341 FunctionTemplateDecl *FunctionTemplate = nullptr; 9342 bool isMemberSpecialization = false; 9343 bool isFunctionTemplateSpecialization = false; 9344 9345 bool isDependentClassScopeExplicitSpecialization = false; 9346 bool HasExplicitTemplateArgs = false; 9347 TemplateArgumentListInfo TemplateArgs; 9348 9349 bool isVirtualOkay = false; 9350 9351 DeclContext *OriginalDC = DC; 9352 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9353 9354 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9355 isVirtualOkay); 9356 if (!NewFD) return nullptr; 9357 9358 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9359 NewFD->setTopLevelDeclInObjCContainer(); 9360 9361 // Set the lexical context. If this is a function-scope declaration, or has a 9362 // C++ scope specifier, or is the object of a friend declaration, the lexical 9363 // context will be different from the semantic context. 9364 NewFD->setLexicalDeclContext(CurContext); 9365 9366 if (IsLocalExternDecl) 9367 NewFD->setLocalExternDecl(); 9368 9369 if (getLangOpts().CPlusPlus) { 9370 bool isInline = D.getDeclSpec().isInlineSpecified(); 9371 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9372 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9373 isFriend = D.getDeclSpec().isFriendSpecified(); 9374 if (isFriend && !isInline && D.isFunctionDefinition()) { 9375 // C++ [class.friend]p5 9376 // A function can be defined in a friend declaration of a 9377 // class . . . . Such a function is implicitly inline. 9378 NewFD->setImplicitlyInline(); 9379 } 9380 9381 // If this is a method defined in an __interface, and is not a constructor 9382 // or an overloaded operator, then set the pure flag (isVirtual will already 9383 // return true). 9384 if (const CXXRecordDecl *Parent = 9385 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9386 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9387 NewFD->setPure(true); 9388 9389 // C++ [class.union]p2 9390 // A union can have member functions, but not virtual functions. 9391 if (isVirtual && Parent->isUnion()) { 9392 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9393 NewFD->setInvalidDecl(); 9394 } 9395 if ((Parent->isClass() || Parent->isStruct()) && 9396 Parent->hasAttr<SYCLSpecialClassAttr>() && 9397 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9398 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9399 if (auto *Def = Parent->getDefinition()) 9400 Def->setInitMethod(true); 9401 } 9402 } 9403 9404 SetNestedNameSpecifier(*this, NewFD, D); 9405 isMemberSpecialization = false; 9406 isFunctionTemplateSpecialization = false; 9407 if (D.isInvalidType()) 9408 NewFD->setInvalidDecl(); 9409 9410 // Match up the template parameter lists with the scope specifier, then 9411 // determine whether we have a template or a template specialization. 9412 bool Invalid = false; 9413 TemplateParameterList *TemplateParams = 9414 MatchTemplateParametersToScopeSpecifier( 9415 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9416 D.getCXXScopeSpec(), 9417 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9418 ? D.getName().TemplateId 9419 : nullptr, 9420 TemplateParamLists, isFriend, isMemberSpecialization, 9421 Invalid); 9422 if (TemplateParams) { 9423 // Check that we can declare a template here. 9424 if (CheckTemplateDeclScope(S, TemplateParams)) 9425 NewFD->setInvalidDecl(); 9426 9427 if (TemplateParams->size() > 0) { 9428 // This is a function template 9429 9430 // A destructor cannot be a template. 9431 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9432 Diag(NewFD->getLocation(), diag::err_destructor_template); 9433 NewFD->setInvalidDecl(); 9434 } 9435 9436 // If we're adding a template to a dependent context, we may need to 9437 // rebuilding some of the types used within the template parameter list, 9438 // now that we know what the current instantiation is. 9439 if (DC->isDependentContext()) { 9440 ContextRAII SavedContext(*this, DC); 9441 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9442 Invalid = true; 9443 } 9444 9445 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9446 NewFD->getLocation(), 9447 Name, TemplateParams, 9448 NewFD); 9449 FunctionTemplate->setLexicalDeclContext(CurContext); 9450 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9451 9452 // For source fidelity, store the other template param lists. 9453 if (TemplateParamLists.size() > 1) { 9454 NewFD->setTemplateParameterListsInfo(Context, 9455 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9456 .drop_back(1)); 9457 } 9458 } else { 9459 // This is a function template specialization. 9460 isFunctionTemplateSpecialization = true; 9461 // For source fidelity, store all the template param lists. 9462 if (TemplateParamLists.size() > 0) 9463 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9464 9465 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9466 if (isFriend) { 9467 // We want to remove the "template<>", found here. 9468 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9469 9470 // If we remove the template<> and the name is not a 9471 // template-id, we're actually silently creating a problem: 9472 // the friend declaration will refer to an untemplated decl, 9473 // and clearly the user wants a template specialization. So 9474 // we need to insert '<>' after the name. 9475 SourceLocation InsertLoc; 9476 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9477 InsertLoc = D.getName().getSourceRange().getEnd(); 9478 InsertLoc = getLocForEndOfToken(InsertLoc); 9479 } 9480 9481 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9482 << Name << RemoveRange 9483 << FixItHint::CreateRemoval(RemoveRange) 9484 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9485 Invalid = true; 9486 } 9487 } 9488 } else { 9489 // Check that we can declare a template here. 9490 if (!TemplateParamLists.empty() && isMemberSpecialization && 9491 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9492 NewFD->setInvalidDecl(); 9493 9494 // All template param lists were matched against the scope specifier: 9495 // this is NOT (an explicit specialization of) a template. 9496 if (TemplateParamLists.size() > 0) 9497 // For source fidelity, store all the template param lists. 9498 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9499 } 9500 9501 if (Invalid) { 9502 NewFD->setInvalidDecl(); 9503 if (FunctionTemplate) 9504 FunctionTemplate->setInvalidDecl(); 9505 } 9506 9507 // C++ [dcl.fct.spec]p5: 9508 // The virtual specifier shall only be used in declarations of 9509 // nonstatic class member functions that appear within a 9510 // member-specification of a class declaration; see 10.3. 9511 // 9512 if (isVirtual && !NewFD->isInvalidDecl()) { 9513 if (!isVirtualOkay) { 9514 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9515 diag::err_virtual_non_function); 9516 } else if (!CurContext->isRecord()) { 9517 // 'virtual' was specified outside of the class. 9518 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9519 diag::err_virtual_out_of_class) 9520 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9521 } else if (NewFD->getDescribedFunctionTemplate()) { 9522 // C++ [temp.mem]p3: 9523 // A member function template shall not be virtual. 9524 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9525 diag::err_virtual_member_function_template) 9526 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9527 } else { 9528 // Okay: Add virtual to the method. 9529 NewFD->setVirtualAsWritten(true); 9530 } 9531 9532 if (getLangOpts().CPlusPlus14 && 9533 NewFD->getReturnType()->isUndeducedType()) 9534 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9535 } 9536 9537 if (getLangOpts().CPlusPlus14 && 9538 (NewFD->isDependentContext() || 9539 (isFriend && CurContext->isDependentContext())) && 9540 NewFD->getReturnType()->isUndeducedType()) { 9541 // If the function template is referenced directly (for instance, as a 9542 // member of the current instantiation), pretend it has a dependent type. 9543 // This is not really justified by the standard, but is the only sane 9544 // thing to do. 9545 // FIXME: For a friend function, we have not marked the function as being 9546 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9547 const FunctionProtoType *FPT = 9548 NewFD->getType()->castAs<FunctionProtoType>(); 9549 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9550 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9551 FPT->getExtProtoInfo())); 9552 } 9553 9554 // C++ [dcl.fct.spec]p3: 9555 // The inline specifier shall not appear on a block scope function 9556 // declaration. 9557 if (isInline && !NewFD->isInvalidDecl()) { 9558 if (CurContext->isFunctionOrMethod()) { 9559 // 'inline' is not allowed on block scope function declaration. 9560 Diag(D.getDeclSpec().getInlineSpecLoc(), 9561 diag::err_inline_declaration_block_scope) << Name 9562 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9563 } 9564 } 9565 9566 // C++ [dcl.fct.spec]p6: 9567 // The explicit specifier shall be used only in the declaration of a 9568 // constructor or conversion function within its class definition; 9569 // see 12.3.1 and 12.3.2. 9570 if (hasExplicit && !NewFD->isInvalidDecl() && 9571 !isa<CXXDeductionGuideDecl>(NewFD)) { 9572 if (!CurContext->isRecord()) { 9573 // 'explicit' was specified outside of the class. 9574 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9575 diag::err_explicit_out_of_class) 9576 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9577 } else if (!isa<CXXConstructorDecl>(NewFD) && 9578 !isa<CXXConversionDecl>(NewFD)) { 9579 // 'explicit' was specified on a function that wasn't a constructor 9580 // or conversion function. 9581 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9582 diag::err_explicit_non_ctor_or_conv_function) 9583 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9584 } 9585 } 9586 9587 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9588 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9589 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9590 // are implicitly inline. 9591 NewFD->setImplicitlyInline(); 9592 9593 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9594 // be either constructors or to return a literal type. Therefore, 9595 // destructors cannot be declared constexpr. 9596 if (isa<CXXDestructorDecl>(NewFD) && 9597 (!getLangOpts().CPlusPlus20 || 9598 ConstexprKind == ConstexprSpecKind::Consteval)) { 9599 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9600 << static_cast<int>(ConstexprKind); 9601 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9602 ? ConstexprSpecKind::Unspecified 9603 : ConstexprSpecKind::Constexpr); 9604 } 9605 // C++20 [dcl.constexpr]p2: An allocation function, or a 9606 // deallocation function shall not be declared with the consteval 9607 // specifier. 9608 if (ConstexprKind == ConstexprSpecKind::Consteval && 9609 (NewFD->getOverloadedOperator() == OO_New || 9610 NewFD->getOverloadedOperator() == OO_Array_New || 9611 NewFD->getOverloadedOperator() == OO_Delete || 9612 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9613 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9614 diag::err_invalid_consteval_decl_kind) 9615 << NewFD; 9616 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9617 } 9618 } 9619 9620 // If __module_private__ was specified, mark the function accordingly. 9621 if (D.getDeclSpec().isModulePrivateSpecified()) { 9622 if (isFunctionTemplateSpecialization) { 9623 SourceLocation ModulePrivateLoc 9624 = D.getDeclSpec().getModulePrivateSpecLoc(); 9625 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9626 << 0 9627 << FixItHint::CreateRemoval(ModulePrivateLoc); 9628 } else { 9629 NewFD->setModulePrivate(); 9630 if (FunctionTemplate) 9631 FunctionTemplate->setModulePrivate(); 9632 } 9633 } 9634 9635 if (isFriend) { 9636 if (FunctionTemplate) { 9637 FunctionTemplate->setObjectOfFriendDecl(); 9638 FunctionTemplate->setAccess(AS_public); 9639 } 9640 NewFD->setObjectOfFriendDecl(); 9641 NewFD->setAccess(AS_public); 9642 } 9643 9644 // If a function is defined as defaulted or deleted, mark it as such now. 9645 // We'll do the relevant checks on defaulted / deleted functions later. 9646 switch (D.getFunctionDefinitionKind()) { 9647 case FunctionDefinitionKind::Declaration: 9648 case FunctionDefinitionKind::Definition: 9649 break; 9650 9651 case FunctionDefinitionKind::Defaulted: 9652 NewFD->setDefaulted(); 9653 break; 9654 9655 case FunctionDefinitionKind::Deleted: 9656 NewFD->setDeletedAsWritten(); 9657 break; 9658 } 9659 9660 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9661 D.isFunctionDefinition()) { 9662 // C++ [class.mfct]p2: 9663 // A member function may be defined (8.4) in its class definition, in 9664 // which case it is an inline member function (7.1.2) 9665 NewFD->setImplicitlyInline(); 9666 } 9667 9668 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9669 !CurContext->isRecord()) { 9670 // C++ [class.static]p1: 9671 // A data or function member of a class may be declared static 9672 // in a class definition, in which case it is a static member of 9673 // the class. 9674 9675 // Complain about the 'static' specifier if it's on an out-of-line 9676 // member function definition. 9677 9678 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9679 // member function template declaration and class member template 9680 // declaration (MSVC versions before 2015), warn about this. 9681 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9682 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9683 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9684 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9685 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9686 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9687 } 9688 9689 // C++11 [except.spec]p15: 9690 // A deallocation function with no exception-specification is treated 9691 // as if it were specified with noexcept(true). 9692 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9693 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9694 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9695 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9696 NewFD->setType(Context.getFunctionType( 9697 FPT->getReturnType(), FPT->getParamTypes(), 9698 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9699 } 9700 9701 // Filter out previous declarations that don't match the scope. 9702 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9703 D.getCXXScopeSpec().isNotEmpty() || 9704 isMemberSpecialization || 9705 isFunctionTemplateSpecialization); 9706 9707 // Handle GNU asm-label extension (encoded as an attribute). 9708 if (Expr *E = (Expr*) D.getAsmLabel()) { 9709 // The parser guarantees this is a string. 9710 StringLiteral *SE = cast<StringLiteral>(E); 9711 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9712 /*IsLiteralLabel=*/true, 9713 SE->getStrTokenLoc(0))); 9714 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9715 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9716 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9717 if (I != ExtnameUndeclaredIdentifiers.end()) { 9718 if (isDeclExternC(NewFD)) { 9719 NewFD->addAttr(I->second); 9720 ExtnameUndeclaredIdentifiers.erase(I); 9721 } else 9722 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9723 << /*Variable*/0 << NewFD; 9724 } 9725 } 9726 9727 // Copy the parameter declarations from the declarator D to the function 9728 // declaration NewFD, if they are available. First scavenge them into Params. 9729 SmallVector<ParmVarDecl*, 16> Params; 9730 unsigned FTIIdx; 9731 if (D.isFunctionDeclarator(FTIIdx)) { 9732 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9733 9734 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9735 // function that takes no arguments, not a function that takes a 9736 // single void argument. 9737 // We let through "const void" here because Sema::GetTypeForDeclarator 9738 // already checks for that case. 9739 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9740 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9741 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9742 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9743 Param->setDeclContext(NewFD); 9744 Params.push_back(Param); 9745 9746 if (Param->isInvalidDecl()) 9747 NewFD->setInvalidDecl(); 9748 } 9749 } 9750 9751 if (!getLangOpts().CPlusPlus) { 9752 // In C, find all the tag declarations from the prototype and move them 9753 // into the function DeclContext. Remove them from the surrounding tag 9754 // injection context of the function, which is typically but not always 9755 // the TU. 9756 DeclContext *PrototypeTagContext = 9757 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9758 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9759 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9760 9761 // We don't want to reparent enumerators. Look at their parent enum 9762 // instead. 9763 if (!TD) { 9764 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9765 TD = cast<EnumDecl>(ECD->getDeclContext()); 9766 } 9767 if (!TD) 9768 continue; 9769 DeclContext *TagDC = TD->getLexicalDeclContext(); 9770 if (!TagDC->containsDecl(TD)) 9771 continue; 9772 TagDC->removeDecl(TD); 9773 TD->setDeclContext(NewFD); 9774 NewFD->addDecl(TD); 9775 9776 // Preserve the lexical DeclContext if it is not the surrounding tag 9777 // injection context of the FD. In this example, the semantic context of 9778 // E will be f and the lexical context will be S, while both the 9779 // semantic and lexical contexts of S will be f: 9780 // void f(struct S { enum E { a } f; } s); 9781 if (TagDC != PrototypeTagContext) 9782 TD->setLexicalDeclContext(TagDC); 9783 } 9784 } 9785 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9786 // When we're declaring a function with a typedef, typeof, etc as in the 9787 // following example, we'll need to synthesize (unnamed) 9788 // parameters for use in the declaration. 9789 // 9790 // @code 9791 // typedef void fn(int); 9792 // fn f; 9793 // @endcode 9794 9795 // Synthesize a parameter for each argument type. 9796 for (const auto &AI : FT->param_types()) { 9797 ParmVarDecl *Param = 9798 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9799 Param->setScopeInfo(0, Params.size()); 9800 Params.push_back(Param); 9801 } 9802 } else { 9803 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9804 "Should not need args for typedef of non-prototype fn"); 9805 } 9806 9807 // Finally, we know we have the right number of parameters, install them. 9808 NewFD->setParams(Params); 9809 9810 if (D.getDeclSpec().isNoreturnSpecified()) 9811 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9812 D.getDeclSpec().getNoreturnSpecLoc(), 9813 AttributeCommonInfo::AS_Keyword)); 9814 9815 // Functions returning a variably modified type violate C99 6.7.5.2p2 9816 // because all functions have linkage. 9817 if (!NewFD->isInvalidDecl() && 9818 NewFD->getReturnType()->isVariablyModifiedType()) { 9819 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9820 NewFD->setInvalidDecl(); 9821 } 9822 9823 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9824 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9825 !NewFD->hasAttr<SectionAttr>()) 9826 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9827 Context, PragmaClangTextSection.SectionName, 9828 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9829 9830 // Apply an implicit SectionAttr if #pragma code_seg is active. 9831 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9832 !NewFD->hasAttr<SectionAttr>()) { 9833 NewFD->addAttr(SectionAttr::CreateImplicit( 9834 Context, CodeSegStack.CurrentValue->getString(), 9835 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9836 SectionAttr::Declspec_allocate)); 9837 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9838 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9839 ASTContext::PSF_Read, 9840 NewFD)) 9841 NewFD->dropAttr<SectionAttr>(); 9842 } 9843 9844 // Apply an implicit CodeSegAttr from class declspec or 9845 // apply an implicit SectionAttr from #pragma code_seg if active. 9846 if (!NewFD->hasAttr<CodeSegAttr>()) { 9847 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9848 D.isFunctionDefinition())) { 9849 NewFD->addAttr(SAttr); 9850 } 9851 } 9852 9853 // Handle attributes. 9854 ProcessDeclAttributes(S, NewFD, D); 9855 9856 if (getLangOpts().OpenCL) { 9857 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9858 // type declaration will generate a compilation error. 9859 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9860 if (AddressSpace != LangAS::Default) { 9861 Diag(NewFD->getLocation(), 9862 diag::err_opencl_return_value_with_address_space); 9863 NewFD->setInvalidDecl(); 9864 } 9865 } 9866 9867 if (!getLangOpts().CPlusPlus) { 9868 // Perform semantic checking on the function declaration. 9869 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9870 CheckMain(NewFD, D.getDeclSpec()); 9871 9872 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9873 CheckMSVCRTEntryPoint(NewFD); 9874 9875 if (!NewFD->isInvalidDecl()) 9876 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9877 isMemberSpecialization, 9878 D.isFunctionDefinition())); 9879 else if (!Previous.empty()) 9880 // Recover gracefully from an invalid redeclaration. 9881 D.setRedeclaration(true); 9882 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9883 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9884 "previous declaration set still overloaded"); 9885 9886 // Diagnose no-prototype function declarations with calling conventions that 9887 // don't support variadic calls. Only do this in C and do it after merging 9888 // possibly prototyped redeclarations. 9889 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9890 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9891 CallingConv CC = FT->getExtInfo().getCC(); 9892 if (!supportsVariadicCall(CC)) { 9893 // Windows system headers sometimes accidentally use stdcall without 9894 // (void) parameters, so we relax this to a warning. 9895 int DiagID = 9896 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9897 Diag(NewFD->getLocation(), DiagID) 9898 << FunctionType::getNameForCallConv(CC); 9899 } 9900 } 9901 9902 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9903 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9904 checkNonTrivialCUnion(NewFD->getReturnType(), 9905 NewFD->getReturnTypeSourceRange().getBegin(), 9906 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9907 } else { 9908 // C++11 [replacement.functions]p3: 9909 // The program's definitions shall not be specified as inline. 9910 // 9911 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9912 // 9913 // Suppress the diagnostic if the function is __attribute__((used)), since 9914 // that forces an external definition to be emitted. 9915 if (D.getDeclSpec().isInlineSpecified() && 9916 NewFD->isReplaceableGlobalAllocationFunction() && 9917 !NewFD->hasAttr<UsedAttr>()) 9918 Diag(D.getDeclSpec().getInlineSpecLoc(), 9919 diag::ext_operator_new_delete_declared_inline) 9920 << NewFD->getDeclName(); 9921 9922 // If the declarator is a template-id, translate the parser's template 9923 // argument list into our AST format. 9924 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9925 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9926 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9927 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9928 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9929 TemplateId->NumArgs); 9930 translateTemplateArguments(TemplateArgsPtr, 9931 TemplateArgs); 9932 9933 HasExplicitTemplateArgs = true; 9934 9935 if (NewFD->isInvalidDecl()) { 9936 HasExplicitTemplateArgs = false; 9937 } else if (FunctionTemplate) { 9938 // Function template with explicit template arguments. 9939 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9940 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9941 9942 HasExplicitTemplateArgs = false; 9943 } else { 9944 assert((isFunctionTemplateSpecialization || 9945 D.getDeclSpec().isFriendSpecified()) && 9946 "should have a 'template<>' for this decl"); 9947 // "friend void foo<>(int);" is an implicit specialization decl. 9948 isFunctionTemplateSpecialization = true; 9949 } 9950 } else if (isFriend && isFunctionTemplateSpecialization) { 9951 // This combination is only possible in a recovery case; the user 9952 // wrote something like: 9953 // template <> friend void foo(int); 9954 // which we're recovering from as if the user had written: 9955 // friend void foo<>(int); 9956 // Go ahead and fake up a template id. 9957 HasExplicitTemplateArgs = true; 9958 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9959 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9960 } 9961 9962 // We do not add HD attributes to specializations here because 9963 // they may have different constexpr-ness compared to their 9964 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9965 // may end up with different effective targets. Instead, a 9966 // specialization inherits its target attributes from its template 9967 // in the CheckFunctionTemplateSpecialization() call below. 9968 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9969 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9970 9971 // If it's a friend (and only if it's a friend), it's possible 9972 // that either the specialized function type or the specialized 9973 // template is dependent, and therefore matching will fail. In 9974 // this case, don't check the specialization yet. 9975 if (isFunctionTemplateSpecialization && isFriend && 9976 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9977 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9978 TemplateArgs.arguments()))) { 9979 assert(HasExplicitTemplateArgs && 9980 "friend function specialization without template args"); 9981 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9982 Previous)) 9983 NewFD->setInvalidDecl(); 9984 } else if (isFunctionTemplateSpecialization) { 9985 if (CurContext->isDependentContext() && CurContext->isRecord() 9986 && !isFriend) { 9987 isDependentClassScopeExplicitSpecialization = true; 9988 } else if (!NewFD->isInvalidDecl() && 9989 CheckFunctionTemplateSpecialization( 9990 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9991 Previous)) 9992 NewFD->setInvalidDecl(); 9993 9994 // C++ [dcl.stc]p1: 9995 // A storage-class-specifier shall not be specified in an explicit 9996 // specialization (14.7.3) 9997 FunctionTemplateSpecializationInfo *Info = 9998 NewFD->getTemplateSpecializationInfo(); 9999 if (Info && SC != SC_None) { 10000 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 10001 Diag(NewFD->getLocation(), 10002 diag::err_explicit_specialization_inconsistent_storage_class) 10003 << SC 10004 << FixItHint::CreateRemoval( 10005 D.getDeclSpec().getStorageClassSpecLoc()); 10006 10007 else 10008 Diag(NewFD->getLocation(), 10009 diag::ext_explicit_specialization_storage_class) 10010 << FixItHint::CreateRemoval( 10011 D.getDeclSpec().getStorageClassSpecLoc()); 10012 } 10013 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 10014 if (CheckMemberSpecialization(NewFD, Previous)) 10015 NewFD->setInvalidDecl(); 10016 } 10017 10018 // Perform semantic checking on the function declaration. 10019 if (!isDependentClassScopeExplicitSpecialization) { 10020 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10021 CheckMain(NewFD, D.getDeclSpec()); 10022 10023 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10024 CheckMSVCRTEntryPoint(NewFD); 10025 10026 if (!NewFD->isInvalidDecl()) 10027 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10028 isMemberSpecialization, 10029 D.isFunctionDefinition())); 10030 else if (!Previous.empty()) 10031 // Recover gracefully from an invalid redeclaration. 10032 D.setRedeclaration(true); 10033 } 10034 10035 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 10036 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10037 "previous declaration set still overloaded"); 10038 10039 NamedDecl *PrincipalDecl = (FunctionTemplate 10040 ? cast<NamedDecl>(FunctionTemplate) 10041 : NewFD); 10042 10043 if (isFriend && NewFD->getPreviousDecl()) { 10044 AccessSpecifier Access = AS_public; 10045 if (!NewFD->isInvalidDecl()) 10046 Access = NewFD->getPreviousDecl()->getAccess(); 10047 10048 NewFD->setAccess(Access); 10049 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 10050 } 10051 10052 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 10053 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 10054 PrincipalDecl->setNonMemberOperator(); 10055 10056 // If we have a function template, check the template parameter 10057 // list. This will check and merge default template arguments. 10058 if (FunctionTemplate) { 10059 FunctionTemplateDecl *PrevTemplate = 10060 FunctionTemplate->getPreviousDecl(); 10061 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 10062 PrevTemplate ? PrevTemplate->getTemplateParameters() 10063 : nullptr, 10064 D.getDeclSpec().isFriendSpecified() 10065 ? (D.isFunctionDefinition() 10066 ? TPC_FriendFunctionTemplateDefinition 10067 : TPC_FriendFunctionTemplate) 10068 : (D.getCXXScopeSpec().isSet() && 10069 DC && DC->isRecord() && 10070 DC->isDependentContext()) 10071 ? TPC_ClassTemplateMember 10072 : TPC_FunctionTemplate); 10073 } 10074 10075 if (NewFD->isInvalidDecl()) { 10076 // Ignore all the rest of this. 10077 } else if (!D.isRedeclaration()) { 10078 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 10079 AddToScope }; 10080 // Fake up an access specifier if it's supposed to be a class member. 10081 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 10082 NewFD->setAccess(AS_public); 10083 10084 // Qualified decls generally require a previous declaration. 10085 if (D.getCXXScopeSpec().isSet()) { 10086 // ...with the major exception of templated-scope or 10087 // dependent-scope friend declarations. 10088 10089 // TODO: we currently also suppress this check in dependent 10090 // contexts because (1) the parameter depth will be off when 10091 // matching friend templates and (2) we might actually be 10092 // selecting a friend based on a dependent factor. But there 10093 // are situations where these conditions don't apply and we 10094 // can actually do this check immediately. 10095 // 10096 // Unless the scope is dependent, it's always an error if qualified 10097 // redeclaration lookup found nothing at all. Diagnose that now; 10098 // nothing will diagnose that error later. 10099 if (isFriend && 10100 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 10101 (!Previous.empty() && CurContext->isDependentContext()))) { 10102 // ignore these 10103 } else if (NewFD->isCPUDispatchMultiVersion() || 10104 NewFD->isCPUSpecificMultiVersion()) { 10105 // ignore this, we allow the redeclaration behavior here to create new 10106 // versions of the function. 10107 } else { 10108 // The user tried to provide an out-of-line definition for a 10109 // function that is a member of a class or namespace, but there 10110 // was no such member function declared (C++ [class.mfct]p2, 10111 // C++ [namespace.memdef]p2). For example: 10112 // 10113 // class X { 10114 // void f() const; 10115 // }; 10116 // 10117 // void X::f() { } // ill-formed 10118 // 10119 // Complain about this problem, and attempt to suggest close 10120 // matches (e.g., those that differ only in cv-qualifiers and 10121 // whether the parameter types are references). 10122 10123 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10124 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 10125 AddToScope = ExtraArgs.AddToScope; 10126 return Result; 10127 } 10128 } 10129 10130 // Unqualified local friend declarations are required to resolve 10131 // to something. 10132 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 10133 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10134 *this, Previous, NewFD, ExtraArgs, true, S)) { 10135 AddToScope = ExtraArgs.AddToScope; 10136 return Result; 10137 } 10138 } 10139 } else if (!D.isFunctionDefinition() && 10140 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 10141 !isFriend && !isFunctionTemplateSpecialization && 10142 !isMemberSpecialization) { 10143 // An out-of-line member function declaration must also be a 10144 // definition (C++ [class.mfct]p2). 10145 // Note that this is not the case for explicit specializations of 10146 // function templates or member functions of class templates, per 10147 // C++ [temp.expl.spec]p2. We also allow these declarations as an 10148 // extension for compatibility with old SWIG code which likes to 10149 // generate them. 10150 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 10151 << D.getCXXScopeSpec().getRange(); 10152 } 10153 } 10154 10155 // If this is the first declaration of a library builtin function, add 10156 // attributes as appropriate. 10157 if (!D.isRedeclaration()) { 10158 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 10159 if (unsigned BuiltinID = II->getBuiltinID()) { 10160 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID); 10161 if (!InStdNamespace && 10162 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 10163 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 10164 // Validate the type matches unless this builtin is specified as 10165 // matching regardless of its declared type. 10166 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 10167 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10168 } else { 10169 ASTContext::GetBuiltinTypeError Error; 10170 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10171 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 10172 10173 if (!Error && !BuiltinType.isNull() && 10174 Context.hasSameFunctionTypeIgnoringExceptionSpec( 10175 NewFD->getType(), BuiltinType)) 10176 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10177 } 10178 } 10179 } else if (InStdNamespace && NewFD->isInStdNamespace() && 10180 isStdBuiltin(Context, NewFD, BuiltinID)) { 10181 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10182 } 10183 } 10184 } 10185 } 10186 10187 ProcessPragmaWeak(S, NewFD); 10188 checkAttributesAfterMerging(*this, *NewFD); 10189 10190 AddKnownFunctionAttributes(NewFD); 10191 10192 if (NewFD->hasAttr<OverloadableAttr>() && 10193 !NewFD->getType()->getAs<FunctionProtoType>()) { 10194 Diag(NewFD->getLocation(), 10195 diag::err_attribute_overloadable_no_prototype) 10196 << NewFD; 10197 10198 // Turn this into a variadic function with no parameters. 10199 const auto *FT = NewFD->getType()->castAs<FunctionType>(); 10200 FunctionProtoType::ExtProtoInfo EPI( 10201 Context.getDefaultCallingConvention(true, false)); 10202 EPI.Variadic = true; 10203 EPI.ExtInfo = FT->getExtInfo(); 10204 10205 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 10206 NewFD->setType(R); 10207 } 10208 10209 // If there's a #pragma GCC visibility in scope, and this isn't a class 10210 // member, set the visibility of this function. 10211 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10212 AddPushedVisibilityAttribute(NewFD); 10213 10214 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10215 // marking the function. 10216 AddCFAuditedAttribute(NewFD); 10217 10218 // If this is a function definition, check if we have to apply optnone due to 10219 // a pragma. 10220 if(D.isFunctionDefinition()) 10221 AddRangeBasedOptnone(NewFD); 10222 10223 // If this is the first declaration of an extern C variable, update 10224 // the map of such variables. 10225 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10226 isIncompleteDeclExternC(*this, NewFD)) 10227 RegisterLocallyScopedExternCDecl(NewFD, S); 10228 10229 // Set this FunctionDecl's range up to the right paren. 10230 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10231 10232 if (D.isRedeclaration() && !Previous.empty()) { 10233 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10234 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10235 isMemberSpecialization || 10236 isFunctionTemplateSpecialization, 10237 D.isFunctionDefinition()); 10238 } 10239 10240 if (getLangOpts().CUDA) { 10241 IdentifierInfo *II = NewFD->getIdentifier(); 10242 if (II && II->isStr(getCudaConfigureFuncName()) && 10243 !NewFD->isInvalidDecl() && 10244 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10245 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10246 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10247 << getCudaConfigureFuncName(); 10248 Context.setcudaConfigureCallDecl(NewFD); 10249 } 10250 10251 // Variadic functions, other than a *declaration* of printf, are not allowed 10252 // in device-side CUDA code, unless someone passed 10253 // -fcuda-allow-variadic-functions. 10254 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10255 (NewFD->hasAttr<CUDADeviceAttr>() || 10256 NewFD->hasAttr<CUDAGlobalAttr>()) && 10257 !(II && II->isStr("printf") && NewFD->isExternC() && 10258 !D.isFunctionDefinition())) { 10259 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10260 } 10261 } 10262 10263 MarkUnusedFileScopedDecl(NewFD); 10264 10265 10266 10267 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10268 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10269 if (SC == SC_Static) { 10270 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10271 D.setInvalidType(); 10272 } 10273 10274 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10275 if (!NewFD->getReturnType()->isVoidType()) { 10276 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10277 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10278 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10279 : FixItHint()); 10280 D.setInvalidType(); 10281 } 10282 10283 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10284 for (auto Param : NewFD->parameters()) 10285 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10286 10287 if (getLangOpts().OpenCLCPlusPlus) { 10288 if (DC->isRecord()) { 10289 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10290 D.setInvalidType(); 10291 } 10292 if (FunctionTemplate) { 10293 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10294 D.setInvalidType(); 10295 } 10296 } 10297 } 10298 10299 if (getLangOpts().CPlusPlus) { 10300 if (FunctionTemplate) { 10301 if (NewFD->isInvalidDecl()) 10302 FunctionTemplate->setInvalidDecl(); 10303 return FunctionTemplate; 10304 } 10305 10306 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10307 CompleteMemberSpecialization(NewFD, Previous); 10308 } 10309 10310 for (const ParmVarDecl *Param : NewFD->parameters()) { 10311 QualType PT = Param->getType(); 10312 10313 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10314 // types. 10315 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10316 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10317 QualType ElemTy = PipeTy->getElementType(); 10318 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10319 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10320 D.setInvalidType(); 10321 } 10322 } 10323 } 10324 } 10325 10326 // Here we have an function template explicit specialization at class scope. 10327 // The actual specialization will be postponed to template instatiation 10328 // time via the ClassScopeFunctionSpecializationDecl node. 10329 if (isDependentClassScopeExplicitSpecialization) { 10330 ClassScopeFunctionSpecializationDecl *NewSpec = 10331 ClassScopeFunctionSpecializationDecl::Create( 10332 Context, CurContext, NewFD->getLocation(), 10333 cast<CXXMethodDecl>(NewFD), 10334 HasExplicitTemplateArgs, TemplateArgs); 10335 CurContext->addDecl(NewSpec); 10336 AddToScope = false; 10337 } 10338 10339 // Diagnose availability attributes. Availability cannot be used on functions 10340 // that are run during load/unload. 10341 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10342 if (NewFD->hasAttr<ConstructorAttr>()) { 10343 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10344 << 1; 10345 NewFD->dropAttr<AvailabilityAttr>(); 10346 } 10347 if (NewFD->hasAttr<DestructorAttr>()) { 10348 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10349 << 2; 10350 NewFD->dropAttr<AvailabilityAttr>(); 10351 } 10352 } 10353 10354 // Diagnose no_builtin attribute on function declaration that are not a 10355 // definition. 10356 // FIXME: We should really be doing this in 10357 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10358 // the FunctionDecl and at this point of the code 10359 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10360 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10361 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10362 switch (D.getFunctionDefinitionKind()) { 10363 case FunctionDefinitionKind::Defaulted: 10364 case FunctionDefinitionKind::Deleted: 10365 Diag(NBA->getLocation(), 10366 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10367 << NBA->getSpelling(); 10368 break; 10369 case FunctionDefinitionKind::Declaration: 10370 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10371 << NBA->getSpelling(); 10372 break; 10373 case FunctionDefinitionKind::Definition: 10374 break; 10375 } 10376 10377 return NewFD; 10378 } 10379 10380 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10381 /// when __declspec(code_seg) "is applied to a class, all member functions of 10382 /// the class and nested classes -- this includes compiler-generated special 10383 /// member functions -- are put in the specified segment." 10384 /// The actual behavior is a little more complicated. The Microsoft compiler 10385 /// won't check outer classes if there is an active value from #pragma code_seg. 10386 /// The CodeSeg is always applied from the direct parent but only from outer 10387 /// classes when the #pragma code_seg stack is empty. See: 10388 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10389 /// available since MS has removed the page. 10390 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10391 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10392 if (!Method) 10393 return nullptr; 10394 const CXXRecordDecl *Parent = Method->getParent(); 10395 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10396 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10397 NewAttr->setImplicit(true); 10398 return NewAttr; 10399 } 10400 10401 // The Microsoft compiler won't check outer classes for the CodeSeg 10402 // when the #pragma code_seg stack is active. 10403 if (S.CodeSegStack.CurrentValue) 10404 return nullptr; 10405 10406 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10407 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10408 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10409 NewAttr->setImplicit(true); 10410 return NewAttr; 10411 } 10412 } 10413 return nullptr; 10414 } 10415 10416 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10417 /// containing class. Otherwise it will return implicit SectionAttr if the 10418 /// function is a definition and there is an active value on CodeSegStack 10419 /// (from the current #pragma code-seg value). 10420 /// 10421 /// \param FD Function being declared. 10422 /// \param IsDefinition Whether it is a definition or just a declarartion. 10423 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10424 /// nullptr if no attribute should be added. 10425 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10426 bool IsDefinition) { 10427 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10428 return A; 10429 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10430 CodeSegStack.CurrentValue) 10431 return SectionAttr::CreateImplicit( 10432 getASTContext(), CodeSegStack.CurrentValue->getString(), 10433 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10434 SectionAttr::Declspec_allocate); 10435 return nullptr; 10436 } 10437 10438 /// Determines if we can perform a correct type check for \p D as a 10439 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10440 /// best-effort check. 10441 /// 10442 /// \param NewD The new declaration. 10443 /// \param OldD The old declaration. 10444 /// \param NewT The portion of the type of the new declaration to check. 10445 /// \param OldT The portion of the type of the old declaration to check. 10446 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10447 QualType NewT, QualType OldT) { 10448 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10449 return true; 10450 10451 // For dependently-typed local extern declarations and friends, we can't 10452 // perform a correct type check in general until instantiation: 10453 // 10454 // int f(); 10455 // template<typename T> void g() { T f(); } 10456 // 10457 // (valid if g() is only instantiated with T = int). 10458 if (NewT->isDependentType() && 10459 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10460 return false; 10461 10462 // Similarly, if the previous declaration was a dependent local extern 10463 // declaration, we don't really know its type yet. 10464 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10465 return false; 10466 10467 return true; 10468 } 10469 10470 /// Checks if the new declaration declared in dependent context must be 10471 /// put in the same redeclaration chain as the specified declaration. 10472 /// 10473 /// \param D Declaration that is checked. 10474 /// \param PrevDecl Previous declaration found with proper lookup method for the 10475 /// same declaration name. 10476 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10477 /// belongs to. 10478 /// 10479 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10480 if (!D->getLexicalDeclContext()->isDependentContext()) 10481 return true; 10482 10483 // Don't chain dependent friend function definitions until instantiation, to 10484 // permit cases like 10485 // 10486 // void func(); 10487 // template<typename T> class C1 { friend void func() {} }; 10488 // template<typename T> class C2 { friend void func() {} }; 10489 // 10490 // ... which is valid if only one of C1 and C2 is ever instantiated. 10491 // 10492 // FIXME: This need only apply to function definitions. For now, we proxy 10493 // this by checking for a file-scope function. We do not want this to apply 10494 // to friend declarations nominating member functions, because that gets in 10495 // the way of access checks. 10496 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10497 return false; 10498 10499 auto *VD = dyn_cast<ValueDecl>(D); 10500 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10501 return !VD || !PrevVD || 10502 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10503 PrevVD->getType()); 10504 } 10505 10506 /// Check the target attribute of the function for MultiVersion 10507 /// validity. 10508 /// 10509 /// Returns true if there was an error, false otherwise. 10510 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10511 const auto *TA = FD->getAttr<TargetAttr>(); 10512 assert(TA && "MultiVersion Candidate requires a target attribute"); 10513 ParsedTargetAttr ParseInfo = TA->parse(); 10514 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10515 enum ErrType { Feature = 0, Architecture = 1 }; 10516 10517 if (!ParseInfo.Architecture.empty() && 10518 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10519 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10520 << Architecture << ParseInfo.Architecture; 10521 return true; 10522 } 10523 10524 for (const auto &Feat : ParseInfo.Features) { 10525 auto BareFeat = StringRef{Feat}.substr(1); 10526 if (Feat[0] == '-') { 10527 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10528 << Feature << ("no-" + BareFeat).str(); 10529 return true; 10530 } 10531 10532 if (!TargetInfo.validateCpuSupports(BareFeat) || 10533 !TargetInfo.isValidFeatureName(BareFeat)) { 10534 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10535 << Feature << BareFeat; 10536 return true; 10537 } 10538 } 10539 return false; 10540 } 10541 10542 // Provide a white-list of attributes that are allowed to be combined with 10543 // multiversion functions. 10544 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10545 MultiVersionKind MVKind) { 10546 // Note: this list/diagnosis must match the list in 10547 // checkMultiversionAttributesAllSame. 10548 switch (Kind) { 10549 default: 10550 return false; 10551 case attr::Used: 10552 return MVKind == MultiVersionKind::Target; 10553 case attr::NonNull: 10554 case attr::NoThrow: 10555 return true; 10556 } 10557 } 10558 10559 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10560 const FunctionDecl *FD, 10561 const FunctionDecl *CausedFD, 10562 MultiVersionKind MVKind) { 10563 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 10564 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10565 << static_cast<unsigned>(MVKind) << A; 10566 if (CausedFD) 10567 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10568 return true; 10569 }; 10570 10571 for (const Attr *A : FD->attrs()) { 10572 switch (A->getKind()) { 10573 case attr::CPUDispatch: 10574 case attr::CPUSpecific: 10575 if (MVKind != MultiVersionKind::CPUDispatch && 10576 MVKind != MultiVersionKind::CPUSpecific) 10577 return Diagnose(S, A); 10578 break; 10579 case attr::Target: 10580 if (MVKind != MultiVersionKind::Target) 10581 return Diagnose(S, A); 10582 break; 10583 case attr::TargetClones: 10584 if (MVKind != MultiVersionKind::TargetClones) 10585 return Diagnose(S, A); 10586 break; 10587 default: 10588 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 10589 return Diagnose(S, A); 10590 break; 10591 } 10592 } 10593 return false; 10594 } 10595 10596 bool Sema::areMultiversionVariantFunctionsCompatible( 10597 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10598 const PartialDiagnostic &NoProtoDiagID, 10599 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10600 const PartialDiagnosticAt &NoSupportDiagIDAt, 10601 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10602 bool ConstexprSupported, bool CLinkageMayDiffer) { 10603 enum DoesntSupport { 10604 FuncTemplates = 0, 10605 VirtFuncs = 1, 10606 DeducedReturn = 2, 10607 Constructors = 3, 10608 Destructors = 4, 10609 DeletedFuncs = 5, 10610 DefaultedFuncs = 6, 10611 ConstexprFuncs = 7, 10612 ConstevalFuncs = 8, 10613 Lambda = 9, 10614 }; 10615 enum Different { 10616 CallingConv = 0, 10617 ReturnType = 1, 10618 ConstexprSpec = 2, 10619 InlineSpec = 3, 10620 Linkage = 4, 10621 LanguageLinkage = 5, 10622 }; 10623 10624 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10625 !OldFD->getType()->getAs<FunctionProtoType>()) { 10626 Diag(OldFD->getLocation(), NoProtoDiagID); 10627 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10628 return true; 10629 } 10630 10631 if (NoProtoDiagID.getDiagID() != 0 && 10632 !NewFD->getType()->getAs<FunctionProtoType>()) 10633 return Diag(NewFD->getLocation(), NoProtoDiagID); 10634 10635 if (!TemplatesSupported && 10636 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10637 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10638 << FuncTemplates; 10639 10640 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10641 if (NewCXXFD->isVirtual()) 10642 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10643 << VirtFuncs; 10644 10645 if (isa<CXXConstructorDecl>(NewCXXFD)) 10646 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10647 << Constructors; 10648 10649 if (isa<CXXDestructorDecl>(NewCXXFD)) 10650 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10651 << Destructors; 10652 } 10653 10654 if (NewFD->isDeleted()) 10655 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10656 << DeletedFuncs; 10657 10658 if (NewFD->isDefaulted()) 10659 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10660 << DefaultedFuncs; 10661 10662 if (!ConstexprSupported && NewFD->isConstexpr()) 10663 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10664 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10665 10666 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10667 const auto *NewType = cast<FunctionType>(NewQType); 10668 QualType NewReturnType = NewType->getReturnType(); 10669 10670 if (NewReturnType->isUndeducedType()) 10671 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10672 << DeducedReturn; 10673 10674 // Ensure the return type is identical. 10675 if (OldFD) { 10676 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10677 const auto *OldType = cast<FunctionType>(OldQType); 10678 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10679 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10680 10681 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10682 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10683 10684 QualType OldReturnType = OldType->getReturnType(); 10685 10686 if (OldReturnType != NewReturnType) 10687 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10688 10689 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10690 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10691 10692 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10693 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10694 10695 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10696 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10697 10698 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10699 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10700 10701 if (CheckEquivalentExceptionSpec( 10702 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10703 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10704 return true; 10705 } 10706 return false; 10707 } 10708 10709 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10710 const FunctionDecl *NewFD, 10711 bool CausesMV, 10712 MultiVersionKind MVKind) { 10713 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10714 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10715 if (OldFD) 10716 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10717 return true; 10718 } 10719 10720 bool IsCPUSpecificCPUDispatchMVKind = 10721 MVKind == MultiVersionKind::CPUDispatch || 10722 MVKind == MultiVersionKind::CPUSpecific; 10723 10724 if (CausesMV && OldFD && 10725 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 10726 return true; 10727 10728 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 10729 return true; 10730 10731 // Only allow transition to MultiVersion if it hasn't been used. 10732 if (OldFD && CausesMV && OldFD->isUsed(false)) 10733 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10734 10735 return S.areMultiversionVariantFunctionsCompatible( 10736 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10737 PartialDiagnosticAt(NewFD->getLocation(), 10738 S.PDiag(diag::note_multiversioning_caused_here)), 10739 PartialDiagnosticAt(NewFD->getLocation(), 10740 S.PDiag(diag::err_multiversion_doesnt_support) 10741 << static_cast<unsigned>(MVKind)), 10742 PartialDiagnosticAt(NewFD->getLocation(), 10743 S.PDiag(diag::err_multiversion_diff)), 10744 /*TemplatesSupported=*/false, 10745 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 10746 /*CLinkageMayDiffer=*/false); 10747 } 10748 10749 /// Check the validity of a multiversion function declaration that is the 10750 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10751 /// 10752 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10753 /// 10754 /// Returns true if there was an error, false otherwise. 10755 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10756 MultiVersionKind MVKind, 10757 const TargetAttr *TA) { 10758 assert(MVKind != MultiVersionKind::None && 10759 "Function lacks multiversion attribute"); 10760 10761 // Target only causes MV if it is default, otherwise this is a normal 10762 // function. 10763 if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion()) 10764 return false; 10765 10766 if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10767 FD->setInvalidDecl(); 10768 return true; 10769 } 10770 10771 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 10772 FD->setInvalidDecl(); 10773 return true; 10774 } 10775 10776 FD->setIsMultiVersion(); 10777 return false; 10778 } 10779 10780 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10781 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10782 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10783 return true; 10784 } 10785 10786 return false; 10787 } 10788 10789 static bool CheckTargetCausesMultiVersioning( 10790 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10791 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { 10792 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10793 ParsedTargetAttr NewParsed = NewTA->parse(); 10794 // Sort order doesn't matter, it just needs to be consistent. 10795 llvm::sort(NewParsed.Features); 10796 10797 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10798 // to change, this is a simple redeclaration. 10799 if (!NewTA->isDefaultVersion() && 10800 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10801 return false; 10802 10803 // Otherwise, this decl causes MultiVersioning. 10804 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10805 MultiVersionKind::Target)) { 10806 NewFD->setInvalidDecl(); 10807 return true; 10808 } 10809 10810 if (CheckMultiVersionValue(S, NewFD)) { 10811 NewFD->setInvalidDecl(); 10812 return true; 10813 } 10814 10815 // If this is 'default', permit the forward declaration. 10816 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10817 Redeclaration = true; 10818 OldDecl = OldFD; 10819 OldFD->setIsMultiVersion(); 10820 NewFD->setIsMultiVersion(); 10821 return false; 10822 } 10823 10824 if (CheckMultiVersionValue(S, OldFD)) { 10825 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10826 NewFD->setInvalidDecl(); 10827 return true; 10828 } 10829 10830 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10831 10832 if (OldParsed == NewParsed) { 10833 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10834 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10835 NewFD->setInvalidDecl(); 10836 return true; 10837 } 10838 10839 for (const auto *FD : OldFD->redecls()) { 10840 const auto *CurTA = FD->getAttr<TargetAttr>(); 10841 // We allow forward declarations before ANY multiversioning attributes, but 10842 // nothing after the fact. 10843 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10844 (!CurTA || CurTA->isInherited())) { 10845 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10846 << 0; 10847 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10848 NewFD->setInvalidDecl(); 10849 return true; 10850 } 10851 } 10852 10853 OldFD->setIsMultiVersion(); 10854 NewFD->setIsMultiVersion(); 10855 Redeclaration = false; 10856 OldDecl = nullptr; 10857 Previous.clear(); 10858 return false; 10859 } 10860 10861 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 10862 MultiVersionKind New) { 10863 if (Old == New || Old == MultiVersionKind::None || 10864 New == MultiVersionKind::None) 10865 return true; 10866 10867 return (Old == MultiVersionKind::CPUDispatch && 10868 New == MultiVersionKind::CPUSpecific) || 10869 (Old == MultiVersionKind::CPUSpecific && 10870 New == MultiVersionKind::CPUDispatch); 10871 } 10872 10873 /// Check the validity of a new function declaration being added to an existing 10874 /// multiversioned declaration collection. 10875 static bool CheckMultiVersionAdditionalDecl( 10876 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10877 MultiVersionKind NewMVKind, const TargetAttr *NewTA, 10878 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10879 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 10880 LookupResult &Previous) { 10881 10882 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 10883 // Disallow mixing of multiversioning types. 10884 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { 10885 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10886 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10887 NewFD->setInvalidDecl(); 10888 return true; 10889 } 10890 10891 ParsedTargetAttr NewParsed; 10892 if (NewTA) { 10893 NewParsed = NewTA->parse(); 10894 llvm::sort(NewParsed.Features); 10895 } 10896 10897 bool UseMemberUsingDeclRules = 10898 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10899 10900 bool MayNeedOverloadableChecks = 10901 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 10902 10903 // Next, check ALL non-overloads to see if this is a redeclaration of a 10904 // previous member of the MultiVersion set. 10905 for (NamedDecl *ND : Previous) { 10906 FunctionDecl *CurFD = ND->getAsFunction(); 10907 if (!CurFD) 10908 continue; 10909 if (MayNeedOverloadableChecks && 10910 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10911 continue; 10912 10913 switch (NewMVKind) { 10914 case MultiVersionKind::None: 10915 assert(OldMVKind == MultiVersionKind::TargetClones && 10916 "Only target_clones can be omitted in subsequent declarations"); 10917 break; 10918 case MultiVersionKind::Target: { 10919 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10920 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10921 NewFD->setIsMultiVersion(); 10922 Redeclaration = true; 10923 OldDecl = ND; 10924 return false; 10925 } 10926 10927 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10928 if (CurParsed == NewParsed) { 10929 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10930 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10931 NewFD->setInvalidDecl(); 10932 return true; 10933 } 10934 break; 10935 } 10936 case MultiVersionKind::TargetClones: { 10937 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 10938 Redeclaration = true; 10939 OldDecl = CurFD; 10940 NewFD->setIsMultiVersion(); 10941 10942 if (CurClones && NewClones && 10943 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 10944 !std::equal(CurClones->featuresStrs_begin(), 10945 CurClones->featuresStrs_end(), 10946 NewClones->featuresStrs_begin()))) { 10947 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 10948 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10949 NewFD->setInvalidDecl(); 10950 return true; 10951 } 10952 10953 return false; 10954 } 10955 case MultiVersionKind::CPUSpecific: 10956 case MultiVersionKind::CPUDispatch: { 10957 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10958 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10959 // Handle CPUDispatch/CPUSpecific versions. 10960 // Only 1 CPUDispatch function is allowed, this will make it go through 10961 // the redeclaration errors. 10962 if (NewMVKind == MultiVersionKind::CPUDispatch && 10963 CurFD->hasAttr<CPUDispatchAttr>()) { 10964 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10965 std::equal( 10966 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10967 NewCPUDisp->cpus_begin(), 10968 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10969 return Cur->getName() == New->getName(); 10970 })) { 10971 NewFD->setIsMultiVersion(); 10972 Redeclaration = true; 10973 OldDecl = ND; 10974 return false; 10975 } 10976 10977 // If the declarations don't match, this is an error condition. 10978 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10979 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10980 NewFD->setInvalidDecl(); 10981 return true; 10982 } 10983 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10984 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10985 std::equal( 10986 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10987 NewCPUSpec->cpus_begin(), 10988 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10989 return Cur->getName() == New->getName(); 10990 })) { 10991 NewFD->setIsMultiVersion(); 10992 Redeclaration = true; 10993 OldDecl = ND; 10994 return false; 10995 } 10996 10997 // Only 1 version of CPUSpecific is allowed for each CPU. 10998 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10999 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 11000 if (CurII == NewII) { 11001 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 11002 << NewII; 11003 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11004 NewFD->setInvalidDecl(); 11005 return true; 11006 } 11007 } 11008 } 11009 } 11010 break; 11011 } 11012 } 11013 } 11014 11015 // Else, this is simply a non-redecl case. Checking the 'value' is only 11016 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 11017 // handled in the attribute adding step. 11018 if (NewMVKind == MultiVersionKind::Target && 11019 CheckMultiVersionValue(S, NewFD)) { 11020 NewFD->setInvalidDecl(); 11021 return true; 11022 } 11023 11024 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 11025 !OldFD->isMultiVersion(), NewMVKind)) { 11026 NewFD->setInvalidDecl(); 11027 return true; 11028 } 11029 11030 // Permit forward declarations in the case where these two are compatible. 11031 if (!OldFD->isMultiVersion()) { 11032 OldFD->setIsMultiVersion(); 11033 NewFD->setIsMultiVersion(); 11034 Redeclaration = true; 11035 OldDecl = OldFD; 11036 return false; 11037 } 11038 11039 NewFD->setIsMultiVersion(); 11040 Redeclaration = false; 11041 OldDecl = nullptr; 11042 Previous.clear(); 11043 return false; 11044 } 11045 11046 /// Check the validity of a mulitversion function declaration. 11047 /// Also sets the multiversion'ness' of the function itself. 11048 /// 11049 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11050 /// 11051 /// Returns true if there was an error, false otherwise. 11052 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 11053 bool &Redeclaration, NamedDecl *&OldDecl, 11054 LookupResult &Previous) { 11055 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11056 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 11057 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 11058 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 11059 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 11060 11061 // Main isn't allowed to become a multiversion function, however it IS 11062 // permitted to have 'main' be marked with the 'target' optimization hint. 11063 if (NewFD->isMain()) { 11064 if (MVKind != MultiVersionKind::None && 11065 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { 11066 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 11067 NewFD->setInvalidDecl(); 11068 return true; 11069 } 11070 return false; 11071 } 11072 11073 if (!OldDecl || !OldDecl->getAsFunction() || 11074 OldDecl->getDeclContext()->getRedeclContext() != 11075 NewFD->getDeclContext()->getRedeclContext()) { 11076 // If there's no previous declaration, AND this isn't attempting to cause 11077 // multiversioning, this isn't an error condition. 11078 if (MVKind == MultiVersionKind::None) 11079 return false; 11080 return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA); 11081 } 11082 11083 FunctionDecl *OldFD = OldDecl->getAsFunction(); 11084 11085 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) 11086 return false; 11087 11088 // Multiversioned redeclarations aren't allowed to omit the attribute, except 11089 // for target_clones. 11090 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 11091 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { 11092 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 11093 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 11094 NewFD->setInvalidDecl(); 11095 return true; 11096 } 11097 11098 if (!OldFD->isMultiVersion()) { 11099 switch (MVKind) { 11100 case MultiVersionKind::Target: 11101 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 11102 Redeclaration, OldDecl, Previous); 11103 case MultiVersionKind::TargetClones: 11104 if (OldFD->isUsed(false)) { 11105 NewFD->setInvalidDecl(); 11106 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11107 } 11108 OldFD->setIsMultiVersion(); 11109 break; 11110 case MultiVersionKind::CPUDispatch: 11111 case MultiVersionKind::CPUSpecific: 11112 case MultiVersionKind::None: 11113 break; 11114 } 11115 } 11116 11117 // At this point, we have a multiversion function decl (in OldFD) AND an 11118 // appropriate attribute in the current function decl. Resolve that these are 11119 // still compatible with previous declarations. 11120 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA, 11121 NewCPUDisp, NewCPUSpec, NewClones, 11122 Redeclaration, OldDecl, Previous); 11123 } 11124 11125 /// Perform semantic checking of a new function declaration. 11126 /// 11127 /// Performs semantic analysis of the new function declaration 11128 /// NewFD. This routine performs all semantic checking that does not 11129 /// require the actual declarator involved in the declaration, and is 11130 /// used both for the declaration of functions as they are parsed 11131 /// (called via ActOnDeclarator) and for the declaration of functions 11132 /// that have been instantiated via C++ template instantiation (called 11133 /// via InstantiateDecl). 11134 /// 11135 /// \param IsMemberSpecialization whether this new function declaration is 11136 /// a member specialization (that replaces any definition provided by the 11137 /// previous declaration). 11138 /// 11139 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11140 /// 11141 /// \returns true if the function declaration is a redeclaration. 11142 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 11143 LookupResult &Previous, 11144 bool IsMemberSpecialization, 11145 bool DeclIsDefn) { 11146 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 11147 "Variably modified return types are not handled here"); 11148 11149 // Determine whether the type of this function should be merged with 11150 // a previous visible declaration. This never happens for functions in C++, 11151 // and always happens in C if the previous declaration was visible. 11152 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 11153 !Previous.isShadowed(); 11154 11155 bool Redeclaration = false; 11156 NamedDecl *OldDecl = nullptr; 11157 bool MayNeedOverloadableChecks = false; 11158 11159 // Merge or overload the declaration with an existing declaration of 11160 // the same name, if appropriate. 11161 if (!Previous.empty()) { 11162 // Determine whether NewFD is an overload of PrevDecl or 11163 // a declaration that requires merging. If it's an overload, 11164 // there's no more work to do here; we'll just add the new 11165 // function to the scope. 11166 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 11167 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 11168 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 11169 Redeclaration = true; 11170 OldDecl = Candidate; 11171 } 11172 } else { 11173 MayNeedOverloadableChecks = true; 11174 switch (CheckOverload(S, NewFD, Previous, OldDecl, 11175 /*NewIsUsingDecl*/ false)) { 11176 case Ovl_Match: 11177 Redeclaration = true; 11178 break; 11179 11180 case Ovl_NonFunction: 11181 Redeclaration = true; 11182 break; 11183 11184 case Ovl_Overload: 11185 Redeclaration = false; 11186 break; 11187 } 11188 } 11189 } 11190 11191 // Check for a previous extern "C" declaration with this name. 11192 if (!Redeclaration && 11193 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 11194 if (!Previous.empty()) { 11195 // This is an extern "C" declaration with the same name as a previous 11196 // declaration, and thus redeclares that entity... 11197 Redeclaration = true; 11198 OldDecl = Previous.getFoundDecl(); 11199 MergeTypeWithPrevious = false; 11200 11201 // ... except in the presence of __attribute__((overloadable)). 11202 if (OldDecl->hasAttr<OverloadableAttr>() || 11203 NewFD->hasAttr<OverloadableAttr>()) { 11204 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11205 MayNeedOverloadableChecks = true; 11206 Redeclaration = false; 11207 OldDecl = nullptr; 11208 } 11209 } 11210 } 11211 } 11212 11213 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 11214 return Redeclaration; 11215 11216 // PPC MMA non-pointer types are not allowed as function return types. 11217 if (Context.getTargetInfo().getTriple().isPPC64() && 11218 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11219 NewFD->setInvalidDecl(); 11220 } 11221 11222 // C++11 [dcl.constexpr]p8: 11223 // A constexpr specifier for a non-static member function that is not 11224 // a constructor declares that member function to be const. 11225 // 11226 // This needs to be delayed until we know whether this is an out-of-line 11227 // definition of a static member function. 11228 // 11229 // This rule is not present in C++1y, so we produce a backwards 11230 // compatibility warning whenever it happens in C++11. 11231 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11232 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11233 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11234 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11235 CXXMethodDecl *OldMD = nullptr; 11236 if (OldDecl) 11237 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11238 if (!OldMD || !OldMD->isStatic()) { 11239 const FunctionProtoType *FPT = 11240 MD->getType()->castAs<FunctionProtoType>(); 11241 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11242 EPI.TypeQuals.addConst(); 11243 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11244 FPT->getParamTypes(), EPI)); 11245 11246 // Warn that we did this, if we're not performing template instantiation. 11247 // In that case, we'll have warned already when the template was defined. 11248 if (!inTemplateInstantiation()) { 11249 SourceLocation AddConstLoc; 11250 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11251 .IgnoreParens().getAs<FunctionTypeLoc>()) 11252 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11253 11254 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11255 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11256 } 11257 } 11258 } 11259 11260 if (Redeclaration) { 11261 // NewFD and OldDecl represent declarations that need to be 11262 // merged. 11263 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious, 11264 DeclIsDefn)) { 11265 NewFD->setInvalidDecl(); 11266 return Redeclaration; 11267 } 11268 11269 Previous.clear(); 11270 Previous.addDecl(OldDecl); 11271 11272 if (FunctionTemplateDecl *OldTemplateDecl = 11273 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11274 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11275 FunctionTemplateDecl *NewTemplateDecl 11276 = NewFD->getDescribedFunctionTemplate(); 11277 assert(NewTemplateDecl && "Template/non-template mismatch"); 11278 11279 // The call to MergeFunctionDecl above may have created some state in 11280 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11281 // can add it as a redeclaration. 11282 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11283 11284 NewFD->setPreviousDeclaration(OldFD); 11285 if (NewFD->isCXXClassMember()) { 11286 NewFD->setAccess(OldTemplateDecl->getAccess()); 11287 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11288 } 11289 11290 // If this is an explicit specialization of a member that is a function 11291 // template, mark it as a member specialization. 11292 if (IsMemberSpecialization && 11293 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11294 NewTemplateDecl->setMemberSpecialization(); 11295 assert(OldTemplateDecl->isMemberSpecialization()); 11296 // Explicit specializations of a member template do not inherit deleted 11297 // status from the parent member template that they are specializing. 11298 if (OldFD->isDeleted()) { 11299 // FIXME: This assert will not hold in the presence of modules. 11300 assert(OldFD->getCanonicalDecl() == OldFD); 11301 // FIXME: We need an update record for this AST mutation. 11302 OldFD->setDeletedAsWritten(false); 11303 } 11304 } 11305 11306 } else { 11307 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11308 auto *OldFD = cast<FunctionDecl>(OldDecl); 11309 // This needs to happen first so that 'inline' propagates. 11310 NewFD->setPreviousDeclaration(OldFD); 11311 if (NewFD->isCXXClassMember()) 11312 NewFD->setAccess(OldFD->getAccess()); 11313 } 11314 } 11315 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11316 !NewFD->getAttr<OverloadableAttr>()) { 11317 assert((Previous.empty() || 11318 llvm::any_of(Previous, 11319 [](const NamedDecl *ND) { 11320 return ND->hasAttr<OverloadableAttr>(); 11321 })) && 11322 "Non-redecls shouldn't happen without overloadable present"); 11323 11324 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11325 const auto *FD = dyn_cast<FunctionDecl>(ND); 11326 return FD && !FD->hasAttr<OverloadableAttr>(); 11327 }); 11328 11329 if (OtherUnmarkedIter != Previous.end()) { 11330 Diag(NewFD->getLocation(), 11331 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11332 Diag((*OtherUnmarkedIter)->getLocation(), 11333 diag::note_attribute_overloadable_prev_overload) 11334 << false; 11335 11336 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11337 } 11338 } 11339 11340 if (LangOpts.OpenMP) 11341 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11342 11343 // Semantic checking for this function declaration (in isolation). 11344 11345 if (getLangOpts().CPlusPlus) { 11346 // C++-specific checks. 11347 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11348 CheckConstructor(Constructor); 11349 } else if (CXXDestructorDecl *Destructor = 11350 dyn_cast<CXXDestructorDecl>(NewFD)) { 11351 CXXRecordDecl *Record = Destructor->getParent(); 11352 QualType ClassType = Context.getTypeDeclType(Record); 11353 11354 // FIXME: Shouldn't we be able to perform this check even when the class 11355 // type is dependent? Both gcc and edg can handle that. 11356 if (!ClassType->isDependentType()) { 11357 DeclarationName Name 11358 = Context.DeclarationNames.getCXXDestructorName( 11359 Context.getCanonicalType(ClassType)); 11360 if (NewFD->getDeclName() != Name) { 11361 Diag(NewFD->getLocation(), diag::err_destructor_name); 11362 NewFD->setInvalidDecl(); 11363 return Redeclaration; 11364 } 11365 } 11366 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11367 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11368 CheckDeductionGuideTemplate(TD); 11369 11370 // A deduction guide is not on the list of entities that can be 11371 // explicitly specialized. 11372 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11373 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11374 << /*explicit specialization*/ 1; 11375 } 11376 11377 // Find any virtual functions that this function overrides. 11378 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11379 if (!Method->isFunctionTemplateSpecialization() && 11380 !Method->getDescribedFunctionTemplate() && 11381 Method->isCanonicalDecl()) { 11382 AddOverriddenMethods(Method->getParent(), Method); 11383 } 11384 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11385 // C++2a [class.virtual]p6 11386 // A virtual method shall not have a requires-clause. 11387 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11388 diag::err_constrained_virtual_method); 11389 11390 if (Method->isStatic()) 11391 checkThisInStaticMemberFunctionType(Method); 11392 } 11393 11394 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11395 ActOnConversionDeclarator(Conversion); 11396 11397 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11398 if (NewFD->isOverloadedOperator() && 11399 CheckOverloadedOperatorDeclaration(NewFD)) { 11400 NewFD->setInvalidDecl(); 11401 return Redeclaration; 11402 } 11403 11404 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11405 if (NewFD->getLiteralIdentifier() && 11406 CheckLiteralOperatorDeclaration(NewFD)) { 11407 NewFD->setInvalidDecl(); 11408 return Redeclaration; 11409 } 11410 11411 // In C++, check default arguments now that we have merged decls. Unless 11412 // the lexical context is the class, because in this case this is done 11413 // during delayed parsing anyway. 11414 if (!CurContext->isRecord()) 11415 CheckCXXDefaultArguments(NewFD); 11416 11417 // If this function is declared as being extern "C", then check to see if 11418 // the function returns a UDT (class, struct, or union type) that is not C 11419 // compatible, and if it does, warn the user. 11420 // But, issue any diagnostic on the first declaration only. 11421 if (Previous.empty() && NewFD->isExternC()) { 11422 QualType R = NewFD->getReturnType(); 11423 if (R->isIncompleteType() && !R->isVoidType()) 11424 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11425 << NewFD << R; 11426 else if (!R.isPODType(Context) && !R->isVoidType() && 11427 !R->isObjCObjectPointerType()) 11428 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11429 } 11430 11431 // C++1z [dcl.fct]p6: 11432 // [...] whether the function has a non-throwing exception-specification 11433 // [is] part of the function type 11434 // 11435 // This results in an ABI break between C++14 and C++17 for functions whose 11436 // declared type includes an exception-specification in a parameter or 11437 // return type. (Exception specifications on the function itself are OK in 11438 // most cases, and exception specifications are not permitted in most other 11439 // contexts where they could make it into a mangling.) 11440 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11441 auto HasNoexcept = [&](QualType T) -> bool { 11442 // Strip off declarator chunks that could be between us and a function 11443 // type. We don't need to look far, exception specifications are very 11444 // restricted prior to C++17. 11445 if (auto *RT = T->getAs<ReferenceType>()) 11446 T = RT->getPointeeType(); 11447 else if (T->isAnyPointerType()) 11448 T = T->getPointeeType(); 11449 else if (auto *MPT = T->getAs<MemberPointerType>()) 11450 T = MPT->getPointeeType(); 11451 if (auto *FPT = T->getAs<FunctionProtoType>()) 11452 if (FPT->isNothrow()) 11453 return true; 11454 return false; 11455 }; 11456 11457 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11458 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11459 for (QualType T : FPT->param_types()) 11460 AnyNoexcept |= HasNoexcept(T); 11461 if (AnyNoexcept) 11462 Diag(NewFD->getLocation(), 11463 diag::warn_cxx17_compat_exception_spec_in_signature) 11464 << NewFD; 11465 } 11466 11467 if (!Redeclaration && LangOpts.CUDA) 11468 checkCUDATargetOverload(NewFD, Previous); 11469 } 11470 return Redeclaration; 11471 } 11472 11473 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11474 // C++11 [basic.start.main]p3: 11475 // A program that [...] declares main to be inline, static or 11476 // constexpr is ill-formed. 11477 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11478 // appear in a declaration of main. 11479 // static main is not an error under C99, but we should warn about it. 11480 // We accept _Noreturn main as an extension. 11481 if (FD->getStorageClass() == SC_Static) 11482 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11483 ? diag::err_static_main : diag::warn_static_main) 11484 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11485 if (FD->isInlineSpecified()) 11486 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11487 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11488 if (DS.isNoreturnSpecified()) { 11489 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11490 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11491 Diag(NoreturnLoc, diag::ext_noreturn_main); 11492 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11493 << FixItHint::CreateRemoval(NoreturnRange); 11494 } 11495 if (FD->isConstexpr()) { 11496 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11497 << FD->isConsteval() 11498 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11499 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11500 } 11501 11502 if (getLangOpts().OpenCL) { 11503 Diag(FD->getLocation(), diag::err_opencl_no_main) 11504 << FD->hasAttr<OpenCLKernelAttr>(); 11505 FD->setInvalidDecl(); 11506 return; 11507 } 11508 11509 // Functions named main in hlsl are default entries, but don't have specific 11510 // signatures they are required to conform to. 11511 if (getLangOpts().HLSL) 11512 return; 11513 11514 QualType T = FD->getType(); 11515 assert(T->isFunctionType() && "function decl is not of function type"); 11516 const FunctionType* FT = T->castAs<FunctionType>(); 11517 11518 // Set default calling convention for main() 11519 if (FT->getCallConv() != CC_C) { 11520 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11521 FD->setType(QualType(FT, 0)); 11522 T = Context.getCanonicalType(FD->getType()); 11523 } 11524 11525 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11526 // In C with GNU extensions we allow main() to have non-integer return 11527 // type, but we should warn about the extension, and we disable the 11528 // implicit-return-zero rule. 11529 11530 // GCC in C mode accepts qualified 'int'. 11531 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11532 FD->setHasImplicitReturnZero(true); 11533 else { 11534 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11535 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11536 if (RTRange.isValid()) 11537 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11538 << FixItHint::CreateReplacement(RTRange, "int"); 11539 } 11540 } else { 11541 // In C and C++, main magically returns 0 if you fall off the end; 11542 // set the flag which tells us that. 11543 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11544 11545 // All the standards say that main() should return 'int'. 11546 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11547 FD->setHasImplicitReturnZero(true); 11548 else { 11549 // Otherwise, this is just a flat-out error. 11550 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11551 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11552 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11553 : FixItHint()); 11554 FD->setInvalidDecl(true); 11555 } 11556 } 11557 11558 // Treat protoless main() as nullary. 11559 if (isa<FunctionNoProtoType>(FT)) return; 11560 11561 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11562 unsigned nparams = FTP->getNumParams(); 11563 assert(FD->getNumParams() == nparams); 11564 11565 bool HasExtraParameters = (nparams > 3); 11566 11567 if (FTP->isVariadic()) { 11568 Diag(FD->getLocation(), diag::ext_variadic_main); 11569 // FIXME: if we had information about the location of the ellipsis, we 11570 // could add a FixIt hint to remove it as a parameter. 11571 } 11572 11573 // Darwin passes an undocumented fourth argument of type char**. If 11574 // other platforms start sprouting these, the logic below will start 11575 // getting shifty. 11576 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11577 HasExtraParameters = false; 11578 11579 if (HasExtraParameters) { 11580 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11581 FD->setInvalidDecl(true); 11582 nparams = 3; 11583 } 11584 11585 // FIXME: a lot of the following diagnostics would be improved 11586 // if we had some location information about types. 11587 11588 QualType CharPP = 11589 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11590 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11591 11592 for (unsigned i = 0; i < nparams; ++i) { 11593 QualType AT = FTP->getParamType(i); 11594 11595 bool mismatch = true; 11596 11597 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11598 mismatch = false; 11599 else if (Expected[i] == CharPP) { 11600 // As an extension, the following forms are okay: 11601 // char const ** 11602 // char const * const * 11603 // char * const * 11604 11605 QualifierCollector qs; 11606 const PointerType* PT; 11607 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11608 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11609 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11610 Context.CharTy)) { 11611 qs.removeConst(); 11612 mismatch = !qs.empty(); 11613 } 11614 } 11615 11616 if (mismatch) { 11617 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11618 // TODO: suggest replacing given type with expected type 11619 FD->setInvalidDecl(true); 11620 } 11621 } 11622 11623 if (nparams == 1 && !FD->isInvalidDecl()) { 11624 Diag(FD->getLocation(), diag::warn_main_one_arg); 11625 } 11626 11627 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11628 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11629 FD->setInvalidDecl(); 11630 } 11631 } 11632 11633 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11634 11635 // Default calling convention for main and wmain is __cdecl 11636 if (FD->getName() == "main" || FD->getName() == "wmain") 11637 return false; 11638 11639 // Default calling convention for MinGW is __cdecl 11640 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11641 if (T.isWindowsGNUEnvironment()) 11642 return false; 11643 11644 // Default calling convention for WinMain, wWinMain and DllMain 11645 // is __stdcall on 32 bit Windows 11646 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11647 return true; 11648 11649 return false; 11650 } 11651 11652 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11653 QualType T = FD->getType(); 11654 assert(T->isFunctionType() && "function decl is not of function type"); 11655 const FunctionType *FT = T->castAs<FunctionType>(); 11656 11657 // Set an implicit return of 'zero' if the function can return some integral, 11658 // enumeration, pointer or nullptr type. 11659 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11660 FT->getReturnType()->isAnyPointerType() || 11661 FT->getReturnType()->isNullPtrType()) 11662 // DllMain is exempt because a return value of zero means it failed. 11663 if (FD->getName() != "DllMain") 11664 FD->setHasImplicitReturnZero(true); 11665 11666 // Explicity specified calling conventions are applied to MSVC entry points 11667 if (!hasExplicitCallingConv(T)) { 11668 if (isDefaultStdCall(FD, *this)) { 11669 if (FT->getCallConv() != CC_X86StdCall) { 11670 FT = Context.adjustFunctionType( 11671 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11672 FD->setType(QualType(FT, 0)); 11673 } 11674 } else if (FT->getCallConv() != CC_C) { 11675 FT = Context.adjustFunctionType(FT, 11676 FT->getExtInfo().withCallingConv(CC_C)); 11677 FD->setType(QualType(FT, 0)); 11678 } 11679 } 11680 11681 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11682 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11683 FD->setInvalidDecl(); 11684 } 11685 } 11686 11687 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11688 // FIXME: Need strict checking. In C89, we need to check for 11689 // any assignment, increment, decrement, function-calls, or 11690 // commas outside of a sizeof. In C99, it's the same list, 11691 // except that the aforementioned are allowed in unevaluated 11692 // expressions. Everything else falls under the 11693 // "may accept other forms of constant expressions" exception. 11694 // 11695 // Regular C++ code will not end up here (exceptions: language extensions, 11696 // OpenCL C++ etc), so the constant expression rules there don't matter. 11697 if (Init->isValueDependent()) { 11698 assert(Init->containsErrors() && 11699 "Dependent code should only occur in error-recovery path."); 11700 return true; 11701 } 11702 const Expr *Culprit; 11703 if (Init->isConstantInitializer(Context, false, &Culprit)) 11704 return false; 11705 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11706 << Culprit->getSourceRange(); 11707 return true; 11708 } 11709 11710 namespace { 11711 // Visits an initialization expression to see if OrigDecl is evaluated in 11712 // its own initialization and throws a warning if it does. 11713 class SelfReferenceChecker 11714 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11715 Sema &S; 11716 Decl *OrigDecl; 11717 bool isRecordType; 11718 bool isPODType; 11719 bool isReferenceType; 11720 11721 bool isInitList; 11722 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11723 11724 public: 11725 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11726 11727 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11728 S(S), OrigDecl(OrigDecl) { 11729 isPODType = false; 11730 isRecordType = false; 11731 isReferenceType = false; 11732 isInitList = false; 11733 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11734 isPODType = VD->getType().isPODType(S.Context); 11735 isRecordType = VD->getType()->isRecordType(); 11736 isReferenceType = VD->getType()->isReferenceType(); 11737 } 11738 } 11739 11740 // For most expressions, just call the visitor. For initializer lists, 11741 // track the index of the field being initialized since fields are 11742 // initialized in order allowing use of previously initialized fields. 11743 void CheckExpr(Expr *E) { 11744 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11745 if (!InitList) { 11746 Visit(E); 11747 return; 11748 } 11749 11750 // Track and increment the index here. 11751 isInitList = true; 11752 InitFieldIndex.push_back(0); 11753 for (auto Child : InitList->children()) { 11754 CheckExpr(cast<Expr>(Child)); 11755 ++InitFieldIndex.back(); 11756 } 11757 InitFieldIndex.pop_back(); 11758 } 11759 11760 // Returns true if MemberExpr is checked and no further checking is needed. 11761 // Returns false if additional checking is required. 11762 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11763 llvm::SmallVector<FieldDecl*, 4> Fields; 11764 Expr *Base = E; 11765 bool ReferenceField = false; 11766 11767 // Get the field members used. 11768 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11769 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11770 if (!FD) 11771 return false; 11772 Fields.push_back(FD); 11773 if (FD->getType()->isReferenceType()) 11774 ReferenceField = true; 11775 Base = ME->getBase()->IgnoreParenImpCasts(); 11776 } 11777 11778 // Keep checking only if the base Decl is the same. 11779 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11780 if (!DRE || DRE->getDecl() != OrigDecl) 11781 return false; 11782 11783 // A reference field can be bound to an unininitialized field. 11784 if (CheckReference && !ReferenceField) 11785 return true; 11786 11787 // Convert FieldDecls to their index number. 11788 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11789 for (const FieldDecl *I : llvm::reverse(Fields)) 11790 UsedFieldIndex.push_back(I->getFieldIndex()); 11791 11792 // See if a warning is needed by checking the first difference in index 11793 // numbers. If field being used has index less than the field being 11794 // initialized, then the use is safe. 11795 for (auto UsedIter = UsedFieldIndex.begin(), 11796 UsedEnd = UsedFieldIndex.end(), 11797 OrigIter = InitFieldIndex.begin(), 11798 OrigEnd = InitFieldIndex.end(); 11799 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11800 if (*UsedIter < *OrigIter) 11801 return true; 11802 if (*UsedIter > *OrigIter) 11803 break; 11804 } 11805 11806 // TODO: Add a different warning which will print the field names. 11807 HandleDeclRefExpr(DRE); 11808 return true; 11809 } 11810 11811 // For most expressions, the cast is directly above the DeclRefExpr. 11812 // For conditional operators, the cast can be outside the conditional 11813 // operator if both expressions are DeclRefExpr's. 11814 void HandleValue(Expr *E) { 11815 E = E->IgnoreParens(); 11816 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11817 HandleDeclRefExpr(DRE); 11818 return; 11819 } 11820 11821 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11822 Visit(CO->getCond()); 11823 HandleValue(CO->getTrueExpr()); 11824 HandleValue(CO->getFalseExpr()); 11825 return; 11826 } 11827 11828 if (BinaryConditionalOperator *BCO = 11829 dyn_cast<BinaryConditionalOperator>(E)) { 11830 Visit(BCO->getCond()); 11831 HandleValue(BCO->getFalseExpr()); 11832 return; 11833 } 11834 11835 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11836 HandleValue(OVE->getSourceExpr()); 11837 return; 11838 } 11839 11840 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11841 if (BO->getOpcode() == BO_Comma) { 11842 Visit(BO->getLHS()); 11843 HandleValue(BO->getRHS()); 11844 return; 11845 } 11846 } 11847 11848 if (isa<MemberExpr>(E)) { 11849 if (isInitList) { 11850 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11851 false /*CheckReference*/)) 11852 return; 11853 } 11854 11855 Expr *Base = E->IgnoreParenImpCasts(); 11856 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11857 // Check for static member variables and don't warn on them. 11858 if (!isa<FieldDecl>(ME->getMemberDecl())) 11859 return; 11860 Base = ME->getBase()->IgnoreParenImpCasts(); 11861 } 11862 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11863 HandleDeclRefExpr(DRE); 11864 return; 11865 } 11866 11867 Visit(E); 11868 } 11869 11870 // Reference types not handled in HandleValue are handled here since all 11871 // uses of references are bad, not just r-value uses. 11872 void VisitDeclRefExpr(DeclRefExpr *E) { 11873 if (isReferenceType) 11874 HandleDeclRefExpr(E); 11875 } 11876 11877 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11878 if (E->getCastKind() == CK_LValueToRValue) { 11879 HandleValue(E->getSubExpr()); 11880 return; 11881 } 11882 11883 Inherited::VisitImplicitCastExpr(E); 11884 } 11885 11886 void VisitMemberExpr(MemberExpr *E) { 11887 if (isInitList) { 11888 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11889 return; 11890 } 11891 11892 // Don't warn on arrays since they can be treated as pointers. 11893 if (E->getType()->canDecayToPointerType()) return; 11894 11895 // Warn when a non-static method call is followed by non-static member 11896 // field accesses, which is followed by a DeclRefExpr. 11897 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11898 bool Warn = (MD && !MD->isStatic()); 11899 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11900 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11901 if (!isa<FieldDecl>(ME->getMemberDecl())) 11902 Warn = false; 11903 Base = ME->getBase()->IgnoreParenImpCasts(); 11904 } 11905 11906 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11907 if (Warn) 11908 HandleDeclRefExpr(DRE); 11909 return; 11910 } 11911 11912 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11913 // Visit that expression. 11914 Visit(Base); 11915 } 11916 11917 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11918 Expr *Callee = E->getCallee(); 11919 11920 if (isa<UnresolvedLookupExpr>(Callee)) 11921 return Inherited::VisitCXXOperatorCallExpr(E); 11922 11923 Visit(Callee); 11924 for (auto Arg: E->arguments()) 11925 HandleValue(Arg->IgnoreParenImpCasts()); 11926 } 11927 11928 void VisitUnaryOperator(UnaryOperator *E) { 11929 // For POD record types, addresses of its own members are well-defined. 11930 if (E->getOpcode() == UO_AddrOf && isRecordType && 11931 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11932 if (!isPODType) 11933 HandleValue(E->getSubExpr()); 11934 return; 11935 } 11936 11937 if (E->isIncrementDecrementOp()) { 11938 HandleValue(E->getSubExpr()); 11939 return; 11940 } 11941 11942 Inherited::VisitUnaryOperator(E); 11943 } 11944 11945 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11946 11947 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11948 if (E->getConstructor()->isCopyConstructor()) { 11949 Expr *ArgExpr = E->getArg(0); 11950 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11951 if (ILE->getNumInits() == 1) 11952 ArgExpr = ILE->getInit(0); 11953 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11954 if (ICE->getCastKind() == CK_NoOp) 11955 ArgExpr = ICE->getSubExpr(); 11956 HandleValue(ArgExpr); 11957 return; 11958 } 11959 Inherited::VisitCXXConstructExpr(E); 11960 } 11961 11962 void VisitCallExpr(CallExpr *E) { 11963 // Treat std::move as a use. 11964 if (E->isCallToStdMove()) { 11965 HandleValue(E->getArg(0)); 11966 return; 11967 } 11968 11969 Inherited::VisitCallExpr(E); 11970 } 11971 11972 void VisitBinaryOperator(BinaryOperator *E) { 11973 if (E->isCompoundAssignmentOp()) { 11974 HandleValue(E->getLHS()); 11975 Visit(E->getRHS()); 11976 return; 11977 } 11978 11979 Inherited::VisitBinaryOperator(E); 11980 } 11981 11982 // A custom visitor for BinaryConditionalOperator is needed because the 11983 // regular visitor would check the condition and true expression separately 11984 // but both point to the same place giving duplicate diagnostics. 11985 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11986 Visit(E->getCond()); 11987 Visit(E->getFalseExpr()); 11988 } 11989 11990 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11991 Decl* ReferenceDecl = DRE->getDecl(); 11992 if (OrigDecl != ReferenceDecl) return; 11993 unsigned diag; 11994 if (isReferenceType) { 11995 diag = diag::warn_uninit_self_reference_in_reference_init; 11996 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11997 diag = diag::warn_static_self_reference_in_init; 11998 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11999 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 12000 DRE->getDecl()->getType()->isRecordType()) { 12001 diag = diag::warn_uninit_self_reference_in_init; 12002 } else { 12003 // Local variables will be handled by the CFG analysis. 12004 return; 12005 } 12006 12007 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 12008 S.PDiag(diag) 12009 << DRE->getDecl() << OrigDecl->getLocation() 12010 << DRE->getSourceRange()); 12011 } 12012 }; 12013 12014 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 12015 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 12016 bool DirectInit) { 12017 // Parameters arguments are occassionially constructed with itself, 12018 // for instance, in recursive functions. Skip them. 12019 if (isa<ParmVarDecl>(OrigDecl)) 12020 return; 12021 12022 E = E->IgnoreParens(); 12023 12024 // Skip checking T a = a where T is not a record or reference type. 12025 // Doing so is a way to silence uninitialized warnings. 12026 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 12027 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 12028 if (ICE->getCastKind() == CK_LValueToRValue) 12029 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 12030 if (DRE->getDecl() == OrigDecl) 12031 return; 12032 12033 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 12034 } 12035 } // end anonymous namespace 12036 12037 namespace { 12038 // Simple wrapper to add the name of a variable or (if no variable is 12039 // available) a DeclarationName into a diagnostic. 12040 struct VarDeclOrName { 12041 VarDecl *VDecl; 12042 DeclarationName Name; 12043 12044 friend const Sema::SemaDiagnosticBuilder & 12045 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 12046 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 12047 } 12048 }; 12049 } // end anonymous namespace 12050 12051 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 12052 DeclarationName Name, QualType Type, 12053 TypeSourceInfo *TSI, 12054 SourceRange Range, bool DirectInit, 12055 Expr *Init) { 12056 bool IsInitCapture = !VDecl; 12057 assert((!VDecl || !VDecl->isInitCapture()) && 12058 "init captures are expected to be deduced prior to initialization"); 12059 12060 VarDeclOrName VN{VDecl, Name}; 12061 12062 DeducedType *Deduced = Type->getContainedDeducedType(); 12063 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 12064 12065 // C++11 [dcl.spec.auto]p3 12066 if (!Init) { 12067 assert(VDecl && "no init for init capture deduction?"); 12068 12069 // Except for class argument deduction, and then for an initializing 12070 // declaration only, i.e. no static at class scope or extern. 12071 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 12072 VDecl->hasExternalStorage() || 12073 VDecl->isStaticDataMember()) { 12074 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 12075 << VDecl->getDeclName() << Type; 12076 return QualType(); 12077 } 12078 } 12079 12080 ArrayRef<Expr*> DeduceInits; 12081 if (Init) 12082 DeduceInits = Init; 12083 12084 if (DirectInit) { 12085 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 12086 DeduceInits = PL->exprs(); 12087 } 12088 12089 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 12090 assert(VDecl && "non-auto type for init capture deduction?"); 12091 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12092 InitializationKind Kind = InitializationKind::CreateForInit( 12093 VDecl->getLocation(), DirectInit, Init); 12094 // FIXME: Initialization should not be taking a mutable list of inits. 12095 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 12096 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 12097 InitsCopy); 12098 } 12099 12100 if (DirectInit) { 12101 if (auto *IL = dyn_cast<InitListExpr>(Init)) 12102 DeduceInits = IL->inits(); 12103 } 12104 12105 // Deduction only works if we have exactly one source expression. 12106 if (DeduceInits.empty()) { 12107 // It isn't possible to write this directly, but it is possible to 12108 // end up in this situation with "auto x(some_pack...);" 12109 Diag(Init->getBeginLoc(), IsInitCapture 12110 ? diag::err_init_capture_no_expression 12111 : diag::err_auto_var_init_no_expression) 12112 << VN << Type << Range; 12113 return QualType(); 12114 } 12115 12116 if (DeduceInits.size() > 1) { 12117 Diag(DeduceInits[1]->getBeginLoc(), 12118 IsInitCapture ? diag::err_init_capture_multiple_expressions 12119 : diag::err_auto_var_init_multiple_expressions) 12120 << VN << Type << Range; 12121 return QualType(); 12122 } 12123 12124 Expr *DeduceInit = DeduceInits[0]; 12125 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 12126 Diag(Init->getBeginLoc(), IsInitCapture 12127 ? diag::err_init_capture_paren_braces 12128 : diag::err_auto_var_init_paren_braces) 12129 << isa<InitListExpr>(Init) << VN << Type << Range; 12130 return QualType(); 12131 } 12132 12133 // Expressions default to 'id' when we're in a debugger. 12134 bool DefaultedAnyToId = false; 12135 if (getLangOpts().DebuggerCastResultToId && 12136 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 12137 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12138 if (Result.isInvalid()) { 12139 return QualType(); 12140 } 12141 Init = Result.get(); 12142 DefaultedAnyToId = true; 12143 } 12144 12145 // C++ [dcl.decomp]p1: 12146 // If the assignment-expression [...] has array type A and no ref-qualifier 12147 // is present, e has type cv A 12148 if (VDecl && isa<DecompositionDecl>(VDecl) && 12149 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 12150 DeduceInit->getType()->isConstantArrayType()) 12151 return Context.getQualifiedType(DeduceInit->getType(), 12152 Type.getQualifiers()); 12153 12154 QualType DeducedType; 12155 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 12156 if (!IsInitCapture) 12157 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 12158 else if (isa<InitListExpr>(Init)) 12159 Diag(Range.getBegin(), 12160 diag::err_init_capture_deduction_failure_from_init_list) 12161 << VN 12162 << (DeduceInit->getType().isNull() ? TSI->getType() 12163 : DeduceInit->getType()) 12164 << DeduceInit->getSourceRange(); 12165 else 12166 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 12167 << VN << TSI->getType() 12168 << (DeduceInit->getType().isNull() ? TSI->getType() 12169 : DeduceInit->getType()) 12170 << DeduceInit->getSourceRange(); 12171 } 12172 12173 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 12174 // 'id' instead of a specific object type prevents most of our usual 12175 // checks. 12176 // We only want to warn outside of template instantiations, though: 12177 // inside a template, the 'id' could have come from a parameter. 12178 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 12179 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 12180 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 12181 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 12182 } 12183 12184 return DeducedType; 12185 } 12186 12187 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 12188 Expr *Init) { 12189 assert(!Init || !Init->containsErrors()); 12190 QualType DeducedType = deduceVarTypeFromInitializer( 12191 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 12192 VDecl->getSourceRange(), DirectInit, Init); 12193 if (DeducedType.isNull()) { 12194 VDecl->setInvalidDecl(); 12195 return true; 12196 } 12197 12198 VDecl->setType(DeducedType); 12199 assert(VDecl->isLinkageValid()); 12200 12201 // In ARC, infer lifetime. 12202 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 12203 VDecl->setInvalidDecl(); 12204 12205 if (getLangOpts().OpenCL) 12206 deduceOpenCLAddressSpace(VDecl); 12207 12208 // If this is a redeclaration, check that the type we just deduced matches 12209 // the previously declared type. 12210 if (VarDecl *Old = VDecl->getPreviousDecl()) { 12211 // We never need to merge the type, because we cannot form an incomplete 12212 // array of auto, nor deduce such a type. 12213 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 12214 } 12215 12216 // Check the deduced type is valid for a variable declaration. 12217 CheckVariableDeclarationType(VDecl); 12218 return VDecl->isInvalidDecl(); 12219 } 12220 12221 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 12222 SourceLocation Loc) { 12223 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 12224 Init = EWC->getSubExpr(); 12225 12226 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 12227 Init = CE->getSubExpr(); 12228 12229 QualType InitType = Init->getType(); 12230 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12231 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 12232 "shouldn't be called if type doesn't have a non-trivial C struct"); 12233 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 12234 for (auto I : ILE->inits()) { 12235 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 12236 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12237 continue; 12238 SourceLocation SL = I->getExprLoc(); 12239 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 12240 } 12241 return; 12242 } 12243 12244 if (isa<ImplicitValueInitExpr>(Init)) { 12245 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12246 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 12247 NTCUK_Init); 12248 } else { 12249 // Assume all other explicit initializers involving copying some existing 12250 // object. 12251 // TODO: ignore any explicit initializers where we can guarantee 12252 // copy-elision. 12253 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 12254 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 12255 } 12256 } 12257 12258 namespace { 12259 12260 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 12261 // Ignore unavailable fields. A field can be marked as unavailable explicitly 12262 // in the source code or implicitly by the compiler if it is in a union 12263 // defined in a system header and has non-trivial ObjC ownership 12264 // qualifications. We don't want those fields to participate in determining 12265 // whether the containing union is non-trivial. 12266 return FD->hasAttr<UnavailableAttr>(); 12267 } 12268 12269 struct DiagNonTrivalCUnionDefaultInitializeVisitor 12270 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12271 void> { 12272 using Super = 12273 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12274 void>; 12275 12276 DiagNonTrivalCUnionDefaultInitializeVisitor( 12277 QualType OrigTy, SourceLocation OrigLoc, 12278 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12279 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12280 12281 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 12282 const FieldDecl *FD, bool InNonTrivialUnion) { 12283 if (const auto *AT = S.Context.getAsArrayType(QT)) 12284 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12285 InNonTrivialUnion); 12286 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 12287 } 12288 12289 void visitARCStrong(QualType QT, const FieldDecl *FD, 12290 bool InNonTrivialUnion) { 12291 if (InNonTrivialUnion) 12292 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12293 << 1 << 0 << QT << FD->getName(); 12294 } 12295 12296 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12297 if (InNonTrivialUnion) 12298 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12299 << 1 << 0 << QT << FD->getName(); 12300 } 12301 12302 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12303 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12304 if (RD->isUnion()) { 12305 if (OrigLoc.isValid()) { 12306 bool IsUnion = false; 12307 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12308 IsUnion = OrigRD->isUnion(); 12309 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12310 << 0 << OrigTy << IsUnion << UseContext; 12311 // Reset OrigLoc so that this diagnostic is emitted only once. 12312 OrigLoc = SourceLocation(); 12313 } 12314 InNonTrivialUnion = true; 12315 } 12316 12317 if (InNonTrivialUnion) 12318 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12319 << 0 << 0 << QT.getUnqualifiedType() << ""; 12320 12321 for (const FieldDecl *FD : RD->fields()) 12322 if (!shouldIgnoreForRecordTriviality(FD)) 12323 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12324 } 12325 12326 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12327 12328 // The non-trivial C union type or the struct/union type that contains a 12329 // non-trivial C union. 12330 QualType OrigTy; 12331 SourceLocation OrigLoc; 12332 Sema::NonTrivialCUnionContext UseContext; 12333 Sema &S; 12334 }; 12335 12336 struct DiagNonTrivalCUnionDestructedTypeVisitor 12337 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12338 using Super = 12339 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12340 12341 DiagNonTrivalCUnionDestructedTypeVisitor( 12342 QualType OrigTy, SourceLocation OrigLoc, 12343 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12344 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12345 12346 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12347 const FieldDecl *FD, bool InNonTrivialUnion) { 12348 if (const auto *AT = S.Context.getAsArrayType(QT)) 12349 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12350 InNonTrivialUnion); 12351 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12352 } 12353 12354 void visitARCStrong(QualType QT, const FieldDecl *FD, 12355 bool InNonTrivialUnion) { 12356 if (InNonTrivialUnion) 12357 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12358 << 1 << 1 << QT << FD->getName(); 12359 } 12360 12361 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12362 if (InNonTrivialUnion) 12363 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12364 << 1 << 1 << QT << FD->getName(); 12365 } 12366 12367 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12368 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12369 if (RD->isUnion()) { 12370 if (OrigLoc.isValid()) { 12371 bool IsUnion = false; 12372 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12373 IsUnion = OrigRD->isUnion(); 12374 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12375 << 1 << OrigTy << IsUnion << UseContext; 12376 // Reset OrigLoc so that this diagnostic is emitted only once. 12377 OrigLoc = SourceLocation(); 12378 } 12379 InNonTrivialUnion = true; 12380 } 12381 12382 if (InNonTrivialUnion) 12383 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12384 << 0 << 1 << QT.getUnqualifiedType() << ""; 12385 12386 for (const FieldDecl *FD : RD->fields()) 12387 if (!shouldIgnoreForRecordTriviality(FD)) 12388 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12389 } 12390 12391 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12392 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12393 bool InNonTrivialUnion) {} 12394 12395 // The non-trivial C union type or the struct/union type that contains a 12396 // non-trivial C union. 12397 QualType OrigTy; 12398 SourceLocation OrigLoc; 12399 Sema::NonTrivialCUnionContext UseContext; 12400 Sema &S; 12401 }; 12402 12403 struct DiagNonTrivalCUnionCopyVisitor 12404 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12405 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12406 12407 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12408 Sema::NonTrivialCUnionContext UseContext, 12409 Sema &S) 12410 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12411 12412 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12413 const FieldDecl *FD, bool InNonTrivialUnion) { 12414 if (const auto *AT = S.Context.getAsArrayType(QT)) 12415 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12416 InNonTrivialUnion); 12417 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12418 } 12419 12420 void visitARCStrong(QualType QT, const FieldDecl *FD, 12421 bool InNonTrivialUnion) { 12422 if (InNonTrivialUnion) 12423 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12424 << 1 << 2 << QT << FD->getName(); 12425 } 12426 12427 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12428 if (InNonTrivialUnion) 12429 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12430 << 1 << 2 << QT << FD->getName(); 12431 } 12432 12433 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12434 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12435 if (RD->isUnion()) { 12436 if (OrigLoc.isValid()) { 12437 bool IsUnion = false; 12438 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12439 IsUnion = OrigRD->isUnion(); 12440 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12441 << 2 << OrigTy << IsUnion << UseContext; 12442 // Reset OrigLoc so that this diagnostic is emitted only once. 12443 OrigLoc = SourceLocation(); 12444 } 12445 InNonTrivialUnion = true; 12446 } 12447 12448 if (InNonTrivialUnion) 12449 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12450 << 0 << 2 << QT.getUnqualifiedType() << ""; 12451 12452 for (const FieldDecl *FD : RD->fields()) 12453 if (!shouldIgnoreForRecordTriviality(FD)) 12454 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12455 } 12456 12457 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12458 const FieldDecl *FD, bool InNonTrivialUnion) {} 12459 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12460 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12461 bool InNonTrivialUnion) {} 12462 12463 // The non-trivial C union type or the struct/union type that contains a 12464 // non-trivial C union. 12465 QualType OrigTy; 12466 SourceLocation OrigLoc; 12467 Sema::NonTrivialCUnionContext UseContext; 12468 Sema &S; 12469 }; 12470 12471 } // namespace 12472 12473 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12474 NonTrivialCUnionContext UseContext, 12475 unsigned NonTrivialKind) { 12476 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12477 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12478 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12479 "shouldn't be called if type doesn't have a non-trivial C union"); 12480 12481 if ((NonTrivialKind & NTCUK_Init) && 12482 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12483 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12484 .visit(QT, nullptr, false); 12485 if ((NonTrivialKind & NTCUK_Destruct) && 12486 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12487 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12488 .visit(QT, nullptr, false); 12489 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12490 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12491 .visit(QT, nullptr, false); 12492 } 12493 12494 /// AddInitializerToDecl - Adds the initializer Init to the 12495 /// declaration dcl. If DirectInit is true, this is C++ direct 12496 /// initialization rather than copy initialization. 12497 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12498 // If there is no declaration, there was an error parsing it. Just ignore 12499 // the initializer. 12500 if (!RealDecl || RealDecl->isInvalidDecl()) { 12501 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12502 return; 12503 } 12504 12505 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12506 // Pure-specifiers are handled in ActOnPureSpecifier. 12507 Diag(Method->getLocation(), diag::err_member_function_initialization) 12508 << Method->getDeclName() << Init->getSourceRange(); 12509 Method->setInvalidDecl(); 12510 return; 12511 } 12512 12513 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12514 if (!VDecl) { 12515 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12516 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12517 RealDecl->setInvalidDecl(); 12518 return; 12519 } 12520 12521 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12522 if (VDecl->getType()->isUndeducedType()) { 12523 // Attempt typo correction early so that the type of the init expression can 12524 // be deduced based on the chosen correction if the original init contains a 12525 // TypoExpr. 12526 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12527 if (!Res.isUsable()) { 12528 // There are unresolved typos in Init, just drop them. 12529 // FIXME: improve the recovery strategy to preserve the Init. 12530 RealDecl->setInvalidDecl(); 12531 return; 12532 } 12533 if (Res.get()->containsErrors()) { 12534 // Invalidate the decl as we don't know the type for recovery-expr yet. 12535 RealDecl->setInvalidDecl(); 12536 VDecl->setInit(Res.get()); 12537 return; 12538 } 12539 Init = Res.get(); 12540 12541 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12542 return; 12543 } 12544 12545 // dllimport cannot be used on variable definitions. 12546 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12547 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12548 VDecl->setInvalidDecl(); 12549 return; 12550 } 12551 12552 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12553 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12554 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12555 VDecl->setInvalidDecl(); 12556 return; 12557 } 12558 12559 if (!VDecl->getType()->isDependentType()) { 12560 // A definition must end up with a complete type, which means it must be 12561 // complete with the restriction that an array type might be completed by 12562 // the initializer; note that later code assumes this restriction. 12563 QualType BaseDeclType = VDecl->getType(); 12564 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12565 BaseDeclType = Array->getElementType(); 12566 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12567 diag::err_typecheck_decl_incomplete_type)) { 12568 RealDecl->setInvalidDecl(); 12569 return; 12570 } 12571 12572 // The variable can not have an abstract class type. 12573 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12574 diag::err_abstract_type_in_decl, 12575 AbstractVariableType)) 12576 VDecl->setInvalidDecl(); 12577 } 12578 12579 // If adding the initializer will turn this declaration into a definition, 12580 // and we already have a definition for this variable, diagnose or otherwise 12581 // handle the situation. 12582 if (VarDecl *Def = VDecl->getDefinition()) 12583 if (Def != VDecl && 12584 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12585 !VDecl->isThisDeclarationADemotedDefinition() && 12586 checkVarDeclRedefinition(Def, VDecl)) 12587 return; 12588 12589 if (getLangOpts().CPlusPlus) { 12590 // C++ [class.static.data]p4 12591 // If a static data member is of const integral or const 12592 // enumeration type, its declaration in the class definition can 12593 // specify a constant-initializer which shall be an integral 12594 // constant expression (5.19). In that case, the member can appear 12595 // in integral constant expressions. The member shall still be 12596 // defined in a namespace scope if it is used in the program and the 12597 // namespace scope definition shall not contain an initializer. 12598 // 12599 // We already performed a redefinition check above, but for static 12600 // data members we also need to check whether there was an in-class 12601 // declaration with an initializer. 12602 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12603 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12604 << VDecl->getDeclName(); 12605 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12606 diag::note_previous_initializer) 12607 << 0; 12608 return; 12609 } 12610 12611 if (VDecl->hasLocalStorage()) 12612 setFunctionHasBranchProtectedScope(); 12613 12614 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12615 VDecl->setInvalidDecl(); 12616 return; 12617 } 12618 } 12619 12620 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12621 // a kernel function cannot be initialized." 12622 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12623 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12624 VDecl->setInvalidDecl(); 12625 return; 12626 } 12627 12628 // The LoaderUninitialized attribute acts as a definition (of undef). 12629 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12630 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12631 VDecl->setInvalidDecl(); 12632 return; 12633 } 12634 12635 // Get the decls type and save a reference for later, since 12636 // CheckInitializerTypes may change it. 12637 QualType DclT = VDecl->getType(), SavT = DclT; 12638 12639 // Expressions default to 'id' when we're in a debugger 12640 // and we are assigning it to a variable of Objective-C pointer type. 12641 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12642 Init->getType() == Context.UnknownAnyTy) { 12643 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12644 if (Result.isInvalid()) { 12645 VDecl->setInvalidDecl(); 12646 return; 12647 } 12648 Init = Result.get(); 12649 } 12650 12651 // Perform the initialization. 12652 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12653 if (!VDecl->isInvalidDecl()) { 12654 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12655 InitializationKind Kind = InitializationKind::CreateForInit( 12656 VDecl->getLocation(), DirectInit, Init); 12657 12658 MultiExprArg Args = Init; 12659 if (CXXDirectInit) 12660 Args = MultiExprArg(CXXDirectInit->getExprs(), 12661 CXXDirectInit->getNumExprs()); 12662 12663 // Try to correct any TypoExprs in the initialization arguments. 12664 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12665 ExprResult Res = CorrectDelayedTyposInExpr( 12666 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12667 [this, Entity, Kind](Expr *E) { 12668 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12669 return Init.Failed() ? ExprError() : E; 12670 }); 12671 if (Res.isInvalid()) { 12672 VDecl->setInvalidDecl(); 12673 } else if (Res.get() != Args[Idx]) { 12674 Args[Idx] = Res.get(); 12675 } 12676 } 12677 if (VDecl->isInvalidDecl()) 12678 return; 12679 12680 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12681 /*TopLevelOfInitList=*/false, 12682 /*TreatUnavailableAsInvalid=*/false); 12683 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12684 if (Result.isInvalid()) { 12685 // If the provided initializer fails to initialize the var decl, 12686 // we attach a recovery expr for better recovery. 12687 auto RecoveryExpr = 12688 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12689 if (RecoveryExpr.get()) 12690 VDecl->setInit(RecoveryExpr.get()); 12691 return; 12692 } 12693 12694 Init = Result.getAs<Expr>(); 12695 } 12696 12697 // Check for self-references within variable initializers. 12698 // Variables declared within a function/method body (except for references) 12699 // are handled by a dataflow analysis. 12700 // This is undefined behavior in C++, but valid in C. 12701 if (getLangOpts().CPlusPlus) 12702 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12703 VDecl->getType()->isReferenceType()) 12704 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12705 12706 // If the type changed, it means we had an incomplete type that was 12707 // completed by the initializer. For example: 12708 // int ary[] = { 1, 3, 5 }; 12709 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12710 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12711 VDecl->setType(DclT); 12712 12713 if (!VDecl->isInvalidDecl()) { 12714 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12715 12716 if (VDecl->hasAttr<BlocksAttr>()) 12717 checkRetainCycles(VDecl, Init); 12718 12719 // It is safe to assign a weak reference into a strong variable. 12720 // Although this code can still have problems: 12721 // id x = self.weakProp; 12722 // id y = self.weakProp; 12723 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12724 // paths through the function. This should be revisited if 12725 // -Wrepeated-use-of-weak is made flow-sensitive. 12726 if (FunctionScopeInfo *FSI = getCurFunction()) 12727 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12728 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12729 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12730 Init->getBeginLoc())) 12731 FSI->markSafeWeakUse(Init); 12732 } 12733 12734 // The initialization is usually a full-expression. 12735 // 12736 // FIXME: If this is a braced initialization of an aggregate, it is not 12737 // an expression, and each individual field initializer is a separate 12738 // full-expression. For instance, in: 12739 // 12740 // struct Temp { ~Temp(); }; 12741 // struct S { S(Temp); }; 12742 // struct T { S a, b; } t = { Temp(), Temp() } 12743 // 12744 // we should destroy the first Temp before constructing the second. 12745 ExprResult Result = 12746 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12747 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12748 if (Result.isInvalid()) { 12749 VDecl->setInvalidDecl(); 12750 return; 12751 } 12752 Init = Result.get(); 12753 12754 // Attach the initializer to the decl. 12755 VDecl->setInit(Init); 12756 12757 if (VDecl->isLocalVarDecl()) { 12758 // Don't check the initializer if the declaration is malformed. 12759 if (VDecl->isInvalidDecl()) { 12760 // do nothing 12761 12762 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12763 // This is true even in C++ for OpenCL. 12764 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12765 CheckForConstantInitializer(Init, DclT); 12766 12767 // Otherwise, C++ does not restrict the initializer. 12768 } else if (getLangOpts().CPlusPlus) { 12769 // do nothing 12770 12771 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12772 // static storage duration shall be constant expressions or string literals. 12773 } else if (VDecl->getStorageClass() == SC_Static) { 12774 CheckForConstantInitializer(Init, DclT); 12775 12776 // C89 is stricter than C99 for aggregate initializers. 12777 // C89 6.5.7p3: All the expressions [...] in an initializer list 12778 // for an object that has aggregate or union type shall be 12779 // constant expressions. 12780 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12781 isa<InitListExpr>(Init)) { 12782 const Expr *Culprit; 12783 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12784 Diag(Culprit->getExprLoc(), 12785 diag::ext_aggregate_init_not_constant) 12786 << Culprit->getSourceRange(); 12787 } 12788 } 12789 12790 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12791 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12792 if (VDecl->hasLocalStorage()) 12793 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12794 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12795 VDecl->getLexicalDeclContext()->isRecord()) { 12796 // This is an in-class initialization for a static data member, e.g., 12797 // 12798 // struct S { 12799 // static const int value = 17; 12800 // }; 12801 12802 // C++ [class.mem]p4: 12803 // A member-declarator can contain a constant-initializer only 12804 // if it declares a static member (9.4) of const integral or 12805 // const enumeration type, see 9.4.2. 12806 // 12807 // C++11 [class.static.data]p3: 12808 // If a non-volatile non-inline const static data member is of integral 12809 // or enumeration type, its declaration in the class definition can 12810 // specify a brace-or-equal-initializer in which every initializer-clause 12811 // that is an assignment-expression is a constant expression. A static 12812 // data member of literal type can be declared in the class definition 12813 // with the constexpr specifier; if so, its declaration shall specify a 12814 // brace-or-equal-initializer in which every initializer-clause that is 12815 // an assignment-expression is a constant expression. 12816 12817 // Do nothing on dependent types. 12818 if (DclT->isDependentType()) { 12819 12820 // Allow any 'static constexpr' members, whether or not they are of literal 12821 // type. We separately check that every constexpr variable is of literal 12822 // type. 12823 } else if (VDecl->isConstexpr()) { 12824 12825 // Require constness. 12826 } else if (!DclT.isConstQualified()) { 12827 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12828 << Init->getSourceRange(); 12829 VDecl->setInvalidDecl(); 12830 12831 // We allow integer constant expressions in all cases. 12832 } else if (DclT->isIntegralOrEnumerationType()) { 12833 // Check whether the expression is a constant expression. 12834 SourceLocation Loc; 12835 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12836 // In C++11, a non-constexpr const static data member with an 12837 // in-class initializer cannot be volatile. 12838 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12839 else if (Init->isValueDependent()) 12840 ; // Nothing to check. 12841 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12842 ; // Ok, it's an ICE! 12843 else if (Init->getType()->isScopedEnumeralType() && 12844 Init->isCXX11ConstantExpr(Context)) 12845 ; // Ok, it is a scoped-enum constant expression. 12846 else if (Init->isEvaluatable(Context)) { 12847 // If we can constant fold the initializer through heroics, accept it, 12848 // but report this as a use of an extension for -pedantic. 12849 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12850 << Init->getSourceRange(); 12851 } else { 12852 // Otherwise, this is some crazy unknown case. Report the issue at the 12853 // location provided by the isIntegerConstantExpr failed check. 12854 Diag(Loc, diag::err_in_class_initializer_non_constant) 12855 << Init->getSourceRange(); 12856 VDecl->setInvalidDecl(); 12857 } 12858 12859 // We allow foldable floating-point constants as an extension. 12860 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12861 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12862 // it anyway and provide a fixit to add the 'constexpr'. 12863 if (getLangOpts().CPlusPlus11) { 12864 Diag(VDecl->getLocation(), 12865 diag::ext_in_class_initializer_float_type_cxx11) 12866 << DclT << Init->getSourceRange(); 12867 Diag(VDecl->getBeginLoc(), 12868 diag::note_in_class_initializer_float_type_cxx11) 12869 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12870 } else { 12871 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12872 << DclT << Init->getSourceRange(); 12873 12874 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12875 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12876 << Init->getSourceRange(); 12877 VDecl->setInvalidDecl(); 12878 } 12879 } 12880 12881 // Suggest adding 'constexpr' in C++11 for literal types. 12882 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12883 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12884 << DclT << Init->getSourceRange() 12885 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12886 VDecl->setConstexpr(true); 12887 12888 } else { 12889 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12890 << DclT << Init->getSourceRange(); 12891 VDecl->setInvalidDecl(); 12892 } 12893 } else if (VDecl->isFileVarDecl()) { 12894 // In C, extern is typically used to avoid tentative definitions when 12895 // declaring variables in headers, but adding an intializer makes it a 12896 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12897 // In C++, extern is often used to give implictly static const variables 12898 // external linkage, so don't warn in that case. If selectany is present, 12899 // this might be header code intended for C and C++ inclusion, so apply the 12900 // C++ rules. 12901 if (VDecl->getStorageClass() == SC_Extern && 12902 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12903 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12904 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12905 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12906 Diag(VDecl->getLocation(), diag::warn_extern_init); 12907 12908 // In Microsoft C++ mode, a const variable defined in namespace scope has 12909 // external linkage by default if the variable is declared with 12910 // __declspec(dllexport). 12911 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12912 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12913 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12914 VDecl->setStorageClass(SC_Extern); 12915 12916 // C99 6.7.8p4. All file scoped initializers need to be constant. 12917 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12918 CheckForConstantInitializer(Init, DclT); 12919 } 12920 12921 QualType InitType = Init->getType(); 12922 if (!InitType.isNull() && 12923 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12924 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12925 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12926 12927 // We will represent direct-initialization similarly to copy-initialization: 12928 // int x(1); -as-> int x = 1; 12929 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12930 // 12931 // Clients that want to distinguish between the two forms, can check for 12932 // direct initializer using VarDecl::getInitStyle(). 12933 // A major benefit is that clients that don't particularly care about which 12934 // exactly form was it (like the CodeGen) can handle both cases without 12935 // special case code. 12936 12937 // C++ 8.5p11: 12938 // The form of initialization (using parentheses or '=') is generally 12939 // insignificant, but does matter when the entity being initialized has a 12940 // class type. 12941 if (CXXDirectInit) { 12942 assert(DirectInit && "Call-style initializer must be direct init."); 12943 VDecl->setInitStyle(VarDecl::CallInit); 12944 } else if (DirectInit) { 12945 // This must be list-initialization. No other way is direct-initialization. 12946 VDecl->setInitStyle(VarDecl::ListInit); 12947 } 12948 12949 if (LangOpts.OpenMP && 12950 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 12951 VDecl->isFileVarDecl()) 12952 DeclsToCheckForDeferredDiags.insert(VDecl); 12953 CheckCompleteVariableDeclaration(VDecl); 12954 } 12955 12956 /// ActOnInitializerError - Given that there was an error parsing an 12957 /// initializer for the given declaration, try to at least re-establish 12958 /// invariants such as whether a variable's type is either dependent or 12959 /// complete. 12960 void Sema::ActOnInitializerError(Decl *D) { 12961 // Our main concern here is re-establishing invariants like "a 12962 // variable's type is either dependent or complete". 12963 if (!D || D->isInvalidDecl()) return; 12964 12965 VarDecl *VD = dyn_cast<VarDecl>(D); 12966 if (!VD) return; 12967 12968 // Bindings are not usable if we can't make sense of the initializer. 12969 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12970 for (auto *BD : DD->bindings()) 12971 BD->setInvalidDecl(); 12972 12973 // Auto types are meaningless if we can't make sense of the initializer. 12974 if (VD->getType()->isUndeducedType()) { 12975 D->setInvalidDecl(); 12976 return; 12977 } 12978 12979 QualType Ty = VD->getType(); 12980 if (Ty->isDependentType()) return; 12981 12982 // Require a complete type. 12983 if (RequireCompleteType(VD->getLocation(), 12984 Context.getBaseElementType(Ty), 12985 diag::err_typecheck_decl_incomplete_type)) { 12986 VD->setInvalidDecl(); 12987 return; 12988 } 12989 12990 // Require a non-abstract type. 12991 if (RequireNonAbstractType(VD->getLocation(), Ty, 12992 diag::err_abstract_type_in_decl, 12993 AbstractVariableType)) { 12994 VD->setInvalidDecl(); 12995 return; 12996 } 12997 12998 // Don't bother complaining about constructors or destructors, 12999 // though. 13000 } 13001 13002 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 13003 // If there is no declaration, there was an error parsing it. Just ignore it. 13004 if (!RealDecl) 13005 return; 13006 13007 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 13008 QualType Type = Var->getType(); 13009 13010 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 13011 if (isa<DecompositionDecl>(RealDecl)) { 13012 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 13013 Var->setInvalidDecl(); 13014 return; 13015 } 13016 13017 if (Type->isUndeducedType() && 13018 DeduceVariableDeclarationType(Var, false, nullptr)) 13019 return; 13020 13021 // C++11 [class.static.data]p3: A static data member can be declared with 13022 // the constexpr specifier; if so, its declaration shall specify 13023 // a brace-or-equal-initializer. 13024 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 13025 // the definition of a variable [...] or the declaration of a static data 13026 // member. 13027 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 13028 !Var->isThisDeclarationADemotedDefinition()) { 13029 if (Var->isStaticDataMember()) { 13030 // C++1z removes the relevant rule; the in-class declaration is always 13031 // a definition there. 13032 if (!getLangOpts().CPlusPlus17 && 13033 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13034 Diag(Var->getLocation(), 13035 diag::err_constexpr_static_mem_var_requires_init) 13036 << Var; 13037 Var->setInvalidDecl(); 13038 return; 13039 } 13040 } else { 13041 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 13042 Var->setInvalidDecl(); 13043 return; 13044 } 13045 } 13046 13047 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 13048 // be initialized. 13049 if (!Var->isInvalidDecl() && 13050 Var->getType().getAddressSpace() == LangAS::opencl_constant && 13051 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 13052 bool HasConstExprDefaultConstructor = false; 13053 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13054 for (auto *Ctor : RD->ctors()) { 13055 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 13056 Ctor->getMethodQualifiers().getAddressSpace() == 13057 LangAS::opencl_constant) { 13058 HasConstExprDefaultConstructor = true; 13059 } 13060 } 13061 } 13062 if (!HasConstExprDefaultConstructor) { 13063 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 13064 Var->setInvalidDecl(); 13065 return; 13066 } 13067 } 13068 13069 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 13070 if (Var->getStorageClass() == SC_Extern) { 13071 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 13072 << Var; 13073 Var->setInvalidDecl(); 13074 return; 13075 } 13076 if (RequireCompleteType(Var->getLocation(), Var->getType(), 13077 diag::err_typecheck_decl_incomplete_type)) { 13078 Var->setInvalidDecl(); 13079 return; 13080 } 13081 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13082 if (!RD->hasTrivialDefaultConstructor()) { 13083 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 13084 Var->setInvalidDecl(); 13085 return; 13086 } 13087 } 13088 // The declaration is unitialized, no need for further checks. 13089 return; 13090 } 13091 13092 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 13093 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 13094 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13095 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 13096 NTCUC_DefaultInitializedObject, NTCUK_Init); 13097 13098 13099 switch (DefKind) { 13100 case VarDecl::Definition: 13101 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 13102 break; 13103 13104 // We have an out-of-line definition of a static data member 13105 // that has an in-class initializer, so we type-check this like 13106 // a declaration. 13107 // 13108 LLVM_FALLTHROUGH; 13109 13110 case VarDecl::DeclarationOnly: 13111 // It's only a declaration. 13112 13113 // Block scope. C99 6.7p7: If an identifier for an object is 13114 // declared with no linkage (C99 6.2.2p6), the type for the 13115 // object shall be complete. 13116 if (!Type->isDependentType() && Var->isLocalVarDecl() && 13117 !Var->hasLinkage() && !Var->isInvalidDecl() && 13118 RequireCompleteType(Var->getLocation(), Type, 13119 diag::err_typecheck_decl_incomplete_type)) 13120 Var->setInvalidDecl(); 13121 13122 // Make sure that the type is not abstract. 13123 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13124 RequireNonAbstractType(Var->getLocation(), Type, 13125 diag::err_abstract_type_in_decl, 13126 AbstractVariableType)) 13127 Var->setInvalidDecl(); 13128 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13129 Var->getStorageClass() == SC_PrivateExtern) { 13130 Diag(Var->getLocation(), diag::warn_private_extern); 13131 Diag(Var->getLocation(), diag::note_private_extern); 13132 } 13133 13134 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 13135 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 13136 ExternalDeclarations.push_back(Var); 13137 13138 return; 13139 13140 case VarDecl::TentativeDefinition: 13141 // File scope. C99 6.9.2p2: A declaration of an identifier for an 13142 // object that has file scope without an initializer, and without a 13143 // storage-class specifier or with the storage-class specifier "static", 13144 // constitutes a tentative definition. Note: A tentative definition with 13145 // external linkage is valid (C99 6.2.2p5). 13146 if (!Var->isInvalidDecl()) { 13147 if (const IncompleteArrayType *ArrayT 13148 = Context.getAsIncompleteArrayType(Type)) { 13149 if (RequireCompleteSizedType( 13150 Var->getLocation(), ArrayT->getElementType(), 13151 diag::err_array_incomplete_or_sizeless_type)) 13152 Var->setInvalidDecl(); 13153 } else if (Var->getStorageClass() == SC_Static) { 13154 // C99 6.9.2p3: If the declaration of an identifier for an object is 13155 // a tentative definition and has internal linkage (C99 6.2.2p3), the 13156 // declared type shall not be an incomplete type. 13157 // NOTE: code such as the following 13158 // static struct s; 13159 // struct s { int a; }; 13160 // is accepted by gcc. Hence here we issue a warning instead of 13161 // an error and we do not invalidate the static declaration. 13162 // NOTE: to avoid multiple warnings, only check the first declaration. 13163 if (Var->isFirstDecl()) 13164 RequireCompleteType(Var->getLocation(), Type, 13165 diag::ext_typecheck_decl_incomplete_type); 13166 } 13167 } 13168 13169 // Record the tentative definition; we're done. 13170 if (!Var->isInvalidDecl()) 13171 TentativeDefinitions.push_back(Var); 13172 return; 13173 } 13174 13175 // Provide a specific diagnostic for uninitialized variable 13176 // definitions with incomplete array type. 13177 if (Type->isIncompleteArrayType()) { 13178 Diag(Var->getLocation(), 13179 diag::err_typecheck_incomplete_array_needs_initializer); 13180 Var->setInvalidDecl(); 13181 return; 13182 } 13183 13184 // Provide a specific diagnostic for uninitialized variable 13185 // definitions with reference type. 13186 if (Type->isReferenceType()) { 13187 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 13188 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 13189 Var->setInvalidDecl(); 13190 return; 13191 } 13192 13193 // Do not attempt to type-check the default initializer for a 13194 // variable with dependent type. 13195 if (Type->isDependentType()) 13196 return; 13197 13198 if (Var->isInvalidDecl()) 13199 return; 13200 13201 if (!Var->hasAttr<AliasAttr>()) { 13202 if (RequireCompleteType(Var->getLocation(), 13203 Context.getBaseElementType(Type), 13204 diag::err_typecheck_decl_incomplete_type)) { 13205 Var->setInvalidDecl(); 13206 return; 13207 } 13208 } else { 13209 return; 13210 } 13211 13212 // The variable can not have an abstract class type. 13213 if (RequireNonAbstractType(Var->getLocation(), Type, 13214 diag::err_abstract_type_in_decl, 13215 AbstractVariableType)) { 13216 Var->setInvalidDecl(); 13217 return; 13218 } 13219 13220 // Check for jumps past the implicit initializer. C++0x 13221 // clarifies that this applies to a "variable with automatic 13222 // storage duration", not a "local variable". 13223 // C++11 [stmt.dcl]p3 13224 // A program that jumps from a point where a variable with automatic 13225 // storage duration is not in scope to a point where it is in scope is 13226 // ill-formed unless the variable has scalar type, class type with a 13227 // trivial default constructor and a trivial destructor, a cv-qualified 13228 // version of one of these types, or an array of one of the preceding 13229 // types and is declared without an initializer. 13230 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 13231 if (const RecordType *Record 13232 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 13233 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 13234 // Mark the function (if we're in one) for further checking even if the 13235 // looser rules of C++11 do not require such checks, so that we can 13236 // diagnose incompatibilities with C++98. 13237 if (!CXXRecord->isPOD()) 13238 setFunctionHasBranchProtectedScope(); 13239 } 13240 } 13241 // In OpenCL, we can't initialize objects in the __local address space, 13242 // even implicitly, so don't synthesize an implicit initializer. 13243 if (getLangOpts().OpenCL && 13244 Var->getType().getAddressSpace() == LangAS::opencl_local) 13245 return; 13246 // C++03 [dcl.init]p9: 13247 // If no initializer is specified for an object, and the 13248 // object is of (possibly cv-qualified) non-POD class type (or 13249 // array thereof), the object shall be default-initialized; if 13250 // the object is of const-qualified type, the underlying class 13251 // type shall have a user-declared default 13252 // constructor. Otherwise, if no initializer is specified for 13253 // a non- static object, the object and its subobjects, if 13254 // any, have an indeterminate initial value); if the object 13255 // or any of its subobjects are of const-qualified type, the 13256 // program is ill-formed. 13257 // C++0x [dcl.init]p11: 13258 // If no initializer is specified for an object, the object is 13259 // default-initialized; [...]. 13260 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 13261 InitializationKind Kind 13262 = InitializationKind::CreateDefault(Var->getLocation()); 13263 13264 InitializationSequence InitSeq(*this, Entity, Kind, None); 13265 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 13266 13267 if (Init.get()) { 13268 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 13269 // This is important for template substitution. 13270 Var->setInitStyle(VarDecl::CallInit); 13271 } else if (Init.isInvalid()) { 13272 // If default-init fails, attach a recovery-expr initializer to track 13273 // that initialization was attempted and failed. 13274 auto RecoveryExpr = 13275 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 13276 if (RecoveryExpr.get()) 13277 Var->setInit(RecoveryExpr.get()); 13278 } 13279 13280 CheckCompleteVariableDeclaration(Var); 13281 } 13282 } 13283 13284 void Sema::ActOnCXXForRangeDecl(Decl *D) { 13285 // If there is no declaration, there was an error parsing it. Ignore it. 13286 if (!D) 13287 return; 13288 13289 VarDecl *VD = dyn_cast<VarDecl>(D); 13290 if (!VD) { 13291 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 13292 D->setInvalidDecl(); 13293 return; 13294 } 13295 13296 VD->setCXXForRangeDecl(true); 13297 13298 // for-range-declaration cannot be given a storage class specifier. 13299 int Error = -1; 13300 switch (VD->getStorageClass()) { 13301 case SC_None: 13302 break; 13303 case SC_Extern: 13304 Error = 0; 13305 break; 13306 case SC_Static: 13307 Error = 1; 13308 break; 13309 case SC_PrivateExtern: 13310 Error = 2; 13311 break; 13312 case SC_Auto: 13313 Error = 3; 13314 break; 13315 case SC_Register: 13316 Error = 4; 13317 break; 13318 } 13319 13320 // for-range-declaration cannot be given a storage class specifier con't. 13321 switch (VD->getTSCSpec()) { 13322 case TSCS_thread_local: 13323 Error = 6; 13324 break; 13325 case TSCS___thread: 13326 case TSCS__Thread_local: 13327 case TSCS_unspecified: 13328 break; 13329 } 13330 13331 if (Error != -1) { 13332 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 13333 << VD << Error; 13334 D->setInvalidDecl(); 13335 } 13336 } 13337 13338 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13339 IdentifierInfo *Ident, 13340 ParsedAttributes &Attrs) { 13341 // C++1y [stmt.iter]p1: 13342 // A range-based for statement of the form 13343 // for ( for-range-identifier : for-range-initializer ) statement 13344 // is equivalent to 13345 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13346 DeclSpec DS(Attrs.getPool().getFactory()); 13347 13348 const char *PrevSpec; 13349 unsigned DiagID; 13350 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13351 getPrintingPolicy()); 13352 13353 Declarator D(DS, DeclaratorContext::ForInit); 13354 D.SetIdentifier(Ident, IdentLoc); 13355 D.takeAttributes(Attrs); 13356 13357 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13358 IdentLoc); 13359 Decl *Var = ActOnDeclarator(S, D); 13360 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13361 FinalizeDeclaration(Var); 13362 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13363 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 13364 : IdentLoc); 13365 } 13366 13367 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13368 if (var->isInvalidDecl()) return; 13369 13370 MaybeAddCUDAConstantAttr(var); 13371 13372 if (getLangOpts().OpenCL) { 13373 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13374 // initialiser 13375 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13376 !var->hasInit()) { 13377 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13378 << 1 /*Init*/; 13379 var->setInvalidDecl(); 13380 return; 13381 } 13382 } 13383 13384 // In Objective-C, don't allow jumps past the implicit initialization of a 13385 // local retaining variable. 13386 if (getLangOpts().ObjC && 13387 var->hasLocalStorage()) { 13388 switch (var->getType().getObjCLifetime()) { 13389 case Qualifiers::OCL_None: 13390 case Qualifiers::OCL_ExplicitNone: 13391 case Qualifiers::OCL_Autoreleasing: 13392 break; 13393 13394 case Qualifiers::OCL_Weak: 13395 case Qualifiers::OCL_Strong: 13396 setFunctionHasBranchProtectedScope(); 13397 break; 13398 } 13399 } 13400 13401 if (var->hasLocalStorage() && 13402 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13403 setFunctionHasBranchProtectedScope(); 13404 13405 // Warn about externally-visible variables being defined without a 13406 // prior declaration. We only want to do this for global 13407 // declarations, but we also specifically need to avoid doing it for 13408 // class members because the linkage of an anonymous class can 13409 // change if it's later given a typedef name. 13410 if (var->isThisDeclarationADefinition() && 13411 var->getDeclContext()->getRedeclContext()->isFileContext() && 13412 var->isExternallyVisible() && var->hasLinkage() && 13413 !var->isInline() && !var->getDescribedVarTemplate() && 13414 !isa<VarTemplatePartialSpecializationDecl>(var) && 13415 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13416 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13417 var->getLocation())) { 13418 // Find a previous declaration that's not a definition. 13419 VarDecl *prev = var->getPreviousDecl(); 13420 while (prev && prev->isThisDeclarationADefinition()) 13421 prev = prev->getPreviousDecl(); 13422 13423 if (!prev) { 13424 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13425 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13426 << /* variable */ 0; 13427 } 13428 } 13429 13430 // Cache the result of checking for constant initialization. 13431 Optional<bool> CacheHasConstInit; 13432 const Expr *CacheCulprit = nullptr; 13433 auto checkConstInit = [&]() mutable { 13434 if (!CacheHasConstInit) 13435 CacheHasConstInit = var->getInit()->isConstantInitializer( 13436 Context, var->getType()->isReferenceType(), &CacheCulprit); 13437 return *CacheHasConstInit; 13438 }; 13439 13440 if (var->getTLSKind() == VarDecl::TLS_Static) { 13441 if (var->getType().isDestructedType()) { 13442 // GNU C++98 edits for __thread, [basic.start.term]p3: 13443 // The type of an object with thread storage duration shall not 13444 // have a non-trivial destructor. 13445 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13446 if (getLangOpts().CPlusPlus11) 13447 Diag(var->getLocation(), diag::note_use_thread_local); 13448 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13449 if (!checkConstInit()) { 13450 // GNU C++98 edits for __thread, [basic.start.init]p4: 13451 // An object of thread storage duration shall not require dynamic 13452 // initialization. 13453 // FIXME: Need strict checking here. 13454 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13455 << CacheCulprit->getSourceRange(); 13456 if (getLangOpts().CPlusPlus11) 13457 Diag(var->getLocation(), diag::note_use_thread_local); 13458 } 13459 } 13460 } 13461 13462 13463 if (!var->getType()->isStructureType() && var->hasInit() && 13464 isa<InitListExpr>(var->getInit())) { 13465 const auto *ILE = cast<InitListExpr>(var->getInit()); 13466 unsigned NumInits = ILE->getNumInits(); 13467 if (NumInits > 2) 13468 for (unsigned I = 0; I < NumInits; ++I) { 13469 const auto *Init = ILE->getInit(I); 13470 if (!Init) 13471 break; 13472 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13473 if (!SL) 13474 break; 13475 13476 unsigned NumConcat = SL->getNumConcatenated(); 13477 // Diagnose missing comma in string array initialization. 13478 // Do not warn when all the elements in the initializer are concatenated 13479 // together. Do not warn for macros too. 13480 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13481 bool OnlyOneMissingComma = true; 13482 for (unsigned J = I + 1; J < NumInits; ++J) { 13483 const auto *Init = ILE->getInit(J); 13484 if (!Init) 13485 break; 13486 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13487 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13488 OnlyOneMissingComma = false; 13489 break; 13490 } 13491 } 13492 13493 if (OnlyOneMissingComma) { 13494 SmallVector<FixItHint, 1> Hints; 13495 for (unsigned i = 0; i < NumConcat - 1; ++i) 13496 Hints.push_back(FixItHint::CreateInsertion( 13497 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13498 13499 Diag(SL->getStrTokenLoc(1), 13500 diag::warn_concatenated_literal_array_init) 13501 << Hints; 13502 Diag(SL->getBeginLoc(), 13503 diag::note_concatenated_string_literal_silence); 13504 } 13505 // In any case, stop now. 13506 break; 13507 } 13508 } 13509 } 13510 13511 13512 QualType type = var->getType(); 13513 13514 if (var->hasAttr<BlocksAttr>()) 13515 getCurFunction()->addByrefBlockVar(var); 13516 13517 Expr *Init = var->getInit(); 13518 bool GlobalStorage = var->hasGlobalStorage(); 13519 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13520 QualType baseType = Context.getBaseElementType(type); 13521 bool HasConstInit = true; 13522 13523 // Check whether the initializer is sufficiently constant. 13524 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13525 !Init->isValueDependent() && 13526 (GlobalStorage || var->isConstexpr() || 13527 var->mightBeUsableInConstantExpressions(Context))) { 13528 // If this variable might have a constant initializer or might be usable in 13529 // constant expressions, check whether or not it actually is now. We can't 13530 // do this lazily, because the result might depend on things that change 13531 // later, such as which constexpr functions happen to be defined. 13532 SmallVector<PartialDiagnosticAt, 8> Notes; 13533 if (!getLangOpts().CPlusPlus11) { 13534 // Prior to C++11, in contexts where a constant initializer is required, 13535 // the set of valid constant initializers is described by syntactic rules 13536 // in [expr.const]p2-6. 13537 // FIXME: Stricter checking for these rules would be useful for constinit / 13538 // -Wglobal-constructors. 13539 HasConstInit = checkConstInit(); 13540 13541 // Compute and cache the constant value, and remember that we have a 13542 // constant initializer. 13543 if (HasConstInit) { 13544 (void)var->checkForConstantInitialization(Notes); 13545 Notes.clear(); 13546 } else if (CacheCulprit) { 13547 Notes.emplace_back(CacheCulprit->getExprLoc(), 13548 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13549 Notes.back().second << CacheCulprit->getSourceRange(); 13550 } 13551 } else { 13552 // Evaluate the initializer to see if it's a constant initializer. 13553 HasConstInit = var->checkForConstantInitialization(Notes); 13554 } 13555 13556 if (HasConstInit) { 13557 // FIXME: Consider replacing the initializer with a ConstantExpr. 13558 } else if (var->isConstexpr()) { 13559 SourceLocation DiagLoc = var->getLocation(); 13560 // If the note doesn't add any useful information other than a source 13561 // location, fold it into the primary diagnostic. 13562 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13563 diag::note_invalid_subexpr_in_const_expr) { 13564 DiagLoc = Notes[0].first; 13565 Notes.clear(); 13566 } 13567 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13568 << var << Init->getSourceRange(); 13569 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13570 Diag(Notes[I].first, Notes[I].second); 13571 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13572 auto *Attr = var->getAttr<ConstInitAttr>(); 13573 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13574 << Init->getSourceRange(); 13575 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13576 << Attr->getRange() << Attr->isConstinit(); 13577 for (auto &it : Notes) 13578 Diag(it.first, it.second); 13579 } else if (IsGlobal && 13580 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13581 var->getLocation())) { 13582 // Warn about globals which don't have a constant initializer. Don't 13583 // warn about globals with a non-trivial destructor because we already 13584 // warned about them. 13585 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13586 if (!(RD && !RD->hasTrivialDestructor())) { 13587 // checkConstInit() here permits trivial default initialization even in 13588 // C++11 onwards, where such an initializer is not a constant initializer 13589 // but nonetheless doesn't require a global constructor. 13590 if (!checkConstInit()) 13591 Diag(var->getLocation(), diag::warn_global_constructor) 13592 << Init->getSourceRange(); 13593 } 13594 } 13595 } 13596 13597 // Apply section attributes and pragmas to global variables. 13598 if (GlobalStorage && var->isThisDeclarationADefinition() && 13599 !inTemplateInstantiation()) { 13600 PragmaStack<StringLiteral *> *Stack = nullptr; 13601 int SectionFlags = ASTContext::PSF_Read; 13602 if (var->getType().isConstQualified()) { 13603 if (HasConstInit) 13604 Stack = &ConstSegStack; 13605 else { 13606 Stack = &BSSSegStack; 13607 SectionFlags |= ASTContext::PSF_Write; 13608 } 13609 } else if (var->hasInit() && HasConstInit) { 13610 Stack = &DataSegStack; 13611 SectionFlags |= ASTContext::PSF_Write; 13612 } else { 13613 Stack = &BSSSegStack; 13614 SectionFlags |= ASTContext::PSF_Write; 13615 } 13616 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13617 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13618 SectionFlags |= ASTContext::PSF_Implicit; 13619 UnifySection(SA->getName(), SectionFlags, var); 13620 } else if (Stack->CurrentValue) { 13621 SectionFlags |= ASTContext::PSF_Implicit; 13622 auto SectionName = Stack->CurrentValue->getString(); 13623 var->addAttr(SectionAttr::CreateImplicit( 13624 Context, SectionName, Stack->CurrentPragmaLocation, 13625 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13626 if (UnifySection(SectionName, SectionFlags, var)) 13627 var->dropAttr<SectionAttr>(); 13628 } 13629 13630 // Apply the init_seg attribute if this has an initializer. If the 13631 // initializer turns out to not be dynamic, we'll end up ignoring this 13632 // attribute. 13633 if (CurInitSeg && var->getInit()) 13634 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13635 CurInitSegLoc, 13636 AttributeCommonInfo::AS_Pragma)); 13637 } 13638 13639 // All the following checks are C++ only. 13640 if (!getLangOpts().CPlusPlus) { 13641 // If this variable must be emitted, add it as an initializer for the 13642 // current module. 13643 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13644 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13645 return; 13646 } 13647 13648 // Require the destructor. 13649 if (!type->isDependentType()) 13650 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13651 FinalizeVarWithDestructor(var, recordType); 13652 13653 // If this variable must be emitted, add it as an initializer for the current 13654 // module. 13655 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13656 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13657 13658 // Build the bindings if this is a structured binding declaration. 13659 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13660 CheckCompleteDecompositionDeclaration(DD); 13661 } 13662 13663 /// Check if VD needs to be dllexport/dllimport due to being in a 13664 /// dllexport/import function. 13665 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13666 assert(VD->isStaticLocal()); 13667 13668 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13669 13670 // Find outermost function when VD is in lambda function. 13671 while (FD && !getDLLAttr(FD) && 13672 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13673 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13674 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13675 } 13676 13677 if (!FD) 13678 return; 13679 13680 // Static locals inherit dll attributes from their function. 13681 if (Attr *A = getDLLAttr(FD)) { 13682 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13683 NewAttr->setInherited(true); 13684 VD->addAttr(NewAttr); 13685 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13686 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13687 NewAttr->setInherited(true); 13688 VD->addAttr(NewAttr); 13689 13690 // Export this function to enforce exporting this static variable even 13691 // if it is not used in this compilation unit. 13692 if (!FD->hasAttr<DLLExportAttr>()) 13693 FD->addAttr(NewAttr); 13694 13695 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13696 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13697 NewAttr->setInherited(true); 13698 VD->addAttr(NewAttr); 13699 } 13700 } 13701 13702 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13703 /// any semantic actions necessary after any initializer has been attached. 13704 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13705 // Note that we are no longer parsing the initializer for this declaration. 13706 ParsingInitForAutoVars.erase(ThisDecl); 13707 13708 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13709 if (!VD) 13710 return; 13711 13712 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13713 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13714 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13715 if (PragmaClangBSSSection.Valid) 13716 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13717 Context, PragmaClangBSSSection.SectionName, 13718 PragmaClangBSSSection.PragmaLocation, 13719 AttributeCommonInfo::AS_Pragma)); 13720 if (PragmaClangDataSection.Valid) 13721 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13722 Context, PragmaClangDataSection.SectionName, 13723 PragmaClangDataSection.PragmaLocation, 13724 AttributeCommonInfo::AS_Pragma)); 13725 if (PragmaClangRodataSection.Valid) 13726 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13727 Context, PragmaClangRodataSection.SectionName, 13728 PragmaClangRodataSection.PragmaLocation, 13729 AttributeCommonInfo::AS_Pragma)); 13730 if (PragmaClangRelroSection.Valid) 13731 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13732 Context, PragmaClangRelroSection.SectionName, 13733 PragmaClangRelroSection.PragmaLocation, 13734 AttributeCommonInfo::AS_Pragma)); 13735 } 13736 13737 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13738 for (auto *BD : DD->bindings()) { 13739 FinalizeDeclaration(BD); 13740 } 13741 } 13742 13743 checkAttributesAfterMerging(*this, *VD); 13744 13745 // Perform TLS alignment check here after attributes attached to the variable 13746 // which may affect the alignment have been processed. Only perform the check 13747 // if the target has a maximum TLS alignment (zero means no constraints). 13748 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13749 // Protect the check so that it's not performed on dependent types and 13750 // dependent alignments (we can't determine the alignment in that case). 13751 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13752 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13753 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13754 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13755 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13756 << (unsigned)MaxAlignChars.getQuantity(); 13757 } 13758 } 13759 } 13760 13761 if (VD->isStaticLocal()) 13762 CheckStaticLocalForDllExport(VD); 13763 13764 // Perform check for initializers of device-side global variables. 13765 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13766 // 7.5). We must also apply the same checks to all __shared__ 13767 // variables whether they are local or not. CUDA also allows 13768 // constant initializers for __constant__ and __device__ variables. 13769 if (getLangOpts().CUDA) 13770 checkAllowedCUDAInitializer(VD); 13771 13772 // Grab the dllimport or dllexport attribute off of the VarDecl. 13773 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13774 13775 // Imported static data members cannot be defined out-of-line. 13776 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13777 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13778 VD->isThisDeclarationADefinition()) { 13779 // We allow definitions of dllimport class template static data members 13780 // with a warning. 13781 CXXRecordDecl *Context = 13782 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13783 bool IsClassTemplateMember = 13784 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13785 Context->getDescribedClassTemplate(); 13786 13787 Diag(VD->getLocation(), 13788 IsClassTemplateMember 13789 ? diag::warn_attribute_dllimport_static_field_definition 13790 : diag::err_attribute_dllimport_static_field_definition); 13791 Diag(IA->getLocation(), diag::note_attribute); 13792 if (!IsClassTemplateMember) 13793 VD->setInvalidDecl(); 13794 } 13795 } 13796 13797 // dllimport/dllexport variables cannot be thread local, their TLS index 13798 // isn't exported with the variable. 13799 if (DLLAttr && VD->getTLSKind()) { 13800 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13801 if (F && getDLLAttr(F)) { 13802 assert(VD->isStaticLocal()); 13803 // But if this is a static local in a dlimport/dllexport function, the 13804 // function will never be inlined, which means the var would never be 13805 // imported, so having it marked import/export is safe. 13806 } else { 13807 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13808 << DLLAttr; 13809 VD->setInvalidDecl(); 13810 } 13811 } 13812 13813 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13814 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13815 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13816 << Attr; 13817 VD->dropAttr<UsedAttr>(); 13818 } 13819 } 13820 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13821 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13822 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13823 << Attr; 13824 VD->dropAttr<RetainAttr>(); 13825 } 13826 } 13827 13828 const DeclContext *DC = VD->getDeclContext(); 13829 // If there's a #pragma GCC visibility in scope, and this isn't a class 13830 // member, set the visibility of this variable. 13831 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13832 AddPushedVisibilityAttribute(VD); 13833 13834 // FIXME: Warn on unused var template partial specializations. 13835 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13836 MarkUnusedFileScopedDecl(VD); 13837 13838 // Now we have parsed the initializer and can update the table of magic 13839 // tag values. 13840 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13841 !VD->getType()->isIntegralOrEnumerationType()) 13842 return; 13843 13844 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13845 const Expr *MagicValueExpr = VD->getInit(); 13846 if (!MagicValueExpr) { 13847 continue; 13848 } 13849 Optional<llvm::APSInt> MagicValueInt; 13850 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13851 Diag(I->getRange().getBegin(), 13852 diag::err_type_tag_for_datatype_not_ice) 13853 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13854 continue; 13855 } 13856 if (MagicValueInt->getActiveBits() > 64) { 13857 Diag(I->getRange().getBegin(), 13858 diag::err_type_tag_for_datatype_too_large) 13859 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13860 continue; 13861 } 13862 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13863 RegisterTypeTagForDatatype(I->getArgumentKind(), 13864 MagicValue, 13865 I->getMatchingCType(), 13866 I->getLayoutCompatible(), 13867 I->getMustBeNull()); 13868 } 13869 } 13870 13871 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13872 auto *VD = dyn_cast<VarDecl>(DD); 13873 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13874 } 13875 13876 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13877 ArrayRef<Decl *> Group) { 13878 SmallVector<Decl*, 8> Decls; 13879 13880 if (DS.isTypeSpecOwned()) 13881 Decls.push_back(DS.getRepAsDecl()); 13882 13883 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13884 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13885 bool DiagnosedMultipleDecomps = false; 13886 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13887 bool DiagnosedNonDeducedAuto = false; 13888 13889 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13890 if (Decl *D = Group[i]) { 13891 // For declarators, there are some additional syntactic-ish checks we need 13892 // to perform. 13893 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13894 if (!FirstDeclaratorInGroup) 13895 FirstDeclaratorInGroup = DD; 13896 if (!FirstDecompDeclaratorInGroup) 13897 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13898 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13899 !hasDeducedAuto(DD)) 13900 FirstNonDeducedAutoInGroup = DD; 13901 13902 if (FirstDeclaratorInGroup != DD) { 13903 // A decomposition declaration cannot be combined with any other 13904 // declaration in the same group. 13905 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13906 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13907 diag::err_decomp_decl_not_alone) 13908 << FirstDeclaratorInGroup->getSourceRange() 13909 << DD->getSourceRange(); 13910 DiagnosedMultipleDecomps = true; 13911 } 13912 13913 // A declarator that uses 'auto' in any way other than to declare a 13914 // variable with a deduced type cannot be combined with any other 13915 // declarator in the same group. 13916 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13917 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13918 diag::err_auto_non_deduced_not_alone) 13919 << FirstNonDeducedAutoInGroup->getType() 13920 ->hasAutoForTrailingReturnType() 13921 << FirstDeclaratorInGroup->getSourceRange() 13922 << DD->getSourceRange(); 13923 DiagnosedNonDeducedAuto = true; 13924 } 13925 } 13926 } 13927 13928 Decls.push_back(D); 13929 } 13930 } 13931 13932 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13933 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13934 handleTagNumbering(Tag, S); 13935 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13936 getLangOpts().CPlusPlus) 13937 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13938 } 13939 } 13940 13941 return BuildDeclaratorGroup(Decls); 13942 } 13943 13944 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13945 /// group, performing any necessary semantic checking. 13946 Sema::DeclGroupPtrTy 13947 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13948 // C++14 [dcl.spec.auto]p7: (DR1347) 13949 // If the type that replaces the placeholder type is not the same in each 13950 // deduction, the program is ill-formed. 13951 if (Group.size() > 1) { 13952 QualType Deduced; 13953 VarDecl *DeducedDecl = nullptr; 13954 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13955 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13956 if (!D || D->isInvalidDecl()) 13957 break; 13958 DeducedType *DT = D->getType()->getContainedDeducedType(); 13959 if (!DT || DT->getDeducedType().isNull()) 13960 continue; 13961 if (Deduced.isNull()) { 13962 Deduced = DT->getDeducedType(); 13963 DeducedDecl = D; 13964 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13965 auto *AT = dyn_cast<AutoType>(DT); 13966 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13967 diag::err_auto_different_deductions) 13968 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13969 << DeducedDecl->getDeclName() << DT->getDeducedType() 13970 << D->getDeclName(); 13971 if (DeducedDecl->hasInit()) 13972 Dia << DeducedDecl->getInit()->getSourceRange(); 13973 if (D->getInit()) 13974 Dia << D->getInit()->getSourceRange(); 13975 D->setInvalidDecl(); 13976 break; 13977 } 13978 } 13979 } 13980 13981 ActOnDocumentableDecls(Group); 13982 13983 return DeclGroupPtrTy::make( 13984 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13985 } 13986 13987 void Sema::ActOnDocumentableDecl(Decl *D) { 13988 ActOnDocumentableDecls(D); 13989 } 13990 13991 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13992 // Don't parse the comment if Doxygen diagnostics are ignored. 13993 if (Group.empty() || !Group[0]) 13994 return; 13995 13996 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13997 Group[0]->getLocation()) && 13998 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13999 Group[0]->getLocation())) 14000 return; 14001 14002 if (Group.size() >= 2) { 14003 // This is a decl group. Normally it will contain only declarations 14004 // produced from declarator list. But in case we have any definitions or 14005 // additional declaration references: 14006 // 'typedef struct S {} S;' 14007 // 'typedef struct S *S;' 14008 // 'struct S *pS;' 14009 // FinalizeDeclaratorGroup adds these as separate declarations. 14010 Decl *MaybeTagDecl = Group[0]; 14011 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 14012 Group = Group.slice(1); 14013 } 14014 } 14015 14016 // FIMXE: We assume every Decl in the group is in the same file. 14017 // This is false when preprocessor constructs the group from decls in 14018 // different files (e. g. macros or #include). 14019 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 14020 } 14021 14022 /// Common checks for a parameter-declaration that should apply to both function 14023 /// parameters and non-type template parameters. 14024 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 14025 // Check that there are no default arguments inside the type of this 14026 // parameter. 14027 if (getLangOpts().CPlusPlus) 14028 CheckExtraCXXDefaultArguments(D); 14029 14030 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 14031 if (D.getCXXScopeSpec().isSet()) { 14032 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 14033 << D.getCXXScopeSpec().getRange(); 14034 } 14035 14036 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 14037 // simple identifier except [...irrelevant cases...]. 14038 switch (D.getName().getKind()) { 14039 case UnqualifiedIdKind::IK_Identifier: 14040 break; 14041 14042 case UnqualifiedIdKind::IK_OperatorFunctionId: 14043 case UnqualifiedIdKind::IK_ConversionFunctionId: 14044 case UnqualifiedIdKind::IK_LiteralOperatorId: 14045 case UnqualifiedIdKind::IK_ConstructorName: 14046 case UnqualifiedIdKind::IK_DestructorName: 14047 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14048 case UnqualifiedIdKind::IK_DeductionGuideName: 14049 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 14050 << GetNameForDeclarator(D).getName(); 14051 break; 14052 14053 case UnqualifiedIdKind::IK_TemplateId: 14054 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14055 // GetNameForDeclarator would not produce a useful name in this case. 14056 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 14057 break; 14058 } 14059 } 14060 14061 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 14062 /// to introduce parameters into function prototype scope. 14063 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 14064 const DeclSpec &DS = D.getDeclSpec(); 14065 14066 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 14067 14068 // C++03 [dcl.stc]p2 also permits 'auto'. 14069 StorageClass SC = SC_None; 14070 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 14071 SC = SC_Register; 14072 // In C++11, the 'register' storage class specifier is deprecated. 14073 // In C++17, it is not allowed, but we tolerate it as an extension. 14074 if (getLangOpts().CPlusPlus11) { 14075 Diag(DS.getStorageClassSpecLoc(), 14076 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 14077 : diag::warn_deprecated_register) 14078 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 14079 } 14080 } else if (getLangOpts().CPlusPlus && 14081 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 14082 SC = SC_Auto; 14083 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 14084 Diag(DS.getStorageClassSpecLoc(), 14085 diag::err_invalid_storage_class_in_func_decl); 14086 D.getMutableDeclSpec().ClearStorageClassSpecs(); 14087 } 14088 14089 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 14090 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 14091 << DeclSpec::getSpecifierName(TSCS); 14092 if (DS.isInlineSpecified()) 14093 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 14094 << getLangOpts().CPlusPlus17; 14095 if (DS.hasConstexprSpecifier()) 14096 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 14097 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 14098 14099 DiagnoseFunctionSpecifiers(DS); 14100 14101 CheckFunctionOrTemplateParamDeclarator(S, D); 14102 14103 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14104 QualType parmDeclType = TInfo->getType(); 14105 14106 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 14107 IdentifierInfo *II = D.getIdentifier(); 14108 if (II) { 14109 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 14110 ForVisibleRedeclaration); 14111 LookupName(R, S); 14112 if (R.isSingleResult()) { 14113 NamedDecl *PrevDecl = R.getFoundDecl(); 14114 if (PrevDecl->isTemplateParameter()) { 14115 // Maybe we will complain about the shadowed template parameter. 14116 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14117 // Just pretend that we didn't see the previous declaration. 14118 PrevDecl = nullptr; 14119 } else if (S->isDeclScope(PrevDecl)) { 14120 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 14121 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14122 14123 // Recover by removing the name 14124 II = nullptr; 14125 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 14126 D.setInvalidType(true); 14127 } 14128 } 14129 } 14130 14131 // Temporarily put parameter variables in the translation unit, not 14132 // the enclosing context. This prevents them from accidentally 14133 // looking like class members in C++. 14134 ParmVarDecl *New = 14135 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 14136 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 14137 14138 if (D.isInvalidType()) 14139 New->setInvalidDecl(); 14140 14141 assert(S->isFunctionPrototypeScope()); 14142 assert(S->getFunctionPrototypeDepth() >= 1); 14143 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 14144 S->getNextFunctionPrototypeIndex()); 14145 14146 // Add the parameter declaration into this scope. 14147 S->AddDecl(New); 14148 if (II) 14149 IdResolver.AddDecl(New); 14150 14151 ProcessDeclAttributes(S, New, D); 14152 14153 if (D.getDeclSpec().isModulePrivateSpecified()) 14154 Diag(New->getLocation(), diag::err_module_private_local) 14155 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14156 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14157 14158 if (New->hasAttr<BlocksAttr>()) { 14159 Diag(New->getLocation(), diag::err_block_on_nonlocal); 14160 } 14161 14162 if (getLangOpts().OpenCL) 14163 deduceOpenCLAddressSpace(New); 14164 14165 return New; 14166 } 14167 14168 /// Synthesizes a variable for a parameter arising from a 14169 /// typedef. 14170 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 14171 SourceLocation Loc, 14172 QualType T) { 14173 /* FIXME: setting StartLoc == Loc. 14174 Would it be worth to modify callers so as to provide proper source 14175 location for the unnamed parameters, embedding the parameter's type? */ 14176 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 14177 T, Context.getTrivialTypeSourceInfo(T, Loc), 14178 SC_None, nullptr); 14179 Param->setImplicit(); 14180 return Param; 14181 } 14182 14183 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 14184 // Don't diagnose unused-parameter errors in template instantiations; we 14185 // will already have done so in the template itself. 14186 if (inTemplateInstantiation()) 14187 return; 14188 14189 for (const ParmVarDecl *Parameter : Parameters) { 14190 if (!Parameter->isReferenced() && Parameter->getDeclName() && 14191 !Parameter->hasAttr<UnusedAttr>()) { 14192 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 14193 << Parameter->getDeclName(); 14194 } 14195 } 14196 } 14197 14198 void Sema::DiagnoseSizeOfParametersAndReturnValue( 14199 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 14200 if (LangOpts.NumLargeByValueCopy == 0) // No check. 14201 return; 14202 14203 // Warn if the return value is pass-by-value and larger than the specified 14204 // threshold. 14205 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 14206 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 14207 if (Size > LangOpts.NumLargeByValueCopy) 14208 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 14209 } 14210 14211 // Warn if any parameter is pass-by-value and larger than the specified 14212 // threshold. 14213 for (const ParmVarDecl *Parameter : Parameters) { 14214 QualType T = Parameter->getType(); 14215 if (T->isDependentType() || !T.isPODType(Context)) 14216 continue; 14217 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 14218 if (Size > LangOpts.NumLargeByValueCopy) 14219 Diag(Parameter->getLocation(), diag::warn_parameter_size) 14220 << Parameter << Size; 14221 } 14222 } 14223 14224 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 14225 SourceLocation NameLoc, IdentifierInfo *Name, 14226 QualType T, TypeSourceInfo *TSInfo, 14227 StorageClass SC) { 14228 // In ARC, infer a lifetime qualifier for appropriate parameter types. 14229 if (getLangOpts().ObjCAutoRefCount && 14230 T.getObjCLifetime() == Qualifiers::OCL_None && 14231 T->isObjCLifetimeType()) { 14232 14233 Qualifiers::ObjCLifetime lifetime; 14234 14235 // Special cases for arrays: 14236 // - if it's const, use __unsafe_unretained 14237 // - otherwise, it's an error 14238 if (T->isArrayType()) { 14239 if (!T.isConstQualified()) { 14240 if (DelayedDiagnostics.shouldDelayDiagnostics()) 14241 DelayedDiagnostics.add( 14242 sema::DelayedDiagnostic::makeForbiddenType( 14243 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 14244 else 14245 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 14246 << TSInfo->getTypeLoc().getSourceRange(); 14247 } 14248 lifetime = Qualifiers::OCL_ExplicitNone; 14249 } else { 14250 lifetime = T->getObjCARCImplicitLifetime(); 14251 } 14252 T = Context.getLifetimeQualifiedType(T, lifetime); 14253 } 14254 14255 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 14256 Context.getAdjustedParameterType(T), 14257 TSInfo, SC, nullptr); 14258 14259 // Make a note if we created a new pack in the scope of a lambda, so that 14260 // we know that references to that pack must also be expanded within the 14261 // lambda scope. 14262 if (New->isParameterPack()) 14263 if (auto *LSI = getEnclosingLambda()) 14264 LSI->LocalPacks.push_back(New); 14265 14266 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 14267 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14268 checkNonTrivialCUnion(New->getType(), New->getLocation(), 14269 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 14270 14271 // Parameters can not be abstract class types. 14272 // For record types, this is done by the AbstractClassUsageDiagnoser once 14273 // the class has been completely parsed. 14274 if (!CurContext->isRecord() && 14275 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 14276 AbstractParamType)) 14277 New->setInvalidDecl(); 14278 14279 // Parameter declarators cannot be interface types. All ObjC objects are 14280 // passed by reference. 14281 if (T->isObjCObjectType()) { 14282 SourceLocation TypeEndLoc = 14283 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 14284 Diag(NameLoc, 14285 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 14286 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 14287 T = Context.getObjCObjectPointerType(T); 14288 New->setType(T); 14289 } 14290 14291 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 14292 // duration shall not be qualified by an address-space qualifier." 14293 // Since all parameters have automatic store duration, they can not have 14294 // an address space. 14295 if (T.getAddressSpace() != LangAS::Default && 14296 // OpenCL allows function arguments declared to be an array of a type 14297 // to be qualified with an address space. 14298 !(getLangOpts().OpenCL && 14299 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 14300 Diag(NameLoc, diag::err_arg_with_address_space); 14301 New->setInvalidDecl(); 14302 } 14303 14304 // PPC MMA non-pointer types are not allowed as function argument types. 14305 if (Context.getTargetInfo().getTriple().isPPC64() && 14306 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 14307 New->setInvalidDecl(); 14308 } 14309 14310 return New; 14311 } 14312 14313 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 14314 SourceLocation LocAfterDecls) { 14315 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 14316 14317 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 14318 // for a K&R function. 14319 if (!FTI.hasPrototype) { 14320 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 14321 --i; 14322 if (FTI.Params[i].Param == nullptr) { 14323 SmallString<256> Code; 14324 llvm::raw_svector_ostream(Code) 14325 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 14326 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 14327 << FTI.Params[i].Ident 14328 << FixItHint::CreateInsertion(LocAfterDecls, Code); 14329 14330 // Implicitly declare the argument as type 'int' for lack of a better 14331 // type. 14332 AttributeFactory attrs; 14333 DeclSpec DS(attrs); 14334 const char* PrevSpec; // unused 14335 unsigned DiagID; // unused 14336 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14337 DiagID, Context.getPrintingPolicy()); 14338 // Use the identifier location for the type source range. 14339 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14340 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14341 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14342 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14343 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14344 } 14345 } 14346 } 14347 } 14348 14349 Decl * 14350 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14351 MultiTemplateParamsArg TemplateParameterLists, 14352 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { 14353 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14354 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14355 Scope *ParentScope = FnBodyScope->getParent(); 14356 14357 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14358 // we define a non-templated function definition, we will create a declaration 14359 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14360 // The base function declaration will have the equivalent of an `omp declare 14361 // variant` annotation which specifies the mangled definition as a 14362 // specialization function under the OpenMP context defined as part of the 14363 // `omp begin declare variant`. 14364 SmallVector<FunctionDecl *, 4> Bases; 14365 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14366 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14367 ParentScope, D, TemplateParameterLists, Bases); 14368 14369 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14370 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14371 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind); 14372 14373 if (!Bases.empty()) 14374 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14375 14376 return Dcl; 14377 } 14378 14379 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14380 Consumer.HandleInlineFunctionDefinition(D); 14381 } 14382 14383 static bool 14384 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14385 const FunctionDecl *&PossiblePrototype) { 14386 // Don't warn about invalid declarations. 14387 if (FD->isInvalidDecl()) 14388 return false; 14389 14390 // Or declarations that aren't global. 14391 if (!FD->isGlobal()) 14392 return false; 14393 14394 // Don't warn about C++ member functions. 14395 if (isa<CXXMethodDecl>(FD)) 14396 return false; 14397 14398 // Don't warn about 'main'. 14399 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14400 if (IdentifierInfo *II = FD->getIdentifier()) 14401 if (II->isStr("main") || II->isStr("efi_main")) 14402 return false; 14403 14404 // Don't warn about inline functions. 14405 if (FD->isInlined()) 14406 return false; 14407 14408 // Don't warn about function templates. 14409 if (FD->getDescribedFunctionTemplate()) 14410 return false; 14411 14412 // Don't warn about function template specializations. 14413 if (FD->isFunctionTemplateSpecialization()) 14414 return false; 14415 14416 // Don't warn for OpenCL kernels. 14417 if (FD->hasAttr<OpenCLKernelAttr>()) 14418 return false; 14419 14420 // Don't warn on explicitly deleted functions. 14421 if (FD->isDeleted()) 14422 return false; 14423 14424 // Don't warn on implicitly local functions (such as having local-typed 14425 // parameters). 14426 if (!FD->isExternallyVisible()) 14427 return false; 14428 14429 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14430 Prev; Prev = Prev->getPreviousDecl()) { 14431 // Ignore any declarations that occur in function or method 14432 // scope, because they aren't visible from the header. 14433 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14434 continue; 14435 14436 PossiblePrototype = Prev; 14437 return Prev->getType()->isFunctionNoProtoType(); 14438 } 14439 14440 return true; 14441 } 14442 14443 void 14444 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14445 const FunctionDecl *EffectiveDefinition, 14446 SkipBodyInfo *SkipBody) { 14447 const FunctionDecl *Definition = EffectiveDefinition; 14448 if (!Definition && 14449 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14450 return; 14451 14452 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14453 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14454 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14455 // A merged copy of the same function, instantiated as a member of 14456 // the same class, is OK. 14457 if (declaresSameEntity(OrigFD, OrigDef) && 14458 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14459 cast<Decl>(FD->getLexicalDeclContext()))) 14460 return; 14461 } 14462 } 14463 } 14464 14465 if (canRedefineFunction(Definition, getLangOpts())) 14466 return; 14467 14468 // Don't emit an error when this is redefinition of a typo-corrected 14469 // definition. 14470 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14471 return; 14472 14473 // If we don't have a visible definition of the function, and it's inline or 14474 // a template, skip the new definition. 14475 if (SkipBody && !hasVisibleDefinition(Definition) && 14476 (Definition->getFormalLinkage() == InternalLinkage || 14477 Definition->isInlined() || 14478 Definition->getDescribedFunctionTemplate() || 14479 Definition->getNumTemplateParameterLists())) { 14480 SkipBody->ShouldSkip = true; 14481 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14482 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14483 makeMergedDefinitionVisible(TD); 14484 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14485 return; 14486 } 14487 14488 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14489 Definition->getStorageClass() == SC_Extern) 14490 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14491 << FD << getLangOpts().CPlusPlus; 14492 else 14493 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14494 14495 Diag(Definition->getLocation(), diag::note_previous_definition); 14496 FD->setInvalidDecl(); 14497 } 14498 14499 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14500 Sema &S) { 14501 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14502 14503 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14504 LSI->CallOperator = CallOperator; 14505 LSI->Lambda = LambdaClass; 14506 LSI->ReturnType = CallOperator->getReturnType(); 14507 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14508 14509 if (LCD == LCD_None) 14510 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14511 else if (LCD == LCD_ByCopy) 14512 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14513 else if (LCD == LCD_ByRef) 14514 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14515 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14516 14517 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14518 LSI->Mutable = !CallOperator->isConst(); 14519 14520 // Add the captures to the LSI so they can be noted as already 14521 // captured within tryCaptureVar. 14522 auto I = LambdaClass->field_begin(); 14523 for (const auto &C : LambdaClass->captures()) { 14524 if (C.capturesVariable()) { 14525 VarDecl *VD = C.getCapturedVar(); 14526 if (VD->isInitCapture()) 14527 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14528 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14529 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14530 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14531 /*EllipsisLoc*/C.isPackExpansion() 14532 ? C.getEllipsisLoc() : SourceLocation(), 14533 I->getType(), /*Invalid*/false); 14534 14535 } else if (C.capturesThis()) { 14536 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14537 C.getCaptureKind() == LCK_StarThis); 14538 } else { 14539 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14540 I->getType()); 14541 } 14542 ++I; 14543 } 14544 } 14545 14546 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14547 SkipBodyInfo *SkipBody, 14548 FnBodyKind BodyKind) { 14549 if (!D) { 14550 // Parsing the function declaration failed in some way. Push on a fake scope 14551 // anyway so we can try to parse the function body. 14552 PushFunctionScope(); 14553 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14554 return D; 14555 } 14556 14557 FunctionDecl *FD = nullptr; 14558 14559 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14560 FD = FunTmpl->getTemplatedDecl(); 14561 else 14562 FD = cast<FunctionDecl>(D); 14563 14564 // Do not push if it is a lambda because one is already pushed when building 14565 // the lambda in ActOnStartOfLambdaDefinition(). 14566 if (!isLambdaCallOperator(FD)) 14567 PushExpressionEvaluationContext( 14568 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14569 : ExprEvalContexts.back().Context); 14570 14571 // Check for defining attributes before the check for redefinition. 14572 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14573 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14574 FD->dropAttr<AliasAttr>(); 14575 FD->setInvalidDecl(); 14576 } 14577 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14578 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14579 FD->dropAttr<IFuncAttr>(); 14580 FD->setInvalidDecl(); 14581 } 14582 14583 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14584 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14585 Ctor->isDefaultConstructor() && 14586 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14587 // If this is an MS ABI dllexport default constructor, instantiate any 14588 // default arguments. 14589 InstantiateDefaultCtorDefaultArgs(Ctor); 14590 } 14591 } 14592 14593 // See if this is a redefinition. If 'will have body' (or similar) is already 14594 // set, then these checks were already performed when it was set. 14595 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14596 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14597 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14598 14599 // If we're skipping the body, we're done. Don't enter the scope. 14600 if (SkipBody && SkipBody->ShouldSkip) 14601 return D; 14602 } 14603 14604 // Mark this function as "will have a body eventually". This lets users to 14605 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14606 // this function. 14607 FD->setWillHaveBody(); 14608 14609 // If we are instantiating a generic lambda call operator, push 14610 // a LambdaScopeInfo onto the function stack. But use the information 14611 // that's already been calculated (ActOnLambdaExpr) to prime the current 14612 // LambdaScopeInfo. 14613 // When the template operator is being specialized, the LambdaScopeInfo, 14614 // has to be properly restored so that tryCaptureVariable doesn't try 14615 // and capture any new variables. In addition when calculating potential 14616 // captures during transformation of nested lambdas, it is necessary to 14617 // have the LSI properly restored. 14618 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14619 assert(inTemplateInstantiation() && 14620 "There should be an active template instantiation on the stack " 14621 "when instantiating a generic lambda!"); 14622 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14623 } else { 14624 // Enter a new function scope 14625 PushFunctionScope(); 14626 } 14627 14628 // Builtin functions cannot be defined. 14629 if (unsigned BuiltinID = FD->getBuiltinID()) { 14630 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14631 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14632 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14633 FD->setInvalidDecl(); 14634 } 14635 } 14636 14637 // The return type of a function definition must be complete (C99 6.9.1p3), 14638 // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2) 14639 QualType ResultType = FD->getReturnType(); 14640 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14641 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && 14642 RequireCompleteType(FD->getLocation(), ResultType, 14643 diag::err_func_def_incomplete_result)) 14644 FD->setInvalidDecl(); 14645 14646 if (FnBodyScope) 14647 PushDeclContext(FnBodyScope, FD); 14648 14649 // Check the validity of our function parameters 14650 if (BodyKind != FnBodyKind::Delete) 14651 CheckParmsForFunctionDef(FD->parameters(), 14652 /*CheckParameterNames=*/true); 14653 14654 // Add non-parameter declarations already in the function to the current 14655 // scope. 14656 if (FnBodyScope) { 14657 for (Decl *NPD : FD->decls()) { 14658 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14659 if (!NonParmDecl) 14660 continue; 14661 assert(!isa<ParmVarDecl>(NonParmDecl) && 14662 "parameters should not be in newly created FD yet"); 14663 14664 // If the decl has a name, make it accessible in the current scope. 14665 if (NonParmDecl->getDeclName()) 14666 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14667 14668 // Similarly, dive into enums and fish their constants out, making them 14669 // accessible in this scope. 14670 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14671 for (auto *EI : ED->enumerators()) 14672 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14673 } 14674 } 14675 } 14676 14677 // Introduce our parameters into the function scope 14678 for (auto Param : FD->parameters()) { 14679 Param->setOwningFunction(FD); 14680 14681 // If this has an identifier, add it to the scope stack. 14682 if (Param->getIdentifier() && FnBodyScope) { 14683 CheckShadow(FnBodyScope, Param); 14684 14685 PushOnScopeChains(Param, FnBodyScope); 14686 } 14687 } 14688 14689 // Ensure that the function's exception specification is instantiated. 14690 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14691 ResolveExceptionSpec(D->getLocation(), FPT); 14692 14693 // dllimport cannot be applied to non-inline function definitions. 14694 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14695 !FD->isTemplateInstantiation()) { 14696 assert(!FD->hasAttr<DLLExportAttr>()); 14697 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14698 FD->setInvalidDecl(); 14699 return D; 14700 } 14701 // We want to attach documentation to original Decl (which might be 14702 // a function template). 14703 ActOnDocumentableDecl(D); 14704 if (getCurLexicalContext()->isObjCContainer() && 14705 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14706 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14707 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14708 14709 return D; 14710 } 14711 14712 /// Given the set of return statements within a function body, 14713 /// compute the variables that are subject to the named return value 14714 /// optimization. 14715 /// 14716 /// Each of the variables that is subject to the named return value 14717 /// optimization will be marked as NRVO variables in the AST, and any 14718 /// return statement that has a marked NRVO variable as its NRVO candidate can 14719 /// use the named return value optimization. 14720 /// 14721 /// This function applies a very simplistic algorithm for NRVO: if every return 14722 /// statement in the scope of a variable has the same NRVO candidate, that 14723 /// candidate is an NRVO variable. 14724 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14725 ReturnStmt **Returns = Scope->Returns.data(); 14726 14727 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14728 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14729 if (!NRVOCandidate->isNRVOVariable()) 14730 Returns[I]->setNRVOCandidate(nullptr); 14731 } 14732 } 14733 } 14734 14735 bool Sema::canDelayFunctionBody(const Declarator &D) { 14736 // We can't delay parsing the body of a constexpr function template (yet). 14737 if (D.getDeclSpec().hasConstexprSpecifier()) 14738 return false; 14739 14740 // We can't delay parsing the body of a function template with a deduced 14741 // return type (yet). 14742 if (D.getDeclSpec().hasAutoTypeSpec()) { 14743 // If the placeholder introduces a non-deduced trailing return type, 14744 // we can still delay parsing it. 14745 if (D.getNumTypeObjects()) { 14746 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14747 if (Outer.Kind == DeclaratorChunk::Function && 14748 Outer.Fun.hasTrailingReturnType()) { 14749 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14750 return Ty.isNull() || !Ty->isUndeducedType(); 14751 } 14752 } 14753 return false; 14754 } 14755 14756 return true; 14757 } 14758 14759 bool Sema::canSkipFunctionBody(Decl *D) { 14760 // We cannot skip the body of a function (or function template) which is 14761 // constexpr, since we may need to evaluate its body in order to parse the 14762 // rest of the file. 14763 // We cannot skip the body of a function with an undeduced return type, 14764 // because any callers of that function need to know the type. 14765 if (const FunctionDecl *FD = D->getAsFunction()) { 14766 if (FD->isConstexpr()) 14767 return false; 14768 // We can't simply call Type::isUndeducedType here, because inside template 14769 // auto can be deduced to a dependent type, which is not considered 14770 // "undeduced". 14771 if (FD->getReturnType()->getContainedDeducedType()) 14772 return false; 14773 } 14774 return Consumer.shouldSkipFunctionBody(D); 14775 } 14776 14777 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14778 if (!Decl) 14779 return nullptr; 14780 if (FunctionDecl *FD = Decl->getAsFunction()) 14781 FD->setHasSkippedBody(); 14782 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14783 MD->setHasSkippedBody(); 14784 return Decl; 14785 } 14786 14787 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14788 return ActOnFinishFunctionBody(D, BodyArg, false); 14789 } 14790 14791 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14792 /// body. 14793 class ExitFunctionBodyRAII { 14794 public: 14795 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14796 ~ExitFunctionBodyRAII() { 14797 if (!IsLambda) 14798 S.PopExpressionEvaluationContext(); 14799 } 14800 14801 private: 14802 Sema &S; 14803 bool IsLambda = false; 14804 }; 14805 14806 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14807 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14808 14809 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14810 if (EscapeInfo.count(BD)) 14811 return EscapeInfo[BD]; 14812 14813 bool R = false; 14814 const BlockDecl *CurBD = BD; 14815 14816 do { 14817 R = !CurBD->doesNotEscape(); 14818 if (R) 14819 break; 14820 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14821 } while (CurBD); 14822 14823 return EscapeInfo[BD] = R; 14824 }; 14825 14826 // If the location where 'self' is implicitly retained is inside a escaping 14827 // block, emit a diagnostic. 14828 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14829 S.ImplicitlyRetainedSelfLocs) 14830 if (IsOrNestedInEscapingBlock(P.second)) 14831 S.Diag(P.first, diag::warn_implicitly_retains_self) 14832 << FixItHint::CreateInsertion(P.first, "self->"); 14833 } 14834 14835 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14836 bool IsInstantiation) { 14837 FunctionScopeInfo *FSI = getCurFunction(); 14838 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14839 14840 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14841 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14842 14843 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14844 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14845 14846 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14847 CheckCompletedCoroutineBody(FD, Body); 14848 14849 { 14850 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14851 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14852 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14853 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14854 14855 if (FD) { 14856 FD->setBody(Body); 14857 FD->setWillHaveBody(false); 14858 14859 if (getLangOpts().CPlusPlus14) { 14860 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14861 FD->getReturnType()->isUndeducedType()) { 14862 // For a function with a deduced result type to return void, 14863 // the result type as written must be 'auto' or 'decltype(auto)', 14864 // possibly cv-qualified or constrained, but not ref-qualified. 14865 if (!FD->getReturnType()->getAs<AutoType>()) { 14866 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14867 << FD->getReturnType(); 14868 FD->setInvalidDecl(); 14869 } else { 14870 // Falling off the end of the function is the same as 'return;'. 14871 Expr *Dummy = nullptr; 14872 if (DeduceFunctionTypeFromReturnExpr( 14873 FD, dcl->getLocation(), Dummy, 14874 FD->getReturnType()->getAs<AutoType>())) 14875 FD->setInvalidDecl(); 14876 } 14877 } 14878 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14879 // In C++11, we don't use 'auto' deduction rules for lambda call 14880 // operators because we don't support return type deduction. 14881 auto *LSI = getCurLambda(); 14882 if (LSI->HasImplicitReturnType) { 14883 deduceClosureReturnType(*LSI); 14884 14885 // C++11 [expr.prim.lambda]p4: 14886 // [...] if there are no return statements in the compound-statement 14887 // [the deduced type is] the type void 14888 QualType RetType = 14889 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14890 14891 // Update the return type to the deduced type. 14892 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14893 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14894 Proto->getExtProtoInfo())); 14895 } 14896 } 14897 14898 // If the function implicitly returns zero (like 'main') or is naked, 14899 // don't complain about missing return statements. 14900 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14901 WP.disableCheckFallThrough(); 14902 14903 // MSVC permits the use of pure specifier (=0) on function definition, 14904 // defined at class scope, warn about this non-standard construct. 14905 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14906 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14907 14908 if (!FD->isInvalidDecl()) { 14909 // Don't diagnose unused parameters of defaulted, deleted or naked 14910 // functions. 14911 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 14912 !FD->hasAttr<NakedAttr>()) 14913 DiagnoseUnusedParameters(FD->parameters()); 14914 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14915 FD->getReturnType(), FD); 14916 14917 // If this is a structor, we need a vtable. 14918 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14919 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14920 else if (CXXDestructorDecl *Destructor = 14921 dyn_cast<CXXDestructorDecl>(FD)) 14922 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14923 14924 // Try to apply the named return value optimization. We have to check 14925 // if we can do this here because lambdas keep return statements around 14926 // to deduce an implicit return type. 14927 if (FD->getReturnType()->isRecordType() && 14928 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14929 computeNRVO(Body, FSI); 14930 } 14931 14932 // GNU warning -Wmissing-prototypes: 14933 // Warn if a global function is defined without a previous 14934 // prototype declaration. This warning is issued even if the 14935 // definition itself provides a prototype. The aim is to detect 14936 // global functions that fail to be declared in header files. 14937 const FunctionDecl *PossiblePrototype = nullptr; 14938 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14939 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14940 14941 if (PossiblePrototype) { 14942 // We found a declaration that is not a prototype, 14943 // but that could be a zero-parameter prototype 14944 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14945 TypeLoc TL = TI->getTypeLoc(); 14946 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14947 Diag(PossiblePrototype->getLocation(), 14948 diag::note_declaration_not_a_prototype) 14949 << (FD->getNumParams() != 0) 14950 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 14951 FTL.getRParenLoc(), "void") 14952 : FixItHint{}); 14953 } 14954 } else { 14955 // Returns true if the token beginning at this Loc is `const`. 14956 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14957 const LangOptions &LangOpts) { 14958 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14959 if (LocInfo.first.isInvalid()) 14960 return false; 14961 14962 bool Invalid = false; 14963 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14964 if (Invalid) 14965 return false; 14966 14967 if (LocInfo.second > Buffer.size()) 14968 return false; 14969 14970 const char *LexStart = Buffer.data() + LocInfo.second; 14971 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14972 14973 return StartTok.consume_front("const") && 14974 (StartTok.empty() || isWhitespace(StartTok[0]) || 14975 StartTok.startswith("/*") || StartTok.startswith("//")); 14976 }; 14977 14978 auto findBeginLoc = [&]() { 14979 // If the return type has `const` qualifier, we want to insert 14980 // `static` before `const` (and not before the typename). 14981 if ((FD->getReturnType()->isAnyPointerType() && 14982 FD->getReturnType()->getPointeeType().isConstQualified()) || 14983 FD->getReturnType().isConstQualified()) { 14984 // But only do this if we can determine where the `const` is. 14985 14986 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14987 getLangOpts())) 14988 14989 return FD->getBeginLoc(); 14990 } 14991 return FD->getTypeSpecStartLoc(); 14992 }; 14993 Diag(FD->getTypeSpecStartLoc(), 14994 diag::note_static_for_internal_linkage) 14995 << /* function */ 1 14996 << (FD->getStorageClass() == SC_None 14997 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14998 : FixItHint{}); 14999 } 15000 } 15001 15002 // If the function being defined does not have a prototype, then we may 15003 // need to diagnose it as changing behavior in C2x because we now know 15004 // whether the function accepts arguments or not. This only handles the 15005 // case where the definition has no prototype but does have parameters 15006 // and either there is no previous potential prototype, or the previous 15007 // potential prototype also has no actual prototype. This handles cases 15008 // like: 15009 // void f(); void f(a) int a; {} 15010 // void g(a) int a; {} 15011 // See MergeFunctionDecl() for other cases of the behavior change 15012 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 15013 // type without a prototype. 15014 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && 15015 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && 15016 !PossiblePrototype->isImplicit()))) { 15017 // The function definition has parameters, so this will change behavior 15018 // in C2x. If there is a possible prototype, it comes before the 15019 // function definition. 15020 // FIXME: The declaration may have already been diagnosed as being 15021 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but 15022 // there's no way to test for the "changes behavior" condition in 15023 // SemaType.cpp when forming the declaration's function type. So, we do 15024 // this awkward dance instead. 15025 // 15026 // If we have a possible prototype and it declares a function with a 15027 // prototype, we don't want to diagnose it; if we have a possible 15028 // prototype and it has no prototype, it may have already been 15029 // diagnosed in SemaType.cpp as deprecated depending on whether 15030 // -Wstrict-prototypes is enabled. If we already warned about it being 15031 // deprecated, add a note that it also changes behavior. If we didn't 15032 // warn about it being deprecated (because the diagnostic is not 15033 // enabled), warn now that it is deprecated and changes behavior. 15034 bool AddNote = false; 15035 if (PossiblePrototype) { 15036 if (Diags.isIgnored(diag::warn_strict_prototypes, 15037 PossiblePrototype->getLocation())) { 15038 15039 PartialDiagnostic PD = 15040 PDiag(diag::warn_non_prototype_changes_behavior); 15041 if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) { 15042 if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>()) 15043 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 15044 } 15045 Diag(PossiblePrototype->getLocation(), PD); 15046 } else { 15047 AddNote = true; 15048 } 15049 } 15050 15051 // Because this function definition has no prototype and it has 15052 // parameters, it will definitely change behavior in C2x. 15053 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior); 15054 if (AddNote) 15055 Diag(PossiblePrototype->getLocation(), 15056 diag::note_func_decl_changes_behavior); 15057 } 15058 15059 // Warn on CPUDispatch with an actual body. 15060 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 15061 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 15062 if (!CmpndBody->body_empty()) 15063 Diag(CmpndBody->body_front()->getBeginLoc(), 15064 diag::warn_dispatch_body_ignored); 15065 15066 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 15067 const CXXMethodDecl *KeyFunction; 15068 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 15069 MD->isVirtual() && 15070 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 15071 MD == KeyFunction->getCanonicalDecl()) { 15072 // Update the key-function state if necessary for this ABI. 15073 if (FD->isInlined() && 15074 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 15075 Context.setNonKeyFunction(MD); 15076 15077 // If the newly-chosen key function is already defined, then we 15078 // need to mark the vtable as used retroactively. 15079 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 15080 const FunctionDecl *Definition; 15081 if (KeyFunction && KeyFunction->isDefined(Definition)) 15082 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 15083 } else { 15084 // We just defined they key function; mark the vtable as used. 15085 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 15086 } 15087 } 15088 } 15089 15090 assert( 15091 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 15092 "Function parsing confused"); 15093 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 15094 assert(MD == getCurMethodDecl() && "Method parsing confused"); 15095 MD->setBody(Body); 15096 if (!MD->isInvalidDecl()) { 15097 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 15098 MD->getReturnType(), MD); 15099 15100 if (Body) 15101 computeNRVO(Body, FSI); 15102 } 15103 if (FSI->ObjCShouldCallSuper) { 15104 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 15105 << MD->getSelector().getAsString(); 15106 FSI->ObjCShouldCallSuper = false; 15107 } 15108 if (FSI->ObjCWarnForNoDesignatedInitChain) { 15109 const ObjCMethodDecl *InitMethod = nullptr; 15110 bool isDesignated = 15111 MD->isDesignatedInitializerForTheInterface(&InitMethod); 15112 assert(isDesignated && InitMethod); 15113 (void)isDesignated; 15114 15115 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 15116 auto IFace = MD->getClassInterface(); 15117 if (!IFace) 15118 return false; 15119 auto SuperD = IFace->getSuperClass(); 15120 if (!SuperD) 15121 return false; 15122 return SuperD->getIdentifier() == 15123 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 15124 }; 15125 // Don't issue this warning for unavailable inits or direct subclasses 15126 // of NSObject. 15127 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 15128 Diag(MD->getLocation(), 15129 diag::warn_objc_designated_init_missing_super_call); 15130 Diag(InitMethod->getLocation(), 15131 diag::note_objc_designated_init_marked_here); 15132 } 15133 FSI->ObjCWarnForNoDesignatedInitChain = false; 15134 } 15135 if (FSI->ObjCWarnForNoInitDelegation) { 15136 // Don't issue this warning for unavaialable inits. 15137 if (!MD->isUnavailable()) 15138 Diag(MD->getLocation(), 15139 diag::warn_objc_secondary_init_missing_init_call); 15140 FSI->ObjCWarnForNoInitDelegation = false; 15141 } 15142 15143 diagnoseImplicitlyRetainedSelf(*this); 15144 } else { 15145 // Parsing the function declaration failed in some way. Pop the fake scope 15146 // we pushed on. 15147 PopFunctionScopeInfo(ActivePolicy, dcl); 15148 return nullptr; 15149 } 15150 15151 if (Body && FSI->HasPotentialAvailabilityViolations) 15152 DiagnoseUnguardedAvailabilityViolations(dcl); 15153 15154 assert(!FSI->ObjCShouldCallSuper && 15155 "This should only be set for ObjC methods, which should have been " 15156 "handled in the block above."); 15157 15158 // Verify and clean out per-function state. 15159 if (Body && (!FD || !FD->isDefaulted())) { 15160 // C++ constructors that have function-try-blocks can't have return 15161 // statements in the handlers of that block. (C++ [except.handle]p14) 15162 // Verify this. 15163 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 15164 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 15165 15166 // Verify that gotos and switch cases don't jump into scopes illegally. 15167 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 15168 DiagnoseInvalidJumps(Body); 15169 15170 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 15171 if (!Destructor->getParent()->isDependentType()) 15172 CheckDestructor(Destructor); 15173 15174 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 15175 Destructor->getParent()); 15176 } 15177 15178 // If any errors have occurred, clear out any temporaries that may have 15179 // been leftover. This ensures that these temporaries won't be picked up 15180 // for deletion in some later function. 15181 if (hasUncompilableErrorOccurred() || 15182 getDiagnostics().getSuppressAllDiagnostics()) { 15183 DiscardCleanupsInEvaluationContext(); 15184 } 15185 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 15186 // Since the body is valid, issue any analysis-based warnings that are 15187 // enabled. 15188 ActivePolicy = &WP; 15189 } 15190 15191 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 15192 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 15193 FD->setInvalidDecl(); 15194 15195 if (FD && FD->hasAttr<NakedAttr>()) { 15196 for (const Stmt *S : Body->children()) { 15197 // Allow local register variables without initializer as they don't 15198 // require prologue. 15199 bool RegisterVariables = false; 15200 if (auto *DS = dyn_cast<DeclStmt>(S)) { 15201 for (const auto *Decl : DS->decls()) { 15202 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 15203 RegisterVariables = 15204 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 15205 if (!RegisterVariables) 15206 break; 15207 } 15208 } 15209 } 15210 if (RegisterVariables) 15211 continue; 15212 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 15213 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 15214 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 15215 FD->setInvalidDecl(); 15216 break; 15217 } 15218 } 15219 } 15220 15221 assert(ExprCleanupObjects.size() == 15222 ExprEvalContexts.back().NumCleanupObjects && 15223 "Leftover temporaries in function"); 15224 assert(!Cleanup.exprNeedsCleanups() && 15225 "Unaccounted cleanups in function"); 15226 assert(MaybeODRUseExprs.empty() && 15227 "Leftover expressions for odr-use checking"); 15228 } 15229 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 15230 // the declaration context below. Otherwise, we're unable to transform 15231 // 'this' expressions when transforming immediate context functions. 15232 15233 if (!IsInstantiation) 15234 PopDeclContext(); 15235 15236 PopFunctionScopeInfo(ActivePolicy, dcl); 15237 // If any errors have occurred, clear out any temporaries that may have 15238 // been leftover. This ensures that these temporaries won't be picked up for 15239 // deletion in some later function. 15240 if (hasUncompilableErrorOccurred()) { 15241 DiscardCleanupsInEvaluationContext(); 15242 } 15243 15244 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 15245 !LangOpts.OMPTargetTriples.empty())) || 15246 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 15247 auto ES = getEmissionStatus(FD); 15248 if (ES == Sema::FunctionEmissionStatus::Emitted || 15249 ES == Sema::FunctionEmissionStatus::Unknown) 15250 DeclsToCheckForDeferredDiags.insert(FD); 15251 } 15252 15253 if (FD && !FD->isDeleted()) 15254 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 15255 15256 return dcl; 15257 } 15258 15259 /// When we finish delayed parsing of an attribute, we must attach it to the 15260 /// relevant Decl. 15261 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 15262 ParsedAttributes &Attrs) { 15263 // Always attach attributes to the underlying decl. 15264 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 15265 D = TD->getTemplatedDecl(); 15266 ProcessDeclAttributeList(S, D, Attrs); 15267 15268 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 15269 if (Method->isStatic()) 15270 checkThisInStaticMemberFunctionAttributes(Method); 15271 } 15272 15273 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 15274 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 15275 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 15276 IdentifierInfo &II, Scope *S) { 15277 // It is not valid to implicitly define a function in C2x. 15278 assert(!LangOpts.C2x && "Cannot implicitly define a function in C2x"); 15279 15280 // Find the scope in which the identifier is injected and the corresponding 15281 // DeclContext. 15282 // FIXME: C89 does not say what happens if there is no enclosing block scope. 15283 // In that case, we inject the declaration into the translation unit scope 15284 // instead. 15285 Scope *BlockScope = S; 15286 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 15287 BlockScope = BlockScope->getParent(); 15288 15289 Scope *ContextScope = BlockScope; 15290 while (!ContextScope->getEntity()) 15291 ContextScope = ContextScope->getParent(); 15292 ContextRAII SavedContext(*this, ContextScope->getEntity()); 15293 15294 // Before we produce a declaration for an implicitly defined 15295 // function, see whether there was a locally-scoped declaration of 15296 // this name as a function or variable. If so, use that 15297 // (non-visible) declaration, and complain about it. 15298 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 15299 if (ExternCPrev) { 15300 // We still need to inject the function into the enclosing block scope so 15301 // that later (non-call) uses can see it. 15302 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 15303 15304 // C89 footnote 38: 15305 // If in fact it is not defined as having type "function returning int", 15306 // the behavior is undefined. 15307 if (!isa<FunctionDecl>(ExternCPrev) || 15308 !Context.typesAreCompatible( 15309 cast<FunctionDecl>(ExternCPrev)->getType(), 15310 Context.getFunctionNoProtoType(Context.IntTy))) { 15311 Diag(Loc, diag::ext_use_out_of_scope_declaration) 15312 << ExternCPrev << !getLangOpts().C99; 15313 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 15314 return ExternCPrev; 15315 } 15316 } 15317 15318 // Extension in C99 (defaults to error). Legal in C89, but warn about it. 15319 unsigned diag_id; 15320 if (II.getName().startswith("__builtin_")) 15321 diag_id = diag::warn_builtin_unknown; 15322 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 15323 else if (getLangOpts().OpenCL) 15324 diag_id = diag::err_opencl_implicit_function_decl; 15325 else if (getLangOpts().C99) 15326 diag_id = diag::ext_implicit_function_decl_c99; 15327 else 15328 diag_id = diag::warn_implicit_function_decl; 15329 15330 TypoCorrection Corrected; 15331 // Because typo correction is expensive, only do it if the implicit 15332 // function declaration is going to be treated as an error. 15333 // 15334 // Perform the corection before issuing the main diagnostic, as some consumers 15335 // use typo-correction callbacks to enhance the main diagnostic. 15336 if (S && !ExternCPrev && 15337 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 15338 DeclFilterCCC<FunctionDecl> CCC{}; 15339 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 15340 S, nullptr, CCC, CTK_NonError); 15341 } 15342 15343 Diag(Loc, diag_id) << &II; 15344 if (Corrected) { 15345 // If the correction is going to suggest an implicitly defined function, 15346 // skip the correction as not being a particularly good idea. 15347 bool Diagnose = true; 15348 if (const auto *D = Corrected.getCorrectionDecl()) 15349 Diagnose = !D->isImplicit(); 15350 if (Diagnose) 15351 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 15352 /*ErrorRecovery*/ false); 15353 } 15354 15355 // If we found a prior declaration of this function, don't bother building 15356 // another one. We've already pushed that one into scope, so there's nothing 15357 // more to do. 15358 if (ExternCPrev) 15359 return ExternCPrev; 15360 15361 // Set a Declarator for the implicit definition: int foo(); 15362 const char *Dummy; 15363 AttributeFactory attrFactory; 15364 DeclSpec DS(attrFactory); 15365 unsigned DiagID; 15366 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 15367 Context.getPrintingPolicy()); 15368 (void)Error; // Silence warning. 15369 assert(!Error && "Error setting up implicit decl!"); 15370 SourceLocation NoLoc; 15371 Declarator D(DS, DeclaratorContext::Block); 15372 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 15373 /*IsAmbiguous=*/false, 15374 /*LParenLoc=*/NoLoc, 15375 /*Params=*/nullptr, 15376 /*NumParams=*/0, 15377 /*EllipsisLoc=*/NoLoc, 15378 /*RParenLoc=*/NoLoc, 15379 /*RefQualifierIsLvalueRef=*/true, 15380 /*RefQualifierLoc=*/NoLoc, 15381 /*MutableLoc=*/NoLoc, EST_None, 15382 /*ESpecRange=*/SourceRange(), 15383 /*Exceptions=*/nullptr, 15384 /*ExceptionRanges=*/nullptr, 15385 /*NumExceptions=*/0, 15386 /*NoexceptExpr=*/nullptr, 15387 /*ExceptionSpecTokens=*/nullptr, 15388 /*DeclsInPrototype=*/None, Loc, 15389 Loc, D), 15390 std::move(DS.getAttributes()), SourceLocation()); 15391 D.SetIdentifier(&II, Loc); 15392 15393 // Insert this function into the enclosing block scope. 15394 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 15395 FD->setImplicit(); 15396 15397 AddKnownFunctionAttributes(FD); 15398 15399 return FD; 15400 } 15401 15402 /// If this function is a C++ replaceable global allocation function 15403 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15404 /// adds any function attributes that we know a priori based on the standard. 15405 /// 15406 /// We need to check for duplicate attributes both here and where user-written 15407 /// attributes are applied to declarations. 15408 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15409 FunctionDecl *FD) { 15410 if (FD->isInvalidDecl()) 15411 return; 15412 15413 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15414 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15415 return; 15416 15417 Optional<unsigned> AlignmentParam; 15418 bool IsNothrow = false; 15419 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15420 return; 15421 15422 // C++2a [basic.stc.dynamic.allocation]p4: 15423 // An allocation function that has a non-throwing exception specification 15424 // indicates failure by returning a null pointer value. Any other allocation 15425 // function never returns a null pointer value and indicates failure only by 15426 // throwing an exception [...] 15427 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15428 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15429 15430 // C++2a [basic.stc.dynamic.allocation]p2: 15431 // An allocation function attempts to allocate the requested amount of 15432 // storage. [...] If the request succeeds, the value returned by a 15433 // replaceable allocation function is a [...] pointer value p0 different 15434 // from any previously returned value p1 [...] 15435 // 15436 // However, this particular information is being added in codegen, 15437 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15438 15439 // C++2a [basic.stc.dynamic.allocation]p2: 15440 // An allocation function attempts to allocate the requested amount of 15441 // storage. If it is successful, it returns the address of the start of a 15442 // block of storage whose length in bytes is at least as large as the 15443 // requested size. 15444 if (!FD->hasAttr<AllocSizeAttr>()) { 15445 FD->addAttr(AllocSizeAttr::CreateImplicit( 15446 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15447 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15448 } 15449 15450 // C++2a [basic.stc.dynamic.allocation]p3: 15451 // For an allocation function [...], the pointer returned on a successful 15452 // call shall represent the address of storage that is aligned as follows: 15453 // (3.1) If the allocation function takes an argument of type 15454 // std::align_val_t, the storage will have the alignment 15455 // specified by the value of this argument. 15456 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15457 FD->addAttr(AllocAlignAttr::CreateImplicit( 15458 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15459 } 15460 15461 // FIXME: 15462 // C++2a [basic.stc.dynamic.allocation]p3: 15463 // For an allocation function [...], the pointer returned on a successful 15464 // call shall represent the address of storage that is aligned as follows: 15465 // (3.2) Otherwise, if the allocation function is named operator new[], 15466 // the storage is aligned for any object that does not have 15467 // new-extended alignment ([basic.align]) and is no larger than the 15468 // requested size. 15469 // (3.3) Otherwise, the storage is aligned for any object that does not 15470 // have new-extended alignment and is of the requested size. 15471 } 15472 15473 /// Adds any function attributes that we know a priori based on 15474 /// the declaration of this function. 15475 /// 15476 /// These attributes can apply both to implicitly-declared builtins 15477 /// (like __builtin___printf_chk) or to library-declared functions 15478 /// like NSLog or printf. 15479 /// 15480 /// We need to check for duplicate attributes both here and where user-written 15481 /// attributes are applied to declarations. 15482 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15483 if (FD->isInvalidDecl()) 15484 return; 15485 15486 // If this is a built-in function, map its builtin attributes to 15487 // actual attributes. 15488 if (unsigned BuiltinID = FD->getBuiltinID()) { 15489 // Handle printf-formatting attributes. 15490 unsigned FormatIdx; 15491 bool HasVAListArg; 15492 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15493 if (!FD->hasAttr<FormatAttr>()) { 15494 const char *fmt = "printf"; 15495 unsigned int NumParams = FD->getNumParams(); 15496 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15497 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15498 fmt = "NSString"; 15499 FD->addAttr(FormatAttr::CreateImplicit(Context, 15500 &Context.Idents.get(fmt), 15501 FormatIdx+1, 15502 HasVAListArg ? 0 : FormatIdx+2, 15503 FD->getLocation())); 15504 } 15505 } 15506 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15507 HasVAListArg)) { 15508 if (!FD->hasAttr<FormatAttr>()) 15509 FD->addAttr(FormatAttr::CreateImplicit(Context, 15510 &Context.Idents.get("scanf"), 15511 FormatIdx+1, 15512 HasVAListArg ? 0 : FormatIdx+2, 15513 FD->getLocation())); 15514 } 15515 15516 // Handle automatically recognized callbacks. 15517 SmallVector<int, 4> Encoding; 15518 if (!FD->hasAttr<CallbackAttr>() && 15519 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15520 FD->addAttr(CallbackAttr::CreateImplicit( 15521 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15522 15523 // Mark const if we don't care about errno and that is the only thing 15524 // preventing the function from being const. This allows IRgen to use LLVM 15525 // intrinsics for such functions. 15526 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15527 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15528 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15529 15530 // We make "fma" on GNU or Windows const because we know it does not set 15531 // errno in those environments even though it could set errno based on the 15532 // C standard. 15533 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15534 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 15535 !FD->hasAttr<ConstAttr>()) { 15536 switch (BuiltinID) { 15537 case Builtin::BI__builtin_fma: 15538 case Builtin::BI__builtin_fmaf: 15539 case Builtin::BI__builtin_fmal: 15540 case Builtin::BIfma: 15541 case Builtin::BIfmaf: 15542 case Builtin::BIfmal: 15543 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15544 break; 15545 default: 15546 break; 15547 } 15548 } 15549 15550 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15551 !FD->hasAttr<ReturnsTwiceAttr>()) 15552 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15553 FD->getLocation())); 15554 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15555 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15556 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15557 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15558 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15559 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15560 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15561 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15562 // Add the appropriate attribute, depending on the CUDA compilation mode 15563 // and which target the builtin belongs to. For example, during host 15564 // compilation, aux builtins are __device__, while the rest are __host__. 15565 if (getLangOpts().CUDAIsDevice != 15566 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15567 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15568 else 15569 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15570 } 15571 15572 // Add known guaranteed alignment for allocation functions. 15573 switch (BuiltinID) { 15574 case Builtin::BImemalign: 15575 case Builtin::BIaligned_alloc: 15576 if (!FD->hasAttr<AllocAlignAttr>()) 15577 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15578 FD->getLocation())); 15579 break; 15580 default: 15581 break; 15582 } 15583 15584 // Add allocsize attribute for allocation functions. 15585 switch (BuiltinID) { 15586 case Builtin::BIcalloc: 15587 FD->addAttr(AllocSizeAttr::CreateImplicit( 15588 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 15589 break; 15590 case Builtin::BImemalign: 15591 case Builtin::BIaligned_alloc: 15592 case Builtin::BIrealloc: 15593 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 15594 ParamIdx(), FD->getLocation())); 15595 break; 15596 case Builtin::BImalloc: 15597 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 15598 ParamIdx(), FD->getLocation())); 15599 break; 15600 default: 15601 break; 15602 } 15603 } 15604 15605 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15606 15607 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15608 // throw, add an implicit nothrow attribute to any extern "C" function we come 15609 // across. 15610 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15611 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15612 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15613 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15614 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15615 } 15616 15617 IdentifierInfo *Name = FD->getIdentifier(); 15618 if (!Name) 15619 return; 15620 if ((!getLangOpts().CPlusPlus && 15621 FD->getDeclContext()->isTranslationUnit()) || 15622 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15623 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15624 LinkageSpecDecl::lang_c)) { 15625 // Okay: this could be a libc/libm/Objective-C function we know 15626 // about. 15627 } else 15628 return; 15629 15630 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15631 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15632 // target-specific builtins, perhaps? 15633 if (!FD->hasAttr<FormatAttr>()) 15634 FD->addAttr(FormatAttr::CreateImplicit(Context, 15635 &Context.Idents.get("printf"), 2, 15636 Name->isStr("vasprintf") ? 0 : 3, 15637 FD->getLocation())); 15638 } 15639 15640 if (Name->isStr("__CFStringMakeConstantString")) { 15641 // We already have a __builtin___CFStringMakeConstantString, 15642 // but builds that use -fno-constant-cfstrings don't go through that. 15643 if (!FD->hasAttr<FormatArgAttr>()) 15644 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15645 FD->getLocation())); 15646 } 15647 } 15648 15649 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15650 TypeSourceInfo *TInfo) { 15651 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15652 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15653 15654 if (!TInfo) { 15655 assert(D.isInvalidType() && "no declarator info for valid type"); 15656 TInfo = Context.getTrivialTypeSourceInfo(T); 15657 } 15658 15659 // Scope manipulation handled by caller. 15660 TypedefDecl *NewTD = 15661 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15662 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15663 15664 // Bail out immediately if we have an invalid declaration. 15665 if (D.isInvalidType()) { 15666 NewTD->setInvalidDecl(); 15667 return NewTD; 15668 } 15669 15670 if (D.getDeclSpec().isModulePrivateSpecified()) { 15671 if (CurContext->isFunctionOrMethod()) 15672 Diag(NewTD->getLocation(), diag::err_module_private_local) 15673 << 2 << NewTD 15674 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15675 << FixItHint::CreateRemoval( 15676 D.getDeclSpec().getModulePrivateSpecLoc()); 15677 else 15678 NewTD->setModulePrivate(); 15679 } 15680 15681 // C++ [dcl.typedef]p8: 15682 // If the typedef declaration defines an unnamed class (or 15683 // enum), the first typedef-name declared by the declaration 15684 // to be that class type (or enum type) is used to denote the 15685 // class type (or enum type) for linkage purposes only. 15686 // We need to check whether the type was declared in the declaration. 15687 switch (D.getDeclSpec().getTypeSpecType()) { 15688 case TST_enum: 15689 case TST_struct: 15690 case TST_interface: 15691 case TST_union: 15692 case TST_class: { 15693 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15694 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15695 break; 15696 } 15697 15698 default: 15699 break; 15700 } 15701 15702 return NewTD; 15703 } 15704 15705 /// Check that this is a valid underlying type for an enum declaration. 15706 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15707 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15708 QualType T = TI->getType(); 15709 15710 if (T->isDependentType()) 15711 return false; 15712 15713 // This doesn't use 'isIntegralType' despite the error message mentioning 15714 // integral type because isIntegralType would also allow enum types in C. 15715 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15716 if (BT->isInteger()) 15717 return false; 15718 15719 if (T->isBitIntType()) 15720 return false; 15721 15722 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15723 } 15724 15725 /// Check whether this is a valid redeclaration of a previous enumeration. 15726 /// \return true if the redeclaration was invalid. 15727 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15728 QualType EnumUnderlyingTy, bool IsFixed, 15729 const EnumDecl *Prev) { 15730 if (IsScoped != Prev->isScoped()) { 15731 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15732 << Prev->isScoped(); 15733 Diag(Prev->getLocation(), diag::note_previous_declaration); 15734 return true; 15735 } 15736 15737 if (IsFixed && Prev->isFixed()) { 15738 if (!EnumUnderlyingTy->isDependentType() && 15739 !Prev->getIntegerType()->isDependentType() && 15740 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15741 Prev->getIntegerType())) { 15742 // TODO: Highlight the underlying type of the redeclaration. 15743 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15744 << EnumUnderlyingTy << Prev->getIntegerType(); 15745 Diag(Prev->getLocation(), diag::note_previous_declaration) 15746 << Prev->getIntegerTypeRange(); 15747 return true; 15748 } 15749 } else if (IsFixed != Prev->isFixed()) { 15750 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15751 << Prev->isFixed(); 15752 Diag(Prev->getLocation(), diag::note_previous_declaration); 15753 return true; 15754 } 15755 15756 return false; 15757 } 15758 15759 /// Get diagnostic %select index for tag kind for 15760 /// redeclaration diagnostic message. 15761 /// WARNING: Indexes apply to particular diagnostics only! 15762 /// 15763 /// \returns diagnostic %select index. 15764 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15765 switch (Tag) { 15766 case TTK_Struct: return 0; 15767 case TTK_Interface: return 1; 15768 case TTK_Class: return 2; 15769 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15770 } 15771 } 15772 15773 /// Determine if tag kind is a class-key compatible with 15774 /// class for redeclaration (class, struct, or __interface). 15775 /// 15776 /// \returns true iff the tag kind is compatible. 15777 static bool isClassCompatTagKind(TagTypeKind Tag) 15778 { 15779 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15780 } 15781 15782 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15783 TagTypeKind TTK) { 15784 if (isa<TypedefDecl>(PrevDecl)) 15785 return NTK_Typedef; 15786 else if (isa<TypeAliasDecl>(PrevDecl)) 15787 return NTK_TypeAlias; 15788 else if (isa<ClassTemplateDecl>(PrevDecl)) 15789 return NTK_Template; 15790 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15791 return NTK_TypeAliasTemplate; 15792 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15793 return NTK_TemplateTemplateArgument; 15794 switch (TTK) { 15795 case TTK_Struct: 15796 case TTK_Interface: 15797 case TTK_Class: 15798 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15799 case TTK_Union: 15800 return NTK_NonUnion; 15801 case TTK_Enum: 15802 return NTK_NonEnum; 15803 } 15804 llvm_unreachable("invalid TTK"); 15805 } 15806 15807 /// Determine whether a tag with a given kind is acceptable 15808 /// as a redeclaration of the given tag declaration. 15809 /// 15810 /// \returns true if the new tag kind is acceptable, false otherwise. 15811 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15812 TagTypeKind NewTag, bool isDefinition, 15813 SourceLocation NewTagLoc, 15814 const IdentifierInfo *Name) { 15815 // C++ [dcl.type.elab]p3: 15816 // The class-key or enum keyword present in the 15817 // elaborated-type-specifier shall agree in kind with the 15818 // declaration to which the name in the elaborated-type-specifier 15819 // refers. This rule also applies to the form of 15820 // elaborated-type-specifier that declares a class-name or 15821 // friend class since it can be construed as referring to the 15822 // definition of the class. Thus, in any 15823 // elaborated-type-specifier, the enum keyword shall be used to 15824 // refer to an enumeration (7.2), the union class-key shall be 15825 // used to refer to a union (clause 9), and either the class or 15826 // struct class-key shall be used to refer to a class (clause 9) 15827 // declared using the class or struct class-key. 15828 TagTypeKind OldTag = Previous->getTagKind(); 15829 if (OldTag != NewTag && 15830 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15831 return false; 15832 15833 // Tags are compatible, but we might still want to warn on mismatched tags. 15834 // Non-class tags can't be mismatched at this point. 15835 if (!isClassCompatTagKind(NewTag)) 15836 return true; 15837 15838 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15839 // by our warning analysis. We don't want to warn about mismatches with (eg) 15840 // declarations in system headers that are designed to be specialized, but if 15841 // a user asks us to warn, we should warn if their code contains mismatched 15842 // declarations. 15843 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15844 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15845 Loc); 15846 }; 15847 if (IsIgnoredLoc(NewTagLoc)) 15848 return true; 15849 15850 auto IsIgnored = [&](const TagDecl *Tag) { 15851 return IsIgnoredLoc(Tag->getLocation()); 15852 }; 15853 while (IsIgnored(Previous)) { 15854 Previous = Previous->getPreviousDecl(); 15855 if (!Previous) 15856 return true; 15857 OldTag = Previous->getTagKind(); 15858 } 15859 15860 bool isTemplate = false; 15861 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15862 isTemplate = Record->getDescribedClassTemplate(); 15863 15864 if (inTemplateInstantiation()) { 15865 if (OldTag != NewTag) { 15866 // In a template instantiation, do not offer fix-its for tag mismatches 15867 // since they usually mess up the template instead of fixing the problem. 15868 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15869 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15870 << getRedeclDiagFromTagKind(OldTag); 15871 // FIXME: Note previous location? 15872 } 15873 return true; 15874 } 15875 15876 if (isDefinition) { 15877 // On definitions, check all previous tags and issue a fix-it for each 15878 // one that doesn't match the current tag. 15879 if (Previous->getDefinition()) { 15880 // Don't suggest fix-its for redefinitions. 15881 return true; 15882 } 15883 15884 bool previousMismatch = false; 15885 for (const TagDecl *I : Previous->redecls()) { 15886 if (I->getTagKind() != NewTag) { 15887 // Ignore previous declarations for which the warning was disabled. 15888 if (IsIgnored(I)) 15889 continue; 15890 15891 if (!previousMismatch) { 15892 previousMismatch = true; 15893 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15894 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15895 << getRedeclDiagFromTagKind(I->getTagKind()); 15896 } 15897 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15898 << getRedeclDiagFromTagKind(NewTag) 15899 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15900 TypeWithKeyword::getTagTypeKindName(NewTag)); 15901 } 15902 } 15903 return true; 15904 } 15905 15906 // Identify the prevailing tag kind: this is the kind of the definition (if 15907 // there is a non-ignored definition), or otherwise the kind of the prior 15908 // (non-ignored) declaration. 15909 const TagDecl *PrevDef = Previous->getDefinition(); 15910 if (PrevDef && IsIgnored(PrevDef)) 15911 PrevDef = nullptr; 15912 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15913 if (Redecl->getTagKind() != NewTag) { 15914 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15915 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15916 << getRedeclDiagFromTagKind(OldTag); 15917 Diag(Redecl->getLocation(), diag::note_previous_use); 15918 15919 // If there is a previous definition, suggest a fix-it. 15920 if (PrevDef) { 15921 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15922 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15923 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15924 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15925 } 15926 } 15927 15928 return true; 15929 } 15930 15931 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15932 /// from an outer enclosing namespace or file scope inside a friend declaration. 15933 /// This should provide the commented out code in the following snippet: 15934 /// namespace N { 15935 /// struct X; 15936 /// namespace M { 15937 /// struct Y { friend struct /*N::*/ X; }; 15938 /// } 15939 /// } 15940 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15941 SourceLocation NameLoc) { 15942 // While the decl is in a namespace, do repeated lookup of that name and see 15943 // if we get the same namespace back. If we do not, continue until 15944 // translation unit scope, at which point we have a fully qualified NNS. 15945 SmallVector<IdentifierInfo *, 4> Namespaces; 15946 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15947 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15948 // This tag should be declared in a namespace, which can only be enclosed by 15949 // other namespaces. Bail if there's an anonymous namespace in the chain. 15950 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15951 if (!Namespace || Namespace->isAnonymousNamespace()) 15952 return FixItHint(); 15953 IdentifierInfo *II = Namespace->getIdentifier(); 15954 Namespaces.push_back(II); 15955 NamedDecl *Lookup = SemaRef.LookupSingleName( 15956 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15957 if (Lookup == Namespace) 15958 break; 15959 } 15960 15961 // Once we have all the namespaces, reverse them to go outermost first, and 15962 // build an NNS. 15963 SmallString<64> Insertion; 15964 llvm::raw_svector_ostream OS(Insertion); 15965 if (DC->isTranslationUnit()) 15966 OS << "::"; 15967 std::reverse(Namespaces.begin(), Namespaces.end()); 15968 for (auto *II : Namespaces) 15969 OS << II->getName() << "::"; 15970 return FixItHint::CreateInsertion(NameLoc, Insertion); 15971 } 15972 15973 /// Determine whether a tag originally declared in context \p OldDC can 15974 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15975 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15976 /// using-declaration). 15977 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15978 DeclContext *NewDC) { 15979 OldDC = OldDC->getRedeclContext(); 15980 NewDC = NewDC->getRedeclContext(); 15981 15982 if (OldDC->Equals(NewDC)) 15983 return true; 15984 15985 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15986 // encloses the other). 15987 if (S.getLangOpts().MSVCCompat && 15988 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15989 return true; 15990 15991 return false; 15992 } 15993 15994 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15995 /// former case, Name will be non-null. In the later case, Name will be null. 15996 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15997 /// reference/declaration/definition of a tag. 15998 /// 15999 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 16000 /// trailing-type-specifier) other than one in an alias-declaration. 16001 /// 16002 /// \param SkipBody If non-null, will be set to indicate if the caller should 16003 /// skip the definition of this tag and treat it as if it were a declaration. 16004 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 16005 SourceLocation KWLoc, CXXScopeSpec &SS, 16006 IdentifierInfo *Name, SourceLocation NameLoc, 16007 const ParsedAttributesView &Attrs, AccessSpecifier AS, 16008 SourceLocation ModulePrivateLoc, 16009 MultiTemplateParamsArg TemplateParameterLists, 16010 bool &OwnedDecl, bool &IsDependent, 16011 SourceLocation ScopedEnumKWLoc, 16012 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 16013 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 16014 SkipBodyInfo *SkipBody) { 16015 // If this is not a definition, it must have a name. 16016 IdentifierInfo *OrigName = Name; 16017 assert((Name != nullptr || TUK == TUK_Definition) && 16018 "Nameless record must be a definition!"); 16019 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 16020 16021 OwnedDecl = false; 16022 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16023 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 16024 16025 // FIXME: Check member specializations more carefully. 16026 bool isMemberSpecialization = false; 16027 bool Invalid = false; 16028 16029 // We only need to do this matching if we have template parameters 16030 // or a scope specifier, which also conveniently avoids this work 16031 // for non-C++ cases. 16032 if (TemplateParameterLists.size() > 0 || 16033 (SS.isNotEmpty() && TUK != TUK_Reference)) { 16034 if (TemplateParameterList *TemplateParams = 16035 MatchTemplateParametersToScopeSpecifier( 16036 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 16037 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 16038 if (Kind == TTK_Enum) { 16039 Diag(KWLoc, diag::err_enum_template); 16040 return nullptr; 16041 } 16042 16043 if (TemplateParams->size() > 0) { 16044 // This is a declaration or definition of a class template (which may 16045 // be a member of another template). 16046 16047 if (Invalid) 16048 return nullptr; 16049 16050 OwnedDecl = false; 16051 DeclResult Result = CheckClassTemplate( 16052 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 16053 AS, ModulePrivateLoc, 16054 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 16055 TemplateParameterLists.data(), SkipBody); 16056 return Result.get(); 16057 } else { 16058 // The "template<>" header is extraneous. 16059 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16060 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16061 isMemberSpecialization = true; 16062 } 16063 } 16064 16065 if (!TemplateParameterLists.empty() && isMemberSpecialization && 16066 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 16067 return nullptr; 16068 } 16069 16070 // Figure out the underlying type if this a enum declaration. We need to do 16071 // this early, because it's needed to detect if this is an incompatible 16072 // redeclaration. 16073 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 16074 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 16075 16076 if (Kind == TTK_Enum) { 16077 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 16078 // No underlying type explicitly specified, or we failed to parse the 16079 // type, default to int. 16080 EnumUnderlying = Context.IntTy.getTypePtr(); 16081 } else if (UnderlyingType.get()) { 16082 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 16083 // integral type; any cv-qualification is ignored. 16084 TypeSourceInfo *TI = nullptr; 16085 GetTypeFromParser(UnderlyingType.get(), &TI); 16086 EnumUnderlying = TI; 16087 16088 if (CheckEnumUnderlyingType(TI)) 16089 // Recover by falling back to int. 16090 EnumUnderlying = Context.IntTy.getTypePtr(); 16091 16092 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 16093 UPPC_FixedUnderlyingType)) 16094 EnumUnderlying = Context.IntTy.getTypePtr(); 16095 16096 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 16097 // For MSVC ABI compatibility, unfixed enums must use an underlying type 16098 // of 'int'. However, if this is an unfixed forward declaration, don't set 16099 // the underlying type unless the user enables -fms-compatibility. This 16100 // makes unfixed forward declared enums incomplete and is more conforming. 16101 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 16102 EnumUnderlying = Context.IntTy.getTypePtr(); 16103 } 16104 } 16105 16106 DeclContext *SearchDC = CurContext; 16107 DeclContext *DC = CurContext; 16108 bool isStdBadAlloc = false; 16109 bool isStdAlignValT = false; 16110 16111 RedeclarationKind Redecl = forRedeclarationInCurContext(); 16112 if (TUK == TUK_Friend || TUK == TUK_Reference) 16113 Redecl = NotForRedeclaration; 16114 16115 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 16116 /// implemented asks for structural equivalence checking, the returned decl 16117 /// here is passed back to the parser, allowing the tag body to be parsed. 16118 auto createTagFromNewDecl = [&]() -> TagDecl * { 16119 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 16120 // If there is an identifier, use the location of the identifier as the 16121 // location of the decl, otherwise use the location of the struct/union 16122 // keyword. 16123 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16124 TagDecl *New = nullptr; 16125 16126 if (Kind == TTK_Enum) { 16127 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 16128 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 16129 // If this is an undefined enum, bail. 16130 if (TUK != TUK_Definition && !Invalid) 16131 return nullptr; 16132 if (EnumUnderlying) { 16133 EnumDecl *ED = cast<EnumDecl>(New); 16134 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 16135 ED->setIntegerTypeSourceInfo(TI); 16136 else 16137 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 16138 ED->setPromotionType(ED->getIntegerType()); 16139 } 16140 } else { // struct/union 16141 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16142 nullptr); 16143 } 16144 16145 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16146 // Add alignment attributes if necessary; these attributes are checked 16147 // when the ASTContext lays out the structure. 16148 // 16149 // It is important for implementing the correct semantics that this 16150 // happen here (in ActOnTag). The #pragma pack stack is 16151 // maintained as a result of parser callbacks which can occur at 16152 // many points during the parsing of a struct declaration (because 16153 // the #pragma tokens are effectively skipped over during the 16154 // parsing of the struct). 16155 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16156 AddAlignmentAttributesForRecord(RD); 16157 AddMsStructLayoutForRecord(RD); 16158 } 16159 } 16160 New->setLexicalDeclContext(CurContext); 16161 return New; 16162 }; 16163 16164 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 16165 if (Name && SS.isNotEmpty()) { 16166 // We have a nested-name tag ('struct foo::bar'). 16167 16168 // Check for invalid 'foo::'. 16169 if (SS.isInvalid()) { 16170 Name = nullptr; 16171 goto CreateNewDecl; 16172 } 16173 16174 // If this is a friend or a reference to a class in a dependent 16175 // context, don't try to make a decl for it. 16176 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16177 DC = computeDeclContext(SS, false); 16178 if (!DC) { 16179 IsDependent = true; 16180 return nullptr; 16181 } 16182 } else { 16183 DC = computeDeclContext(SS, true); 16184 if (!DC) { 16185 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 16186 << SS.getRange(); 16187 return nullptr; 16188 } 16189 } 16190 16191 if (RequireCompleteDeclContext(SS, DC)) 16192 return nullptr; 16193 16194 SearchDC = DC; 16195 // Look-up name inside 'foo::'. 16196 LookupQualifiedName(Previous, DC); 16197 16198 if (Previous.isAmbiguous()) 16199 return nullptr; 16200 16201 if (Previous.empty()) { 16202 // Name lookup did not find anything. However, if the 16203 // nested-name-specifier refers to the current instantiation, 16204 // and that current instantiation has any dependent base 16205 // classes, we might find something at instantiation time: treat 16206 // this as a dependent elaborated-type-specifier. 16207 // But this only makes any sense for reference-like lookups. 16208 if (Previous.wasNotFoundInCurrentInstantiation() && 16209 (TUK == TUK_Reference || TUK == TUK_Friend)) { 16210 IsDependent = true; 16211 return nullptr; 16212 } 16213 16214 // A tag 'foo::bar' must already exist. 16215 Diag(NameLoc, diag::err_not_tag_in_scope) 16216 << Kind << Name << DC << SS.getRange(); 16217 Name = nullptr; 16218 Invalid = true; 16219 goto CreateNewDecl; 16220 } 16221 } else if (Name) { 16222 // C++14 [class.mem]p14: 16223 // If T is the name of a class, then each of the following shall have a 16224 // name different from T: 16225 // -- every member of class T that is itself a type 16226 if (TUK != TUK_Reference && TUK != TUK_Friend && 16227 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 16228 return nullptr; 16229 16230 // If this is a named struct, check to see if there was a previous forward 16231 // declaration or definition. 16232 // FIXME: We're looking into outer scopes here, even when we 16233 // shouldn't be. Doing so can result in ambiguities that we 16234 // shouldn't be diagnosing. 16235 LookupName(Previous, S); 16236 16237 // When declaring or defining a tag, ignore ambiguities introduced 16238 // by types using'ed into this scope. 16239 if (Previous.isAmbiguous() && 16240 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 16241 LookupResult::Filter F = Previous.makeFilter(); 16242 while (F.hasNext()) { 16243 NamedDecl *ND = F.next(); 16244 if (!ND->getDeclContext()->getRedeclContext()->Equals( 16245 SearchDC->getRedeclContext())) 16246 F.erase(); 16247 } 16248 F.done(); 16249 } 16250 16251 // C++11 [namespace.memdef]p3: 16252 // If the name in a friend declaration is neither qualified nor 16253 // a template-id and the declaration is a function or an 16254 // elaborated-type-specifier, the lookup to determine whether 16255 // the entity has been previously declared shall not consider 16256 // any scopes outside the innermost enclosing namespace. 16257 // 16258 // MSVC doesn't implement the above rule for types, so a friend tag 16259 // declaration may be a redeclaration of a type declared in an enclosing 16260 // scope. They do implement this rule for friend functions. 16261 // 16262 // Does it matter that this should be by scope instead of by 16263 // semantic context? 16264 if (!Previous.empty() && TUK == TUK_Friend) { 16265 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 16266 LookupResult::Filter F = Previous.makeFilter(); 16267 bool FriendSawTagOutsideEnclosingNamespace = false; 16268 while (F.hasNext()) { 16269 NamedDecl *ND = F.next(); 16270 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 16271 if (DC->isFileContext() && 16272 !EnclosingNS->Encloses(ND->getDeclContext())) { 16273 if (getLangOpts().MSVCCompat) 16274 FriendSawTagOutsideEnclosingNamespace = true; 16275 else 16276 F.erase(); 16277 } 16278 } 16279 F.done(); 16280 16281 // Diagnose this MSVC extension in the easy case where lookup would have 16282 // unambiguously found something outside the enclosing namespace. 16283 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 16284 NamedDecl *ND = Previous.getFoundDecl(); 16285 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 16286 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 16287 } 16288 } 16289 16290 // Note: there used to be some attempt at recovery here. 16291 if (Previous.isAmbiguous()) 16292 return nullptr; 16293 16294 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 16295 // FIXME: This makes sure that we ignore the contexts associated 16296 // with C structs, unions, and enums when looking for a matching 16297 // tag declaration or definition. See the similar lookup tweak 16298 // in Sema::LookupName; is there a better way to deal with this? 16299 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) 16300 SearchDC = SearchDC->getParent(); 16301 } else if (getLangOpts().CPlusPlus) { 16302 // Inside ObjCContainer want to keep it as a lexical decl context but go 16303 // past it (most often to TranslationUnit) to find the semantic decl 16304 // context. 16305 while (isa<ObjCContainerDecl>(SearchDC)) 16306 SearchDC = SearchDC->getParent(); 16307 } 16308 } else if (getLangOpts().CPlusPlus) { 16309 // Don't use ObjCContainerDecl as the semantic decl context for anonymous 16310 // TagDecl the same way as we skip it for named TagDecl. 16311 while (isa<ObjCContainerDecl>(SearchDC)) 16312 SearchDC = SearchDC->getParent(); 16313 } 16314 16315 if (Previous.isSingleResult() && 16316 Previous.getFoundDecl()->isTemplateParameter()) { 16317 // Maybe we will complain about the shadowed template parameter. 16318 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 16319 // Just pretend that we didn't see the previous declaration. 16320 Previous.clear(); 16321 } 16322 16323 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 16324 DC->Equals(getStdNamespace())) { 16325 if (Name->isStr("bad_alloc")) { 16326 // This is a declaration of or a reference to "std::bad_alloc". 16327 isStdBadAlloc = true; 16328 16329 // If std::bad_alloc has been implicitly declared (but made invisible to 16330 // name lookup), fill in this implicit declaration as the previous 16331 // declaration, so that the declarations get chained appropriately. 16332 if (Previous.empty() && StdBadAlloc) 16333 Previous.addDecl(getStdBadAlloc()); 16334 } else if (Name->isStr("align_val_t")) { 16335 isStdAlignValT = true; 16336 if (Previous.empty() && StdAlignValT) 16337 Previous.addDecl(getStdAlignValT()); 16338 } 16339 } 16340 16341 // If we didn't find a previous declaration, and this is a reference 16342 // (or friend reference), move to the correct scope. In C++, we 16343 // also need to do a redeclaration lookup there, just in case 16344 // there's a shadow friend decl. 16345 if (Name && Previous.empty() && 16346 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 16347 if (Invalid) goto CreateNewDecl; 16348 assert(SS.isEmpty()); 16349 16350 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 16351 // C++ [basic.scope.pdecl]p5: 16352 // -- for an elaborated-type-specifier of the form 16353 // 16354 // class-key identifier 16355 // 16356 // if the elaborated-type-specifier is used in the 16357 // decl-specifier-seq or parameter-declaration-clause of a 16358 // function defined in namespace scope, the identifier is 16359 // declared as a class-name in the namespace that contains 16360 // the declaration; otherwise, except as a friend 16361 // declaration, the identifier is declared in the smallest 16362 // non-class, non-function-prototype scope that contains the 16363 // declaration. 16364 // 16365 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 16366 // C structs and unions. 16367 // 16368 // It is an error in C++ to declare (rather than define) an enum 16369 // type, including via an elaborated type specifier. We'll 16370 // diagnose that later; for now, declare the enum in the same 16371 // scope as we would have picked for any other tag type. 16372 // 16373 // GNU C also supports this behavior as part of its incomplete 16374 // enum types extension, while GNU C++ does not. 16375 // 16376 // Find the context where we'll be declaring the tag. 16377 // FIXME: We would like to maintain the current DeclContext as the 16378 // lexical context, 16379 SearchDC = getTagInjectionContext(SearchDC); 16380 16381 // Find the scope where we'll be declaring the tag. 16382 S = getTagInjectionScope(S, getLangOpts()); 16383 } else { 16384 assert(TUK == TUK_Friend); 16385 // C++ [namespace.memdef]p3: 16386 // If a friend declaration in a non-local class first declares a 16387 // class or function, the friend class or function is a member of 16388 // the innermost enclosing namespace. 16389 SearchDC = SearchDC->getEnclosingNamespaceContext(); 16390 } 16391 16392 // In C++, we need to do a redeclaration lookup to properly 16393 // diagnose some problems. 16394 // FIXME: redeclaration lookup is also used (with and without C++) to find a 16395 // hidden declaration so that we don't get ambiguity errors when using a 16396 // type declared by an elaborated-type-specifier. In C that is not correct 16397 // and we should instead merge compatible types found by lookup. 16398 if (getLangOpts().CPlusPlus) { 16399 // FIXME: This can perform qualified lookups into function contexts, 16400 // which are meaningless. 16401 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16402 LookupQualifiedName(Previous, SearchDC); 16403 } else { 16404 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16405 LookupName(Previous, S); 16406 } 16407 } 16408 16409 // If we have a known previous declaration to use, then use it. 16410 if (Previous.empty() && SkipBody && SkipBody->Previous) 16411 Previous.addDecl(SkipBody->Previous); 16412 16413 if (!Previous.empty()) { 16414 NamedDecl *PrevDecl = Previous.getFoundDecl(); 16415 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 16416 16417 // It's okay to have a tag decl in the same scope as a typedef 16418 // which hides a tag decl in the same scope. Finding this 16419 // with a redeclaration lookup can only actually happen in C++. 16420 // 16421 // This is also okay for elaborated-type-specifiers, which is 16422 // technically forbidden by the current standard but which is 16423 // okay according to the likely resolution of an open issue; 16424 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16425 if (getLangOpts().CPlusPlus) { 16426 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16427 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16428 TagDecl *Tag = TT->getDecl(); 16429 if (Tag->getDeclName() == Name && 16430 Tag->getDeclContext()->getRedeclContext() 16431 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16432 PrevDecl = Tag; 16433 Previous.clear(); 16434 Previous.addDecl(Tag); 16435 Previous.resolveKind(); 16436 } 16437 } 16438 } 16439 } 16440 16441 // If this is a redeclaration of a using shadow declaration, it must 16442 // declare a tag in the same context. In MSVC mode, we allow a 16443 // redefinition if either context is within the other. 16444 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16445 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16446 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16447 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16448 !(OldTag && isAcceptableTagRedeclContext( 16449 *this, OldTag->getDeclContext(), SearchDC))) { 16450 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16451 Diag(Shadow->getTargetDecl()->getLocation(), 16452 diag::note_using_decl_target); 16453 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16454 << 0; 16455 // Recover by ignoring the old declaration. 16456 Previous.clear(); 16457 goto CreateNewDecl; 16458 } 16459 } 16460 16461 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16462 // If this is a use of a previous tag, or if the tag is already declared 16463 // in the same scope (so that the definition/declaration completes or 16464 // rementions the tag), reuse the decl. 16465 if (TUK == TUK_Reference || TUK == TUK_Friend || 16466 isDeclInScope(DirectPrevDecl, SearchDC, S, 16467 SS.isNotEmpty() || isMemberSpecialization)) { 16468 // Make sure that this wasn't declared as an enum and now used as a 16469 // struct or something similar. 16470 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16471 TUK == TUK_Definition, KWLoc, 16472 Name)) { 16473 bool SafeToContinue 16474 = (PrevTagDecl->getTagKind() != TTK_Enum && 16475 Kind != TTK_Enum); 16476 if (SafeToContinue) 16477 Diag(KWLoc, diag::err_use_with_wrong_tag) 16478 << Name 16479 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16480 PrevTagDecl->getKindName()); 16481 else 16482 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16483 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16484 16485 if (SafeToContinue) 16486 Kind = PrevTagDecl->getTagKind(); 16487 else { 16488 // Recover by making this an anonymous redefinition. 16489 Name = nullptr; 16490 Previous.clear(); 16491 Invalid = true; 16492 } 16493 } 16494 16495 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16496 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16497 if (TUK == TUK_Reference || TUK == TUK_Friend) 16498 return PrevTagDecl; 16499 16500 QualType EnumUnderlyingTy; 16501 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16502 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16503 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16504 EnumUnderlyingTy = QualType(T, 0); 16505 16506 // All conflicts with previous declarations are recovered by 16507 // returning the previous declaration, unless this is a definition, 16508 // in which case we want the caller to bail out. 16509 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16510 ScopedEnum, EnumUnderlyingTy, 16511 IsFixed, PrevEnum)) 16512 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16513 } 16514 16515 // C++11 [class.mem]p1: 16516 // A member shall not be declared twice in the member-specification, 16517 // except that a nested class or member class template can be declared 16518 // and then later defined. 16519 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16520 S->isDeclScope(PrevDecl)) { 16521 Diag(NameLoc, diag::ext_member_redeclared); 16522 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16523 } 16524 16525 if (!Invalid) { 16526 // If this is a use, just return the declaration we found, unless 16527 // we have attributes. 16528 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16529 if (!Attrs.empty()) { 16530 // FIXME: Diagnose these attributes. For now, we create a new 16531 // declaration to hold them. 16532 } else if (TUK == TUK_Reference && 16533 (PrevTagDecl->getFriendObjectKind() == 16534 Decl::FOK_Undeclared || 16535 PrevDecl->getOwningModule() != getCurrentModule()) && 16536 SS.isEmpty()) { 16537 // This declaration is a reference to an existing entity, but 16538 // has different visibility from that entity: it either makes 16539 // a friend visible or it makes a type visible in a new module. 16540 // In either case, create a new declaration. We only do this if 16541 // the declaration would have meant the same thing if no prior 16542 // declaration were found, that is, if it was found in the same 16543 // scope where we would have injected a declaration. 16544 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16545 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16546 return PrevTagDecl; 16547 // This is in the injected scope, create a new declaration in 16548 // that scope. 16549 S = getTagInjectionScope(S, getLangOpts()); 16550 } else { 16551 return PrevTagDecl; 16552 } 16553 } 16554 16555 // Diagnose attempts to redefine a tag. 16556 if (TUK == TUK_Definition) { 16557 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16558 // If we're defining a specialization and the previous definition 16559 // is from an implicit instantiation, don't emit an error 16560 // here; we'll catch this in the general case below. 16561 bool IsExplicitSpecializationAfterInstantiation = false; 16562 if (isMemberSpecialization) { 16563 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16564 IsExplicitSpecializationAfterInstantiation = 16565 RD->getTemplateSpecializationKind() != 16566 TSK_ExplicitSpecialization; 16567 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16568 IsExplicitSpecializationAfterInstantiation = 16569 ED->getTemplateSpecializationKind() != 16570 TSK_ExplicitSpecialization; 16571 } 16572 16573 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16574 // not keep more that one definition around (merge them). However, 16575 // ensure the decl passes the structural compatibility check in 16576 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16577 NamedDecl *Hidden = nullptr; 16578 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16579 // There is a definition of this tag, but it is not visible. We 16580 // explicitly make use of C++'s one definition rule here, and 16581 // assume that this definition is identical to the hidden one 16582 // we already have. Make the existing definition visible and 16583 // use it in place of this one. 16584 if (!getLangOpts().CPlusPlus) { 16585 // Postpone making the old definition visible until after we 16586 // complete parsing the new one and do the structural 16587 // comparison. 16588 SkipBody->CheckSameAsPrevious = true; 16589 SkipBody->New = createTagFromNewDecl(); 16590 SkipBody->Previous = Def; 16591 return Def; 16592 } else { 16593 SkipBody->ShouldSkip = true; 16594 SkipBody->Previous = Def; 16595 makeMergedDefinitionVisible(Hidden); 16596 // Carry on and handle it like a normal definition. We'll 16597 // skip starting the definitiion later. 16598 } 16599 } else if (!IsExplicitSpecializationAfterInstantiation) { 16600 // A redeclaration in function prototype scope in C isn't 16601 // visible elsewhere, so merely issue a warning. 16602 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16603 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16604 else 16605 Diag(NameLoc, diag::err_redefinition) << Name; 16606 notePreviousDefinition(Def, 16607 NameLoc.isValid() ? NameLoc : KWLoc); 16608 // If this is a redefinition, recover by making this 16609 // struct be anonymous, which will make any later 16610 // references get the previous definition. 16611 Name = nullptr; 16612 Previous.clear(); 16613 Invalid = true; 16614 } 16615 } else { 16616 // If the type is currently being defined, complain 16617 // about a nested redefinition. 16618 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16619 if (TD->isBeingDefined()) { 16620 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16621 Diag(PrevTagDecl->getLocation(), 16622 diag::note_previous_definition); 16623 Name = nullptr; 16624 Previous.clear(); 16625 Invalid = true; 16626 } 16627 } 16628 16629 // Okay, this is definition of a previously declared or referenced 16630 // tag. We're going to create a new Decl for it. 16631 } 16632 16633 // Okay, we're going to make a redeclaration. If this is some kind 16634 // of reference, make sure we build the redeclaration in the same DC 16635 // as the original, and ignore the current access specifier. 16636 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16637 SearchDC = PrevTagDecl->getDeclContext(); 16638 AS = AS_none; 16639 } 16640 } 16641 // If we get here we have (another) forward declaration or we 16642 // have a definition. Just create a new decl. 16643 16644 } else { 16645 // If we get here, this is a definition of a new tag type in a nested 16646 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16647 // new decl/type. We set PrevDecl to NULL so that the entities 16648 // have distinct types. 16649 Previous.clear(); 16650 } 16651 // If we get here, we're going to create a new Decl. If PrevDecl 16652 // is non-NULL, it's a definition of the tag declared by 16653 // PrevDecl. If it's NULL, we have a new definition. 16654 16655 // Otherwise, PrevDecl is not a tag, but was found with tag 16656 // lookup. This is only actually possible in C++, where a few 16657 // things like templates still live in the tag namespace. 16658 } else { 16659 // Use a better diagnostic if an elaborated-type-specifier 16660 // found the wrong kind of type on the first 16661 // (non-redeclaration) lookup. 16662 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16663 !Previous.isForRedeclaration()) { 16664 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16665 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16666 << Kind; 16667 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16668 Invalid = true; 16669 16670 // Otherwise, only diagnose if the declaration is in scope. 16671 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16672 SS.isNotEmpty() || isMemberSpecialization)) { 16673 // do nothing 16674 16675 // Diagnose implicit declarations introduced by elaborated types. 16676 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16677 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16678 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16679 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16680 Invalid = true; 16681 16682 // Otherwise it's a declaration. Call out a particularly common 16683 // case here. 16684 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16685 unsigned Kind = 0; 16686 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16687 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16688 << Name << Kind << TND->getUnderlyingType(); 16689 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16690 Invalid = true; 16691 16692 // Otherwise, diagnose. 16693 } else { 16694 // The tag name clashes with something else in the target scope, 16695 // issue an error and recover by making this tag be anonymous. 16696 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16697 notePreviousDefinition(PrevDecl, NameLoc); 16698 Name = nullptr; 16699 Invalid = true; 16700 } 16701 16702 // The existing declaration isn't relevant to us; we're in a 16703 // new scope, so clear out the previous declaration. 16704 Previous.clear(); 16705 } 16706 } 16707 16708 CreateNewDecl: 16709 16710 TagDecl *PrevDecl = nullptr; 16711 if (Previous.isSingleResult()) 16712 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16713 16714 // If there is an identifier, use the location of the identifier as the 16715 // location of the decl, otherwise use the location of the struct/union 16716 // keyword. 16717 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16718 16719 // Otherwise, create a new declaration. If there is a previous 16720 // declaration of the same entity, the two will be linked via 16721 // PrevDecl. 16722 TagDecl *New; 16723 16724 if (Kind == TTK_Enum) { 16725 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16726 // enum X { A, B, C } D; D should chain to X. 16727 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16728 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16729 ScopedEnumUsesClassTag, IsFixed); 16730 16731 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16732 StdAlignValT = cast<EnumDecl>(New); 16733 16734 // If this is an undefined enum, warn. 16735 if (TUK != TUK_Definition && !Invalid) { 16736 TagDecl *Def; 16737 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16738 // C++0x: 7.2p2: opaque-enum-declaration. 16739 // Conflicts are diagnosed above. Do nothing. 16740 } 16741 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16742 Diag(Loc, diag::ext_forward_ref_enum_def) 16743 << New; 16744 Diag(Def->getLocation(), diag::note_previous_definition); 16745 } else { 16746 unsigned DiagID = diag::ext_forward_ref_enum; 16747 if (getLangOpts().MSVCCompat) 16748 DiagID = diag::ext_ms_forward_ref_enum; 16749 else if (getLangOpts().CPlusPlus) 16750 DiagID = diag::err_forward_ref_enum; 16751 Diag(Loc, DiagID); 16752 } 16753 } 16754 16755 if (EnumUnderlying) { 16756 EnumDecl *ED = cast<EnumDecl>(New); 16757 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16758 ED->setIntegerTypeSourceInfo(TI); 16759 else 16760 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16761 ED->setPromotionType(ED->getIntegerType()); 16762 assert(ED->isComplete() && "enum with type should be complete"); 16763 } 16764 } else { 16765 // struct/union/class 16766 16767 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16768 // struct X { int A; } D; D should chain to X. 16769 if (getLangOpts().CPlusPlus) { 16770 // FIXME: Look for a way to use RecordDecl for simple structs. 16771 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16772 cast_or_null<CXXRecordDecl>(PrevDecl)); 16773 16774 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16775 StdBadAlloc = cast<CXXRecordDecl>(New); 16776 } else 16777 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16778 cast_or_null<RecordDecl>(PrevDecl)); 16779 } 16780 16781 // C++11 [dcl.type]p3: 16782 // A type-specifier-seq shall not define a class or enumeration [...]. 16783 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16784 TUK == TUK_Definition) { 16785 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16786 << Context.getTagDeclType(New); 16787 Invalid = true; 16788 } 16789 16790 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16791 DC->getDeclKind() == Decl::Enum) { 16792 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16793 << Context.getTagDeclType(New); 16794 Invalid = true; 16795 } 16796 16797 // Maybe add qualifier info. 16798 if (SS.isNotEmpty()) { 16799 if (SS.isSet()) { 16800 // If this is either a declaration or a definition, check the 16801 // nested-name-specifier against the current context. 16802 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16803 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16804 isMemberSpecialization)) 16805 Invalid = true; 16806 16807 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16808 if (TemplateParameterLists.size() > 0) { 16809 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16810 } 16811 } 16812 else 16813 Invalid = true; 16814 } 16815 16816 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16817 // Add alignment attributes if necessary; these attributes are checked when 16818 // the ASTContext lays out the structure. 16819 // 16820 // It is important for implementing the correct semantics that this 16821 // happen here (in ActOnTag). The #pragma pack stack is 16822 // maintained as a result of parser callbacks which can occur at 16823 // many points during the parsing of a struct declaration (because 16824 // the #pragma tokens are effectively skipped over during the 16825 // parsing of the struct). 16826 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16827 AddAlignmentAttributesForRecord(RD); 16828 AddMsStructLayoutForRecord(RD); 16829 } 16830 } 16831 16832 if (ModulePrivateLoc.isValid()) { 16833 if (isMemberSpecialization) 16834 Diag(New->getLocation(), diag::err_module_private_specialization) 16835 << 2 16836 << FixItHint::CreateRemoval(ModulePrivateLoc); 16837 // __module_private__ does not apply to local classes. However, we only 16838 // diagnose this as an error when the declaration specifiers are 16839 // freestanding. Here, we just ignore the __module_private__. 16840 else if (!SearchDC->isFunctionOrMethod()) 16841 New->setModulePrivate(); 16842 } 16843 16844 // If this is a specialization of a member class (of a class template), 16845 // check the specialization. 16846 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16847 Invalid = true; 16848 16849 // If we're declaring or defining a tag in function prototype scope in C, 16850 // note that this type can only be used within the function and add it to 16851 // the list of decls to inject into the function definition scope. 16852 if ((Name || Kind == TTK_Enum) && 16853 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16854 if (getLangOpts().CPlusPlus) { 16855 // C++ [dcl.fct]p6: 16856 // Types shall not be defined in return or parameter types. 16857 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16858 Diag(Loc, diag::err_type_defined_in_param_type) 16859 << Name; 16860 Invalid = true; 16861 } 16862 } else if (!PrevDecl) { 16863 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16864 } 16865 } 16866 16867 if (Invalid) 16868 New->setInvalidDecl(); 16869 16870 // Set the lexical context. If the tag has a C++ scope specifier, the 16871 // lexical context will be different from the semantic context. 16872 New->setLexicalDeclContext(CurContext); 16873 16874 // Mark this as a friend decl if applicable. 16875 // In Microsoft mode, a friend declaration also acts as a forward 16876 // declaration so we always pass true to setObjectOfFriendDecl to make 16877 // the tag name visible. 16878 if (TUK == TUK_Friend) 16879 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16880 16881 // Set the access specifier. 16882 if (!Invalid && SearchDC->isRecord()) 16883 SetMemberAccessSpecifier(New, PrevDecl, AS); 16884 16885 if (PrevDecl) 16886 CheckRedeclarationInModule(New, PrevDecl); 16887 16888 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16889 New->startDefinition(); 16890 16891 ProcessDeclAttributeList(S, New, Attrs); 16892 AddPragmaAttributes(S, New); 16893 16894 // If this has an identifier, add it to the scope stack. 16895 if (TUK == TUK_Friend) { 16896 // We might be replacing an existing declaration in the lookup tables; 16897 // if so, borrow its access specifier. 16898 if (PrevDecl) 16899 New->setAccess(PrevDecl->getAccess()); 16900 16901 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16902 DC->makeDeclVisibleInContext(New); 16903 if (Name) // can be null along some error paths 16904 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16905 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16906 } else if (Name) { 16907 S = getNonFieldDeclScope(S); 16908 PushOnScopeChains(New, S, true); 16909 } else { 16910 CurContext->addDecl(New); 16911 } 16912 16913 // If this is the C FILE type, notify the AST context. 16914 if (IdentifierInfo *II = New->getIdentifier()) 16915 if (!New->isInvalidDecl() && 16916 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16917 II->isStr("FILE")) 16918 Context.setFILEDecl(New); 16919 16920 if (PrevDecl) 16921 mergeDeclAttributes(New, PrevDecl); 16922 16923 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16924 inferGslOwnerPointerAttribute(CXXRD); 16925 16926 // If there's a #pragma GCC visibility in scope, set the visibility of this 16927 // record. 16928 AddPushedVisibilityAttribute(New); 16929 16930 if (isMemberSpecialization && !New->isInvalidDecl()) 16931 CompleteMemberSpecialization(New, Previous); 16932 16933 OwnedDecl = true; 16934 // In C++, don't return an invalid declaration. We can't recover well from 16935 // the cases where we make the type anonymous. 16936 if (Invalid && getLangOpts().CPlusPlus) { 16937 if (New->isBeingDefined()) 16938 if (auto RD = dyn_cast<RecordDecl>(New)) 16939 RD->completeDefinition(); 16940 return nullptr; 16941 } else if (SkipBody && SkipBody->ShouldSkip) { 16942 return SkipBody->Previous; 16943 } else { 16944 return New; 16945 } 16946 } 16947 16948 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16949 AdjustDeclIfTemplate(TagD); 16950 TagDecl *Tag = cast<TagDecl>(TagD); 16951 16952 // Enter the tag context. 16953 PushDeclContext(S, Tag); 16954 16955 ActOnDocumentableDecl(TagD); 16956 16957 // If there's a #pragma GCC visibility in scope, set the visibility of this 16958 // record. 16959 AddPushedVisibilityAttribute(Tag); 16960 } 16961 16962 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { 16963 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16964 return false; 16965 16966 // Make the previous decl visible. 16967 makeMergedDefinitionVisible(SkipBody.Previous); 16968 return true; 16969 } 16970 16971 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16972 assert(isa<ObjCContainerDecl>(IDecl) && 16973 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16974 DeclContext *OCD = cast<DeclContext>(IDecl); 16975 assert(OCD->getLexicalParent() == CurContext && 16976 "The next DeclContext should be lexically contained in the current one."); 16977 CurContext = OCD; 16978 return IDecl; 16979 } 16980 16981 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16982 SourceLocation FinalLoc, 16983 bool IsFinalSpelledSealed, 16984 bool IsAbstract, 16985 SourceLocation LBraceLoc) { 16986 AdjustDeclIfTemplate(TagD); 16987 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16988 16989 FieldCollector->StartClass(); 16990 16991 if (!Record->getIdentifier()) 16992 return; 16993 16994 if (IsAbstract) 16995 Record->markAbstract(); 16996 16997 if (FinalLoc.isValid()) { 16998 Record->addAttr(FinalAttr::Create( 16999 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 17000 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 17001 } 17002 // C++ [class]p2: 17003 // [...] The class-name is also inserted into the scope of the 17004 // class itself; this is known as the injected-class-name. For 17005 // purposes of access checking, the injected-class-name is treated 17006 // as if it were a public member name. 17007 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 17008 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 17009 Record->getLocation(), Record->getIdentifier(), 17010 /*PrevDecl=*/nullptr, 17011 /*DelayTypeCreation=*/true); 17012 Context.getTypeDeclType(InjectedClassName, Record); 17013 InjectedClassName->setImplicit(); 17014 InjectedClassName->setAccess(AS_public); 17015 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 17016 InjectedClassName->setDescribedClassTemplate(Template); 17017 PushOnScopeChains(InjectedClassName, S); 17018 assert(InjectedClassName->isInjectedClassName() && 17019 "Broken injected-class-name"); 17020 } 17021 17022 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 17023 SourceRange BraceRange) { 17024 AdjustDeclIfTemplate(TagD); 17025 TagDecl *Tag = cast<TagDecl>(TagD); 17026 Tag->setBraceRange(BraceRange); 17027 17028 // Make sure we "complete" the definition even it is invalid. 17029 if (Tag->isBeingDefined()) { 17030 assert(Tag->isInvalidDecl() && "We should already have completed it"); 17031 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 17032 RD->completeDefinition(); 17033 } 17034 17035 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 17036 FieldCollector->FinishClass(); 17037 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 17038 auto *Def = RD->getDefinition(); 17039 assert(Def && "The record is expected to have a completed definition"); 17040 unsigned NumInitMethods = 0; 17041 for (auto *Method : Def->methods()) { 17042 if (!Method->getIdentifier()) 17043 continue; 17044 if (Method->getName() == "__init") 17045 NumInitMethods++; 17046 } 17047 if (NumInitMethods > 1 || !Def->hasInitMethod()) 17048 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 17049 } 17050 } 17051 17052 // Exit this scope of this tag's definition. 17053 PopDeclContext(); 17054 17055 if (getCurLexicalContext()->isObjCContainer() && 17056 Tag->getDeclContext()->isFileContext()) 17057 Tag->setTopLevelDeclInObjCContainer(); 17058 17059 // Notify the consumer that we've defined a tag. 17060 if (!Tag->isInvalidDecl()) 17061 Consumer.HandleTagDeclDefinition(Tag); 17062 17063 // Clangs implementation of #pragma align(packed) differs in bitfield layout 17064 // from XLs and instead matches the XL #pragma pack(1) behavior. 17065 if (Context.getTargetInfo().getTriple().isOSAIX() && 17066 AlignPackStack.hasValue()) { 17067 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 17068 // Only diagnose #pragma align(packed). 17069 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 17070 return; 17071 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 17072 if (!RD) 17073 return; 17074 // Only warn if there is at least 1 bitfield member. 17075 if (llvm::any_of(RD->fields(), 17076 [](const FieldDecl *FD) { return FD->isBitField(); })) 17077 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 17078 } 17079 } 17080 17081 void Sema::ActOnObjCContainerFinishDefinition() { 17082 // Exit this scope of this interface definition. 17083 PopDeclContext(); 17084 } 17085 17086 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 17087 assert(DC == CurContext && "Mismatch of container contexts"); 17088 OriginalLexicalContext = DC; 17089 ActOnObjCContainerFinishDefinition(); 17090 } 17091 17092 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 17093 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 17094 OriginalLexicalContext = nullptr; 17095 } 17096 17097 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 17098 AdjustDeclIfTemplate(TagD); 17099 TagDecl *Tag = cast<TagDecl>(TagD); 17100 Tag->setInvalidDecl(); 17101 17102 // Make sure we "complete" the definition even it is invalid. 17103 if (Tag->isBeingDefined()) { 17104 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 17105 RD->completeDefinition(); 17106 } 17107 17108 // We're undoing ActOnTagStartDefinition here, not 17109 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 17110 // the FieldCollector. 17111 17112 PopDeclContext(); 17113 } 17114 17115 // Note that FieldName may be null for anonymous bitfields. 17116 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 17117 IdentifierInfo *FieldName, 17118 QualType FieldTy, bool IsMsStruct, 17119 Expr *BitWidth, bool *ZeroWidth) { 17120 assert(BitWidth); 17121 if (BitWidth->containsErrors()) 17122 return ExprError(); 17123 17124 // Default to true; that shouldn't confuse checks for emptiness 17125 if (ZeroWidth) 17126 *ZeroWidth = true; 17127 17128 // C99 6.7.2.1p4 - verify the field type. 17129 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 17130 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 17131 // Handle incomplete and sizeless types with a specific error. 17132 if (RequireCompleteSizedType(FieldLoc, FieldTy, 17133 diag::err_field_incomplete_or_sizeless)) 17134 return ExprError(); 17135 if (FieldName) 17136 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 17137 << FieldName << FieldTy << BitWidth->getSourceRange(); 17138 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 17139 << FieldTy << BitWidth->getSourceRange(); 17140 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 17141 UPPC_BitFieldWidth)) 17142 return ExprError(); 17143 17144 // If the bit-width is type- or value-dependent, don't try to check 17145 // it now. 17146 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 17147 return BitWidth; 17148 17149 llvm::APSInt Value; 17150 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 17151 if (ICE.isInvalid()) 17152 return ICE; 17153 BitWidth = ICE.get(); 17154 17155 if (Value != 0 && ZeroWidth) 17156 *ZeroWidth = false; 17157 17158 // Zero-width bitfield is ok for anonymous field. 17159 if (Value == 0 && FieldName) 17160 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 17161 17162 if (Value.isSigned() && Value.isNegative()) { 17163 if (FieldName) 17164 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 17165 << FieldName << toString(Value, 10); 17166 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 17167 << toString(Value, 10); 17168 } 17169 17170 // The size of the bit-field must not exceed our maximum permitted object 17171 // size. 17172 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 17173 return Diag(FieldLoc, diag::err_bitfield_too_wide) 17174 << !FieldName << FieldName << toString(Value, 10); 17175 } 17176 17177 if (!FieldTy->isDependentType()) { 17178 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 17179 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 17180 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 17181 17182 // Over-wide bitfields are an error in C or when using the MSVC bitfield 17183 // ABI. 17184 bool CStdConstraintViolation = 17185 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 17186 bool MSBitfieldViolation = 17187 Value.ugt(TypeStorageSize) && 17188 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 17189 if (CStdConstraintViolation || MSBitfieldViolation) { 17190 unsigned DiagWidth = 17191 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 17192 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 17193 << (bool)FieldName << FieldName << toString(Value, 10) 17194 << !CStdConstraintViolation << DiagWidth; 17195 } 17196 17197 // Warn on types where the user might conceivably expect to get all 17198 // specified bits as value bits: that's all integral types other than 17199 // 'bool'. 17200 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 17201 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 17202 << FieldName << toString(Value, 10) 17203 << (unsigned)TypeWidth; 17204 } 17205 } 17206 17207 return BitWidth; 17208 } 17209 17210 /// ActOnField - Each field of a C struct/union is passed into this in order 17211 /// to create a FieldDecl object for it. 17212 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 17213 Declarator &D, Expr *BitfieldWidth) { 17214 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 17215 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 17216 /*InitStyle=*/ICIS_NoInit, AS_public); 17217 return Res; 17218 } 17219 17220 /// HandleField - Analyze a field of a C struct or a C++ data member. 17221 /// 17222 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 17223 SourceLocation DeclStart, 17224 Declarator &D, Expr *BitWidth, 17225 InClassInitStyle InitStyle, 17226 AccessSpecifier AS) { 17227 if (D.isDecompositionDeclarator()) { 17228 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 17229 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 17230 << Decomp.getSourceRange(); 17231 return nullptr; 17232 } 17233 17234 IdentifierInfo *II = D.getIdentifier(); 17235 SourceLocation Loc = DeclStart; 17236 if (II) Loc = D.getIdentifierLoc(); 17237 17238 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17239 QualType T = TInfo->getType(); 17240 if (getLangOpts().CPlusPlus) { 17241 CheckExtraCXXDefaultArguments(D); 17242 17243 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17244 UPPC_DataMemberType)) { 17245 D.setInvalidType(); 17246 T = Context.IntTy; 17247 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17248 } 17249 } 17250 17251 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17252 17253 if (D.getDeclSpec().isInlineSpecified()) 17254 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17255 << getLangOpts().CPlusPlus17; 17256 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17257 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17258 diag::err_invalid_thread) 17259 << DeclSpec::getSpecifierName(TSCS); 17260 17261 // Check to see if this name was declared as a member previously 17262 NamedDecl *PrevDecl = nullptr; 17263 LookupResult Previous(*this, II, Loc, LookupMemberName, 17264 ForVisibleRedeclaration); 17265 LookupName(Previous, S); 17266 switch (Previous.getResultKind()) { 17267 case LookupResult::Found: 17268 case LookupResult::FoundUnresolvedValue: 17269 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17270 break; 17271 17272 case LookupResult::FoundOverloaded: 17273 PrevDecl = Previous.getRepresentativeDecl(); 17274 break; 17275 17276 case LookupResult::NotFound: 17277 case LookupResult::NotFoundInCurrentInstantiation: 17278 case LookupResult::Ambiguous: 17279 break; 17280 } 17281 Previous.suppressDiagnostics(); 17282 17283 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17284 // Maybe we will complain about the shadowed template parameter. 17285 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17286 // Just pretend that we didn't see the previous declaration. 17287 PrevDecl = nullptr; 17288 } 17289 17290 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17291 PrevDecl = nullptr; 17292 17293 bool Mutable 17294 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 17295 SourceLocation TSSL = D.getBeginLoc(); 17296 FieldDecl *NewFD 17297 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 17298 TSSL, AS, PrevDecl, &D); 17299 17300 if (NewFD->isInvalidDecl()) 17301 Record->setInvalidDecl(); 17302 17303 if (D.getDeclSpec().isModulePrivateSpecified()) 17304 NewFD->setModulePrivate(); 17305 17306 if (NewFD->isInvalidDecl() && PrevDecl) { 17307 // Don't introduce NewFD into scope; there's already something 17308 // with the same name in the same scope. 17309 } else if (II) { 17310 PushOnScopeChains(NewFD, S); 17311 } else 17312 Record->addDecl(NewFD); 17313 17314 return NewFD; 17315 } 17316 17317 /// Build a new FieldDecl and check its well-formedness. 17318 /// 17319 /// This routine builds a new FieldDecl given the fields name, type, 17320 /// record, etc. \p PrevDecl should refer to any previous declaration 17321 /// with the same name and in the same scope as the field to be 17322 /// created. 17323 /// 17324 /// \returns a new FieldDecl. 17325 /// 17326 /// \todo The Declarator argument is a hack. It will be removed once 17327 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 17328 TypeSourceInfo *TInfo, 17329 RecordDecl *Record, SourceLocation Loc, 17330 bool Mutable, Expr *BitWidth, 17331 InClassInitStyle InitStyle, 17332 SourceLocation TSSL, 17333 AccessSpecifier AS, NamedDecl *PrevDecl, 17334 Declarator *D) { 17335 IdentifierInfo *II = Name.getAsIdentifierInfo(); 17336 bool InvalidDecl = false; 17337 if (D) InvalidDecl = D->isInvalidType(); 17338 17339 // If we receive a broken type, recover by assuming 'int' and 17340 // marking this declaration as invalid. 17341 if (T.isNull() || T->containsErrors()) { 17342 InvalidDecl = true; 17343 T = Context.IntTy; 17344 } 17345 17346 QualType EltTy = Context.getBaseElementType(T); 17347 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 17348 if (RequireCompleteSizedType(Loc, EltTy, 17349 diag::err_field_incomplete_or_sizeless)) { 17350 // Fields of incomplete type force their record to be invalid. 17351 Record->setInvalidDecl(); 17352 InvalidDecl = true; 17353 } else { 17354 NamedDecl *Def; 17355 EltTy->isIncompleteType(&Def); 17356 if (Def && Def->isInvalidDecl()) { 17357 Record->setInvalidDecl(); 17358 InvalidDecl = true; 17359 } 17360 } 17361 } 17362 17363 // TR 18037 does not allow fields to be declared with address space 17364 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 17365 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 17366 Diag(Loc, diag::err_field_with_address_space); 17367 Record->setInvalidDecl(); 17368 InvalidDecl = true; 17369 } 17370 17371 if (LangOpts.OpenCL) { 17372 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 17373 // used as structure or union field: image, sampler, event or block types. 17374 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 17375 T->isBlockPointerType()) { 17376 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 17377 Record->setInvalidDecl(); 17378 InvalidDecl = true; 17379 } 17380 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 17381 // is enabled. 17382 if (BitWidth && !getOpenCLOptions().isAvailableOption( 17383 "__cl_clang_bitfields", LangOpts)) { 17384 Diag(Loc, diag::err_opencl_bitfields); 17385 InvalidDecl = true; 17386 } 17387 } 17388 17389 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 17390 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 17391 T.hasQualifiers()) { 17392 InvalidDecl = true; 17393 Diag(Loc, diag::err_anon_bitfield_qualifiers); 17394 } 17395 17396 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17397 // than a variably modified type. 17398 if (!InvalidDecl && T->isVariablyModifiedType()) { 17399 if (!tryToFixVariablyModifiedVarType( 17400 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 17401 InvalidDecl = true; 17402 } 17403 17404 // Fields can not have abstract class types 17405 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 17406 diag::err_abstract_type_in_decl, 17407 AbstractFieldType)) 17408 InvalidDecl = true; 17409 17410 bool ZeroWidth = false; 17411 if (InvalidDecl) 17412 BitWidth = nullptr; 17413 // If this is declared as a bit-field, check the bit-field. 17414 if (BitWidth) { 17415 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 17416 &ZeroWidth).get(); 17417 if (!BitWidth) { 17418 InvalidDecl = true; 17419 BitWidth = nullptr; 17420 ZeroWidth = false; 17421 } 17422 } 17423 17424 // Check that 'mutable' is consistent with the type of the declaration. 17425 if (!InvalidDecl && Mutable) { 17426 unsigned DiagID = 0; 17427 if (T->isReferenceType()) 17428 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 17429 : diag::err_mutable_reference; 17430 else if (T.isConstQualified()) 17431 DiagID = diag::err_mutable_const; 17432 17433 if (DiagID) { 17434 SourceLocation ErrLoc = Loc; 17435 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17436 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17437 Diag(ErrLoc, DiagID); 17438 if (DiagID != diag::ext_mutable_reference) { 17439 Mutable = false; 17440 InvalidDecl = true; 17441 } 17442 } 17443 } 17444 17445 // C++11 [class.union]p8 (DR1460): 17446 // At most one variant member of a union may have a 17447 // brace-or-equal-initializer. 17448 if (InitStyle != ICIS_NoInit) 17449 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17450 17451 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17452 BitWidth, Mutable, InitStyle); 17453 if (InvalidDecl) 17454 NewFD->setInvalidDecl(); 17455 17456 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17457 Diag(Loc, diag::err_duplicate_member) << II; 17458 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17459 NewFD->setInvalidDecl(); 17460 } 17461 17462 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17463 if (Record->isUnion()) { 17464 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17465 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17466 if (RDecl->getDefinition()) { 17467 // C++ [class.union]p1: An object of a class with a non-trivial 17468 // constructor, a non-trivial copy constructor, a non-trivial 17469 // destructor, or a non-trivial copy assignment operator 17470 // cannot be a member of a union, nor can an array of such 17471 // objects. 17472 if (CheckNontrivialField(NewFD)) 17473 NewFD->setInvalidDecl(); 17474 } 17475 } 17476 17477 // C++ [class.union]p1: If a union contains a member of reference type, 17478 // the program is ill-formed, except when compiling with MSVC extensions 17479 // enabled. 17480 if (EltTy->isReferenceType()) { 17481 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17482 diag::ext_union_member_of_reference_type : 17483 diag::err_union_member_of_reference_type) 17484 << NewFD->getDeclName() << EltTy; 17485 if (!getLangOpts().MicrosoftExt) 17486 NewFD->setInvalidDecl(); 17487 } 17488 } 17489 } 17490 17491 // FIXME: We need to pass in the attributes given an AST 17492 // representation, not a parser representation. 17493 if (D) { 17494 // FIXME: The current scope is almost... but not entirely... correct here. 17495 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17496 17497 if (NewFD->hasAttrs()) 17498 CheckAlignasUnderalignment(NewFD); 17499 } 17500 17501 // In auto-retain/release, infer strong retension for fields of 17502 // retainable type. 17503 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17504 NewFD->setInvalidDecl(); 17505 17506 if (T.isObjCGCWeak()) 17507 Diag(Loc, diag::warn_attribute_weak_on_field); 17508 17509 // PPC MMA non-pointer types are not allowed as field types. 17510 if (Context.getTargetInfo().getTriple().isPPC64() && 17511 CheckPPCMMAType(T, NewFD->getLocation())) 17512 NewFD->setInvalidDecl(); 17513 17514 NewFD->setAccess(AS); 17515 return NewFD; 17516 } 17517 17518 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17519 assert(FD); 17520 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17521 17522 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17523 return false; 17524 17525 QualType EltTy = Context.getBaseElementType(FD->getType()); 17526 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17527 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17528 if (RDecl->getDefinition()) { 17529 // We check for copy constructors before constructors 17530 // because otherwise we'll never get complaints about 17531 // copy constructors. 17532 17533 CXXSpecialMember member = CXXInvalid; 17534 // We're required to check for any non-trivial constructors. Since the 17535 // implicit default constructor is suppressed if there are any 17536 // user-declared constructors, we just need to check that there is a 17537 // trivial default constructor and a trivial copy constructor. (We don't 17538 // worry about move constructors here, since this is a C++98 check.) 17539 if (RDecl->hasNonTrivialCopyConstructor()) 17540 member = CXXCopyConstructor; 17541 else if (!RDecl->hasTrivialDefaultConstructor()) 17542 member = CXXDefaultConstructor; 17543 else if (RDecl->hasNonTrivialCopyAssignment()) 17544 member = CXXCopyAssignment; 17545 else if (RDecl->hasNonTrivialDestructor()) 17546 member = CXXDestructor; 17547 17548 if (member != CXXInvalid) { 17549 if (!getLangOpts().CPlusPlus11 && 17550 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17551 // Objective-C++ ARC: it is an error to have a non-trivial field of 17552 // a union. However, system headers in Objective-C programs 17553 // occasionally have Objective-C lifetime objects within unions, 17554 // and rather than cause the program to fail, we make those 17555 // members unavailable. 17556 SourceLocation Loc = FD->getLocation(); 17557 if (getSourceManager().isInSystemHeader(Loc)) { 17558 if (!FD->hasAttr<UnavailableAttr>()) 17559 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17560 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17561 return false; 17562 } 17563 } 17564 17565 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17566 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17567 diag::err_illegal_union_or_anon_struct_member) 17568 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17569 DiagnoseNontrivial(RDecl, member); 17570 return !getLangOpts().CPlusPlus11; 17571 } 17572 } 17573 } 17574 17575 return false; 17576 } 17577 17578 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17579 /// AST enum value. 17580 static ObjCIvarDecl::AccessControl 17581 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17582 switch (ivarVisibility) { 17583 default: llvm_unreachable("Unknown visitibility kind"); 17584 case tok::objc_private: return ObjCIvarDecl::Private; 17585 case tok::objc_public: return ObjCIvarDecl::Public; 17586 case tok::objc_protected: return ObjCIvarDecl::Protected; 17587 case tok::objc_package: return ObjCIvarDecl::Package; 17588 } 17589 } 17590 17591 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17592 /// in order to create an IvarDecl object for it. 17593 Decl *Sema::ActOnIvar(Scope *S, 17594 SourceLocation DeclStart, 17595 Declarator &D, Expr *BitfieldWidth, 17596 tok::ObjCKeywordKind Visibility) { 17597 17598 IdentifierInfo *II = D.getIdentifier(); 17599 Expr *BitWidth = (Expr*)BitfieldWidth; 17600 SourceLocation Loc = DeclStart; 17601 if (II) Loc = D.getIdentifierLoc(); 17602 17603 // FIXME: Unnamed fields can be handled in various different ways, for 17604 // example, unnamed unions inject all members into the struct namespace! 17605 17606 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17607 QualType T = TInfo->getType(); 17608 17609 if (BitWidth) { 17610 // 6.7.2.1p3, 6.7.2.1p4 17611 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17612 if (!BitWidth) 17613 D.setInvalidType(); 17614 } else { 17615 // Not a bitfield. 17616 17617 // validate II. 17618 17619 } 17620 if (T->isReferenceType()) { 17621 Diag(Loc, diag::err_ivar_reference_type); 17622 D.setInvalidType(); 17623 } 17624 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17625 // than a variably modified type. 17626 else if (T->isVariablyModifiedType()) { 17627 if (!tryToFixVariablyModifiedVarType( 17628 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17629 D.setInvalidType(); 17630 } 17631 17632 // Get the visibility (access control) for this ivar. 17633 ObjCIvarDecl::AccessControl ac = 17634 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17635 : ObjCIvarDecl::None; 17636 // Must set ivar's DeclContext to its enclosing interface. 17637 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17638 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17639 return nullptr; 17640 ObjCContainerDecl *EnclosingContext; 17641 if (ObjCImplementationDecl *IMPDecl = 17642 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17643 if (LangOpts.ObjCRuntime.isFragile()) { 17644 // Case of ivar declared in an implementation. Context is that of its class. 17645 EnclosingContext = IMPDecl->getClassInterface(); 17646 assert(EnclosingContext && "Implementation has no class interface!"); 17647 } 17648 else 17649 EnclosingContext = EnclosingDecl; 17650 } else { 17651 if (ObjCCategoryDecl *CDecl = 17652 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17653 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17654 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17655 return nullptr; 17656 } 17657 } 17658 EnclosingContext = EnclosingDecl; 17659 } 17660 17661 // Construct the decl. 17662 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17663 DeclStart, Loc, II, T, 17664 TInfo, ac, (Expr *)BitfieldWidth); 17665 17666 if (II) { 17667 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17668 ForVisibleRedeclaration); 17669 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17670 && !isa<TagDecl>(PrevDecl)) { 17671 Diag(Loc, diag::err_duplicate_member) << II; 17672 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17673 NewID->setInvalidDecl(); 17674 } 17675 } 17676 17677 // Process attributes attached to the ivar. 17678 ProcessDeclAttributes(S, NewID, D); 17679 17680 if (D.isInvalidType()) 17681 NewID->setInvalidDecl(); 17682 17683 // In ARC, infer 'retaining' for ivars of retainable type. 17684 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17685 NewID->setInvalidDecl(); 17686 17687 if (D.getDeclSpec().isModulePrivateSpecified()) 17688 NewID->setModulePrivate(); 17689 17690 if (II) { 17691 // FIXME: When interfaces are DeclContexts, we'll need to add 17692 // these to the interface. 17693 S->AddDecl(NewID); 17694 IdResolver.AddDecl(NewID); 17695 } 17696 17697 if (LangOpts.ObjCRuntime.isNonFragile() && 17698 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17699 Diag(Loc, diag::warn_ivars_in_interface); 17700 17701 return NewID; 17702 } 17703 17704 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17705 /// class and class extensions. For every class \@interface and class 17706 /// extension \@interface, if the last ivar is a bitfield of any type, 17707 /// then add an implicit `char :0` ivar to the end of that interface. 17708 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17709 SmallVectorImpl<Decl *> &AllIvarDecls) { 17710 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17711 return; 17712 17713 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17714 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17715 17716 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17717 return; 17718 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17719 if (!ID) { 17720 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17721 if (!CD->IsClassExtension()) 17722 return; 17723 } 17724 // No need to add this to end of @implementation. 17725 else 17726 return; 17727 } 17728 // All conditions are met. Add a new bitfield to the tail end of ivars. 17729 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17730 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17731 17732 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17733 DeclLoc, DeclLoc, nullptr, 17734 Context.CharTy, 17735 Context.getTrivialTypeSourceInfo(Context.CharTy, 17736 DeclLoc), 17737 ObjCIvarDecl::Private, BW, 17738 true); 17739 AllIvarDecls.push_back(Ivar); 17740 } 17741 17742 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17743 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17744 SourceLocation RBrac, 17745 const ParsedAttributesView &Attrs) { 17746 assert(EnclosingDecl && "missing record or interface decl"); 17747 17748 // If this is an Objective-C @implementation or category and we have 17749 // new fields here we should reset the layout of the interface since 17750 // it will now change. 17751 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17752 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17753 switch (DC->getKind()) { 17754 default: break; 17755 case Decl::ObjCCategory: 17756 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17757 break; 17758 case Decl::ObjCImplementation: 17759 Context. 17760 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17761 break; 17762 } 17763 } 17764 17765 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17766 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17767 17768 // Start counting up the number of named members; make sure to include 17769 // members of anonymous structs and unions in the total. 17770 unsigned NumNamedMembers = 0; 17771 if (Record) { 17772 for (const auto *I : Record->decls()) { 17773 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17774 if (IFD->getDeclName()) 17775 ++NumNamedMembers; 17776 } 17777 } 17778 17779 // Verify that all the fields are okay. 17780 SmallVector<FieldDecl*, 32> RecFields; 17781 17782 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17783 i != end; ++i) { 17784 FieldDecl *FD = cast<FieldDecl>(*i); 17785 17786 // Get the type for the field. 17787 const Type *FDTy = FD->getType().getTypePtr(); 17788 17789 if (!FD->isAnonymousStructOrUnion()) { 17790 // Remember all fields written by the user. 17791 RecFields.push_back(FD); 17792 } 17793 17794 // If the field is already invalid for some reason, don't emit more 17795 // diagnostics about it. 17796 if (FD->isInvalidDecl()) { 17797 EnclosingDecl->setInvalidDecl(); 17798 continue; 17799 } 17800 17801 // C99 6.7.2.1p2: 17802 // A structure or union shall not contain a member with 17803 // incomplete or function type (hence, a structure shall not 17804 // contain an instance of itself, but may contain a pointer to 17805 // an instance of itself), except that the last member of a 17806 // structure with more than one named member may have incomplete 17807 // array type; such a structure (and any union containing, 17808 // possibly recursively, a member that is such a structure) 17809 // shall not be a member of a structure or an element of an 17810 // array. 17811 bool IsLastField = (i + 1 == Fields.end()); 17812 if (FDTy->isFunctionType()) { 17813 // Field declared as a function. 17814 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17815 << FD->getDeclName(); 17816 FD->setInvalidDecl(); 17817 EnclosingDecl->setInvalidDecl(); 17818 continue; 17819 } else if (FDTy->isIncompleteArrayType() && 17820 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17821 if (Record) { 17822 // Flexible array member. 17823 // Microsoft and g++ is more permissive regarding flexible array. 17824 // It will accept flexible array in union and also 17825 // as the sole element of a struct/class. 17826 unsigned DiagID = 0; 17827 if (!Record->isUnion() && !IsLastField) { 17828 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17829 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17830 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17831 FD->setInvalidDecl(); 17832 EnclosingDecl->setInvalidDecl(); 17833 continue; 17834 } else if (Record->isUnion()) 17835 DiagID = getLangOpts().MicrosoftExt 17836 ? diag::ext_flexible_array_union_ms 17837 : getLangOpts().CPlusPlus 17838 ? diag::ext_flexible_array_union_gnu 17839 : diag::err_flexible_array_union; 17840 else if (NumNamedMembers < 1) 17841 DiagID = getLangOpts().MicrosoftExt 17842 ? diag::ext_flexible_array_empty_aggregate_ms 17843 : getLangOpts().CPlusPlus 17844 ? diag::ext_flexible_array_empty_aggregate_gnu 17845 : diag::err_flexible_array_empty_aggregate; 17846 17847 if (DiagID) 17848 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17849 << Record->getTagKind(); 17850 // While the layout of types that contain virtual bases is not specified 17851 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17852 // virtual bases after the derived members. This would make a flexible 17853 // array member declared at the end of an object not adjacent to the end 17854 // of the type. 17855 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17856 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17857 << FD->getDeclName() << Record->getTagKind(); 17858 if (!getLangOpts().C99) 17859 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17860 << FD->getDeclName() << Record->getTagKind(); 17861 17862 // If the element type has a non-trivial destructor, we would not 17863 // implicitly destroy the elements, so disallow it for now. 17864 // 17865 // FIXME: GCC allows this. We should probably either implicitly delete 17866 // the destructor of the containing class, or just allow this. 17867 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17868 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17869 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17870 << FD->getDeclName() << FD->getType(); 17871 FD->setInvalidDecl(); 17872 EnclosingDecl->setInvalidDecl(); 17873 continue; 17874 } 17875 // Okay, we have a legal flexible array member at the end of the struct. 17876 Record->setHasFlexibleArrayMember(true); 17877 } else { 17878 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17879 // unless they are followed by another ivar. That check is done 17880 // elsewhere, after synthesized ivars are known. 17881 } 17882 } else if (!FDTy->isDependentType() && 17883 RequireCompleteSizedType( 17884 FD->getLocation(), FD->getType(), 17885 diag::err_field_incomplete_or_sizeless)) { 17886 // Incomplete type 17887 FD->setInvalidDecl(); 17888 EnclosingDecl->setInvalidDecl(); 17889 continue; 17890 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17891 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17892 // A type which contains a flexible array member is considered to be a 17893 // flexible array member. 17894 Record->setHasFlexibleArrayMember(true); 17895 if (!Record->isUnion()) { 17896 // If this is a struct/class and this is not the last element, reject 17897 // it. Note that GCC supports variable sized arrays in the middle of 17898 // structures. 17899 if (!IsLastField) 17900 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17901 << FD->getDeclName() << FD->getType(); 17902 else { 17903 // We support flexible arrays at the end of structs in 17904 // other structs as an extension. 17905 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17906 << FD->getDeclName(); 17907 } 17908 } 17909 } 17910 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17911 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17912 diag::err_abstract_type_in_decl, 17913 AbstractIvarType)) { 17914 // Ivars can not have abstract class types 17915 FD->setInvalidDecl(); 17916 } 17917 if (Record && FDTTy->getDecl()->hasObjectMember()) 17918 Record->setHasObjectMember(true); 17919 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17920 Record->setHasVolatileMember(true); 17921 } else if (FDTy->isObjCObjectType()) { 17922 /// A field cannot be an Objective-c object 17923 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17924 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17925 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17926 FD->setType(T); 17927 } else if (Record && Record->isUnion() && 17928 FD->getType().hasNonTrivialObjCLifetime() && 17929 getSourceManager().isInSystemHeader(FD->getLocation()) && 17930 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17931 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17932 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17933 // For backward compatibility, fields of C unions declared in system 17934 // headers that have non-trivial ObjC ownership qualifications are marked 17935 // as unavailable unless the qualifier is explicit and __strong. This can 17936 // break ABI compatibility between programs compiled with ARC and MRR, but 17937 // is a better option than rejecting programs using those unions under 17938 // ARC. 17939 FD->addAttr(UnavailableAttr::CreateImplicit( 17940 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17941 FD->getLocation())); 17942 } else if (getLangOpts().ObjC && 17943 getLangOpts().getGC() != LangOptions::NonGC && Record && 17944 !Record->hasObjectMember()) { 17945 if (FD->getType()->isObjCObjectPointerType() || 17946 FD->getType().isObjCGCStrong()) 17947 Record->setHasObjectMember(true); 17948 else if (Context.getAsArrayType(FD->getType())) { 17949 QualType BaseType = Context.getBaseElementType(FD->getType()); 17950 if (BaseType->isRecordType() && 17951 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17952 Record->setHasObjectMember(true); 17953 else if (BaseType->isObjCObjectPointerType() || 17954 BaseType.isObjCGCStrong()) 17955 Record->setHasObjectMember(true); 17956 } 17957 } 17958 17959 if (Record && !getLangOpts().CPlusPlus && 17960 !shouldIgnoreForRecordTriviality(FD)) { 17961 QualType FT = FD->getType(); 17962 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17963 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17964 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17965 Record->isUnion()) 17966 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17967 } 17968 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17969 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17970 Record->setNonTrivialToPrimitiveCopy(true); 17971 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17972 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17973 } 17974 if (FT.isDestructedType()) { 17975 Record->setNonTrivialToPrimitiveDestroy(true); 17976 Record->setParamDestroyedInCallee(true); 17977 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17978 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17979 } 17980 17981 if (const auto *RT = FT->getAs<RecordType>()) { 17982 if (RT->getDecl()->getArgPassingRestrictions() == 17983 RecordDecl::APK_CanNeverPassInRegs) 17984 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17985 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17986 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17987 } 17988 17989 if (Record && FD->getType().isVolatileQualified()) 17990 Record->setHasVolatileMember(true); 17991 // Keep track of the number of named members. 17992 if (FD->getIdentifier()) 17993 ++NumNamedMembers; 17994 } 17995 17996 // Okay, we successfully defined 'Record'. 17997 if (Record) { 17998 bool Completed = false; 17999 if (CXXRecord) { 18000 if (!CXXRecord->isInvalidDecl()) { 18001 // Set access bits correctly on the directly-declared conversions. 18002 for (CXXRecordDecl::conversion_iterator 18003 I = CXXRecord->conversion_begin(), 18004 E = CXXRecord->conversion_end(); I != E; ++I) 18005 I.setAccess((*I)->getAccess()); 18006 } 18007 18008 // Add any implicitly-declared members to this class. 18009 AddImplicitlyDeclaredMembersToClass(CXXRecord); 18010 18011 if (!CXXRecord->isDependentType()) { 18012 if (!CXXRecord->isInvalidDecl()) { 18013 // If we have virtual base classes, we may end up finding multiple 18014 // final overriders for a given virtual function. Check for this 18015 // problem now. 18016 if (CXXRecord->getNumVBases()) { 18017 CXXFinalOverriderMap FinalOverriders; 18018 CXXRecord->getFinalOverriders(FinalOverriders); 18019 18020 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 18021 MEnd = FinalOverriders.end(); 18022 M != MEnd; ++M) { 18023 for (OverridingMethods::iterator SO = M->second.begin(), 18024 SOEnd = M->second.end(); 18025 SO != SOEnd; ++SO) { 18026 assert(SO->second.size() > 0 && 18027 "Virtual function without overriding functions?"); 18028 if (SO->second.size() == 1) 18029 continue; 18030 18031 // C++ [class.virtual]p2: 18032 // In a derived class, if a virtual member function of a base 18033 // class subobject has more than one final overrider the 18034 // program is ill-formed. 18035 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 18036 << (const NamedDecl *)M->first << Record; 18037 Diag(M->first->getLocation(), 18038 diag::note_overridden_virtual_function); 18039 for (OverridingMethods::overriding_iterator 18040 OM = SO->second.begin(), 18041 OMEnd = SO->second.end(); 18042 OM != OMEnd; ++OM) 18043 Diag(OM->Method->getLocation(), diag::note_final_overrider) 18044 << (const NamedDecl *)M->first << OM->Method->getParent(); 18045 18046 Record->setInvalidDecl(); 18047 } 18048 } 18049 CXXRecord->completeDefinition(&FinalOverriders); 18050 Completed = true; 18051 } 18052 } 18053 } 18054 } 18055 18056 if (!Completed) 18057 Record->completeDefinition(); 18058 18059 // Handle attributes before checking the layout. 18060 ProcessDeclAttributeList(S, Record, Attrs); 18061 18062 // Maybe randomize the field order. 18063 if (!getLangOpts().CPlusPlus && Record->hasAttr<RandomizeLayoutAttr>() && 18064 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && 18065 !Record->isRandomized()) { 18066 SmallVector<Decl *, 32> OrigFieldOrdering(Record->fields()); 18067 SmallVector<Decl *, 32> NewFieldOrdering; 18068 if (randstruct::randomizeStructureLayout( 18069 Context, Record->getNameAsString(), OrigFieldOrdering, 18070 NewFieldOrdering)) 18071 Record->reorderFields(NewFieldOrdering); 18072 } 18073 18074 // We may have deferred checking for a deleted destructor. Check now. 18075 if (CXXRecord) { 18076 auto *Dtor = CXXRecord->getDestructor(); 18077 if (Dtor && Dtor->isImplicit() && 18078 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 18079 CXXRecord->setImplicitDestructorIsDeleted(); 18080 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 18081 } 18082 } 18083 18084 if (Record->hasAttrs()) { 18085 CheckAlignasUnderalignment(Record); 18086 18087 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 18088 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 18089 IA->getRange(), IA->getBestCase(), 18090 IA->getInheritanceModel()); 18091 } 18092 18093 // Check if the structure/union declaration is a type that can have zero 18094 // size in C. For C this is a language extension, for C++ it may cause 18095 // compatibility problems. 18096 bool CheckForZeroSize; 18097 if (!getLangOpts().CPlusPlus) { 18098 CheckForZeroSize = true; 18099 } else { 18100 // For C++ filter out types that cannot be referenced in C code. 18101 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 18102 CheckForZeroSize = 18103 CXXRecord->getLexicalDeclContext()->isExternCContext() && 18104 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 18105 CXXRecord->isCLike(); 18106 } 18107 if (CheckForZeroSize) { 18108 bool ZeroSize = true; 18109 bool IsEmpty = true; 18110 unsigned NonBitFields = 0; 18111 for (RecordDecl::field_iterator I = Record->field_begin(), 18112 E = Record->field_end(); 18113 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 18114 IsEmpty = false; 18115 if (I->isUnnamedBitfield()) { 18116 if (!I->isZeroLengthBitField(Context)) 18117 ZeroSize = false; 18118 } else { 18119 ++NonBitFields; 18120 QualType FieldType = I->getType(); 18121 if (FieldType->isIncompleteType() || 18122 !Context.getTypeSizeInChars(FieldType).isZero()) 18123 ZeroSize = false; 18124 } 18125 } 18126 18127 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 18128 // allowed in C++, but warn if its declaration is inside 18129 // extern "C" block. 18130 if (ZeroSize) { 18131 Diag(RecLoc, getLangOpts().CPlusPlus ? 18132 diag::warn_zero_size_struct_union_in_extern_c : 18133 diag::warn_zero_size_struct_union_compat) 18134 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 18135 } 18136 18137 // Structs without named members are extension in C (C99 6.7.2.1p7), 18138 // but are accepted by GCC. 18139 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 18140 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 18141 diag::ext_no_named_members_in_struct_union) 18142 << Record->isUnion(); 18143 } 18144 } 18145 } else { 18146 ObjCIvarDecl **ClsFields = 18147 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 18148 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 18149 ID->setEndOfDefinitionLoc(RBrac); 18150 // Add ivar's to class's DeclContext. 18151 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18152 ClsFields[i]->setLexicalDeclContext(ID); 18153 ID->addDecl(ClsFields[i]); 18154 } 18155 // Must enforce the rule that ivars in the base classes may not be 18156 // duplicates. 18157 if (ID->getSuperClass()) 18158 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 18159 } else if (ObjCImplementationDecl *IMPDecl = 18160 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 18161 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 18162 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 18163 // Ivar declared in @implementation never belongs to the implementation. 18164 // Only it is in implementation's lexical context. 18165 ClsFields[I]->setLexicalDeclContext(IMPDecl); 18166 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 18167 IMPDecl->setIvarLBraceLoc(LBrac); 18168 IMPDecl->setIvarRBraceLoc(RBrac); 18169 } else if (ObjCCategoryDecl *CDecl = 18170 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 18171 // case of ivars in class extension; all other cases have been 18172 // reported as errors elsewhere. 18173 // FIXME. Class extension does not have a LocEnd field. 18174 // CDecl->setLocEnd(RBrac); 18175 // Add ivar's to class extension's DeclContext. 18176 // Diagnose redeclaration of private ivars. 18177 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 18178 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18179 if (IDecl) { 18180 if (const ObjCIvarDecl *ClsIvar = 18181 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 18182 Diag(ClsFields[i]->getLocation(), 18183 diag::err_duplicate_ivar_declaration); 18184 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 18185 continue; 18186 } 18187 for (const auto *Ext : IDecl->known_extensions()) { 18188 if (const ObjCIvarDecl *ClsExtIvar 18189 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 18190 Diag(ClsFields[i]->getLocation(), 18191 diag::err_duplicate_ivar_declaration); 18192 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 18193 continue; 18194 } 18195 } 18196 } 18197 ClsFields[i]->setLexicalDeclContext(CDecl); 18198 CDecl->addDecl(ClsFields[i]); 18199 } 18200 CDecl->setIvarLBraceLoc(LBrac); 18201 CDecl->setIvarRBraceLoc(RBrac); 18202 } 18203 } 18204 } 18205 18206 /// Determine whether the given integral value is representable within 18207 /// the given type T. 18208 static bool isRepresentableIntegerValue(ASTContext &Context, 18209 llvm::APSInt &Value, 18210 QualType T) { 18211 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 18212 "Integral type required!"); 18213 unsigned BitWidth = Context.getIntWidth(T); 18214 18215 if (Value.isUnsigned() || Value.isNonNegative()) { 18216 if (T->isSignedIntegerOrEnumerationType()) 18217 --BitWidth; 18218 return Value.getActiveBits() <= BitWidth; 18219 } 18220 return Value.getMinSignedBits() <= BitWidth; 18221 } 18222 18223 // Given an integral type, return the next larger integral type 18224 // (or a NULL type of no such type exists). 18225 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 18226 // FIXME: Int128/UInt128 support, which also needs to be introduced into 18227 // enum checking below. 18228 assert((T->isIntegralType(Context) || 18229 T->isEnumeralType()) && "Integral type required!"); 18230 const unsigned NumTypes = 4; 18231 QualType SignedIntegralTypes[NumTypes] = { 18232 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 18233 }; 18234 QualType UnsignedIntegralTypes[NumTypes] = { 18235 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 18236 Context.UnsignedLongLongTy 18237 }; 18238 18239 unsigned BitWidth = Context.getTypeSize(T); 18240 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 18241 : UnsignedIntegralTypes; 18242 for (unsigned I = 0; I != NumTypes; ++I) 18243 if (Context.getTypeSize(Types[I]) > BitWidth) 18244 return Types[I]; 18245 18246 return QualType(); 18247 } 18248 18249 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 18250 EnumConstantDecl *LastEnumConst, 18251 SourceLocation IdLoc, 18252 IdentifierInfo *Id, 18253 Expr *Val) { 18254 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18255 llvm::APSInt EnumVal(IntWidth); 18256 QualType EltTy; 18257 18258 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 18259 Val = nullptr; 18260 18261 if (Val) 18262 Val = DefaultLvalueConversion(Val).get(); 18263 18264 if (Val) { 18265 if (Enum->isDependentType() || Val->isTypeDependent() || 18266 Val->containsErrors()) 18267 EltTy = Context.DependentTy; 18268 else { 18269 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 18270 // underlying type, but do allow it in all other contexts. 18271 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 18272 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 18273 // constant-expression in the enumerator-definition shall be a converted 18274 // constant expression of the underlying type. 18275 EltTy = Enum->getIntegerType(); 18276 ExprResult Converted = 18277 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 18278 CCEK_Enumerator); 18279 if (Converted.isInvalid()) 18280 Val = nullptr; 18281 else 18282 Val = Converted.get(); 18283 } else if (!Val->isValueDependent() && 18284 !(Val = 18285 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 18286 .get())) { 18287 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 18288 } else { 18289 if (Enum->isComplete()) { 18290 EltTy = Enum->getIntegerType(); 18291 18292 // In Obj-C and Microsoft mode, require the enumeration value to be 18293 // representable in the underlying type of the enumeration. In C++11, 18294 // we perform a non-narrowing conversion as part of converted constant 18295 // expression checking. 18296 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18297 if (Context.getTargetInfo() 18298 .getTriple() 18299 .isWindowsMSVCEnvironment()) { 18300 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 18301 } else { 18302 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 18303 } 18304 } 18305 18306 // Cast to the underlying type. 18307 Val = ImpCastExprToType(Val, EltTy, 18308 EltTy->isBooleanType() ? CK_IntegralToBoolean 18309 : CK_IntegralCast) 18310 .get(); 18311 } else if (getLangOpts().CPlusPlus) { 18312 // C++11 [dcl.enum]p5: 18313 // If the underlying type is not fixed, the type of each enumerator 18314 // is the type of its initializing value: 18315 // - If an initializer is specified for an enumerator, the 18316 // initializing value has the same type as the expression. 18317 EltTy = Val->getType(); 18318 } else { 18319 // C99 6.7.2.2p2: 18320 // The expression that defines the value of an enumeration constant 18321 // shall be an integer constant expression that has a value 18322 // representable as an int. 18323 18324 // Complain if the value is not representable in an int. 18325 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 18326 Diag(IdLoc, diag::ext_enum_value_not_int) 18327 << toString(EnumVal, 10) << Val->getSourceRange() 18328 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 18329 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 18330 // Force the type of the expression to 'int'. 18331 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 18332 } 18333 EltTy = Val->getType(); 18334 } 18335 } 18336 } 18337 } 18338 18339 if (!Val) { 18340 if (Enum->isDependentType()) 18341 EltTy = Context.DependentTy; 18342 else if (!LastEnumConst) { 18343 // C++0x [dcl.enum]p5: 18344 // If the underlying type is not fixed, the type of each enumerator 18345 // is the type of its initializing value: 18346 // - If no initializer is specified for the first enumerator, the 18347 // initializing value has an unspecified integral type. 18348 // 18349 // GCC uses 'int' for its unspecified integral type, as does 18350 // C99 6.7.2.2p3. 18351 if (Enum->isFixed()) { 18352 EltTy = Enum->getIntegerType(); 18353 } 18354 else { 18355 EltTy = Context.IntTy; 18356 } 18357 } else { 18358 // Assign the last value + 1. 18359 EnumVal = LastEnumConst->getInitVal(); 18360 ++EnumVal; 18361 EltTy = LastEnumConst->getType(); 18362 18363 // Check for overflow on increment. 18364 if (EnumVal < LastEnumConst->getInitVal()) { 18365 // C++0x [dcl.enum]p5: 18366 // If the underlying type is not fixed, the type of each enumerator 18367 // is the type of its initializing value: 18368 // 18369 // - Otherwise the type of the initializing value is the same as 18370 // the type of the initializing value of the preceding enumerator 18371 // unless the incremented value is not representable in that type, 18372 // in which case the type is an unspecified integral type 18373 // sufficient to contain the incremented value. If no such type 18374 // exists, the program is ill-formed. 18375 QualType T = getNextLargerIntegralType(Context, EltTy); 18376 if (T.isNull() || Enum->isFixed()) { 18377 // There is no integral type larger enough to represent this 18378 // value. Complain, then allow the value to wrap around. 18379 EnumVal = LastEnumConst->getInitVal(); 18380 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 18381 ++EnumVal; 18382 if (Enum->isFixed()) 18383 // When the underlying type is fixed, this is ill-formed. 18384 Diag(IdLoc, diag::err_enumerator_wrapped) 18385 << toString(EnumVal, 10) 18386 << EltTy; 18387 else 18388 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 18389 << toString(EnumVal, 10); 18390 } else { 18391 EltTy = T; 18392 } 18393 18394 // Retrieve the last enumerator's value, extent that type to the 18395 // type that is supposed to be large enough to represent the incremented 18396 // value, then increment. 18397 EnumVal = LastEnumConst->getInitVal(); 18398 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18399 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 18400 ++EnumVal; 18401 18402 // If we're not in C++, diagnose the overflow of enumerator values, 18403 // which in C99 means that the enumerator value is not representable in 18404 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 18405 // permits enumerator values that are representable in some larger 18406 // integral type. 18407 if (!getLangOpts().CPlusPlus && !T.isNull()) 18408 Diag(IdLoc, diag::warn_enum_value_overflow); 18409 } else if (!getLangOpts().CPlusPlus && 18410 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18411 // Enforce C99 6.7.2.2p2 even when we compute the next value. 18412 Diag(IdLoc, diag::ext_enum_value_not_int) 18413 << toString(EnumVal, 10) << 1; 18414 } 18415 } 18416 } 18417 18418 if (!EltTy->isDependentType()) { 18419 // Make the enumerator value match the signedness and size of the 18420 // enumerator's type. 18421 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 18422 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18423 } 18424 18425 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 18426 Val, EnumVal); 18427 } 18428 18429 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 18430 SourceLocation IILoc) { 18431 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 18432 !getLangOpts().CPlusPlus) 18433 return SkipBodyInfo(); 18434 18435 // We have an anonymous enum definition. Look up the first enumerator to 18436 // determine if we should merge the definition with an existing one and 18437 // skip the body. 18438 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 18439 forRedeclarationInCurContext()); 18440 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 18441 if (!PrevECD) 18442 return SkipBodyInfo(); 18443 18444 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18445 NamedDecl *Hidden; 18446 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18447 SkipBodyInfo Skip; 18448 Skip.Previous = Hidden; 18449 return Skip; 18450 } 18451 18452 return SkipBodyInfo(); 18453 } 18454 18455 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18456 SourceLocation IdLoc, IdentifierInfo *Id, 18457 const ParsedAttributesView &Attrs, 18458 SourceLocation EqualLoc, Expr *Val) { 18459 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18460 EnumConstantDecl *LastEnumConst = 18461 cast_or_null<EnumConstantDecl>(lastEnumConst); 18462 18463 // The scope passed in may not be a decl scope. Zip up the scope tree until 18464 // we find one that is. 18465 S = getNonFieldDeclScope(S); 18466 18467 // Verify that there isn't already something declared with this name in this 18468 // scope. 18469 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18470 LookupName(R, S); 18471 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18472 18473 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18474 // Maybe we will complain about the shadowed template parameter. 18475 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18476 // Just pretend that we didn't see the previous declaration. 18477 PrevDecl = nullptr; 18478 } 18479 18480 // C++ [class.mem]p15: 18481 // If T is the name of a class, then each of the following shall have a name 18482 // different from T: 18483 // - every enumerator of every member of class T that is an unscoped 18484 // enumerated type 18485 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18486 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18487 DeclarationNameInfo(Id, IdLoc)); 18488 18489 EnumConstantDecl *New = 18490 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18491 if (!New) 18492 return nullptr; 18493 18494 if (PrevDecl) { 18495 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18496 // Check for other kinds of shadowing not already handled. 18497 CheckShadow(New, PrevDecl, R); 18498 } 18499 18500 // When in C++, we may get a TagDecl with the same name; in this case the 18501 // enum constant will 'hide' the tag. 18502 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18503 "Received TagDecl when not in C++!"); 18504 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18505 if (isa<EnumConstantDecl>(PrevDecl)) 18506 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18507 else 18508 Diag(IdLoc, diag::err_redefinition) << Id; 18509 notePreviousDefinition(PrevDecl, IdLoc); 18510 return nullptr; 18511 } 18512 } 18513 18514 // Process attributes. 18515 ProcessDeclAttributeList(S, New, Attrs); 18516 AddPragmaAttributes(S, New); 18517 18518 // Register this decl in the current scope stack. 18519 New->setAccess(TheEnumDecl->getAccess()); 18520 PushOnScopeChains(New, S); 18521 18522 ActOnDocumentableDecl(New); 18523 18524 return New; 18525 } 18526 18527 // Returns true when the enum initial expression does not trigger the 18528 // duplicate enum warning. A few common cases are exempted as follows: 18529 // Element2 = Element1 18530 // Element2 = Element1 + 1 18531 // Element2 = Element1 - 1 18532 // Where Element2 and Element1 are from the same enum. 18533 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18534 Expr *InitExpr = ECD->getInitExpr(); 18535 if (!InitExpr) 18536 return true; 18537 InitExpr = InitExpr->IgnoreImpCasts(); 18538 18539 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18540 if (!BO->isAdditiveOp()) 18541 return true; 18542 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18543 if (!IL) 18544 return true; 18545 if (IL->getValue() != 1) 18546 return true; 18547 18548 InitExpr = BO->getLHS(); 18549 } 18550 18551 // This checks if the elements are from the same enum. 18552 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18553 if (!DRE) 18554 return true; 18555 18556 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18557 if (!EnumConstant) 18558 return true; 18559 18560 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18561 Enum) 18562 return true; 18563 18564 return false; 18565 } 18566 18567 // Emits a warning when an element is implicitly set a value that 18568 // a previous element has already been set to. 18569 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18570 EnumDecl *Enum, QualType EnumType) { 18571 // Avoid anonymous enums 18572 if (!Enum->getIdentifier()) 18573 return; 18574 18575 // Only check for small enums. 18576 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18577 return; 18578 18579 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18580 return; 18581 18582 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18583 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18584 18585 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18586 18587 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18588 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18589 18590 // Use int64_t as a key to avoid needing special handling for map keys. 18591 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18592 llvm::APSInt Val = D->getInitVal(); 18593 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18594 }; 18595 18596 DuplicatesVector DupVector; 18597 ValueToVectorMap EnumMap; 18598 18599 // Populate the EnumMap with all values represented by enum constants without 18600 // an initializer. 18601 for (auto *Element : Elements) { 18602 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18603 18604 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18605 // this constant. Skip this enum since it may be ill-formed. 18606 if (!ECD) { 18607 return; 18608 } 18609 18610 // Constants with initalizers are handled in the next loop. 18611 if (ECD->getInitExpr()) 18612 continue; 18613 18614 // Duplicate values are handled in the next loop. 18615 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18616 } 18617 18618 if (EnumMap.size() == 0) 18619 return; 18620 18621 // Create vectors for any values that has duplicates. 18622 for (auto *Element : Elements) { 18623 // The last loop returned if any constant was null. 18624 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18625 if (!ValidDuplicateEnum(ECD, Enum)) 18626 continue; 18627 18628 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18629 if (Iter == EnumMap.end()) 18630 continue; 18631 18632 DeclOrVector& Entry = Iter->second; 18633 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18634 // Ensure constants are different. 18635 if (D == ECD) 18636 continue; 18637 18638 // Create new vector and push values onto it. 18639 auto Vec = std::make_unique<ECDVector>(); 18640 Vec->push_back(D); 18641 Vec->push_back(ECD); 18642 18643 // Update entry to point to the duplicates vector. 18644 Entry = Vec.get(); 18645 18646 // Store the vector somewhere we can consult later for quick emission of 18647 // diagnostics. 18648 DupVector.emplace_back(std::move(Vec)); 18649 continue; 18650 } 18651 18652 ECDVector *Vec = Entry.get<ECDVector*>(); 18653 // Make sure constants are not added more than once. 18654 if (*Vec->begin() == ECD) 18655 continue; 18656 18657 Vec->push_back(ECD); 18658 } 18659 18660 // Emit diagnostics. 18661 for (const auto &Vec : DupVector) { 18662 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18663 18664 // Emit warning for one enum constant. 18665 auto *FirstECD = Vec->front(); 18666 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18667 << FirstECD << toString(FirstECD->getInitVal(), 10) 18668 << FirstECD->getSourceRange(); 18669 18670 // Emit one note for each of the remaining enum constants with 18671 // the same value. 18672 for (auto *ECD : llvm::drop_begin(*Vec)) 18673 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18674 << ECD << toString(ECD->getInitVal(), 10) 18675 << ECD->getSourceRange(); 18676 } 18677 } 18678 18679 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18680 bool AllowMask) const { 18681 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18682 assert(ED->isCompleteDefinition() && "expected enum definition"); 18683 18684 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18685 llvm::APInt &FlagBits = R.first->second; 18686 18687 if (R.second) { 18688 for (auto *E : ED->enumerators()) { 18689 const auto &EVal = E->getInitVal(); 18690 // Only single-bit enumerators introduce new flag values. 18691 if (EVal.isPowerOf2()) 18692 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18693 } 18694 } 18695 18696 // A value is in a flag enum if either its bits are a subset of the enum's 18697 // flag bits (the first condition) or we are allowing masks and the same is 18698 // true of its complement (the second condition). When masks are allowed, we 18699 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18700 // 18701 // While it's true that any value could be used as a mask, the assumption is 18702 // that a mask will have all of the insignificant bits set. Anything else is 18703 // likely a logic error. 18704 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18705 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18706 } 18707 18708 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18709 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18710 const ParsedAttributesView &Attrs) { 18711 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18712 QualType EnumType = Context.getTypeDeclType(Enum); 18713 18714 ProcessDeclAttributeList(S, Enum, Attrs); 18715 18716 if (Enum->isDependentType()) { 18717 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18718 EnumConstantDecl *ECD = 18719 cast_or_null<EnumConstantDecl>(Elements[i]); 18720 if (!ECD) continue; 18721 18722 ECD->setType(EnumType); 18723 } 18724 18725 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18726 return; 18727 } 18728 18729 // TODO: If the result value doesn't fit in an int, it must be a long or long 18730 // long value. ISO C does not support this, but GCC does as an extension, 18731 // emit a warning. 18732 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18733 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18734 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18735 18736 // Verify that all the values are okay, compute the size of the values, and 18737 // reverse the list. 18738 unsigned NumNegativeBits = 0; 18739 unsigned NumPositiveBits = 0; 18740 18741 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18742 EnumConstantDecl *ECD = 18743 cast_or_null<EnumConstantDecl>(Elements[i]); 18744 if (!ECD) continue; // Already issued a diagnostic. 18745 18746 const llvm::APSInt &InitVal = ECD->getInitVal(); 18747 18748 // Keep track of the size of positive and negative values. 18749 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18750 NumPositiveBits = std::max(NumPositiveBits, 18751 (unsigned)InitVal.getActiveBits()); 18752 else 18753 NumNegativeBits = std::max(NumNegativeBits, 18754 (unsigned)InitVal.getMinSignedBits()); 18755 } 18756 18757 // Figure out the type that should be used for this enum. 18758 QualType BestType; 18759 unsigned BestWidth; 18760 18761 // C++0x N3000 [conv.prom]p3: 18762 // An rvalue of an unscoped enumeration type whose underlying 18763 // type is not fixed can be converted to an rvalue of the first 18764 // of the following types that can represent all the values of 18765 // the enumeration: int, unsigned int, long int, unsigned long 18766 // int, long long int, or unsigned long long int. 18767 // C99 6.4.4.3p2: 18768 // An identifier declared as an enumeration constant has type int. 18769 // The C99 rule is modified by a gcc extension 18770 QualType BestPromotionType; 18771 18772 bool Packed = Enum->hasAttr<PackedAttr>(); 18773 // -fshort-enums is the equivalent to specifying the packed attribute on all 18774 // enum definitions. 18775 if (LangOpts.ShortEnums) 18776 Packed = true; 18777 18778 // If the enum already has a type because it is fixed or dictated by the 18779 // target, promote that type instead of analyzing the enumerators. 18780 if (Enum->isComplete()) { 18781 BestType = Enum->getIntegerType(); 18782 if (BestType->isPromotableIntegerType()) 18783 BestPromotionType = Context.getPromotedIntegerType(BestType); 18784 else 18785 BestPromotionType = BestType; 18786 18787 BestWidth = Context.getIntWidth(BestType); 18788 } 18789 else if (NumNegativeBits) { 18790 // If there is a negative value, figure out the smallest integer type (of 18791 // int/long/longlong) that fits. 18792 // If it's packed, check also if it fits a char or a short. 18793 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18794 BestType = Context.SignedCharTy; 18795 BestWidth = CharWidth; 18796 } else if (Packed && NumNegativeBits <= ShortWidth && 18797 NumPositiveBits < ShortWidth) { 18798 BestType = Context.ShortTy; 18799 BestWidth = ShortWidth; 18800 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18801 BestType = Context.IntTy; 18802 BestWidth = IntWidth; 18803 } else { 18804 BestWidth = Context.getTargetInfo().getLongWidth(); 18805 18806 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18807 BestType = Context.LongTy; 18808 } else { 18809 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18810 18811 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18812 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18813 BestType = Context.LongLongTy; 18814 } 18815 } 18816 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18817 } else { 18818 // If there is no negative value, figure out the smallest type that fits 18819 // all of the enumerator values. 18820 // If it's packed, check also if it fits a char or a short. 18821 if (Packed && NumPositiveBits <= CharWidth) { 18822 BestType = Context.UnsignedCharTy; 18823 BestPromotionType = Context.IntTy; 18824 BestWidth = CharWidth; 18825 } else if (Packed && NumPositiveBits <= ShortWidth) { 18826 BestType = Context.UnsignedShortTy; 18827 BestPromotionType = Context.IntTy; 18828 BestWidth = ShortWidth; 18829 } else if (NumPositiveBits <= IntWidth) { 18830 BestType = Context.UnsignedIntTy; 18831 BestWidth = IntWidth; 18832 BestPromotionType 18833 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18834 ? Context.UnsignedIntTy : Context.IntTy; 18835 } else if (NumPositiveBits <= 18836 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18837 BestType = Context.UnsignedLongTy; 18838 BestPromotionType 18839 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18840 ? Context.UnsignedLongTy : Context.LongTy; 18841 } else { 18842 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18843 assert(NumPositiveBits <= BestWidth && 18844 "How could an initializer get larger than ULL?"); 18845 BestType = Context.UnsignedLongLongTy; 18846 BestPromotionType 18847 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18848 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18849 } 18850 } 18851 18852 // Loop over all of the enumerator constants, changing their types to match 18853 // the type of the enum if needed. 18854 for (auto *D : Elements) { 18855 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18856 if (!ECD) continue; // Already issued a diagnostic. 18857 18858 // Standard C says the enumerators have int type, but we allow, as an 18859 // extension, the enumerators to be larger than int size. If each 18860 // enumerator value fits in an int, type it as an int, otherwise type it the 18861 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18862 // that X has type 'int', not 'unsigned'. 18863 18864 // Determine whether the value fits into an int. 18865 llvm::APSInt InitVal = ECD->getInitVal(); 18866 18867 // If it fits into an integer type, force it. Otherwise force it to match 18868 // the enum decl type. 18869 QualType NewTy; 18870 unsigned NewWidth; 18871 bool NewSign; 18872 if (!getLangOpts().CPlusPlus && 18873 !Enum->isFixed() && 18874 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18875 NewTy = Context.IntTy; 18876 NewWidth = IntWidth; 18877 NewSign = true; 18878 } else if (ECD->getType() == BestType) { 18879 // Already the right type! 18880 if (getLangOpts().CPlusPlus) 18881 // C++ [dcl.enum]p4: Following the closing brace of an 18882 // enum-specifier, each enumerator has the type of its 18883 // enumeration. 18884 ECD->setType(EnumType); 18885 continue; 18886 } else { 18887 NewTy = BestType; 18888 NewWidth = BestWidth; 18889 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18890 } 18891 18892 // Adjust the APSInt value. 18893 InitVal = InitVal.extOrTrunc(NewWidth); 18894 InitVal.setIsSigned(NewSign); 18895 ECD->setInitVal(InitVal); 18896 18897 // Adjust the Expr initializer and type. 18898 if (ECD->getInitExpr() && 18899 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18900 ECD->setInitExpr(ImplicitCastExpr::Create( 18901 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18902 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18903 if (getLangOpts().CPlusPlus) 18904 // C++ [dcl.enum]p4: Following the closing brace of an 18905 // enum-specifier, each enumerator has the type of its 18906 // enumeration. 18907 ECD->setType(EnumType); 18908 else 18909 ECD->setType(NewTy); 18910 } 18911 18912 Enum->completeDefinition(BestType, BestPromotionType, 18913 NumPositiveBits, NumNegativeBits); 18914 18915 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18916 18917 if (Enum->isClosedFlag()) { 18918 for (Decl *D : Elements) { 18919 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18920 if (!ECD) continue; // Already issued a diagnostic. 18921 18922 llvm::APSInt InitVal = ECD->getInitVal(); 18923 if (InitVal != 0 && !InitVal.isPowerOf2() && 18924 !IsValueInFlagEnum(Enum, InitVal, true)) 18925 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18926 << ECD << Enum; 18927 } 18928 } 18929 18930 // Now that the enum type is defined, ensure it's not been underaligned. 18931 if (Enum->hasAttrs()) 18932 CheckAlignasUnderalignment(Enum); 18933 } 18934 18935 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18936 SourceLocation StartLoc, 18937 SourceLocation EndLoc) { 18938 StringLiteral *AsmString = cast<StringLiteral>(expr); 18939 18940 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18941 AsmString, StartLoc, 18942 EndLoc); 18943 CurContext->addDecl(New); 18944 return New; 18945 } 18946 18947 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18948 IdentifierInfo* AliasName, 18949 SourceLocation PragmaLoc, 18950 SourceLocation NameLoc, 18951 SourceLocation AliasNameLoc) { 18952 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18953 LookupOrdinaryName); 18954 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18955 AttributeCommonInfo::AS_Pragma); 18956 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18957 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 18958 18959 // If a declaration that: 18960 // 1) declares a function or a variable 18961 // 2) has external linkage 18962 // already exists, add a label attribute to it. 18963 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18964 if (isDeclExternC(PrevDecl)) 18965 PrevDecl->addAttr(Attr); 18966 else 18967 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18968 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18969 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18970 } else 18971 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18972 } 18973 18974 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18975 SourceLocation PragmaLoc, 18976 SourceLocation NameLoc) { 18977 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18978 18979 if (PrevDecl) { 18980 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18981 } else { 18982 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 18983 } 18984 } 18985 18986 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18987 IdentifierInfo* AliasName, 18988 SourceLocation PragmaLoc, 18989 SourceLocation NameLoc, 18990 SourceLocation AliasNameLoc) { 18991 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18992 LookupOrdinaryName); 18993 WeakInfo W = WeakInfo(Name, NameLoc); 18994 18995 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18996 if (!PrevDecl->hasAttr<AliasAttr>()) 18997 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18998 DeclApplyPragmaWeak(TUScope, ND, W); 18999 } else { 19000 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 19001 } 19002 } 19003 19004 Decl *Sema::getObjCDeclContext() const { 19005 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 19006 } 19007 19008 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 19009 bool Final) { 19010 assert(FD && "Expected non-null FunctionDecl"); 19011 19012 // SYCL functions can be template, so we check if they have appropriate 19013 // attribute prior to checking if it is a template. 19014 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 19015 return FunctionEmissionStatus::Emitted; 19016 19017 // Templates are emitted when they're instantiated. 19018 if (FD->isDependentContext()) 19019 return FunctionEmissionStatus::TemplateDiscarded; 19020 19021 // Check whether this function is an externally visible definition. 19022 auto IsEmittedForExternalSymbol = [this, FD]() { 19023 // We have to check the GVA linkage of the function's *definition* -- if we 19024 // only have a declaration, we don't know whether or not the function will 19025 // be emitted, because (say) the definition could include "inline". 19026 FunctionDecl *Def = FD->getDefinition(); 19027 19028 return Def && !isDiscardableGVALinkage( 19029 getASTContext().GetGVALinkageForFunction(Def)); 19030 }; 19031 19032 if (LangOpts.OpenMPIsDevice) { 19033 // In OpenMP device mode we will not emit host only functions, or functions 19034 // we don't need due to their linkage. 19035 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 19036 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 19037 // DevTy may be changed later by 19038 // #pragma omp declare target to(*) device_type(*). 19039 // Therefore DevTy having no value does not imply host. The emission status 19040 // will be checked again at the end of compilation unit with Final = true. 19041 if (DevTy.hasValue()) 19042 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 19043 return FunctionEmissionStatus::OMPDiscarded; 19044 // If we have an explicit value for the device type, or we are in a target 19045 // declare context, we need to emit all extern and used symbols. 19046 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 19047 if (IsEmittedForExternalSymbol()) 19048 return FunctionEmissionStatus::Emitted; 19049 // Device mode only emits what it must, if it wasn't tagged yet and needed, 19050 // we'll omit it. 19051 if (Final) 19052 return FunctionEmissionStatus::OMPDiscarded; 19053 } else if (LangOpts.OpenMP > 45) { 19054 // In OpenMP host compilation prior to 5.0 everything was an emitted host 19055 // function. In 5.0, no_host was introduced which might cause a function to 19056 // be ommitted. 19057 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 19058 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 19059 if (DevTy.hasValue()) 19060 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 19061 return FunctionEmissionStatus::OMPDiscarded; 19062 } 19063 19064 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 19065 return FunctionEmissionStatus::Emitted; 19066 19067 if (LangOpts.CUDA) { 19068 // When compiling for device, host functions are never emitted. Similarly, 19069 // when compiling for host, device and global functions are never emitted. 19070 // (Technically, we do emit a host-side stub for global functions, but this 19071 // doesn't count for our purposes here.) 19072 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 19073 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 19074 return FunctionEmissionStatus::CUDADiscarded; 19075 if (!LangOpts.CUDAIsDevice && 19076 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 19077 return FunctionEmissionStatus::CUDADiscarded; 19078 19079 if (IsEmittedForExternalSymbol()) 19080 return FunctionEmissionStatus::Emitted; 19081 } 19082 19083 // Otherwise, the function is known-emitted if it's in our set of 19084 // known-emitted functions. 19085 return FunctionEmissionStatus::Unknown; 19086 } 19087 19088 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 19089 // Host-side references to a __global__ function refer to the stub, so the 19090 // function itself is never emitted and therefore should not be marked. 19091 // If we have host fn calls kernel fn calls host+device, the HD function 19092 // does not get instantiated on the host. We model this by omitting at the 19093 // call to the kernel from the callgraph. This ensures that, when compiling 19094 // for host, only HD functions actually called from the host get marked as 19095 // known-emitted. 19096 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 19097 IdentifyCUDATarget(Callee) == CFT_Global; 19098 } 19099