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 8826 NewFD = FunctionDecl::Create( 8827 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8828 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8829 ConstexprSpecKind::Unspecified, 8830 /*TrailingRequiresClause=*/nullptr); 8831 if (D.isInvalidType()) 8832 NewFD->setInvalidDecl(); 8833 8834 return NewFD; 8835 } 8836 8837 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8838 8839 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8840 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8841 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8842 diag::err_constexpr_wrong_decl_kind) 8843 << static_cast<int>(ConstexprKind); 8844 ConstexprKind = ConstexprSpecKind::Unspecified; 8845 D.getMutableDeclSpec().ClearConstexprSpec(); 8846 } 8847 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8848 8849 // Check that the return type is not an abstract class type. 8850 // For record types, this is done by the AbstractClassUsageDiagnoser once 8851 // the class has been completely parsed. 8852 if (!DC->isRecord() && 8853 SemaRef.RequireNonAbstractType( 8854 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8855 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8856 D.setInvalidType(); 8857 8858 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8859 // This is a C++ constructor declaration. 8860 assert(DC->isRecord() && 8861 "Constructors can only be declared in a member context"); 8862 8863 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8864 return CXXConstructorDecl::Create( 8865 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8866 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8867 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8868 InheritedConstructor(), TrailingRequiresClause); 8869 8870 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8871 // This is a C++ destructor declaration. 8872 if (DC->isRecord()) { 8873 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8874 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8875 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8876 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8877 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8878 /*isImplicitlyDeclared=*/false, ConstexprKind, 8879 TrailingRequiresClause); 8880 8881 // If the destructor needs an implicit exception specification, set it 8882 // now. FIXME: It'd be nice to be able to create the right type to start 8883 // with, but the type needs to reference the destructor declaration. 8884 if (SemaRef.getLangOpts().CPlusPlus11) 8885 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8886 8887 IsVirtualOkay = true; 8888 return NewDD; 8889 8890 } else { 8891 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8892 D.setInvalidType(); 8893 8894 // Create a FunctionDecl to satisfy the function definition parsing 8895 // code path. 8896 return FunctionDecl::Create( 8897 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8898 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8899 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8900 } 8901 8902 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8903 if (!DC->isRecord()) { 8904 SemaRef.Diag(D.getIdentifierLoc(), 8905 diag::err_conv_function_not_member); 8906 return nullptr; 8907 } 8908 8909 SemaRef.CheckConversionDeclarator(D, R, SC); 8910 if (D.isInvalidType()) 8911 return nullptr; 8912 8913 IsVirtualOkay = true; 8914 return CXXConversionDecl::Create( 8915 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8916 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8917 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8918 TrailingRequiresClause); 8919 8920 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8921 if (TrailingRequiresClause) 8922 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8923 diag::err_trailing_requires_clause_on_deduction_guide) 8924 << TrailingRequiresClause->getSourceRange(); 8925 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8926 8927 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8928 ExplicitSpecifier, NameInfo, R, TInfo, 8929 D.getEndLoc()); 8930 } else if (DC->isRecord()) { 8931 // If the name of the function is the same as the name of the record, 8932 // then this must be an invalid constructor that has a return type. 8933 // (The parser checks for a return type and makes the declarator a 8934 // constructor if it has no return type). 8935 if (Name.getAsIdentifierInfo() && 8936 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8937 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8938 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8939 << SourceRange(D.getIdentifierLoc()); 8940 return nullptr; 8941 } 8942 8943 // This is a C++ method declaration. 8944 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8945 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8946 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8947 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8948 IsVirtualOkay = !Ret->isStatic(); 8949 return Ret; 8950 } else { 8951 bool isFriend = 8952 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8953 if (!isFriend && SemaRef.CurContext->isRecord()) 8954 return nullptr; 8955 8956 // Determine whether the function was written with a 8957 // prototype. This true when: 8958 // - we're in C++ (where every function has a prototype), 8959 return FunctionDecl::Create( 8960 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8961 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8962 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8963 } 8964 } 8965 8966 enum OpenCLParamType { 8967 ValidKernelParam, 8968 PtrPtrKernelParam, 8969 PtrKernelParam, 8970 InvalidAddrSpacePtrKernelParam, 8971 InvalidKernelParam, 8972 RecordKernelParam 8973 }; 8974 8975 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8976 // Size dependent types are just typedefs to normal integer types 8977 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8978 // integers other than by their names. 8979 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8980 8981 // Remove typedefs one by one until we reach a typedef 8982 // for a size dependent type. 8983 QualType DesugaredTy = Ty; 8984 do { 8985 ArrayRef<StringRef> Names(SizeTypeNames); 8986 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8987 if (Names.end() != Match) 8988 return true; 8989 8990 Ty = DesugaredTy; 8991 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8992 } while (DesugaredTy != Ty); 8993 8994 return false; 8995 } 8996 8997 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8998 if (PT->isDependentType()) 8999 return InvalidKernelParam; 9000 9001 if (PT->isPointerType() || PT->isReferenceType()) { 9002 QualType PointeeType = PT->getPointeeType(); 9003 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 9004 PointeeType.getAddressSpace() == LangAS::opencl_private || 9005 PointeeType.getAddressSpace() == LangAS::Default) 9006 return InvalidAddrSpacePtrKernelParam; 9007 9008 if (PointeeType->isPointerType()) { 9009 // This is a pointer to pointer parameter. 9010 // Recursively check inner type. 9011 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 9012 if (ParamKind == InvalidAddrSpacePtrKernelParam || 9013 ParamKind == InvalidKernelParam) 9014 return ParamKind; 9015 9016 return PtrPtrKernelParam; 9017 } 9018 9019 // C++ for OpenCL v1.0 s2.4: 9020 // Moreover the types used in parameters of the kernel functions must be: 9021 // Standard layout types for pointer parameters. The same applies to 9022 // reference if an implementation supports them in kernel parameters. 9023 if (S.getLangOpts().OpenCLCPlusPlus && 9024 !S.getOpenCLOptions().isAvailableOption( 9025 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9026 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 9027 !PointeeType->isStandardLayoutType()) 9028 return InvalidKernelParam; 9029 9030 return PtrKernelParam; 9031 } 9032 9033 // OpenCL v1.2 s6.9.k: 9034 // Arguments to kernel functions in a program cannot be declared with the 9035 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9036 // uintptr_t or a struct and/or union that contain fields declared to be one 9037 // of these built-in scalar types. 9038 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 9039 return InvalidKernelParam; 9040 9041 if (PT->isImageType()) 9042 return PtrKernelParam; 9043 9044 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 9045 return InvalidKernelParam; 9046 9047 // OpenCL extension spec v1.2 s9.5: 9048 // This extension adds support for half scalar and vector types as built-in 9049 // types that can be used for arithmetic operations, conversions etc. 9050 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 9051 PT->isHalfType()) 9052 return InvalidKernelParam; 9053 9054 // Look into an array argument to check if it has a forbidden type. 9055 if (PT->isArrayType()) { 9056 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 9057 // Call ourself to check an underlying type of an array. Since the 9058 // getPointeeOrArrayElementType returns an innermost type which is not an 9059 // array, this recursive call only happens once. 9060 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 9061 } 9062 9063 // C++ for OpenCL v1.0 s2.4: 9064 // Moreover the types used in parameters of the kernel functions must be: 9065 // Trivial and standard-layout types C++17 [basic.types] (plain old data 9066 // types) for parameters passed by value; 9067 if (S.getLangOpts().OpenCLCPlusPlus && 9068 !S.getOpenCLOptions().isAvailableOption( 9069 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9070 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 9071 return InvalidKernelParam; 9072 9073 if (PT->isRecordType()) 9074 return RecordKernelParam; 9075 9076 return ValidKernelParam; 9077 } 9078 9079 static void checkIsValidOpenCLKernelParameter( 9080 Sema &S, 9081 Declarator &D, 9082 ParmVarDecl *Param, 9083 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 9084 QualType PT = Param->getType(); 9085 9086 // Cache the valid types we encounter to avoid rechecking structs that are 9087 // used again 9088 if (ValidTypes.count(PT.getTypePtr())) 9089 return; 9090 9091 switch (getOpenCLKernelParameterType(S, PT)) { 9092 case PtrPtrKernelParam: 9093 // OpenCL v3.0 s6.11.a: 9094 // A kernel function argument cannot be declared as a pointer to a pointer 9095 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 9096 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 9097 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 9098 D.setInvalidType(); 9099 return; 9100 } 9101 9102 ValidTypes.insert(PT.getTypePtr()); 9103 return; 9104 9105 case InvalidAddrSpacePtrKernelParam: 9106 // OpenCL v1.0 s6.5: 9107 // __kernel function arguments declared to be a pointer of a type can point 9108 // to one of the following address spaces only : __global, __local or 9109 // __constant. 9110 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 9111 D.setInvalidType(); 9112 return; 9113 9114 // OpenCL v1.2 s6.9.k: 9115 // Arguments to kernel functions in a program cannot be declared with the 9116 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9117 // uintptr_t or a struct and/or union that contain fields declared to be 9118 // one of these built-in scalar types. 9119 9120 case InvalidKernelParam: 9121 // OpenCL v1.2 s6.8 n: 9122 // A kernel function argument cannot be declared 9123 // of event_t type. 9124 // Do not diagnose half type since it is diagnosed as invalid argument 9125 // type for any function elsewhere. 9126 if (!PT->isHalfType()) { 9127 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9128 9129 // Explain what typedefs are involved. 9130 const TypedefType *Typedef = nullptr; 9131 while ((Typedef = PT->getAs<TypedefType>())) { 9132 SourceLocation Loc = Typedef->getDecl()->getLocation(); 9133 // SourceLocation may be invalid for a built-in type. 9134 if (Loc.isValid()) 9135 S.Diag(Loc, diag::note_entity_declared_at) << PT; 9136 PT = Typedef->desugar(); 9137 } 9138 } 9139 9140 D.setInvalidType(); 9141 return; 9142 9143 case PtrKernelParam: 9144 case ValidKernelParam: 9145 ValidTypes.insert(PT.getTypePtr()); 9146 return; 9147 9148 case RecordKernelParam: 9149 break; 9150 } 9151 9152 // Track nested structs we will inspect 9153 SmallVector<const Decl *, 4> VisitStack; 9154 9155 // Track where we are in the nested structs. Items will migrate from 9156 // VisitStack to HistoryStack as we do the DFS for bad field. 9157 SmallVector<const FieldDecl *, 4> HistoryStack; 9158 HistoryStack.push_back(nullptr); 9159 9160 // At this point we already handled everything except of a RecordType or 9161 // an ArrayType of a RecordType. 9162 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9163 const RecordType *RecTy = 9164 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9165 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9166 9167 VisitStack.push_back(RecTy->getDecl()); 9168 assert(VisitStack.back() && "First decl null?"); 9169 9170 do { 9171 const Decl *Next = VisitStack.pop_back_val(); 9172 if (!Next) { 9173 assert(!HistoryStack.empty()); 9174 // Found a marker, we have gone up a level 9175 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9176 ValidTypes.insert(Hist->getType().getTypePtr()); 9177 9178 continue; 9179 } 9180 9181 // Adds everything except the original parameter declaration (which is not a 9182 // field itself) to the history stack. 9183 const RecordDecl *RD; 9184 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9185 HistoryStack.push_back(Field); 9186 9187 QualType FieldTy = Field->getType(); 9188 // Other field types (known to be valid or invalid) are handled while we 9189 // walk around RecordDecl::fields(). 9190 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9191 "Unexpected type."); 9192 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9193 9194 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9195 } else { 9196 RD = cast<RecordDecl>(Next); 9197 } 9198 9199 // Add a null marker so we know when we've gone back up a level 9200 VisitStack.push_back(nullptr); 9201 9202 for (const auto *FD : RD->fields()) { 9203 QualType QT = FD->getType(); 9204 9205 if (ValidTypes.count(QT.getTypePtr())) 9206 continue; 9207 9208 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9209 if (ParamType == ValidKernelParam) 9210 continue; 9211 9212 if (ParamType == RecordKernelParam) { 9213 VisitStack.push_back(FD); 9214 continue; 9215 } 9216 9217 // OpenCL v1.2 s6.9.p: 9218 // Arguments to kernel functions that are declared to be a struct or union 9219 // do not allow OpenCL objects to be passed as elements of the struct or 9220 // union. 9221 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9222 ParamType == InvalidAddrSpacePtrKernelParam) { 9223 S.Diag(Param->getLocation(), 9224 diag::err_record_with_pointers_kernel_param) 9225 << PT->isUnionType() 9226 << PT; 9227 } else { 9228 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9229 } 9230 9231 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9232 << OrigRecDecl->getDeclName(); 9233 9234 // We have an error, now let's go back up through history and show where 9235 // the offending field came from 9236 for (ArrayRef<const FieldDecl *>::const_iterator 9237 I = HistoryStack.begin() + 1, 9238 E = HistoryStack.end(); 9239 I != E; ++I) { 9240 const FieldDecl *OuterField = *I; 9241 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9242 << OuterField->getType(); 9243 } 9244 9245 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9246 << QT->isPointerType() 9247 << QT; 9248 D.setInvalidType(); 9249 return; 9250 } 9251 } while (!VisitStack.empty()); 9252 } 9253 9254 /// Find the DeclContext in which a tag is implicitly declared if we see an 9255 /// elaborated type specifier in the specified context, and lookup finds 9256 /// nothing. 9257 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9258 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9259 DC = DC->getParent(); 9260 return DC; 9261 } 9262 9263 /// Find the Scope in which a tag is implicitly declared if we see an 9264 /// elaborated type specifier in the specified context, and lookup finds 9265 /// nothing. 9266 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9267 while (S->isClassScope() || 9268 (LangOpts.CPlusPlus && 9269 S->isFunctionPrototypeScope()) || 9270 ((S->getFlags() & Scope::DeclScope) == 0) || 9271 (S->getEntity() && S->getEntity()->isTransparentContext())) 9272 S = S->getParent(); 9273 return S; 9274 } 9275 9276 /// Determine whether a declaration matches a known function in namespace std. 9277 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, 9278 unsigned BuiltinID) { 9279 switch (BuiltinID) { 9280 case Builtin::BI__GetExceptionInfo: 9281 // No type checking whatsoever. 9282 return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); 9283 9284 case Builtin::BIaddressof: 9285 case Builtin::BI__addressof: 9286 case Builtin::BIforward: 9287 case Builtin::BImove: 9288 case Builtin::BImove_if_noexcept: 9289 case Builtin::BIas_const: { 9290 // Ensure that we don't treat the algorithm 9291 // OutputIt std::move(InputIt, InputIt, OutputIt) 9292 // as the builtin std::move. 9293 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 9294 return FPT->getNumParams() == 1 && !FPT->isVariadic(); 9295 } 9296 9297 default: 9298 return false; 9299 } 9300 } 9301 9302 NamedDecl* 9303 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9304 TypeSourceInfo *TInfo, LookupResult &Previous, 9305 MultiTemplateParamsArg TemplateParamListsRef, 9306 bool &AddToScope) { 9307 QualType R = TInfo->getType(); 9308 9309 assert(R->isFunctionType()); 9310 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9311 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9312 9313 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9314 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9315 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9316 if (!TemplateParamLists.empty() && 9317 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9318 TemplateParamLists.back() = Invented; 9319 else 9320 TemplateParamLists.push_back(Invented); 9321 } 9322 9323 // TODO: consider using NameInfo for diagnostic. 9324 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9325 DeclarationName Name = NameInfo.getName(); 9326 StorageClass SC = getFunctionStorageClass(*this, D); 9327 9328 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9329 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9330 diag::err_invalid_thread) 9331 << DeclSpec::getSpecifierName(TSCS); 9332 9333 if (D.isFirstDeclarationOfMember()) 9334 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9335 D.getIdentifierLoc()); 9336 9337 bool isFriend = false; 9338 FunctionTemplateDecl *FunctionTemplate = nullptr; 9339 bool isMemberSpecialization = false; 9340 bool isFunctionTemplateSpecialization = false; 9341 9342 bool isDependentClassScopeExplicitSpecialization = false; 9343 bool HasExplicitTemplateArgs = false; 9344 TemplateArgumentListInfo TemplateArgs; 9345 9346 bool isVirtualOkay = false; 9347 9348 DeclContext *OriginalDC = DC; 9349 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9350 9351 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9352 isVirtualOkay); 9353 if (!NewFD) return nullptr; 9354 9355 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9356 NewFD->setTopLevelDeclInObjCContainer(); 9357 9358 // Set the lexical context. If this is a function-scope declaration, or has a 9359 // C++ scope specifier, or is the object of a friend declaration, the lexical 9360 // context will be different from the semantic context. 9361 NewFD->setLexicalDeclContext(CurContext); 9362 9363 if (IsLocalExternDecl) 9364 NewFD->setLocalExternDecl(); 9365 9366 if (getLangOpts().CPlusPlus) { 9367 bool isInline = D.getDeclSpec().isInlineSpecified(); 9368 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9369 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9370 isFriend = D.getDeclSpec().isFriendSpecified(); 9371 if (isFriend && !isInline && D.isFunctionDefinition()) { 9372 // C++ [class.friend]p5 9373 // A function can be defined in a friend declaration of a 9374 // class . . . . Such a function is implicitly inline. 9375 NewFD->setImplicitlyInline(); 9376 } 9377 9378 // If this is a method defined in an __interface, and is not a constructor 9379 // or an overloaded operator, then set the pure flag (isVirtual will already 9380 // return true). 9381 if (const CXXRecordDecl *Parent = 9382 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9383 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9384 NewFD->setPure(true); 9385 9386 // C++ [class.union]p2 9387 // A union can have member functions, but not virtual functions. 9388 if (isVirtual && Parent->isUnion()) { 9389 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9390 NewFD->setInvalidDecl(); 9391 } 9392 if ((Parent->isClass() || Parent->isStruct()) && 9393 Parent->hasAttr<SYCLSpecialClassAttr>() && 9394 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9395 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9396 if (auto *Def = Parent->getDefinition()) 9397 Def->setInitMethod(true); 9398 } 9399 } 9400 9401 SetNestedNameSpecifier(*this, NewFD, D); 9402 isMemberSpecialization = false; 9403 isFunctionTemplateSpecialization = false; 9404 if (D.isInvalidType()) 9405 NewFD->setInvalidDecl(); 9406 9407 // Match up the template parameter lists with the scope specifier, then 9408 // determine whether we have a template or a template specialization. 9409 bool Invalid = false; 9410 TemplateParameterList *TemplateParams = 9411 MatchTemplateParametersToScopeSpecifier( 9412 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9413 D.getCXXScopeSpec(), 9414 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9415 ? D.getName().TemplateId 9416 : nullptr, 9417 TemplateParamLists, isFriend, isMemberSpecialization, 9418 Invalid); 9419 if (TemplateParams) { 9420 // Check that we can declare a template here. 9421 if (CheckTemplateDeclScope(S, TemplateParams)) 9422 NewFD->setInvalidDecl(); 9423 9424 if (TemplateParams->size() > 0) { 9425 // This is a function template 9426 9427 // A destructor cannot be a template. 9428 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9429 Diag(NewFD->getLocation(), diag::err_destructor_template); 9430 NewFD->setInvalidDecl(); 9431 } 9432 9433 // If we're adding a template to a dependent context, we may need to 9434 // rebuilding some of the types used within the template parameter list, 9435 // now that we know what the current instantiation is. 9436 if (DC->isDependentContext()) { 9437 ContextRAII SavedContext(*this, DC); 9438 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9439 Invalid = true; 9440 } 9441 9442 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9443 NewFD->getLocation(), 9444 Name, TemplateParams, 9445 NewFD); 9446 FunctionTemplate->setLexicalDeclContext(CurContext); 9447 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9448 9449 // For source fidelity, store the other template param lists. 9450 if (TemplateParamLists.size() > 1) { 9451 NewFD->setTemplateParameterListsInfo(Context, 9452 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9453 .drop_back(1)); 9454 } 9455 } else { 9456 // This is a function template specialization. 9457 isFunctionTemplateSpecialization = true; 9458 // For source fidelity, store all the template param lists. 9459 if (TemplateParamLists.size() > 0) 9460 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9461 9462 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9463 if (isFriend) { 9464 // We want to remove the "template<>", found here. 9465 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9466 9467 // If we remove the template<> and the name is not a 9468 // template-id, we're actually silently creating a problem: 9469 // the friend declaration will refer to an untemplated decl, 9470 // and clearly the user wants a template specialization. So 9471 // we need to insert '<>' after the name. 9472 SourceLocation InsertLoc; 9473 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9474 InsertLoc = D.getName().getSourceRange().getEnd(); 9475 InsertLoc = getLocForEndOfToken(InsertLoc); 9476 } 9477 9478 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9479 << Name << RemoveRange 9480 << FixItHint::CreateRemoval(RemoveRange) 9481 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9482 Invalid = true; 9483 } 9484 } 9485 } else { 9486 // Check that we can declare a template here. 9487 if (!TemplateParamLists.empty() && isMemberSpecialization && 9488 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9489 NewFD->setInvalidDecl(); 9490 9491 // All template param lists were matched against the scope specifier: 9492 // this is NOT (an explicit specialization of) a template. 9493 if (TemplateParamLists.size() > 0) 9494 // For source fidelity, store all the template param lists. 9495 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9496 } 9497 9498 if (Invalid) { 9499 NewFD->setInvalidDecl(); 9500 if (FunctionTemplate) 9501 FunctionTemplate->setInvalidDecl(); 9502 } 9503 9504 // C++ [dcl.fct.spec]p5: 9505 // The virtual specifier shall only be used in declarations of 9506 // nonstatic class member functions that appear within a 9507 // member-specification of a class declaration; see 10.3. 9508 // 9509 if (isVirtual && !NewFD->isInvalidDecl()) { 9510 if (!isVirtualOkay) { 9511 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9512 diag::err_virtual_non_function); 9513 } else if (!CurContext->isRecord()) { 9514 // 'virtual' was specified outside of the class. 9515 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9516 diag::err_virtual_out_of_class) 9517 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9518 } else if (NewFD->getDescribedFunctionTemplate()) { 9519 // C++ [temp.mem]p3: 9520 // A member function template shall not be virtual. 9521 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9522 diag::err_virtual_member_function_template) 9523 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9524 } else { 9525 // Okay: Add virtual to the method. 9526 NewFD->setVirtualAsWritten(true); 9527 } 9528 9529 if (getLangOpts().CPlusPlus14 && 9530 NewFD->getReturnType()->isUndeducedType()) 9531 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9532 } 9533 9534 if (getLangOpts().CPlusPlus14 && 9535 (NewFD->isDependentContext() || 9536 (isFriend && CurContext->isDependentContext())) && 9537 NewFD->getReturnType()->isUndeducedType()) { 9538 // If the function template is referenced directly (for instance, as a 9539 // member of the current instantiation), pretend it has a dependent type. 9540 // This is not really justified by the standard, but is the only sane 9541 // thing to do. 9542 // FIXME: For a friend function, we have not marked the function as being 9543 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9544 const FunctionProtoType *FPT = 9545 NewFD->getType()->castAs<FunctionProtoType>(); 9546 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9547 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9548 FPT->getExtProtoInfo())); 9549 } 9550 9551 // C++ [dcl.fct.spec]p3: 9552 // The inline specifier shall not appear on a block scope function 9553 // declaration. 9554 if (isInline && !NewFD->isInvalidDecl()) { 9555 if (CurContext->isFunctionOrMethod()) { 9556 // 'inline' is not allowed on block scope function declaration. 9557 Diag(D.getDeclSpec().getInlineSpecLoc(), 9558 diag::err_inline_declaration_block_scope) << Name 9559 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9560 } 9561 } 9562 9563 // C++ [dcl.fct.spec]p6: 9564 // The explicit specifier shall be used only in the declaration of a 9565 // constructor or conversion function within its class definition; 9566 // see 12.3.1 and 12.3.2. 9567 if (hasExplicit && !NewFD->isInvalidDecl() && 9568 !isa<CXXDeductionGuideDecl>(NewFD)) { 9569 if (!CurContext->isRecord()) { 9570 // 'explicit' was specified outside of the class. 9571 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9572 diag::err_explicit_out_of_class) 9573 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9574 } else if (!isa<CXXConstructorDecl>(NewFD) && 9575 !isa<CXXConversionDecl>(NewFD)) { 9576 // 'explicit' was specified on a function that wasn't a constructor 9577 // or conversion function. 9578 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9579 diag::err_explicit_non_ctor_or_conv_function) 9580 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9581 } 9582 } 9583 9584 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9585 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9586 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9587 // are implicitly inline. 9588 NewFD->setImplicitlyInline(); 9589 9590 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9591 // be either constructors or to return a literal type. Therefore, 9592 // destructors cannot be declared constexpr. 9593 if (isa<CXXDestructorDecl>(NewFD) && 9594 (!getLangOpts().CPlusPlus20 || 9595 ConstexprKind == ConstexprSpecKind::Consteval)) { 9596 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9597 << static_cast<int>(ConstexprKind); 9598 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9599 ? ConstexprSpecKind::Unspecified 9600 : ConstexprSpecKind::Constexpr); 9601 } 9602 // C++20 [dcl.constexpr]p2: An allocation function, or a 9603 // deallocation function shall not be declared with the consteval 9604 // specifier. 9605 if (ConstexprKind == ConstexprSpecKind::Consteval && 9606 (NewFD->getOverloadedOperator() == OO_New || 9607 NewFD->getOverloadedOperator() == OO_Array_New || 9608 NewFD->getOverloadedOperator() == OO_Delete || 9609 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9610 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9611 diag::err_invalid_consteval_decl_kind) 9612 << NewFD; 9613 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9614 } 9615 } 9616 9617 // If __module_private__ was specified, mark the function accordingly. 9618 if (D.getDeclSpec().isModulePrivateSpecified()) { 9619 if (isFunctionTemplateSpecialization) { 9620 SourceLocation ModulePrivateLoc 9621 = D.getDeclSpec().getModulePrivateSpecLoc(); 9622 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9623 << 0 9624 << FixItHint::CreateRemoval(ModulePrivateLoc); 9625 } else { 9626 NewFD->setModulePrivate(); 9627 if (FunctionTemplate) 9628 FunctionTemplate->setModulePrivate(); 9629 } 9630 } 9631 9632 if (isFriend) { 9633 if (FunctionTemplate) { 9634 FunctionTemplate->setObjectOfFriendDecl(); 9635 FunctionTemplate->setAccess(AS_public); 9636 } 9637 NewFD->setObjectOfFriendDecl(); 9638 NewFD->setAccess(AS_public); 9639 } 9640 9641 // If a function is defined as defaulted or deleted, mark it as such now. 9642 // We'll do the relevant checks on defaulted / deleted functions later. 9643 switch (D.getFunctionDefinitionKind()) { 9644 case FunctionDefinitionKind::Declaration: 9645 case FunctionDefinitionKind::Definition: 9646 break; 9647 9648 case FunctionDefinitionKind::Defaulted: 9649 NewFD->setDefaulted(); 9650 break; 9651 9652 case FunctionDefinitionKind::Deleted: 9653 NewFD->setDeletedAsWritten(); 9654 break; 9655 } 9656 9657 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9658 D.isFunctionDefinition()) { 9659 // C++ [class.mfct]p2: 9660 // A member function may be defined (8.4) in its class definition, in 9661 // which case it is an inline member function (7.1.2) 9662 NewFD->setImplicitlyInline(); 9663 } 9664 9665 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9666 !CurContext->isRecord()) { 9667 // C++ [class.static]p1: 9668 // A data or function member of a class may be declared static 9669 // in a class definition, in which case it is a static member of 9670 // the class. 9671 9672 // Complain about the 'static' specifier if it's on an out-of-line 9673 // member function definition. 9674 9675 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9676 // member function template declaration and class member template 9677 // declaration (MSVC versions before 2015), warn about this. 9678 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9679 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9680 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9681 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9682 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9683 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9684 } 9685 9686 // C++11 [except.spec]p15: 9687 // A deallocation function with no exception-specification is treated 9688 // as if it were specified with noexcept(true). 9689 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9690 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9691 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9692 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9693 NewFD->setType(Context.getFunctionType( 9694 FPT->getReturnType(), FPT->getParamTypes(), 9695 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9696 } 9697 9698 // Filter out previous declarations that don't match the scope. 9699 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9700 D.getCXXScopeSpec().isNotEmpty() || 9701 isMemberSpecialization || 9702 isFunctionTemplateSpecialization); 9703 9704 // Handle GNU asm-label extension (encoded as an attribute). 9705 if (Expr *E = (Expr*) D.getAsmLabel()) { 9706 // The parser guarantees this is a string. 9707 StringLiteral *SE = cast<StringLiteral>(E); 9708 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9709 /*IsLiteralLabel=*/true, 9710 SE->getStrTokenLoc(0))); 9711 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9712 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9713 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9714 if (I != ExtnameUndeclaredIdentifiers.end()) { 9715 if (isDeclExternC(NewFD)) { 9716 NewFD->addAttr(I->second); 9717 ExtnameUndeclaredIdentifiers.erase(I); 9718 } else 9719 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9720 << /*Variable*/0 << NewFD; 9721 } 9722 } 9723 9724 // Copy the parameter declarations from the declarator D to the function 9725 // declaration NewFD, if they are available. First scavenge them into Params. 9726 SmallVector<ParmVarDecl*, 16> Params; 9727 unsigned FTIIdx; 9728 if (D.isFunctionDeclarator(FTIIdx)) { 9729 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9730 9731 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9732 // function that takes no arguments, not a function that takes a 9733 // single void argument. 9734 // We let through "const void" here because Sema::GetTypeForDeclarator 9735 // already checks for that case. 9736 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9737 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9738 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9739 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9740 Param->setDeclContext(NewFD); 9741 Params.push_back(Param); 9742 9743 if (Param->isInvalidDecl()) 9744 NewFD->setInvalidDecl(); 9745 } 9746 } 9747 9748 if (!getLangOpts().CPlusPlus) { 9749 // In C, find all the tag declarations from the prototype and move them 9750 // into the function DeclContext. Remove them from the surrounding tag 9751 // injection context of the function, which is typically but not always 9752 // the TU. 9753 DeclContext *PrototypeTagContext = 9754 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9755 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9756 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9757 9758 // We don't want to reparent enumerators. Look at their parent enum 9759 // instead. 9760 if (!TD) { 9761 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9762 TD = cast<EnumDecl>(ECD->getDeclContext()); 9763 } 9764 if (!TD) 9765 continue; 9766 DeclContext *TagDC = TD->getLexicalDeclContext(); 9767 if (!TagDC->containsDecl(TD)) 9768 continue; 9769 TagDC->removeDecl(TD); 9770 TD->setDeclContext(NewFD); 9771 NewFD->addDecl(TD); 9772 9773 // Preserve the lexical DeclContext if it is not the surrounding tag 9774 // injection context of the FD. In this example, the semantic context of 9775 // E will be f and the lexical context will be S, while both the 9776 // semantic and lexical contexts of S will be f: 9777 // void f(struct S { enum E { a } f; } s); 9778 if (TagDC != PrototypeTagContext) 9779 TD->setLexicalDeclContext(TagDC); 9780 } 9781 } 9782 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9783 // When we're declaring a function with a typedef, typeof, etc as in the 9784 // following example, we'll need to synthesize (unnamed) 9785 // parameters for use in the declaration. 9786 // 9787 // @code 9788 // typedef void fn(int); 9789 // fn f; 9790 // @endcode 9791 9792 // Synthesize a parameter for each argument type. 9793 for (const auto &AI : FT->param_types()) { 9794 ParmVarDecl *Param = 9795 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9796 Param->setScopeInfo(0, Params.size()); 9797 Params.push_back(Param); 9798 } 9799 } else { 9800 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9801 "Should not need args for typedef of non-prototype fn"); 9802 } 9803 9804 // Finally, we know we have the right number of parameters, install them. 9805 NewFD->setParams(Params); 9806 9807 if (D.getDeclSpec().isNoreturnSpecified()) 9808 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9809 D.getDeclSpec().getNoreturnSpecLoc(), 9810 AttributeCommonInfo::AS_Keyword)); 9811 9812 // Functions returning a variably modified type violate C99 6.7.5.2p2 9813 // because all functions have linkage. 9814 if (!NewFD->isInvalidDecl() && 9815 NewFD->getReturnType()->isVariablyModifiedType()) { 9816 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9817 NewFD->setInvalidDecl(); 9818 } 9819 9820 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9821 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9822 !NewFD->hasAttr<SectionAttr>()) 9823 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9824 Context, PragmaClangTextSection.SectionName, 9825 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9826 9827 // Apply an implicit SectionAttr if #pragma code_seg is active. 9828 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9829 !NewFD->hasAttr<SectionAttr>()) { 9830 NewFD->addAttr(SectionAttr::CreateImplicit( 9831 Context, CodeSegStack.CurrentValue->getString(), 9832 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9833 SectionAttr::Declspec_allocate)); 9834 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9835 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9836 ASTContext::PSF_Read, 9837 NewFD)) 9838 NewFD->dropAttr<SectionAttr>(); 9839 } 9840 9841 // Apply an implicit CodeSegAttr from class declspec or 9842 // apply an implicit SectionAttr from #pragma code_seg if active. 9843 if (!NewFD->hasAttr<CodeSegAttr>()) { 9844 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9845 D.isFunctionDefinition())) { 9846 NewFD->addAttr(SAttr); 9847 } 9848 } 9849 9850 // Handle attributes. 9851 ProcessDeclAttributes(S, NewFD, D); 9852 9853 if (getLangOpts().OpenCL) { 9854 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9855 // type declaration will generate a compilation error. 9856 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9857 if (AddressSpace != LangAS::Default) { 9858 Diag(NewFD->getLocation(), 9859 diag::err_opencl_return_value_with_address_space); 9860 NewFD->setInvalidDecl(); 9861 } 9862 } 9863 9864 if (!getLangOpts().CPlusPlus) { 9865 // Perform semantic checking on the function declaration. 9866 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9867 CheckMain(NewFD, D.getDeclSpec()); 9868 9869 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9870 CheckMSVCRTEntryPoint(NewFD); 9871 9872 if (!NewFD->isInvalidDecl()) 9873 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9874 isMemberSpecialization, 9875 D.isFunctionDefinition())); 9876 else if (!Previous.empty()) 9877 // Recover gracefully from an invalid redeclaration. 9878 D.setRedeclaration(true); 9879 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9880 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9881 "previous declaration set still overloaded"); 9882 9883 // Diagnose no-prototype function declarations with calling conventions that 9884 // don't support variadic calls. Only do this in C and do it after merging 9885 // possibly prototyped redeclarations. 9886 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9887 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9888 CallingConv CC = FT->getExtInfo().getCC(); 9889 if (!supportsVariadicCall(CC)) { 9890 // Windows system headers sometimes accidentally use stdcall without 9891 // (void) parameters, so we relax this to a warning. 9892 int DiagID = 9893 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9894 Diag(NewFD->getLocation(), DiagID) 9895 << FunctionType::getNameForCallConv(CC); 9896 } 9897 } 9898 9899 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9900 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9901 checkNonTrivialCUnion(NewFD->getReturnType(), 9902 NewFD->getReturnTypeSourceRange().getBegin(), 9903 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9904 } else { 9905 // C++11 [replacement.functions]p3: 9906 // The program's definitions shall not be specified as inline. 9907 // 9908 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9909 // 9910 // Suppress the diagnostic if the function is __attribute__((used)), since 9911 // that forces an external definition to be emitted. 9912 if (D.getDeclSpec().isInlineSpecified() && 9913 NewFD->isReplaceableGlobalAllocationFunction() && 9914 !NewFD->hasAttr<UsedAttr>()) 9915 Diag(D.getDeclSpec().getInlineSpecLoc(), 9916 diag::ext_operator_new_delete_declared_inline) 9917 << NewFD->getDeclName(); 9918 9919 // If the declarator is a template-id, translate the parser's template 9920 // argument list into our AST format. 9921 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9922 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9923 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9924 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9925 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9926 TemplateId->NumArgs); 9927 translateTemplateArguments(TemplateArgsPtr, 9928 TemplateArgs); 9929 9930 HasExplicitTemplateArgs = true; 9931 9932 if (NewFD->isInvalidDecl()) { 9933 HasExplicitTemplateArgs = false; 9934 } else if (FunctionTemplate) { 9935 // Function template with explicit template arguments. 9936 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9937 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9938 9939 HasExplicitTemplateArgs = false; 9940 } else { 9941 assert((isFunctionTemplateSpecialization || 9942 D.getDeclSpec().isFriendSpecified()) && 9943 "should have a 'template<>' for this decl"); 9944 // "friend void foo<>(int);" is an implicit specialization decl. 9945 isFunctionTemplateSpecialization = true; 9946 } 9947 } else if (isFriend && isFunctionTemplateSpecialization) { 9948 // This combination is only possible in a recovery case; the user 9949 // wrote something like: 9950 // template <> friend void foo(int); 9951 // which we're recovering from as if the user had written: 9952 // friend void foo<>(int); 9953 // Go ahead and fake up a template id. 9954 HasExplicitTemplateArgs = true; 9955 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9956 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9957 } 9958 9959 // We do not add HD attributes to specializations here because 9960 // they may have different constexpr-ness compared to their 9961 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9962 // may end up with different effective targets. Instead, a 9963 // specialization inherits its target attributes from its template 9964 // in the CheckFunctionTemplateSpecialization() call below. 9965 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9966 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9967 9968 // If it's a friend (and only if it's a friend), it's possible 9969 // that either the specialized function type or the specialized 9970 // template is dependent, and therefore matching will fail. In 9971 // this case, don't check the specialization yet. 9972 if (isFunctionTemplateSpecialization && isFriend && 9973 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9974 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9975 TemplateArgs.arguments()))) { 9976 assert(HasExplicitTemplateArgs && 9977 "friend function specialization without template args"); 9978 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9979 Previous)) 9980 NewFD->setInvalidDecl(); 9981 } else if (isFunctionTemplateSpecialization) { 9982 if (CurContext->isDependentContext() && CurContext->isRecord() 9983 && !isFriend) { 9984 isDependentClassScopeExplicitSpecialization = true; 9985 } else if (!NewFD->isInvalidDecl() && 9986 CheckFunctionTemplateSpecialization( 9987 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9988 Previous)) 9989 NewFD->setInvalidDecl(); 9990 9991 // C++ [dcl.stc]p1: 9992 // A storage-class-specifier shall not be specified in an explicit 9993 // specialization (14.7.3) 9994 FunctionTemplateSpecializationInfo *Info = 9995 NewFD->getTemplateSpecializationInfo(); 9996 if (Info && SC != SC_None) { 9997 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9998 Diag(NewFD->getLocation(), 9999 diag::err_explicit_specialization_inconsistent_storage_class) 10000 << SC 10001 << FixItHint::CreateRemoval( 10002 D.getDeclSpec().getStorageClassSpecLoc()); 10003 10004 else 10005 Diag(NewFD->getLocation(), 10006 diag::ext_explicit_specialization_storage_class) 10007 << FixItHint::CreateRemoval( 10008 D.getDeclSpec().getStorageClassSpecLoc()); 10009 } 10010 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 10011 if (CheckMemberSpecialization(NewFD, Previous)) 10012 NewFD->setInvalidDecl(); 10013 } 10014 10015 // Perform semantic checking on the function declaration. 10016 if (!isDependentClassScopeExplicitSpecialization) { 10017 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10018 CheckMain(NewFD, D.getDeclSpec()); 10019 10020 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10021 CheckMSVCRTEntryPoint(NewFD); 10022 10023 if (!NewFD->isInvalidDecl()) 10024 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10025 isMemberSpecialization, 10026 D.isFunctionDefinition())); 10027 else if (!Previous.empty()) 10028 // Recover gracefully from an invalid redeclaration. 10029 D.setRedeclaration(true); 10030 } 10031 10032 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 10033 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10034 "previous declaration set still overloaded"); 10035 10036 NamedDecl *PrincipalDecl = (FunctionTemplate 10037 ? cast<NamedDecl>(FunctionTemplate) 10038 : NewFD); 10039 10040 if (isFriend && NewFD->getPreviousDecl()) { 10041 AccessSpecifier Access = AS_public; 10042 if (!NewFD->isInvalidDecl()) 10043 Access = NewFD->getPreviousDecl()->getAccess(); 10044 10045 NewFD->setAccess(Access); 10046 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 10047 } 10048 10049 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 10050 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 10051 PrincipalDecl->setNonMemberOperator(); 10052 10053 // If we have a function template, check the template parameter 10054 // list. This will check and merge default template arguments. 10055 if (FunctionTemplate) { 10056 FunctionTemplateDecl *PrevTemplate = 10057 FunctionTemplate->getPreviousDecl(); 10058 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 10059 PrevTemplate ? PrevTemplate->getTemplateParameters() 10060 : nullptr, 10061 D.getDeclSpec().isFriendSpecified() 10062 ? (D.isFunctionDefinition() 10063 ? TPC_FriendFunctionTemplateDefinition 10064 : TPC_FriendFunctionTemplate) 10065 : (D.getCXXScopeSpec().isSet() && 10066 DC && DC->isRecord() && 10067 DC->isDependentContext()) 10068 ? TPC_ClassTemplateMember 10069 : TPC_FunctionTemplate); 10070 } 10071 10072 if (NewFD->isInvalidDecl()) { 10073 // Ignore all the rest of this. 10074 } else if (!D.isRedeclaration()) { 10075 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 10076 AddToScope }; 10077 // Fake up an access specifier if it's supposed to be a class member. 10078 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 10079 NewFD->setAccess(AS_public); 10080 10081 // Qualified decls generally require a previous declaration. 10082 if (D.getCXXScopeSpec().isSet()) { 10083 // ...with the major exception of templated-scope or 10084 // dependent-scope friend declarations. 10085 10086 // TODO: we currently also suppress this check in dependent 10087 // contexts because (1) the parameter depth will be off when 10088 // matching friend templates and (2) we might actually be 10089 // selecting a friend based on a dependent factor. But there 10090 // are situations where these conditions don't apply and we 10091 // can actually do this check immediately. 10092 // 10093 // Unless the scope is dependent, it's always an error if qualified 10094 // redeclaration lookup found nothing at all. Diagnose that now; 10095 // nothing will diagnose that error later. 10096 if (isFriend && 10097 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 10098 (!Previous.empty() && CurContext->isDependentContext()))) { 10099 // ignore these 10100 } else if (NewFD->isCPUDispatchMultiVersion() || 10101 NewFD->isCPUSpecificMultiVersion()) { 10102 // ignore this, we allow the redeclaration behavior here to create new 10103 // versions of the function. 10104 } else { 10105 // The user tried to provide an out-of-line definition for a 10106 // function that is a member of a class or namespace, but there 10107 // was no such member function declared (C++ [class.mfct]p2, 10108 // C++ [namespace.memdef]p2). For example: 10109 // 10110 // class X { 10111 // void f() const; 10112 // }; 10113 // 10114 // void X::f() { } // ill-formed 10115 // 10116 // Complain about this problem, and attempt to suggest close 10117 // matches (e.g., those that differ only in cv-qualifiers and 10118 // whether the parameter types are references). 10119 10120 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10121 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 10122 AddToScope = ExtraArgs.AddToScope; 10123 return Result; 10124 } 10125 } 10126 10127 // Unqualified local friend declarations are required to resolve 10128 // to something. 10129 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 10130 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10131 *this, Previous, NewFD, ExtraArgs, true, S)) { 10132 AddToScope = ExtraArgs.AddToScope; 10133 return Result; 10134 } 10135 } 10136 } else if (!D.isFunctionDefinition() && 10137 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 10138 !isFriend && !isFunctionTemplateSpecialization && 10139 !isMemberSpecialization) { 10140 // An out-of-line member function declaration must also be a 10141 // definition (C++ [class.mfct]p2). 10142 // Note that this is not the case for explicit specializations of 10143 // function templates or member functions of class templates, per 10144 // C++ [temp.expl.spec]p2. We also allow these declarations as an 10145 // extension for compatibility with old SWIG code which likes to 10146 // generate them. 10147 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 10148 << D.getCXXScopeSpec().getRange(); 10149 } 10150 } 10151 10152 // If this is the first declaration of a library builtin function, add 10153 // attributes as appropriate. 10154 if (!D.isRedeclaration()) { 10155 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 10156 if (unsigned BuiltinID = II->getBuiltinID()) { 10157 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID); 10158 if (!InStdNamespace && 10159 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 10160 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 10161 // Validate the type matches unless this builtin is specified as 10162 // matching regardless of its declared type. 10163 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 10164 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10165 } else { 10166 ASTContext::GetBuiltinTypeError Error; 10167 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10168 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 10169 10170 if (!Error && !BuiltinType.isNull() && 10171 Context.hasSameFunctionTypeIgnoringExceptionSpec( 10172 NewFD->getType(), BuiltinType)) 10173 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10174 } 10175 } 10176 } else if (InStdNamespace && NewFD->isInStdNamespace() && 10177 isStdBuiltin(Context, NewFD, BuiltinID)) { 10178 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10179 } 10180 } 10181 } 10182 } 10183 10184 ProcessPragmaWeak(S, NewFD); 10185 checkAttributesAfterMerging(*this, *NewFD); 10186 10187 AddKnownFunctionAttributes(NewFD); 10188 10189 if (NewFD->hasAttr<OverloadableAttr>() && 10190 !NewFD->getType()->getAs<FunctionProtoType>()) { 10191 Diag(NewFD->getLocation(), 10192 diag::err_attribute_overloadable_no_prototype) 10193 << NewFD; 10194 10195 // Turn this into a variadic function with no parameters. 10196 const auto *FT = NewFD->getType()->castAs<FunctionType>(); 10197 FunctionProtoType::ExtProtoInfo EPI( 10198 Context.getDefaultCallingConvention(true, false)); 10199 EPI.Variadic = true; 10200 EPI.ExtInfo = FT->getExtInfo(); 10201 10202 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 10203 NewFD->setType(R); 10204 } 10205 10206 // If there's a #pragma GCC visibility in scope, and this isn't a class 10207 // member, set the visibility of this function. 10208 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10209 AddPushedVisibilityAttribute(NewFD); 10210 10211 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10212 // marking the function. 10213 AddCFAuditedAttribute(NewFD); 10214 10215 // If this is a function definition, check if we have to apply optnone due to 10216 // a pragma. 10217 if(D.isFunctionDefinition()) 10218 AddRangeBasedOptnone(NewFD); 10219 10220 // If this is the first declaration of an extern C variable, update 10221 // the map of such variables. 10222 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10223 isIncompleteDeclExternC(*this, NewFD)) 10224 RegisterLocallyScopedExternCDecl(NewFD, S); 10225 10226 // Set this FunctionDecl's range up to the right paren. 10227 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10228 10229 if (D.isRedeclaration() && !Previous.empty()) { 10230 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10231 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10232 isMemberSpecialization || 10233 isFunctionTemplateSpecialization, 10234 D.isFunctionDefinition()); 10235 } 10236 10237 if (getLangOpts().CUDA) { 10238 IdentifierInfo *II = NewFD->getIdentifier(); 10239 if (II && II->isStr(getCudaConfigureFuncName()) && 10240 !NewFD->isInvalidDecl() && 10241 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10242 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10243 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10244 << getCudaConfigureFuncName(); 10245 Context.setcudaConfigureCallDecl(NewFD); 10246 } 10247 10248 // Variadic functions, other than a *declaration* of printf, are not allowed 10249 // in device-side CUDA code, unless someone passed 10250 // -fcuda-allow-variadic-functions. 10251 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10252 (NewFD->hasAttr<CUDADeviceAttr>() || 10253 NewFD->hasAttr<CUDAGlobalAttr>()) && 10254 !(II && II->isStr("printf") && NewFD->isExternC() && 10255 !D.isFunctionDefinition())) { 10256 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10257 } 10258 } 10259 10260 MarkUnusedFileScopedDecl(NewFD); 10261 10262 10263 10264 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10265 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10266 if (SC == SC_Static) { 10267 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10268 D.setInvalidType(); 10269 } 10270 10271 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10272 if (!NewFD->getReturnType()->isVoidType()) { 10273 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10274 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10275 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10276 : FixItHint()); 10277 D.setInvalidType(); 10278 } 10279 10280 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10281 for (auto Param : NewFD->parameters()) 10282 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10283 10284 if (getLangOpts().OpenCLCPlusPlus) { 10285 if (DC->isRecord()) { 10286 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10287 D.setInvalidType(); 10288 } 10289 if (FunctionTemplate) { 10290 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10291 D.setInvalidType(); 10292 } 10293 } 10294 } 10295 10296 if (getLangOpts().CPlusPlus) { 10297 if (FunctionTemplate) { 10298 if (NewFD->isInvalidDecl()) 10299 FunctionTemplate->setInvalidDecl(); 10300 return FunctionTemplate; 10301 } 10302 10303 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10304 CompleteMemberSpecialization(NewFD, Previous); 10305 } 10306 10307 for (const ParmVarDecl *Param : NewFD->parameters()) { 10308 QualType PT = Param->getType(); 10309 10310 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10311 // types. 10312 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10313 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10314 QualType ElemTy = PipeTy->getElementType(); 10315 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10316 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10317 D.setInvalidType(); 10318 } 10319 } 10320 } 10321 } 10322 10323 // Here we have an function template explicit specialization at class scope. 10324 // The actual specialization will be postponed to template instatiation 10325 // time via the ClassScopeFunctionSpecializationDecl node. 10326 if (isDependentClassScopeExplicitSpecialization) { 10327 ClassScopeFunctionSpecializationDecl *NewSpec = 10328 ClassScopeFunctionSpecializationDecl::Create( 10329 Context, CurContext, NewFD->getLocation(), 10330 cast<CXXMethodDecl>(NewFD), 10331 HasExplicitTemplateArgs, TemplateArgs); 10332 CurContext->addDecl(NewSpec); 10333 AddToScope = false; 10334 } 10335 10336 // Diagnose availability attributes. Availability cannot be used on functions 10337 // that are run during load/unload. 10338 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10339 if (NewFD->hasAttr<ConstructorAttr>()) { 10340 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10341 << 1; 10342 NewFD->dropAttr<AvailabilityAttr>(); 10343 } 10344 if (NewFD->hasAttr<DestructorAttr>()) { 10345 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10346 << 2; 10347 NewFD->dropAttr<AvailabilityAttr>(); 10348 } 10349 } 10350 10351 // Diagnose no_builtin attribute on function declaration that are not a 10352 // definition. 10353 // FIXME: We should really be doing this in 10354 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10355 // the FunctionDecl and at this point of the code 10356 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10357 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10358 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10359 switch (D.getFunctionDefinitionKind()) { 10360 case FunctionDefinitionKind::Defaulted: 10361 case FunctionDefinitionKind::Deleted: 10362 Diag(NBA->getLocation(), 10363 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10364 << NBA->getSpelling(); 10365 break; 10366 case FunctionDefinitionKind::Declaration: 10367 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10368 << NBA->getSpelling(); 10369 break; 10370 case FunctionDefinitionKind::Definition: 10371 break; 10372 } 10373 10374 return NewFD; 10375 } 10376 10377 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10378 /// when __declspec(code_seg) "is applied to a class, all member functions of 10379 /// the class and nested classes -- this includes compiler-generated special 10380 /// member functions -- are put in the specified segment." 10381 /// The actual behavior is a little more complicated. The Microsoft compiler 10382 /// won't check outer classes if there is an active value from #pragma code_seg. 10383 /// The CodeSeg is always applied from the direct parent but only from outer 10384 /// classes when the #pragma code_seg stack is empty. See: 10385 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10386 /// available since MS has removed the page. 10387 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10388 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10389 if (!Method) 10390 return nullptr; 10391 const CXXRecordDecl *Parent = Method->getParent(); 10392 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10393 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10394 NewAttr->setImplicit(true); 10395 return NewAttr; 10396 } 10397 10398 // The Microsoft compiler won't check outer classes for the CodeSeg 10399 // when the #pragma code_seg stack is active. 10400 if (S.CodeSegStack.CurrentValue) 10401 return nullptr; 10402 10403 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10404 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10405 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10406 NewAttr->setImplicit(true); 10407 return NewAttr; 10408 } 10409 } 10410 return nullptr; 10411 } 10412 10413 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10414 /// containing class. Otherwise it will return implicit SectionAttr if the 10415 /// function is a definition and there is an active value on CodeSegStack 10416 /// (from the current #pragma code-seg value). 10417 /// 10418 /// \param FD Function being declared. 10419 /// \param IsDefinition Whether it is a definition or just a declarartion. 10420 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10421 /// nullptr if no attribute should be added. 10422 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10423 bool IsDefinition) { 10424 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10425 return A; 10426 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10427 CodeSegStack.CurrentValue) 10428 return SectionAttr::CreateImplicit( 10429 getASTContext(), CodeSegStack.CurrentValue->getString(), 10430 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10431 SectionAttr::Declspec_allocate); 10432 return nullptr; 10433 } 10434 10435 /// Determines if we can perform a correct type check for \p D as a 10436 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10437 /// best-effort check. 10438 /// 10439 /// \param NewD The new declaration. 10440 /// \param OldD The old declaration. 10441 /// \param NewT The portion of the type of the new declaration to check. 10442 /// \param OldT The portion of the type of the old declaration to check. 10443 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10444 QualType NewT, QualType OldT) { 10445 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10446 return true; 10447 10448 // For dependently-typed local extern declarations and friends, we can't 10449 // perform a correct type check in general until instantiation: 10450 // 10451 // int f(); 10452 // template<typename T> void g() { T f(); } 10453 // 10454 // (valid if g() is only instantiated with T = int). 10455 if (NewT->isDependentType() && 10456 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10457 return false; 10458 10459 // Similarly, if the previous declaration was a dependent local extern 10460 // declaration, we don't really know its type yet. 10461 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10462 return false; 10463 10464 return true; 10465 } 10466 10467 /// Checks if the new declaration declared in dependent context must be 10468 /// put in the same redeclaration chain as the specified declaration. 10469 /// 10470 /// \param D Declaration that is checked. 10471 /// \param PrevDecl Previous declaration found with proper lookup method for the 10472 /// same declaration name. 10473 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10474 /// belongs to. 10475 /// 10476 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10477 if (!D->getLexicalDeclContext()->isDependentContext()) 10478 return true; 10479 10480 // Don't chain dependent friend function definitions until instantiation, to 10481 // permit cases like 10482 // 10483 // void func(); 10484 // template<typename T> class C1 { friend void func() {} }; 10485 // template<typename T> class C2 { friend void func() {} }; 10486 // 10487 // ... which is valid if only one of C1 and C2 is ever instantiated. 10488 // 10489 // FIXME: This need only apply to function definitions. For now, we proxy 10490 // this by checking for a file-scope function. We do not want this to apply 10491 // to friend declarations nominating member functions, because that gets in 10492 // the way of access checks. 10493 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10494 return false; 10495 10496 auto *VD = dyn_cast<ValueDecl>(D); 10497 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10498 return !VD || !PrevVD || 10499 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10500 PrevVD->getType()); 10501 } 10502 10503 /// Check the target attribute of the function for MultiVersion 10504 /// validity. 10505 /// 10506 /// Returns true if there was an error, false otherwise. 10507 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10508 const auto *TA = FD->getAttr<TargetAttr>(); 10509 assert(TA && "MultiVersion Candidate requires a target attribute"); 10510 ParsedTargetAttr ParseInfo = TA->parse(); 10511 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10512 enum ErrType { Feature = 0, Architecture = 1 }; 10513 10514 if (!ParseInfo.Architecture.empty() && 10515 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10516 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10517 << Architecture << ParseInfo.Architecture; 10518 return true; 10519 } 10520 10521 for (const auto &Feat : ParseInfo.Features) { 10522 auto BareFeat = StringRef{Feat}.substr(1); 10523 if (Feat[0] == '-') { 10524 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10525 << Feature << ("no-" + BareFeat).str(); 10526 return true; 10527 } 10528 10529 if (!TargetInfo.validateCpuSupports(BareFeat) || 10530 !TargetInfo.isValidFeatureName(BareFeat)) { 10531 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10532 << Feature << BareFeat; 10533 return true; 10534 } 10535 } 10536 return false; 10537 } 10538 10539 // Provide a white-list of attributes that are allowed to be combined with 10540 // multiversion functions. 10541 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10542 MultiVersionKind MVKind) { 10543 // Note: this list/diagnosis must match the list in 10544 // checkMultiversionAttributesAllSame. 10545 switch (Kind) { 10546 default: 10547 return false; 10548 case attr::Used: 10549 return MVKind == MultiVersionKind::Target; 10550 case attr::NonNull: 10551 case attr::NoThrow: 10552 return true; 10553 } 10554 } 10555 10556 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10557 const FunctionDecl *FD, 10558 const FunctionDecl *CausedFD, 10559 MultiVersionKind MVKind) { 10560 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 10561 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10562 << static_cast<unsigned>(MVKind) << A; 10563 if (CausedFD) 10564 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10565 return true; 10566 }; 10567 10568 for (const Attr *A : FD->attrs()) { 10569 switch (A->getKind()) { 10570 case attr::CPUDispatch: 10571 case attr::CPUSpecific: 10572 if (MVKind != MultiVersionKind::CPUDispatch && 10573 MVKind != MultiVersionKind::CPUSpecific) 10574 return Diagnose(S, A); 10575 break; 10576 case attr::Target: 10577 if (MVKind != MultiVersionKind::Target) 10578 return Diagnose(S, A); 10579 break; 10580 case attr::TargetClones: 10581 if (MVKind != MultiVersionKind::TargetClones) 10582 return Diagnose(S, A); 10583 break; 10584 default: 10585 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 10586 return Diagnose(S, A); 10587 break; 10588 } 10589 } 10590 return false; 10591 } 10592 10593 bool Sema::areMultiversionVariantFunctionsCompatible( 10594 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10595 const PartialDiagnostic &NoProtoDiagID, 10596 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10597 const PartialDiagnosticAt &NoSupportDiagIDAt, 10598 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10599 bool ConstexprSupported, bool CLinkageMayDiffer) { 10600 enum DoesntSupport { 10601 FuncTemplates = 0, 10602 VirtFuncs = 1, 10603 DeducedReturn = 2, 10604 Constructors = 3, 10605 Destructors = 4, 10606 DeletedFuncs = 5, 10607 DefaultedFuncs = 6, 10608 ConstexprFuncs = 7, 10609 ConstevalFuncs = 8, 10610 Lambda = 9, 10611 }; 10612 enum Different { 10613 CallingConv = 0, 10614 ReturnType = 1, 10615 ConstexprSpec = 2, 10616 InlineSpec = 3, 10617 Linkage = 4, 10618 LanguageLinkage = 5, 10619 }; 10620 10621 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10622 !OldFD->getType()->getAs<FunctionProtoType>()) { 10623 Diag(OldFD->getLocation(), NoProtoDiagID); 10624 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10625 return true; 10626 } 10627 10628 if (NoProtoDiagID.getDiagID() != 0 && 10629 !NewFD->getType()->getAs<FunctionProtoType>()) 10630 return Diag(NewFD->getLocation(), NoProtoDiagID); 10631 10632 if (!TemplatesSupported && 10633 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10634 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10635 << FuncTemplates; 10636 10637 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10638 if (NewCXXFD->isVirtual()) 10639 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10640 << VirtFuncs; 10641 10642 if (isa<CXXConstructorDecl>(NewCXXFD)) 10643 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10644 << Constructors; 10645 10646 if (isa<CXXDestructorDecl>(NewCXXFD)) 10647 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10648 << Destructors; 10649 } 10650 10651 if (NewFD->isDeleted()) 10652 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10653 << DeletedFuncs; 10654 10655 if (NewFD->isDefaulted()) 10656 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10657 << DefaultedFuncs; 10658 10659 if (!ConstexprSupported && NewFD->isConstexpr()) 10660 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10661 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10662 10663 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10664 const auto *NewType = cast<FunctionType>(NewQType); 10665 QualType NewReturnType = NewType->getReturnType(); 10666 10667 if (NewReturnType->isUndeducedType()) 10668 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10669 << DeducedReturn; 10670 10671 // Ensure the return type is identical. 10672 if (OldFD) { 10673 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10674 const auto *OldType = cast<FunctionType>(OldQType); 10675 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10676 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10677 10678 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10679 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10680 10681 QualType OldReturnType = OldType->getReturnType(); 10682 10683 if (OldReturnType != NewReturnType) 10684 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10685 10686 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10687 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10688 10689 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10690 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10691 10692 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10693 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10694 10695 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10696 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10697 10698 if (CheckEquivalentExceptionSpec( 10699 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10700 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10701 return true; 10702 } 10703 return false; 10704 } 10705 10706 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10707 const FunctionDecl *NewFD, 10708 bool CausesMV, 10709 MultiVersionKind MVKind) { 10710 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10711 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10712 if (OldFD) 10713 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10714 return true; 10715 } 10716 10717 bool IsCPUSpecificCPUDispatchMVKind = 10718 MVKind == MultiVersionKind::CPUDispatch || 10719 MVKind == MultiVersionKind::CPUSpecific; 10720 10721 if (CausesMV && OldFD && 10722 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 10723 return true; 10724 10725 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 10726 return true; 10727 10728 // Only allow transition to MultiVersion if it hasn't been used. 10729 if (OldFD && CausesMV && OldFD->isUsed(false)) 10730 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10731 10732 return S.areMultiversionVariantFunctionsCompatible( 10733 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10734 PartialDiagnosticAt(NewFD->getLocation(), 10735 S.PDiag(diag::note_multiversioning_caused_here)), 10736 PartialDiagnosticAt(NewFD->getLocation(), 10737 S.PDiag(diag::err_multiversion_doesnt_support) 10738 << static_cast<unsigned>(MVKind)), 10739 PartialDiagnosticAt(NewFD->getLocation(), 10740 S.PDiag(diag::err_multiversion_diff)), 10741 /*TemplatesSupported=*/false, 10742 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 10743 /*CLinkageMayDiffer=*/false); 10744 } 10745 10746 /// Check the validity of a multiversion function declaration that is the 10747 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10748 /// 10749 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10750 /// 10751 /// Returns true if there was an error, false otherwise. 10752 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10753 MultiVersionKind MVKind, 10754 const TargetAttr *TA) { 10755 assert(MVKind != MultiVersionKind::None && 10756 "Function lacks multiversion attribute"); 10757 10758 // Target only causes MV if it is default, otherwise this is a normal 10759 // function. 10760 if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion()) 10761 return false; 10762 10763 if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10764 FD->setInvalidDecl(); 10765 return true; 10766 } 10767 10768 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 10769 FD->setInvalidDecl(); 10770 return true; 10771 } 10772 10773 FD->setIsMultiVersion(); 10774 return false; 10775 } 10776 10777 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10778 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10779 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10780 return true; 10781 } 10782 10783 return false; 10784 } 10785 10786 static bool CheckTargetCausesMultiVersioning( 10787 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10788 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { 10789 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10790 ParsedTargetAttr NewParsed = NewTA->parse(); 10791 // Sort order doesn't matter, it just needs to be consistent. 10792 llvm::sort(NewParsed.Features); 10793 10794 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10795 // to change, this is a simple redeclaration. 10796 if (!NewTA->isDefaultVersion() && 10797 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10798 return false; 10799 10800 // Otherwise, this decl causes MultiVersioning. 10801 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10802 MultiVersionKind::Target)) { 10803 NewFD->setInvalidDecl(); 10804 return true; 10805 } 10806 10807 if (CheckMultiVersionValue(S, NewFD)) { 10808 NewFD->setInvalidDecl(); 10809 return true; 10810 } 10811 10812 // If this is 'default', permit the forward declaration. 10813 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10814 Redeclaration = true; 10815 OldDecl = OldFD; 10816 OldFD->setIsMultiVersion(); 10817 NewFD->setIsMultiVersion(); 10818 return false; 10819 } 10820 10821 if (CheckMultiVersionValue(S, OldFD)) { 10822 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10823 NewFD->setInvalidDecl(); 10824 return true; 10825 } 10826 10827 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10828 10829 if (OldParsed == NewParsed) { 10830 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10831 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10832 NewFD->setInvalidDecl(); 10833 return true; 10834 } 10835 10836 for (const auto *FD : OldFD->redecls()) { 10837 const auto *CurTA = FD->getAttr<TargetAttr>(); 10838 // We allow forward declarations before ANY multiversioning attributes, but 10839 // nothing after the fact. 10840 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10841 (!CurTA || CurTA->isInherited())) { 10842 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10843 << 0; 10844 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10845 NewFD->setInvalidDecl(); 10846 return true; 10847 } 10848 } 10849 10850 OldFD->setIsMultiVersion(); 10851 NewFD->setIsMultiVersion(); 10852 Redeclaration = false; 10853 OldDecl = nullptr; 10854 Previous.clear(); 10855 return false; 10856 } 10857 10858 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 10859 MultiVersionKind New) { 10860 if (Old == New || Old == MultiVersionKind::None || 10861 New == MultiVersionKind::None) 10862 return true; 10863 10864 return (Old == MultiVersionKind::CPUDispatch && 10865 New == MultiVersionKind::CPUSpecific) || 10866 (Old == MultiVersionKind::CPUSpecific && 10867 New == MultiVersionKind::CPUDispatch); 10868 } 10869 10870 /// Check the validity of a new function declaration being added to an existing 10871 /// multiversioned declaration collection. 10872 static bool CheckMultiVersionAdditionalDecl( 10873 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10874 MultiVersionKind NewMVKind, const TargetAttr *NewTA, 10875 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10876 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 10877 LookupResult &Previous) { 10878 10879 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 10880 // Disallow mixing of multiversioning types. 10881 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { 10882 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10883 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10884 NewFD->setInvalidDecl(); 10885 return true; 10886 } 10887 10888 ParsedTargetAttr NewParsed; 10889 if (NewTA) { 10890 NewParsed = NewTA->parse(); 10891 llvm::sort(NewParsed.Features); 10892 } 10893 10894 bool UseMemberUsingDeclRules = 10895 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10896 10897 bool MayNeedOverloadableChecks = 10898 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 10899 10900 // Next, check ALL non-overloads to see if this is a redeclaration of a 10901 // previous member of the MultiVersion set. 10902 for (NamedDecl *ND : Previous) { 10903 FunctionDecl *CurFD = ND->getAsFunction(); 10904 if (!CurFD) 10905 continue; 10906 if (MayNeedOverloadableChecks && 10907 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10908 continue; 10909 10910 switch (NewMVKind) { 10911 case MultiVersionKind::None: 10912 assert(OldMVKind == MultiVersionKind::TargetClones && 10913 "Only target_clones can be omitted in subsequent declarations"); 10914 break; 10915 case MultiVersionKind::Target: { 10916 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10917 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10918 NewFD->setIsMultiVersion(); 10919 Redeclaration = true; 10920 OldDecl = ND; 10921 return false; 10922 } 10923 10924 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10925 if (CurParsed == NewParsed) { 10926 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10927 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10928 NewFD->setInvalidDecl(); 10929 return true; 10930 } 10931 break; 10932 } 10933 case MultiVersionKind::TargetClones: { 10934 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 10935 Redeclaration = true; 10936 OldDecl = CurFD; 10937 NewFD->setIsMultiVersion(); 10938 10939 if (CurClones && NewClones && 10940 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 10941 !std::equal(CurClones->featuresStrs_begin(), 10942 CurClones->featuresStrs_end(), 10943 NewClones->featuresStrs_begin()))) { 10944 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 10945 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10946 NewFD->setInvalidDecl(); 10947 return true; 10948 } 10949 10950 return false; 10951 } 10952 case MultiVersionKind::CPUSpecific: 10953 case MultiVersionKind::CPUDispatch: { 10954 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10955 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10956 // Handle CPUDispatch/CPUSpecific versions. 10957 // Only 1 CPUDispatch function is allowed, this will make it go through 10958 // the redeclaration errors. 10959 if (NewMVKind == MultiVersionKind::CPUDispatch && 10960 CurFD->hasAttr<CPUDispatchAttr>()) { 10961 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10962 std::equal( 10963 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10964 NewCPUDisp->cpus_begin(), 10965 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10966 return Cur->getName() == New->getName(); 10967 })) { 10968 NewFD->setIsMultiVersion(); 10969 Redeclaration = true; 10970 OldDecl = ND; 10971 return false; 10972 } 10973 10974 // If the declarations don't match, this is an error condition. 10975 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10976 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10977 NewFD->setInvalidDecl(); 10978 return true; 10979 } 10980 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10981 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10982 std::equal( 10983 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10984 NewCPUSpec->cpus_begin(), 10985 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10986 return Cur->getName() == New->getName(); 10987 })) { 10988 NewFD->setIsMultiVersion(); 10989 Redeclaration = true; 10990 OldDecl = ND; 10991 return false; 10992 } 10993 10994 // Only 1 version of CPUSpecific is allowed for each CPU. 10995 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10996 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10997 if (CurII == NewII) { 10998 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10999 << NewII; 11000 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11001 NewFD->setInvalidDecl(); 11002 return true; 11003 } 11004 } 11005 } 11006 } 11007 break; 11008 } 11009 } 11010 } 11011 11012 // Else, this is simply a non-redecl case. Checking the 'value' is only 11013 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 11014 // handled in the attribute adding step. 11015 if (NewMVKind == MultiVersionKind::Target && 11016 CheckMultiVersionValue(S, NewFD)) { 11017 NewFD->setInvalidDecl(); 11018 return true; 11019 } 11020 11021 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 11022 !OldFD->isMultiVersion(), NewMVKind)) { 11023 NewFD->setInvalidDecl(); 11024 return true; 11025 } 11026 11027 // Permit forward declarations in the case where these two are compatible. 11028 if (!OldFD->isMultiVersion()) { 11029 OldFD->setIsMultiVersion(); 11030 NewFD->setIsMultiVersion(); 11031 Redeclaration = true; 11032 OldDecl = OldFD; 11033 return false; 11034 } 11035 11036 NewFD->setIsMultiVersion(); 11037 Redeclaration = false; 11038 OldDecl = nullptr; 11039 Previous.clear(); 11040 return false; 11041 } 11042 11043 /// Check the validity of a mulitversion function declaration. 11044 /// Also sets the multiversion'ness' of the function itself. 11045 /// 11046 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11047 /// 11048 /// Returns true if there was an error, false otherwise. 11049 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 11050 bool &Redeclaration, NamedDecl *&OldDecl, 11051 LookupResult &Previous) { 11052 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11053 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 11054 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 11055 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 11056 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 11057 11058 // Main isn't allowed to become a multiversion function, however it IS 11059 // permitted to have 'main' be marked with the 'target' optimization hint. 11060 if (NewFD->isMain()) { 11061 if (MVKind != MultiVersionKind::None && 11062 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { 11063 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 11064 NewFD->setInvalidDecl(); 11065 return true; 11066 } 11067 return false; 11068 } 11069 11070 if (!OldDecl || !OldDecl->getAsFunction() || 11071 OldDecl->getDeclContext()->getRedeclContext() != 11072 NewFD->getDeclContext()->getRedeclContext()) { 11073 // If there's no previous declaration, AND this isn't attempting to cause 11074 // multiversioning, this isn't an error condition. 11075 if (MVKind == MultiVersionKind::None) 11076 return false; 11077 return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA); 11078 } 11079 11080 FunctionDecl *OldFD = OldDecl->getAsFunction(); 11081 11082 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) 11083 return false; 11084 11085 // Multiversioned redeclarations aren't allowed to omit the attribute, except 11086 // for target_clones. 11087 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 11088 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { 11089 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 11090 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 11091 NewFD->setInvalidDecl(); 11092 return true; 11093 } 11094 11095 if (!OldFD->isMultiVersion()) { 11096 switch (MVKind) { 11097 case MultiVersionKind::Target: 11098 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 11099 Redeclaration, OldDecl, Previous); 11100 case MultiVersionKind::TargetClones: 11101 if (OldFD->isUsed(false)) { 11102 NewFD->setInvalidDecl(); 11103 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11104 } 11105 OldFD->setIsMultiVersion(); 11106 break; 11107 case MultiVersionKind::CPUDispatch: 11108 case MultiVersionKind::CPUSpecific: 11109 case MultiVersionKind::None: 11110 break; 11111 } 11112 } 11113 11114 // At this point, we have a multiversion function decl (in OldFD) AND an 11115 // appropriate attribute in the current function decl. Resolve that these are 11116 // still compatible with previous declarations. 11117 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA, 11118 NewCPUDisp, NewCPUSpec, NewClones, 11119 Redeclaration, OldDecl, Previous); 11120 } 11121 11122 /// Perform semantic checking of a new function declaration. 11123 /// 11124 /// Performs semantic analysis of the new function declaration 11125 /// NewFD. This routine performs all semantic checking that does not 11126 /// require the actual declarator involved in the declaration, and is 11127 /// used both for the declaration of functions as they are parsed 11128 /// (called via ActOnDeclarator) and for the declaration of functions 11129 /// that have been instantiated via C++ template instantiation (called 11130 /// via InstantiateDecl). 11131 /// 11132 /// \param IsMemberSpecialization whether this new function declaration is 11133 /// a member specialization (that replaces any definition provided by the 11134 /// previous declaration). 11135 /// 11136 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11137 /// 11138 /// \returns true if the function declaration is a redeclaration. 11139 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 11140 LookupResult &Previous, 11141 bool IsMemberSpecialization, 11142 bool DeclIsDefn) { 11143 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 11144 "Variably modified return types are not handled here"); 11145 11146 // Determine whether the type of this function should be merged with 11147 // a previous visible declaration. This never happens for functions in C++, 11148 // and always happens in C if the previous declaration was visible. 11149 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 11150 !Previous.isShadowed(); 11151 11152 bool Redeclaration = false; 11153 NamedDecl *OldDecl = nullptr; 11154 bool MayNeedOverloadableChecks = false; 11155 11156 // Merge or overload the declaration with an existing declaration of 11157 // the same name, if appropriate. 11158 if (!Previous.empty()) { 11159 // Determine whether NewFD is an overload of PrevDecl or 11160 // a declaration that requires merging. If it's an overload, 11161 // there's no more work to do here; we'll just add the new 11162 // function to the scope. 11163 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 11164 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 11165 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 11166 Redeclaration = true; 11167 OldDecl = Candidate; 11168 } 11169 } else { 11170 MayNeedOverloadableChecks = true; 11171 switch (CheckOverload(S, NewFD, Previous, OldDecl, 11172 /*NewIsUsingDecl*/ false)) { 11173 case Ovl_Match: 11174 Redeclaration = true; 11175 break; 11176 11177 case Ovl_NonFunction: 11178 Redeclaration = true; 11179 break; 11180 11181 case Ovl_Overload: 11182 Redeclaration = false; 11183 break; 11184 } 11185 } 11186 } 11187 11188 // Check for a previous extern "C" declaration with this name. 11189 if (!Redeclaration && 11190 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 11191 if (!Previous.empty()) { 11192 // This is an extern "C" declaration with the same name as a previous 11193 // declaration, and thus redeclares that entity... 11194 Redeclaration = true; 11195 OldDecl = Previous.getFoundDecl(); 11196 MergeTypeWithPrevious = false; 11197 11198 // ... except in the presence of __attribute__((overloadable)). 11199 if (OldDecl->hasAttr<OverloadableAttr>() || 11200 NewFD->hasAttr<OverloadableAttr>()) { 11201 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11202 MayNeedOverloadableChecks = true; 11203 Redeclaration = false; 11204 OldDecl = nullptr; 11205 } 11206 } 11207 } 11208 } 11209 11210 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 11211 return Redeclaration; 11212 11213 // PPC MMA non-pointer types are not allowed as function return types. 11214 if (Context.getTargetInfo().getTriple().isPPC64() && 11215 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11216 NewFD->setInvalidDecl(); 11217 } 11218 11219 // C++11 [dcl.constexpr]p8: 11220 // A constexpr specifier for a non-static member function that is not 11221 // a constructor declares that member function to be const. 11222 // 11223 // This needs to be delayed until we know whether this is an out-of-line 11224 // definition of a static member function. 11225 // 11226 // This rule is not present in C++1y, so we produce a backwards 11227 // compatibility warning whenever it happens in C++11. 11228 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11229 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11230 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11231 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11232 CXXMethodDecl *OldMD = nullptr; 11233 if (OldDecl) 11234 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11235 if (!OldMD || !OldMD->isStatic()) { 11236 const FunctionProtoType *FPT = 11237 MD->getType()->castAs<FunctionProtoType>(); 11238 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11239 EPI.TypeQuals.addConst(); 11240 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11241 FPT->getParamTypes(), EPI)); 11242 11243 // Warn that we did this, if we're not performing template instantiation. 11244 // In that case, we'll have warned already when the template was defined. 11245 if (!inTemplateInstantiation()) { 11246 SourceLocation AddConstLoc; 11247 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11248 .IgnoreParens().getAs<FunctionTypeLoc>()) 11249 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11250 11251 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11252 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11253 } 11254 } 11255 } 11256 11257 if (Redeclaration) { 11258 // NewFD and OldDecl represent declarations that need to be 11259 // merged. 11260 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious, 11261 DeclIsDefn)) { 11262 NewFD->setInvalidDecl(); 11263 return Redeclaration; 11264 } 11265 11266 Previous.clear(); 11267 Previous.addDecl(OldDecl); 11268 11269 if (FunctionTemplateDecl *OldTemplateDecl = 11270 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11271 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11272 FunctionTemplateDecl *NewTemplateDecl 11273 = NewFD->getDescribedFunctionTemplate(); 11274 assert(NewTemplateDecl && "Template/non-template mismatch"); 11275 11276 // The call to MergeFunctionDecl above may have created some state in 11277 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11278 // can add it as a redeclaration. 11279 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11280 11281 NewFD->setPreviousDeclaration(OldFD); 11282 if (NewFD->isCXXClassMember()) { 11283 NewFD->setAccess(OldTemplateDecl->getAccess()); 11284 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11285 } 11286 11287 // If this is an explicit specialization of a member that is a function 11288 // template, mark it as a member specialization. 11289 if (IsMemberSpecialization && 11290 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11291 NewTemplateDecl->setMemberSpecialization(); 11292 assert(OldTemplateDecl->isMemberSpecialization()); 11293 // Explicit specializations of a member template do not inherit deleted 11294 // status from the parent member template that they are specializing. 11295 if (OldFD->isDeleted()) { 11296 // FIXME: This assert will not hold in the presence of modules. 11297 assert(OldFD->getCanonicalDecl() == OldFD); 11298 // FIXME: We need an update record for this AST mutation. 11299 OldFD->setDeletedAsWritten(false); 11300 } 11301 } 11302 11303 } else { 11304 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11305 auto *OldFD = cast<FunctionDecl>(OldDecl); 11306 // This needs to happen first so that 'inline' propagates. 11307 NewFD->setPreviousDeclaration(OldFD); 11308 if (NewFD->isCXXClassMember()) 11309 NewFD->setAccess(OldFD->getAccess()); 11310 } 11311 } 11312 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11313 !NewFD->getAttr<OverloadableAttr>()) { 11314 assert((Previous.empty() || 11315 llvm::any_of(Previous, 11316 [](const NamedDecl *ND) { 11317 return ND->hasAttr<OverloadableAttr>(); 11318 })) && 11319 "Non-redecls shouldn't happen without overloadable present"); 11320 11321 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11322 const auto *FD = dyn_cast<FunctionDecl>(ND); 11323 return FD && !FD->hasAttr<OverloadableAttr>(); 11324 }); 11325 11326 if (OtherUnmarkedIter != Previous.end()) { 11327 Diag(NewFD->getLocation(), 11328 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11329 Diag((*OtherUnmarkedIter)->getLocation(), 11330 diag::note_attribute_overloadable_prev_overload) 11331 << false; 11332 11333 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11334 } 11335 } 11336 11337 if (LangOpts.OpenMP) 11338 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11339 11340 // Semantic checking for this function declaration (in isolation). 11341 11342 if (getLangOpts().CPlusPlus) { 11343 // C++-specific checks. 11344 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11345 CheckConstructor(Constructor); 11346 } else if (CXXDestructorDecl *Destructor = 11347 dyn_cast<CXXDestructorDecl>(NewFD)) { 11348 CXXRecordDecl *Record = Destructor->getParent(); 11349 QualType ClassType = Context.getTypeDeclType(Record); 11350 11351 // FIXME: Shouldn't we be able to perform this check even when the class 11352 // type is dependent? Both gcc and edg can handle that. 11353 if (!ClassType->isDependentType()) { 11354 DeclarationName Name 11355 = Context.DeclarationNames.getCXXDestructorName( 11356 Context.getCanonicalType(ClassType)); 11357 if (NewFD->getDeclName() != Name) { 11358 Diag(NewFD->getLocation(), diag::err_destructor_name); 11359 NewFD->setInvalidDecl(); 11360 return Redeclaration; 11361 } 11362 } 11363 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11364 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11365 CheckDeductionGuideTemplate(TD); 11366 11367 // A deduction guide is not on the list of entities that can be 11368 // explicitly specialized. 11369 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11370 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11371 << /*explicit specialization*/ 1; 11372 } 11373 11374 // Find any virtual functions that this function overrides. 11375 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11376 if (!Method->isFunctionTemplateSpecialization() && 11377 !Method->getDescribedFunctionTemplate() && 11378 Method->isCanonicalDecl()) { 11379 AddOverriddenMethods(Method->getParent(), Method); 11380 } 11381 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11382 // C++2a [class.virtual]p6 11383 // A virtual method shall not have a requires-clause. 11384 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11385 diag::err_constrained_virtual_method); 11386 11387 if (Method->isStatic()) 11388 checkThisInStaticMemberFunctionType(Method); 11389 } 11390 11391 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11392 ActOnConversionDeclarator(Conversion); 11393 11394 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11395 if (NewFD->isOverloadedOperator() && 11396 CheckOverloadedOperatorDeclaration(NewFD)) { 11397 NewFD->setInvalidDecl(); 11398 return Redeclaration; 11399 } 11400 11401 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11402 if (NewFD->getLiteralIdentifier() && 11403 CheckLiteralOperatorDeclaration(NewFD)) { 11404 NewFD->setInvalidDecl(); 11405 return Redeclaration; 11406 } 11407 11408 // In C++, check default arguments now that we have merged decls. Unless 11409 // the lexical context is the class, because in this case this is done 11410 // during delayed parsing anyway. 11411 if (!CurContext->isRecord()) 11412 CheckCXXDefaultArguments(NewFD); 11413 11414 // If this function is declared as being extern "C", then check to see if 11415 // the function returns a UDT (class, struct, or union type) that is not C 11416 // compatible, and if it does, warn the user. 11417 // But, issue any diagnostic on the first declaration only. 11418 if (Previous.empty() && NewFD->isExternC()) { 11419 QualType R = NewFD->getReturnType(); 11420 if (R->isIncompleteType() && !R->isVoidType()) 11421 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11422 << NewFD << R; 11423 else if (!R.isPODType(Context) && !R->isVoidType() && 11424 !R->isObjCObjectPointerType()) 11425 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11426 } 11427 11428 // C++1z [dcl.fct]p6: 11429 // [...] whether the function has a non-throwing exception-specification 11430 // [is] part of the function type 11431 // 11432 // This results in an ABI break between C++14 and C++17 for functions whose 11433 // declared type includes an exception-specification in a parameter or 11434 // return type. (Exception specifications on the function itself are OK in 11435 // most cases, and exception specifications are not permitted in most other 11436 // contexts where they could make it into a mangling.) 11437 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11438 auto HasNoexcept = [&](QualType T) -> bool { 11439 // Strip off declarator chunks that could be between us and a function 11440 // type. We don't need to look far, exception specifications are very 11441 // restricted prior to C++17. 11442 if (auto *RT = T->getAs<ReferenceType>()) 11443 T = RT->getPointeeType(); 11444 else if (T->isAnyPointerType()) 11445 T = T->getPointeeType(); 11446 else if (auto *MPT = T->getAs<MemberPointerType>()) 11447 T = MPT->getPointeeType(); 11448 if (auto *FPT = T->getAs<FunctionProtoType>()) 11449 if (FPT->isNothrow()) 11450 return true; 11451 return false; 11452 }; 11453 11454 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11455 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11456 for (QualType T : FPT->param_types()) 11457 AnyNoexcept |= HasNoexcept(T); 11458 if (AnyNoexcept) 11459 Diag(NewFD->getLocation(), 11460 diag::warn_cxx17_compat_exception_spec_in_signature) 11461 << NewFD; 11462 } 11463 11464 if (!Redeclaration && LangOpts.CUDA) 11465 checkCUDATargetOverload(NewFD, Previous); 11466 } 11467 return Redeclaration; 11468 } 11469 11470 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11471 // C++11 [basic.start.main]p3: 11472 // A program that [...] declares main to be inline, static or 11473 // constexpr is ill-formed. 11474 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11475 // appear in a declaration of main. 11476 // static main is not an error under C99, but we should warn about it. 11477 // We accept _Noreturn main as an extension. 11478 if (FD->getStorageClass() == SC_Static) 11479 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11480 ? diag::err_static_main : diag::warn_static_main) 11481 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11482 if (FD->isInlineSpecified()) 11483 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11484 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11485 if (DS.isNoreturnSpecified()) { 11486 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11487 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11488 Diag(NoreturnLoc, diag::ext_noreturn_main); 11489 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11490 << FixItHint::CreateRemoval(NoreturnRange); 11491 } 11492 if (FD->isConstexpr()) { 11493 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11494 << FD->isConsteval() 11495 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11496 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11497 } 11498 11499 if (getLangOpts().OpenCL) { 11500 Diag(FD->getLocation(), diag::err_opencl_no_main) 11501 << FD->hasAttr<OpenCLKernelAttr>(); 11502 FD->setInvalidDecl(); 11503 return; 11504 } 11505 11506 // Functions named main in hlsl are default entries, but don't have specific 11507 // signatures they are required to conform to. 11508 if (getLangOpts().HLSL) 11509 return; 11510 11511 QualType T = FD->getType(); 11512 assert(T->isFunctionType() && "function decl is not of function type"); 11513 const FunctionType* FT = T->castAs<FunctionType>(); 11514 11515 // Set default calling convention for main() 11516 if (FT->getCallConv() != CC_C) { 11517 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11518 FD->setType(QualType(FT, 0)); 11519 T = Context.getCanonicalType(FD->getType()); 11520 } 11521 11522 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11523 // In C with GNU extensions we allow main() to have non-integer return 11524 // type, but we should warn about the extension, and we disable the 11525 // implicit-return-zero rule. 11526 11527 // GCC in C mode accepts qualified 'int'. 11528 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11529 FD->setHasImplicitReturnZero(true); 11530 else { 11531 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11532 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11533 if (RTRange.isValid()) 11534 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11535 << FixItHint::CreateReplacement(RTRange, "int"); 11536 } 11537 } else { 11538 // In C and C++, main magically returns 0 if you fall off the end; 11539 // set the flag which tells us that. 11540 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11541 11542 // All the standards say that main() should return 'int'. 11543 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11544 FD->setHasImplicitReturnZero(true); 11545 else { 11546 // Otherwise, this is just a flat-out error. 11547 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11548 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11549 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11550 : FixItHint()); 11551 FD->setInvalidDecl(true); 11552 } 11553 } 11554 11555 // Treat protoless main() as nullary. 11556 if (isa<FunctionNoProtoType>(FT)) return; 11557 11558 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11559 unsigned nparams = FTP->getNumParams(); 11560 assert(FD->getNumParams() == nparams); 11561 11562 bool HasExtraParameters = (nparams > 3); 11563 11564 if (FTP->isVariadic()) { 11565 Diag(FD->getLocation(), diag::ext_variadic_main); 11566 // FIXME: if we had information about the location of the ellipsis, we 11567 // could add a FixIt hint to remove it as a parameter. 11568 } 11569 11570 // Darwin passes an undocumented fourth argument of type char**. If 11571 // other platforms start sprouting these, the logic below will start 11572 // getting shifty. 11573 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11574 HasExtraParameters = false; 11575 11576 if (HasExtraParameters) { 11577 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11578 FD->setInvalidDecl(true); 11579 nparams = 3; 11580 } 11581 11582 // FIXME: a lot of the following diagnostics would be improved 11583 // if we had some location information about types. 11584 11585 QualType CharPP = 11586 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11587 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11588 11589 for (unsigned i = 0; i < nparams; ++i) { 11590 QualType AT = FTP->getParamType(i); 11591 11592 bool mismatch = true; 11593 11594 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11595 mismatch = false; 11596 else if (Expected[i] == CharPP) { 11597 // As an extension, the following forms are okay: 11598 // char const ** 11599 // char const * const * 11600 // char * const * 11601 11602 QualifierCollector qs; 11603 const PointerType* PT; 11604 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11605 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11606 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11607 Context.CharTy)) { 11608 qs.removeConst(); 11609 mismatch = !qs.empty(); 11610 } 11611 } 11612 11613 if (mismatch) { 11614 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11615 // TODO: suggest replacing given type with expected type 11616 FD->setInvalidDecl(true); 11617 } 11618 } 11619 11620 if (nparams == 1 && !FD->isInvalidDecl()) { 11621 Diag(FD->getLocation(), diag::warn_main_one_arg); 11622 } 11623 11624 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11625 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11626 FD->setInvalidDecl(); 11627 } 11628 } 11629 11630 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11631 11632 // Default calling convention for main and wmain is __cdecl 11633 if (FD->getName() == "main" || FD->getName() == "wmain") 11634 return false; 11635 11636 // Default calling convention for MinGW is __cdecl 11637 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11638 if (T.isWindowsGNUEnvironment()) 11639 return false; 11640 11641 // Default calling convention for WinMain, wWinMain and DllMain 11642 // is __stdcall on 32 bit Windows 11643 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11644 return true; 11645 11646 return false; 11647 } 11648 11649 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11650 QualType T = FD->getType(); 11651 assert(T->isFunctionType() && "function decl is not of function type"); 11652 const FunctionType *FT = T->castAs<FunctionType>(); 11653 11654 // Set an implicit return of 'zero' if the function can return some integral, 11655 // enumeration, pointer or nullptr type. 11656 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11657 FT->getReturnType()->isAnyPointerType() || 11658 FT->getReturnType()->isNullPtrType()) 11659 // DllMain is exempt because a return value of zero means it failed. 11660 if (FD->getName() != "DllMain") 11661 FD->setHasImplicitReturnZero(true); 11662 11663 // Explicity specified calling conventions are applied to MSVC entry points 11664 if (!hasExplicitCallingConv(T)) { 11665 if (isDefaultStdCall(FD, *this)) { 11666 if (FT->getCallConv() != CC_X86StdCall) { 11667 FT = Context.adjustFunctionType( 11668 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11669 FD->setType(QualType(FT, 0)); 11670 } 11671 } else if (FT->getCallConv() != CC_C) { 11672 FT = Context.adjustFunctionType(FT, 11673 FT->getExtInfo().withCallingConv(CC_C)); 11674 FD->setType(QualType(FT, 0)); 11675 } 11676 } 11677 11678 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11679 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11680 FD->setInvalidDecl(); 11681 } 11682 } 11683 11684 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11685 // FIXME: Need strict checking. In C89, we need to check for 11686 // any assignment, increment, decrement, function-calls, or 11687 // commas outside of a sizeof. In C99, it's the same list, 11688 // except that the aforementioned are allowed in unevaluated 11689 // expressions. Everything else falls under the 11690 // "may accept other forms of constant expressions" exception. 11691 // 11692 // Regular C++ code will not end up here (exceptions: language extensions, 11693 // OpenCL C++ etc), so the constant expression rules there don't matter. 11694 if (Init->isValueDependent()) { 11695 assert(Init->containsErrors() && 11696 "Dependent code should only occur in error-recovery path."); 11697 return true; 11698 } 11699 const Expr *Culprit; 11700 if (Init->isConstantInitializer(Context, false, &Culprit)) 11701 return false; 11702 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11703 << Culprit->getSourceRange(); 11704 return true; 11705 } 11706 11707 namespace { 11708 // Visits an initialization expression to see if OrigDecl is evaluated in 11709 // its own initialization and throws a warning if it does. 11710 class SelfReferenceChecker 11711 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11712 Sema &S; 11713 Decl *OrigDecl; 11714 bool isRecordType; 11715 bool isPODType; 11716 bool isReferenceType; 11717 11718 bool isInitList; 11719 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11720 11721 public: 11722 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11723 11724 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11725 S(S), OrigDecl(OrigDecl) { 11726 isPODType = false; 11727 isRecordType = false; 11728 isReferenceType = false; 11729 isInitList = false; 11730 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11731 isPODType = VD->getType().isPODType(S.Context); 11732 isRecordType = VD->getType()->isRecordType(); 11733 isReferenceType = VD->getType()->isReferenceType(); 11734 } 11735 } 11736 11737 // For most expressions, just call the visitor. For initializer lists, 11738 // track the index of the field being initialized since fields are 11739 // initialized in order allowing use of previously initialized fields. 11740 void CheckExpr(Expr *E) { 11741 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11742 if (!InitList) { 11743 Visit(E); 11744 return; 11745 } 11746 11747 // Track and increment the index here. 11748 isInitList = true; 11749 InitFieldIndex.push_back(0); 11750 for (auto Child : InitList->children()) { 11751 CheckExpr(cast<Expr>(Child)); 11752 ++InitFieldIndex.back(); 11753 } 11754 InitFieldIndex.pop_back(); 11755 } 11756 11757 // Returns true if MemberExpr is checked and no further checking is needed. 11758 // Returns false if additional checking is required. 11759 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11760 llvm::SmallVector<FieldDecl*, 4> Fields; 11761 Expr *Base = E; 11762 bool ReferenceField = false; 11763 11764 // Get the field members used. 11765 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11766 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11767 if (!FD) 11768 return false; 11769 Fields.push_back(FD); 11770 if (FD->getType()->isReferenceType()) 11771 ReferenceField = true; 11772 Base = ME->getBase()->IgnoreParenImpCasts(); 11773 } 11774 11775 // Keep checking only if the base Decl is the same. 11776 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11777 if (!DRE || DRE->getDecl() != OrigDecl) 11778 return false; 11779 11780 // A reference field can be bound to an unininitialized field. 11781 if (CheckReference && !ReferenceField) 11782 return true; 11783 11784 // Convert FieldDecls to their index number. 11785 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11786 for (const FieldDecl *I : llvm::reverse(Fields)) 11787 UsedFieldIndex.push_back(I->getFieldIndex()); 11788 11789 // See if a warning is needed by checking the first difference in index 11790 // numbers. If field being used has index less than the field being 11791 // initialized, then the use is safe. 11792 for (auto UsedIter = UsedFieldIndex.begin(), 11793 UsedEnd = UsedFieldIndex.end(), 11794 OrigIter = InitFieldIndex.begin(), 11795 OrigEnd = InitFieldIndex.end(); 11796 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11797 if (*UsedIter < *OrigIter) 11798 return true; 11799 if (*UsedIter > *OrigIter) 11800 break; 11801 } 11802 11803 // TODO: Add a different warning which will print the field names. 11804 HandleDeclRefExpr(DRE); 11805 return true; 11806 } 11807 11808 // For most expressions, the cast is directly above the DeclRefExpr. 11809 // For conditional operators, the cast can be outside the conditional 11810 // operator if both expressions are DeclRefExpr's. 11811 void HandleValue(Expr *E) { 11812 E = E->IgnoreParens(); 11813 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11814 HandleDeclRefExpr(DRE); 11815 return; 11816 } 11817 11818 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11819 Visit(CO->getCond()); 11820 HandleValue(CO->getTrueExpr()); 11821 HandleValue(CO->getFalseExpr()); 11822 return; 11823 } 11824 11825 if (BinaryConditionalOperator *BCO = 11826 dyn_cast<BinaryConditionalOperator>(E)) { 11827 Visit(BCO->getCond()); 11828 HandleValue(BCO->getFalseExpr()); 11829 return; 11830 } 11831 11832 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11833 HandleValue(OVE->getSourceExpr()); 11834 return; 11835 } 11836 11837 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11838 if (BO->getOpcode() == BO_Comma) { 11839 Visit(BO->getLHS()); 11840 HandleValue(BO->getRHS()); 11841 return; 11842 } 11843 } 11844 11845 if (isa<MemberExpr>(E)) { 11846 if (isInitList) { 11847 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11848 false /*CheckReference*/)) 11849 return; 11850 } 11851 11852 Expr *Base = E->IgnoreParenImpCasts(); 11853 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11854 // Check for static member variables and don't warn on them. 11855 if (!isa<FieldDecl>(ME->getMemberDecl())) 11856 return; 11857 Base = ME->getBase()->IgnoreParenImpCasts(); 11858 } 11859 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11860 HandleDeclRefExpr(DRE); 11861 return; 11862 } 11863 11864 Visit(E); 11865 } 11866 11867 // Reference types not handled in HandleValue are handled here since all 11868 // uses of references are bad, not just r-value uses. 11869 void VisitDeclRefExpr(DeclRefExpr *E) { 11870 if (isReferenceType) 11871 HandleDeclRefExpr(E); 11872 } 11873 11874 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11875 if (E->getCastKind() == CK_LValueToRValue) { 11876 HandleValue(E->getSubExpr()); 11877 return; 11878 } 11879 11880 Inherited::VisitImplicitCastExpr(E); 11881 } 11882 11883 void VisitMemberExpr(MemberExpr *E) { 11884 if (isInitList) { 11885 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11886 return; 11887 } 11888 11889 // Don't warn on arrays since they can be treated as pointers. 11890 if (E->getType()->canDecayToPointerType()) return; 11891 11892 // Warn when a non-static method call is followed by non-static member 11893 // field accesses, which is followed by a DeclRefExpr. 11894 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11895 bool Warn = (MD && !MD->isStatic()); 11896 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11897 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11898 if (!isa<FieldDecl>(ME->getMemberDecl())) 11899 Warn = false; 11900 Base = ME->getBase()->IgnoreParenImpCasts(); 11901 } 11902 11903 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11904 if (Warn) 11905 HandleDeclRefExpr(DRE); 11906 return; 11907 } 11908 11909 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11910 // Visit that expression. 11911 Visit(Base); 11912 } 11913 11914 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11915 Expr *Callee = E->getCallee(); 11916 11917 if (isa<UnresolvedLookupExpr>(Callee)) 11918 return Inherited::VisitCXXOperatorCallExpr(E); 11919 11920 Visit(Callee); 11921 for (auto Arg: E->arguments()) 11922 HandleValue(Arg->IgnoreParenImpCasts()); 11923 } 11924 11925 void VisitUnaryOperator(UnaryOperator *E) { 11926 // For POD record types, addresses of its own members are well-defined. 11927 if (E->getOpcode() == UO_AddrOf && isRecordType && 11928 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11929 if (!isPODType) 11930 HandleValue(E->getSubExpr()); 11931 return; 11932 } 11933 11934 if (E->isIncrementDecrementOp()) { 11935 HandleValue(E->getSubExpr()); 11936 return; 11937 } 11938 11939 Inherited::VisitUnaryOperator(E); 11940 } 11941 11942 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11943 11944 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11945 if (E->getConstructor()->isCopyConstructor()) { 11946 Expr *ArgExpr = E->getArg(0); 11947 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11948 if (ILE->getNumInits() == 1) 11949 ArgExpr = ILE->getInit(0); 11950 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11951 if (ICE->getCastKind() == CK_NoOp) 11952 ArgExpr = ICE->getSubExpr(); 11953 HandleValue(ArgExpr); 11954 return; 11955 } 11956 Inherited::VisitCXXConstructExpr(E); 11957 } 11958 11959 void VisitCallExpr(CallExpr *E) { 11960 // Treat std::move as a use. 11961 if (E->isCallToStdMove()) { 11962 HandleValue(E->getArg(0)); 11963 return; 11964 } 11965 11966 Inherited::VisitCallExpr(E); 11967 } 11968 11969 void VisitBinaryOperator(BinaryOperator *E) { 11970 if (E->isCompoundAssignmentOp()) { 11971 HandleValue(E->getLHS()); 11972 Visit(E->getRHS()); 11973 return; 11974 } 11975 11976 Inherited::VisitBinaryOperator(E); 11977 } 11978 11979 // A custom visitor for BinaryConditionalOperator is needed because the 11980 // regular visitor would check the condition and true expression separately 11981 // but both point to the same place giving duplicate diagnostics. 11982 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11983 Visit(E->getCond()); 11984 Visit(E->getFalseExpr()); 11985 } 11986 11987 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11988 Decl* ReferenceDecl = DRE->getDecl(); 11989 if (OrigDecl != ReferenceDecl) return; 11990 unsigned diag; 11991 if (isReferenceType) { 11992 diag = diag::warn_uninit_self_reference_in_reference_init; 11993 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11994 diag = diag::warn_static_self_reference_in_init; 11995 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11996 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11997 DRE->getDecl()->getType()->isRecordType()) { 11998 diag = diag::warn_uninit_self_reference_in_init; 11999 } else { 12000 // Local variables will be handled by the CFG analysis. 12001 return; 12002 } 12003 12004 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 12005 S.PDiag(diag) 12006 << DRE->getDecl() << OrigDecl->getLocation() 12007 << DRE->getSourceRange()); 12008 } 12009 }; 12010 12011 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 12012 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 12013 bool DirectInit) { 12014 // Parameters arguments are occassionially constructed with itself, 12015 // for instance, in recursive functions. Skip them. 12016 if (isa<ParmVarDecl>(OrigDecl)) 12017 return; 12018 12019 E = E->IgnoreParens(); 12020 12021 // Skip checking T a = a where T is not a record or reference type. 12022 // Doing so is a way to silence uninitialized warnings. 12023 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 12024 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 12025 if (ICE->getCastKind() == CK_LValueToRValue) 12026 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 12027 if (DRE->getDecl() == OrigDecl) 12028 return; 12029 12030 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 12031 } 12032 } // end anonymous namespace 12033 12034 namespace { 12035 // Simple wrapper to add the name of a variable or (if no variable is 12036 // available) a DeclarationName into a diagnostic. 12037 struct VarDeclOrName { 12038 VarDecl *VDecl; 12039 DeclarationName Name; 12040 12041 friend const Sema::SemaDiagnosticBuilder & 12042 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 12043 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 12044 } 12045 }; 12046 } // end anonymous namespace 12047 12048 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 12049 DeclarationName Name, QualType Type, 12050 TypeSourceInfo *TSI, 12051 SourceRange Range, bool DirectInit, 12052 Expr *Init) { 12053 bool IsInitCapture = !VDecl; 12054 assert((!VDecl || !VDecl->isInitCapture()) && 12055 "init captures are expected to be deduced prior to initialization"); 12056 12057 VarDeclOrName VN{VDecl, Name}; 12058 12059 DeducedType *Deduced = Type->getContainedDeducedType(); 12060 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 12061 12062 // C++11 [dcl.spec.auto]p3 12063 if (!Init) { 12064 assert(VDecl && "no init for init capture deduction?"); 12065 12066 // Except for class argument deduction, and then for an initializing 12067 // declaration only, i.e. no static at class scope or extern. 12068 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 12069 VDecl->hasExternalStorage() || 12070 VDecl->isStaticDataMember()) { 12071 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 12072 << VDecl->getDeclName() << Type; 12073 return QualType(); 12074 } 12075 } 12076 12077 ArrayRef<Expr*> DeduceInits; 12078 if (Init) 12079 DeduceInits = Init; 12080 12081 if (DirectInit) { 12082 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 12083 DeduceInits = PL->exprs(); 12084 } 12085 12086 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 12087 assert(VDecl && "non-auto type for init capture deduction?"); 12088 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12089 InitializationKind Kind = InitializationKind::CreateForInit( 12090 VDecl->getLocation(), DirectInit, Init); 12091 // FIXME: Initialization should not be taking a mutable list of inits. 12092 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 12093 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 12094 InitsCopy); 12095 } 12096 12097 if (DirectInit) { 12098 if (auto *IL = dyn_cast<InitListExpr>(Init)) 12099 DeduceInits = IL->inits(); 12100 } 12101 12102 // Deduction only works if we have exactly one source expression. 12103 if (DeduceInits.empty()) { 12104 // It isn't possible to write this directly, but it is possible to 12105 // end up in this situation with "auto x(some_pack...);" 12106 Diag(Init->getBeginLoc(), IsInitCapture 12107 ? diag::err_init_capture_no_expression 12108 : diag::err_auto_var_init_no_expression) 12109 << VN << Type << Range; 12110 return QualType(); 12111 } 12112 12113 if (DeduceInits.size() > 1) { 12114 Diag(DeduceInits[1]->getBeginLoc(), 12115 IsInitCapture ? diag::err_init_capture_multiple_expressions 12116 : diag::err_auto_var_init_multiple_expressions) 12117 << VN << Type << Range; 12118 return QualType(); 12119 } 12120 12121 Expr *DeduceInit = DeduceInits[0]; 12122 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 12123 Diag(Init->getBeginLoc(), IsInitCapture 12124 ? diag::err_init_capture_paren_braces 12125 : diag::err_auto_var_init_paren_braces) 12126 << isa<InitListExpr>(Init) << VN << Type << Range; 12127 return QualType(); 12128 } 12129 12130 // Expressions default to 'id' when we're in a debugger. 12131 bool DefaultedAnyToId = false; 12132 if (getLangOpts().DebuggerCastResultToId && 12133 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 12134 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12135 if (Result.isInvalid()) { 12136 return QualType(); 12137 } 12138 Init = Result.get(); 12139 DefaultedAnyToId = true; 12140 } 12141 12142 // C++ [dcl.decomp]p1: 12143 // If the assignment-expression [...] has array type A and no ref-qualifier 12144 // is present, e has type cv A 12145 if (VDecl && isa<DecompositionDecl>(VDecl) && 12146 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 12147 DeduceInit->getType()->isConstantArrayType()) 12148 return Context.getQualifiedType(DeduceInit->getType(), 12149 Type.getQualifiers()); 12150 12151 QualType DeducedType; 12152 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 12153 if (!IsInitCapture) 12154 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 12155 else if (isa<InitListExpr>(Init)) 12156 Diag(Range.getBegin(), 12157 diag::err_init_capture_deduction_failure_from_init_list) 12158 << VN 12159 << (DeduceInit->getType().isNull() ? TSI->getType() 12160 : DeduceInit->getType()) 12161 << DeduceInit->getSourceRange(); 12162 else 12163 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 12164 << VN << TSI->getType() 12165 << (DeduceInit->getType().isNull() ? TSI->getType() 12166 : DeduceInit->getType()) 12167 << DeduceInit->getSourceRange(); 12168 } 12169 12170 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 12171 // 'id' instead of a specific object type prevents most of our usual 12172 // checks. 12173 // We only want to warn outside of template instantiations, though: 12174 // inside a template, the 'id' could have come from a parameter. 12175 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 12176 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 12177 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 12178 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 12179 } 12180 12181 return DeducedType; 12182 } 12183 12184 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 12185 Expr *Init) { 12186 assert(!Init || !Init->containsErrors()); 12187 QualType DeducedType = deduceVarTypeFromInitializer( 12188 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 12189 VDecl->getSourceRange(), DirectInit, Init); 12190 if (DeducedType.isNull()) { 12191 VDecl->setInvalidDecl(); 12192 return true; 12193 } 12194 12195 VDecl->setType(DeducedType); 12196 assert(VDecl->isLinkageValid()); 12197 12198 // In ARC, infer lifetime. 12199 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 12200 VDecl->setInvalidDecl(); 12201 12202 if (getLangOpts().OpenCL) 12203 deduceOpenCLAddressSpace(VDecl); 12204 12205 // If this is a redeclaration, check that the type we just deduced matches 12206 // the previously declared type. 12207 if (VarDecl *Old = VDecl->getPreviousDecl()) { 12208 // We never need to merge the type, because we cannot form an incomplete 12209 // array of auto, nor deduce such a type. 12210 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 12211 } 12212 12213 // Check the deduced type is valid for a variable declaration. 12214 CheckVariableDeclarationType(VDecl); 12215 return VDecl->isInvalidDecl(); 12216 } 12217 12218 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 12219 SourceLocation Loc) { 12220 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 12221 Init = EWC->getSubExpr(); 12222 12223 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 12224 Init = CE->getSubExpr(); 12225 12226 QualType InitType = Init->getType(); 12227 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12228 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 12229 "shouldn't be called if type doesn't have a non-trivial C struct"); 12230 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 12231 for (auto I : ILE->inits()) { 12232 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 12233 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12234 continue; 12235 SourceLocation SL = I->getExprLoc(); 12236 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 12237 } 12238 return; 12239 } 12240 12241 if (isa<ImplicitValueInitExpr>(Init)) { 12242 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12243 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 12244 NTCUK_Init); 12245 } else { 12246 // Assume all other explicit initializers involving copying some existing 12247 // object. 12248 // TODO: ignore any explicit initializers where we can guarantee 12249 // copy-elision. 12250 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 12251 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 12252 } 12253 } 12254 12255 namespace { 12256 12257 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 12258 // Ignore unavailable fields. A field can be marked as unavailable explicitly 12259 // in the source code or implicitly by the compiler if it is in a union 12260 // defined in a system header and has non-trivial ObjC ownership 12261 // qualifications. We don't want those fields to participate in determining 12262 // whether the containing union is non-trivial. 12263 return FD->hasAttr<UnavailableAttr>(); 12264 } 12265 12266 struct DiagNonTrivalCUnionDefaultInitializeVisitor 12267 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12268 void> { 12269 using Super = 12270 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12271 void>; 12272 12273 DiagNonTrivalCUnionDefaultInitializeVisitor( 12274 QualType OrigTy, SourceLocation OrigLoc, 12275 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12276 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12277 12278 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 12279 const FieldDecl *FD, bool InNonTrivialUnion) { 12280 if (const auto *AT = S.Context.getAsArrayType(QT)) 12281 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12282 InNonTrivialUnion); 12283 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 12284 } 12285 12286 void visitARCStrong(QualType QT, const FieldDecl *FD, 12287 bool InNonTrivialUnion) { 12288 if (InNonTrivialUnion) 12289 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12290 << 1 << 0 << QT << FD->getName(); 12291 } 12292 12293 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12294 if (InNonTrivialUnion) 12295 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12296 << 1 << 0 << QT << FD->getName(); 12297 } 12298 12299 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12300 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12301 if (RD->isUnion()) { 12302 if (OrigLoc.isValid()) { 12303 bool IsUnion = false; 12304 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12305 IsUnion = OrigRD->isUnion(); 12306 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12307 << 0 << OrigTy << IsUnion << UseContext; 12308 // Reset OrigLoc so that this diagnostic is emitted only once. 12309 OrigLoc = SourceLocation(); 12310 } 12311 InNonTrivialUnion = true; 12312 } 12313 12314 if (InNonTrivialUnion) 12315 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12316 << 0 << 0 << QT.getUnqualifiedType() << ""; 12317 12318 for (const FieldDecl *FD : RD->fields()) 12319 if (!shouldIgnoreForRecordTriviality(FD)) 12320 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12321 } 12322 12323 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12324 12325 // The non-trivial C union type or the struct/union type that contains a 12326 // non-trivial C union. 12327 QualType OrigTy; 12328 SourceLocation OrigLoc; 12329 Sema::NonTrivialCUnionContext UseContext; 12330 Sema &S; 12331 }; 12332 12333 struct DiagNonTrivalCUnionDestructedTypeVisitor 12334 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12335 using Super = 12336 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12337 12338 DiagNonTrivalCUnionDestructedTypeVisitor( 12339 QualType OrigTy, SourceLocation OrigLoc, 12340 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12341 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12342 12343 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12344 const FieldDecl *FD, bool InNonTrivialUnion) { 12345 if (const auto *AT = S.Context.getAsArrayType(QT)) 12346 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12347 InNonTrivialUnion); 12348 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12349 } 12350 12351 void visitARCStrong(QualType QT, const FieldDecl *FD, 12352 bool InNonTrivialUnion) { 12353 if (InNonTrivialUnion) 12354 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12355 << 1 << 1 << QT << FD->getName(); 12356 } 12357 12358 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12359 if (InNonTrivialUnion) 12360 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12361 << 1 << 1 << QT << FD->getName(); 12362 } 12363 12364 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12365 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12366 if (RD->isUnion()) { 12367 if (OrigLoc.isValid()) { 12368 bool IsUnion = false; 12369 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12370 IsUnion = OrigRD->isUnion(); 12371 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12372 << 1 << OrigTy << IsUnion << UseContext; 12373 // Reset OrigLoc so that this diagnostic is emitted only once. 12374 OrigLoc = SourceLocation(); 12375 } 12376 InNonTrivialUnion = true; 12377 } 12378 12379 if (InNonTrivialUnion) 12380 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12381 << 0 << 1 << QT.getUnqualifiedType() << ""; 12382 12383 for (const FieldDecl *FD : RD->fields()) 12384 if (!shouldIgnoreForRecordTriviality(FD)) 12385 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12386 } 12387 12388 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12389 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12390 bool InNonTrivialUnion) {} 12391 12392 // The non-trivial C union type or the struct/union type that contains a 12393 // non-trivial C union. 12394 QualType OrigTy; 12395 SourceLocation OrigLoc; 12396 Sema::NonTrivialCUnionContext UseContext; 12397 Sema &S; 12398 }; 12399 12400 struct DiagNonTrivalCUnionCopyVisitor 12401 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12402 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12403 12404 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12405 Sema::NonTrivialCUnionContext UseContext, 12406 Sema &S) 12407 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12408 12409 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12410 const FieldDecl *FD, bool InNonTrivialUnion) { 12411 if (const auto *AT = S.Context.getAsArrayType(QT)) 12412 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12413 InNonTrivialUnion); 12414 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12415 } 12416 12417 void visitARCStrong(QualType QT, const FieldDecl *FD, 12418 bool InNonTrivialUnion) { 12419 if (InNonTrivialUnion) 12420 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12421 << 1 << 2 << QT << FD->getName(); 12422 } 12423 12424 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12425 if (InNonTrivialUnion) 12426 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12427 << 1 << 2 << QT << FD->getName(); 12428 } 12429 12430 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12431 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12432 if (RD->isUnion()) { 12433 if (OrigLoc.isValid()) { 12434 bool IsUnion = false; 12435 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12436 IsUnion = OrigRD->isUnion(); 12437 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12438 << 2 << OrigTy << IsUnion << UseContext; 12439 // Reset OrigLoc so that this diagnostic is emitted only once. 12440 OrigLoc = SourceLocation(); 12441 } 12442 InNonTrivialUnion = true; 12443 } 12444 12445 if (InNonTrivialUnion) 12446 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12447 << 0 << 2 << QT.getUnqualifiedType() << ""; 12448 12449 for (const FieldDecl *FD : RD->fields()) 12450 if (!shouldIgnoreForRecordTriviality(FD)) 12451 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12452 } 12453 12454 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12455 const FieldDecl *FD, bool InNonTrivialUnion) {} 12456 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12457 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12458 bool InNonTrivialUnion) {} 12459 12460 // The non-trivial C union type or the struct/union type that contains a 12461 // non-trivial C union. 12462 QualType OrigTy; 12463 SourceLocation OrigLoc; 12464 Sema::NonTrivialCUnionContext UseContext; 12465 Sema &S; 12466 }; 12467 12468 } // namespace 12469 12470 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12471 NonTrivialCUnionContext UseContext, 12472 unsigned NonTrivialKind) { 12473 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12474 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12475 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12476 "shouldn't be called if type doesn't have a non-trivial C union"); 12477 12478 if ((NonTrivialKind & NTCUK_Init) && 12479 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12480 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12481 .visit(QT, nullptr, false); 12482 if ((NonTrivialKind & NTCUK_Destruct) && 12483 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12484 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12485 .visit(QT, nullptr, false); 12486 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12487 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12488 .visit(QT, nullptr, false); 12489 } 12490 12491 /// AddInitializerToDecl - Adds the initializer Init to the 12492 /// declaration dcl. If DirectInit is true, this is C++ direct 12493 /// initialization rather than copy initialization. 12494 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12495 // If there is no declaration, there was an error parsing it. Just ignore 12496 // the initializer. 12497 if (!RealDecl || RealDecl->isInvalidDecl()) { 12498 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12499 return; 12500 } 12501 12502 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12503 // Pure-specifiers are handled in ActOnPureSpecifier. 12504 Diag(Method->getLocation(), diag::err_member_function_initialization) 12505 << Method->getDeclName() << Init->getSourceRange(); 12506 Method->setInvalidDecl(); 12507 return; 12508 } 12509 12510 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12511 if (!VDecl) { 12512 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12513 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12514 RealDecl->setInvalidDecl(); 12515 return; 12516 } 12517 12518 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12519 if (VDecl->getType()->isUndeducedType()) { 12520 // Attempt typo correction early so that the type of the init expression can 12521 // be deduced based on the chosen correction if the original init contains a 12522 // TypoExpr. 12523 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12524 if (!Res.isUsable()) { 12525 // There are unresolved typos in Init, just drop them. 12526 // FIXME: improve the recovery strategy to preserve the Init. 12527 RealDecl->setInvalidDecl(); 12528 return; 12529 } 12530 if (Res.get()->containsErrors()) { 12531 // Invalidate the decl as we don't know the type for recovery-expr yet. 12532 RealDecl->setInvalidDecl(); 12533 VDecl->setInit(Res.get()); 12534 return; 12535 } 12536 Init = Res.get(); 12537 12538 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12539 return; 12540 } 12541 12542 // dllimport cannot be used on variable definitions. 12543 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12544 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12545 VDecl->setInvalidDecl(); 12546 return; 12547 } 12548 12549 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12550 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12551 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12552 VDecl->setInvalidDecl(); 12553 return; 12554 } 12555 12556 if (!VDecl->getType()->isDependentType()) { 12557 // A definition must end up with a complete type, which means it must be 12558 // complete with the restriction that an array type might be completed by 12559 // the initializer; note that later code assumes this restriction. 12560 QualType BaseDeclType = VDecl->getType(); 12561 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12562 BaseDeclType = Array->getElementType(); 12563 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12564 diag::err_typecheck_decl_incomplete_type)) { 12565 RealDecl->setInvalidDecl(); 12566 return; 12567 } 12568 12569 // The variable can not have an abstract class type. 12570 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12571 diag::err_abstract_type_in_decl, 12572 AbstractVariableType)) 12573 VDecl->setInvalidDecl(); 12574 } 12575 12576 // If adding the initializer will turn this declaration into a definition, 12577 // and we already have a definition for this variable, diagnose or otherwise 12578 // handle the situation. 12579 if (VarDecl *Def = VDecl->getDefinition()) 12580 if (Def != VDecl && 12581 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12582 !VDecl->isThisDeclarationADemotedDefinition() && 12583 checkVarDeclRedefinition(Def, VDecl)) 12584 return; 12585 12586 if (getLangOpts().CPlusPlus) { 12587 // C++ [class.static.data]p4 12588 // If a static data member is of const integral or const 12589 // enumeration type, its declaration in the class definition can 12590 // specify a constant-initializer which shall be an integral 12591 // constant expression (5.19). In that case, the member can appear 12592 // in integral constant expressions. The member shall still be 12593 // defined in a namespace scope if it is used in the program and the 12594 // namespace scope definition shall not contain an initializer. 12595 // 12596 // We already performed a redefinition check above, but for static 12597 // data members we also need to check whether there was an in-class 12598 // declaration with an initializer. 12599 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12600 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12601 << VDecl->getDeclName(); 12602 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12603 diag::note_previous_initializer) 12604 << 0; 12605 return; 12606 } 12607 12608 if (VDecl->hasLocalStorage()) 12609 setFunctionHasBranchProtectedScope(); 12610 12611 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12612 VDecl->setInvalidDecl(); 12613 return; 12614 } 12615 } 12616 12617 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12618 // a kernel function cannot be initialized." 12619 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12620 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12621 VDecl->setInvalidDecl(); 12622 return; 12623 } 12624 12625 // The LoaderUninitialized attribute acts as a definition (of undef). 12626 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12627 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12628 VDecl->setInvalidDecl(); 12629 return; 12630 } 12631 12632 // Get the decls type and save a reference for later, since 12633 // CheckInitializerTypes may change it. 12634 QualType DclT = VDecl->getType(), SavT = DclT; 12635 12636 // Expressions default to 'id' when we're in a debugger 12637 // and we are assigning it to a variable of Objective-C pointer type. 12638 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12639 Init->getType() == Context.UnknownAnyTy) { 12640 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12641 if (Result.isInvalid()) { 12642 VDecl->setInvalidDecl(); 12643 return; 12644 } 12645 Init = Result.get(); 12646 } 12647 12648 // Perform the initialization. 12649 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12650 if (!VDecl->isInvalidDecl()) { 12651 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12652 InitializationKind Kind = InitializationKind::CreateForInit( 12653 VDecl->getLocation(), DirectInit, Init); 12654 12655 MultiExprArg Args = Init; 12656 if (CXXDirectInit) 12657 Args = MultiExprArg(CXXDirectInit->getExprs(), 12658 CXXDirectInit->getNumExprs()); 12659 12660 // Try to correct any TypoExprs in the initialization arguments. 12661 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12662 ExprResult Res = CorrectDelayedTyposInExpr( 12663 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12664 [this, Entity, Kind](Expr *E) { 12665 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12666 return Init.Failed() ? ExprError() : E; 12667 }); 12668 if (Res.isInvalid()) { 12669 VDecl->setInvalidDecl(); 12670 } else if (Res.get() != Args[Idx]) { 12671 Args[Idx] = Res.get(); 12672 } 12673 } 12674 if (VDecl->isInvalidDecl()) 12675 return; 12676 12677 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12678 /*TopLevelOfInitList=*/false, 12679 /*TreatUnavailableAsInvalid=*/false); 12680 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12681 if (Result.isInvalid()) { 12682 // If the provided initializer fails to initialize the var decl, 12683 // we attach a recovery expr for better recovery. 12684 auto RecoveryExpr = 12685 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12686 if (RecoveryExpr.get()) 12687 VDecl->setInit(RecoveryExpr.get()); 12688 return; 12689 } 12690 12691 Init = Result.getAs<Expr>(); 12692 } 12693 12694 // Check for self-references within variable initializers. 12695 // Variables declared within a function/method body (except for references) 12696 // are handled by a dataflow analysis. 12697 // This is undefined behavior in C++, but valid in C. 12698 if (getLangOpts().CPlusPlus) 12699 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12700 VDecl->getType()->isReferenceType()) 12701 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12702 12703 // If the type changed, it means we had an incomplete type that was 12704 // completed by the initializer. For example: 12705 // int ary[] = { 1, 3, 5 }; 12706 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12707 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12708 VDecl->setType(DclT); 12709 12710 if (!VDecl->isInvalidDecl()) { 12711 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12712 12713 if (VDecl->hasAttr<BlocksAttr>()) 12714 checkRetainCycles(VDecl, Init); 12715 12716 // It is safe to assign a weak reference into a strong variable. 12717 // Although this code can still have problems: 12718 // id x = self.weakProp; 12719 // id y = self.weakProp; 12720 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12721 // paths through the function. This should be revisited if 12722 // -Wrepeated-use-of-weak is made flow-sensitive. 12723 if (FunctionScopeInfo *FSI = getCurFunction()) 12724 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12725 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12726 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12727 Init->getBeginLoc())) 12728 FSI->markSafeWeakUse(Init); 12729 } 12730 12731 // The initialization is usually a full-expression. 12732 // 12733 // FIXME: If this is a braced initialization of an aggregate, it is not 12734 // an expression, and each individual field initializer is a separate 12735 // full-expression. For instance, in: 12736 // 12737 // struct Temp { ~Temp(); }; 12738 // struct S { S(Temp); }; 12739 // struct T { S a, b; } t = { Temp(), Temp() } 12740 // 12741 // we should destroy the first Temp before constructing the second. 12742 ExprResult Result = 12743 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12744 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12745 if (Result.isInvalid()) { 12746 VDecl->setInvalidDecl(); 12747 return; 12748 } 12749 Init = Result.get(); 12750 12751 // Attach the initializer to the decl. 12752 VDecl->setInit(Init); 12753 12754 if (VDecl->isLocalVarDecl()) { 12755 // Don't check the initializer if the declaration is malformed. 12756 if (VDecl->isInvalidDecl()) { 12757 // do nothing 12758 12759 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12760 // This is true even in C++ for OpenCL. 12761 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12762 CheckForConstantInitializer(Init, DclT); 12763 12764 // Otherwise, C++ does not restrict the initializer. 12765 } else if (getLangOpts().CPlusPlus) { 12766 // do nothing 12767 12768 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12769 // static storage duration shall be constant expressions or string literals. 12770 } else if (VDecl->getStorageClass() == SC_Static) { 12771 CheckForConstantInitializer(Init, DclT); 12772 12773 // C89 is stricter than C99 for aggregate initializers. 12774 // C89 6.5.7p3: All the expressions [...] in an initializer list 12775 // for an object that has aggregate or union type shall be 12776 // constant expressions. 12777 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12778 isa<InitListExpr>(Init)) { 12779 const Expr *Culprit; 12780 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12781 Diag(Culprit->getExprLoc(), 12782 diag::ext_aggregate_init_not_constant) 12783 << Culprit->getSourceRange(); 12784 } 12785 } 12786 12787 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12788 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12789 if (VDecl->hasLocalStorage()) 12790 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12791 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12792 VDecl->getLexicalDeclContext()->isRecord()) { 12793 // This is an in-class initialization for a static data member, e.g., 12794 // 12795 // struct S { 12796 // static const int value = 17; 12797 // }; 12798 12799 // C++ [class.mem]p4: 12800 // A member-declarator can contain a constant-initializer only 12801 // if it declares a static member (9.4) of const integral or 12802 // const enumeration type, see 9.4.2. 12803 // 12804 // C++11 [class.static.data]p3: 12805 // If a non-volatile non-inline const static data member is of integral 12806 // or enumeration type, its declaration in the class definition can 12807 // specify a brace-or-equal-initializer in which every initializer-clause 12808 // that is an assignment-expression is a constant expression. A static 12809 // data member of literal type can be declared in the class definition 12810 // with the constexpr specifier; if so, its declaration shall specify a 12811 // brace-or-equal-initializer in which every initializer-clause that is 12812 // an assignment-expression is a constant expression. 12813 12814 // Do nothing on dependent types. 12815 if (DclT->isDependentType()) { 12816 12817 // Allow any 'static constexpr' members, whether or not they are of literal 12818 // type. We separately check that every constexpr variable is of literal 12819 // type. 12820 } else if (VDecl->isConstexpr()) { 12821 12822 // Require constness. 12823 } else if (!DclT.isConstQualified()) { 12824 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12825 << Init->getSourceRange(); 12826 VDecl->setInvalidDecl(); 12827 12828 // We allow integer constant expressions in all cases. 12829 } else if (DclT->isIntegralOrEnumerationType()) { 12830 // Check whether the expression is a constant expression. 12831 SourceLocation Loc; 12832 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12833 // In C++11, a non-constexpr const static data member with an 12834 // in-class initializer cannot be volatile. 12835 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12836 else if (Init->isValueDependent()) 12837 ; // Nothing to check. 12838 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12839 ; // Ok, it's an ICE! 12840 else if (Init->getType()->isScopedEnumeralType() && 12841 Init->isCXX11ConstantExpr(Context)) 12842 ; // Ok, it is a scoped-enum constant expression. 12843 else if (Init->isEvaluatable(Context)) { 12844 // If we can constant fold the initializer through heroics, accept it, 12845 // but report this as a use of an extension for -pedantic. 12846 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12847 << Init->getSourceRange(); 12848 } else { 12849 // Otherwise, this is some crazy unknown case. Report the issue at the 12850 // location provided by the isIntegerConstantExpr failed check. 12851 Diag(Loc, diag::err_in_class_initializer_non_constant) 12852 << Init->getSourceRange(); 12853 VDecl->setInvalidDecl(); 12854 } 12855 12856 // We allow foldable floating-point constants as an extension. 12857 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12858 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12859 // it anyway and provide a fixit to add the 'constexpr'. 12860 if (getLangOpts().CPlusPlus11) { 12861 Diag(VDecl->getLocation(), 12862 diag::ext_in_class_initializer_float_type_cxx11) 12863 << DclT << Init->getSourceRange(); 12864 Diag(VDecl->getBeginLoc(), 12865 diag::note_in_class_initializer_float_type_cxx11) 12866 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12867 } else { 12868 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12869 << DclT << Init->getSourceRange(); 12870 12871 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12872 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12873 << Init->getSourceRange(); 12874 VDecl->setInvalidDecl(); 12875 } 12876 } 12877 12878 // Suggest adding 'constexpr' in C++11 for literal types. 12879 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12880 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12881 << DclT << Init->getSourceRange() 12882 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12883 VDecl->setConstexpr(true); 12884 12885 } else { 12886 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12887 << DclT << Init->getSourceRange(); 12888 VDecl->setInvalidDecl(); 12889 } 12890 } else if (VDecl->isFileVarDecl()) { 12891 // In C, extern is typically used to avoid tentative definitions when 12892 // declaring variables in headers, but adding an intializer makes it a 12893 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12894 // In C++, extern is often used to give implictly static const variables 12895 // external linkage, so don't warn in that case. If selectany is present, 12896 // this might be header code intended for C and C++ inclusion, so apply the 12897 // C++ rules. 12898 if (VDecl->getStorageClass() == SC_Extern && 12899 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12900 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12901 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12902 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12903 Diag(VDecl->getLocation(), diag::warn_extern_init); 12904 12905 // In Microsoft C++ mode, a const variable defined in namespace scope has 12906 // external linkage by default if the variable is declared with 12907 // __declspec(dllexport). 12908 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12909 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12910 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12911 VDecl->setStorageClass(SC_Extern); 12912 12913 // C99 6.7.8p4. All file scoped initializers need to be constant. 12914 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12915 CheckForConstantInitializer(Init, DclT); 12916 } 12917 12918 QualType InitType = Init->getType(); 12919 if (!InitType.isNull() && 12920 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12921 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12922 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12923 12924 // We will represent direct-initialization similarly to copy-initialization: 12925 // int x(1); -as-> int x = 1; 12926 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12927 // 12928 // Clients that want to distinguish between the two forms, can check for 12929 // direct initializer using VarDecl::getInitStyle(). 12930 // A major benefit is that clients that don't particularly care about which 12931 // exactly form was it (like the CodeGen) can handle both cases without 12932 // special case code. 12933 12934 // C++ 8.5p11: 12935 // The form of initialization (using parentheses or '=') is generally 12936 // insignificant, but does matter when the entity being initialized has a 12937 // class type. 12938 if (CXXDirectInit) { 12939 assert(DirectInit && "Call-style initializer must be direct init."); 12940 VDecl->setInitStyle(VarDecl::CallInit); 12941 } else if (DirectInit) { 12942 // This must be list-initialization. No other way is direct-initialization. 12943 VDecl->setInitStyle(VarDecl::ListInit); 12944 } 12945 12946 if (LangOpts.OpenMP && 12947 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 12948 VDecl->isFileVarDecl()) 12949 DeclsToCheckForDeferredDiags.insert(VDecl); 12950 CheckCompleteVariableDeclaration(VDecl); 12951 } 12952 12953 /// ActOnInitializerError - Given that there was an error parsing an 12954 /// initializer for the given declaration, try to at least re-establish 12955 /// invariants such as whether a variable's type is either dependent or 12956 /// complete. 12957 void Sema::ActOnInitializerError(Decl *D) { 12958 // Our main concern here is re-establishing invariants like "a 12959 // variable's type is either dependent or complete". 12960 if (!D || D->isInvalidDecl()) return; 12961 12962 VarDecl *VD = dyn_cast<VarDecl>(D); 12963 if (!VD) return; 12964 12965 // Bindings are not usable if we can't make sense of the initializer. 12966 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12967 for (auto *BD : DD->bindings()) 12968 BD->setInvalidDecl(); 12969 12970 // Auto types are meaningless if we can't make sense of the initializer. 12971 if (VD->getType()->isUndeducedType()) { 12972 D->setInvalidDecl(); 12973 return; 12974 } 12975 12976 QualType Ty = VD->getType(); 12977 if (Ty->isDependentType()) return; 12978 12979 // Require a complete type. 12980 if (RequireCompleteType(VD->getLocation(), 12981 Context.getBaseElementType(Ty), 12982 diag::err_typecheck_decl_incomplete_type)) { 12983 VD->setInvalidDecl(); 12984 return; 12985 } 12986 12987 // Require a non-abstract type. 12988 if (RequireNonAbstractType(VD->getLocation(), Ty, 12989 diag::err_abstract_type_in_decl, 12990 AbstractVariableType)) { 12991 VD->setInvalidDecl(); 12992 return; 12993 } 12994 12995 // Don't bother complaining about constructors or destructors, 12996 // though. 12997 } 12998 12999 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 13000 // If there is no declaration, there was an error parsing it. Just ignore it. 13001 if (!RealDecl) 13002 return; 13003 13004 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 13005 QualType Type = Var->getType(); 13006 13007 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 13008 if (isa<DecompositionDecl>(RealDecl)) { 13009 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 13010 Var->setInvalidDecl(); 13011 return; 13012 } 13013 13014 if (Type->isUndeducedType() && 13015 DeduceVariableDeclarationType(Var, false, nullptr)) 13016 return; 13017 13018 // C++11 [class.static.data]p3: A static data member can be declared with 13019 // the constexpr specifier; if so, its declaration shall specify 13020 // a brace-or-equal-initializer. 13021 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 13022 // the definition of a variable [...] or the declaration of a static data 13023 // member. 13024 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 13025 !Var->isThisDeclarationADemotedDefinition()) { 13026 if (Var->isStaticDataMember()) { 13027 // C++1z removes the relevant rule; the in-class declaration is always 13028 // a definition there. 13029 if (!getLangOpts().CPlusPlus17 && 13030 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13031 Diag(Var->getLocation(), 13032 diag::err_constexpr_static_mem_var_requires_init) 13033 << Var; 13034 Var->setInvalidDecl(); 13035 return; 13036 } 13037 } else { 13038 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 13039 Var->setInvalidDecl(); 13040 return; 13041 } 13042 } 13043 13044 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 13045 // be initialized. 13046 if (!Var->isInvalidDecl() && 13047 Var->getType().getAddressSpace() == LangAS::opencl_constant && 13048 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 13049 bool HasConstExprDefaultConstructor = false; 13050 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13051 for (auto *Ctor : RD->ctors()) { 13052 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 13053 Ctor->getMethodQualifiers().getAddressSpace() == 13054 LangAS::opencl_constant) { 13055 HasConstExprDefaultConstructor = true; 13056 } 13057 } 13058 } 13059 if (!HasConstExprDefaultConstructor) { 13060 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 13061 Var->setInvalidDecl(); 13062 return; 13063 } 13064 } 13065 13066 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 13067 if (Var->getStorageClass() == SC_Extern) { 13068 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 13069 << Var; 13070 Var->setInvalidDecl(); 13071 return; 13072 } 13073 if (RequireCompleteType(Var->getLocation(), Var->getType(), 13074 diag::err_typecheck_decl_incomplete_type)) { 13075 Var->setInvalidDecl(); 13076 return; 13077 } 13078 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13079 if (!RD->hasTrivialDefaultConstructor()) { 13080 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 13081 Var->setInvalidDecl(); 13082 return; 13083 } 13084 } 13085 // The declaration is unitialized, no need for further checks. 13086 return; 13087 } 13088 13089 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 13090 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 13091 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13092 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 13093 NTCUC_DefaultInitializedObject, NTCUK_Init); 13094 13095 13096 switch (DefKind) { 13097 case VarDecl::Definition: 13098 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 13099 break; 13100 13101 // We have an out-of-line definition of a static data member 13102 // that has an in-class initializer, so we type-check this like 13103 // a declaration. 13104 // 13105 LLVM_FALLTHROUGH; 13106 13107 case VarDecl::DeclarationOnly: 13108 // It's only a declaration. 13109 13110 // Block scope. C99 6.7p7: If an identifier for an object is 13111 // declared with no linkage (C99 6.2.2p6), the type for the 13112 // object shall be complete. 13113 if (!Type->isDependentType() && Var->isLocalVarDecl() && 13114 !Var->hasLinkage() && !Var->isInvalidDecl() && 13115 RequireCompleteType(Var->getLocation(), Type, 13116 diag::err_typecheck_decl_incomplete_type)) 13117 Var->setInvalidDecl(); 13118 13119 // Make sure that the type is not abstract. 13120 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13121 RequireNonAbstractType(Var->getLocation(), Type, 13122 diag::err_abstract_type_in_decl, 13123 AbstractVariableType)) 13124 Var->setInvalidDecl(); 13125 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13126 Var->getStorageClass() == SC_PrivateExtern) { 13127 Diag(Var->getLocation(), diag::warn_private_extern); 13128 Diag(Var->getLocation(), diag::note_private_extern); 13129 } 13130 13131 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 13132 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 13133 ExternalDeclarations.push_back(Var); 13134 13135 return; 13136 13137 case VarDecl::TentativeDefinition: 13138 // File scope. C99 6.9.2p2: A declaration of an identifier for an 13139 // object that has file scope without an initializer, and without a 13140 // storage-class specifier or with the storage-class specifier "static", 13141 // constitutes a tentative definition. Note: A tentative definition with 13142 // external linkage is valid (C99 6.2.2p5). 13143 if (!Var->isInvalidDecl()) { 13144 if (const IncompleteArrayType *ArrayT 13145 = Context.getAsIncompleteArrayType(Type)) { 13146 if (RequireCompleteSizedType( 13147 Var->getLocation(), ArrayT->getElementType(), 13148 diag::err_array_incomplete_or_sizeless_type)) 13149 Var->setInvalidDecl(); 13150 } else if (Var->getStorageClass() == SC_Static) { 13151 // C99 6.9.2p3: If the declaration of an identifier for an object is 13152 // a tentative definition and has internal linkage (C99 6.2.2p3), the 13153 // declared type shall not be an incomplete type. 13154 // NOTE: code such as the following 13155 // static struct s; 13156 // struct s { int a; }; 13157 // is accepted by gcc. Hence here we issue a warning instead of 13158 // an error and we do not invalidate the static declaration. 13159 // NOTE: to avoid multiple warnings, only check the first declaration. 13160 if (Var->isFirstDecl()) 13161 RequireCompleteType(Var->getLocation(), Type, 13162 diag::ext_typecheck_decl_incomplete_type); 13163 } 13164 } 13165 13166 // Record the tentative definition; we're done. 13167 if (!Var->isInvalidDecl()) 13168 TentativeDefinitions.push_back(Var); 13169 return; 13170 } 13171 13172 // Provide a specific diagnostic for uninitialized variable 13173 // definitions with incomplete array type. 13174 if (Type->isIncompleteArrayType()) { 13175 Diag(Var->getLocation(), 13176 diag::err_typecheck_incomplete_array_needs_initializer); 13177 Var->setInvalidDecl(); 13178 return; 13179 } 13180 13181 // Provide a specific diagnostic for uninitialized variable 13182 // definitions with reference type. 13183 if (Type->isReferenceType()) { 13184 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 13185 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 13186 Var->setInvalidDecl(); 13187 return; 13188 } 13189 13190 // Do not attempt to type-check the default initializer for a 13191 // variable with dependent type. 13192 if (Type->isDependentType()) 13193 return; 13194 13195 if (Var->isInvalidDecl()) 13196 return; 13197 13198 if (!Var->hasAttr<AliasAttr>()) { 13199 if (RequireCompleteType(Var->getLocation(), 13200 Context.getBaseElementType(Type), 13201 diag::err_typecheck_decl_incomplete_type)) { 13202 Var->setInvalidDecl(); 13203 return; 13204 } 13205 } else { 13206 return; 13207 } 13208 13209 // The variable can not have an abstract class type. 13210 if (RequireNonAbstractType(Var->getLocation(), Type, 13211 diag::err_abstract_type_in_decl, 13212 AbstractVariableType)) { 13213 Var->setInvalidDecl(); 13214 return; 13215 } 13216 13217 // Check for jumps past the implicit initializer. C++0x 13218 // clarifies that this applies to a "variable with automatic 13219 // storage duration", not a "local variable". 13220 // C++11 [stmt.dcl]p3 13221 // A program that jumps from a point where a variable with automatic 13222 // storage duration is not in scope to a point where it is in scope is 13223 // ill-formed unless the variable has scalar type, class type with a 13224 // trivial default constructor and a trivial destructor, a cv-qualified 13225 // version of one of these types, or an array of one of the preceding 13226 // types and is declared without an initializer. 13227 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 13228 if (const RecordType *Record 13229 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 13230 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 13231 // Mark the function (if we're in one) for further checking even if the 13232 // looser rules of C++11 do not require such checks, so that we can 13233 // diagnose incompatibilities with C++98. 13234 if (!CXXRecord->isPOD()) 13235 setFunctionHasBranchProtectedScope(); 13236 } 13237 } 13238 // In OpenCL, we can't initialize objects in the __local address space, 13239 // even implicitly, so don't synthesize an implicit initializer. 13240 if (getLangOpts().OpenCL && 13241 Var->getType().getAddressSpace() == LangAS::opencl_local) 13242 return; 13243 // C++03 [dcl.init]p9: 13244 // If no initializer is specified for an object, and the 13245 // object is of (possibly cv-qualified) non-POD class type (or 13246 // array thereof), the object shall be default-initialized; if 13247 // the object is of const-qualified type, the underlying class 13248 // type shall have a user-declared default 13249 // constructor. Otherwise, if no initializer is specified for 13250 // a non- static object, the object and its subobjects, if 13251 // any, have an indeterminate initial value); if the object 13252 // or any of its subobjects are of const-qualified type, the 13253 // program is ill-formed. 13254 // C++0x [dcl.init]p11: 13255 // If no initializer is specified for an object, the object is 13256 // default-initialized; [...]. 13257 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 13258 InitializationKind Kind 13259 = InitializationKind::CreateDefault(Var->getLocation()); 13260 13261 InitializationSequence InitSeq(*this, Entity, Kind, None); 13262 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 13263 13264 if (Init.get()) { 13265 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 13266 // This is important for template substitution. 13267 Var->setInitStyle(VarDecl::CallInit); 13268 } else if (Init.isInvalid()) { 13269 // If default-init fails, attach a recovery-expr initializer to track 13270 // that initialization was attempted and failed. 13271 auto RecoveryExpr = 13272 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 13273 if (RecoveryExpr.get()) 13274 Var->setInit(RecoveryExpr.get()); 13275 } 13276 13277 CheckCompleteVariableDeclaration(Var); 13278 } 13279 } 13280 13281 void Sema::ActOnCXXForRangeDecl(Decl *D) { 13282 // If there is no declaration, there was an error parsing it. Ignore it. 13283 if (!D) 13284 return; 13285 13286 VarDecl *VD = dyn_cast<VarDecl>(D); 13287 if (!VD) { 13288 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 13289 D->setInvalidDecl(); 13290 return; 13291 } 13292 13293 VD->setCXXForRangeDecl(true); 13294 13295 // for-range-declaration cannot be given a storage class specifier. 13296 int Error = -1; 13297 switch (VD->getStorageClass()) { 13298 case SC_None: 13299 break; 13300 case SC_Extern: 13301 Error = 0; 13302 break; 13303 case SC_Static: 13304 Error = 1; 13305 break; 13306 case SC_PrivateExtern: 13307 Error = 2; 13308 break; 13309 case SC_Auto: 13310 Error = 3; 13311 break; 13312 case SC_Register: 13313 Error = 4; 13314 break; 13315 } 13316 13317 // for-range-declaration cannot be given a storage class specifier con't. 13318 switch (VD->getTSCSpec()) { 13319 case TSCS_thread_local: 13320 Error = 6; 13321 break; 13322 case TSCS___thread: 13323 case TSCS__Thread_local: 13324 case TSCS_unspecified: 13325 break; 13326 } 13327 13328 if (Error != -1) { 13329 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 13330 << VD << Error; 13331 D->setInvalidDecl(); 13332 } 13333 } 13334 13335 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13336 IdentifierInfo *Ident, 13337 ParsedAttributes &Attrs) { 13338 // C++1y [stmt.iter]p1: 13339 // A range-based for statement of the form 13340 // for ( for-range-identifier : for-range-initializer ) statement 13341 // is equivalent to 13342 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13343 DeclSpec DS(Attrs.getPool().getFactory()); 13344 13345 const char *PrevSpec; 13346 unsigned DiagID; 13347 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13348 getPrintingPolicy()); 13349 13350 Declarator D(DS, DeclaratorContext::ForInit); 13351 D.SetIdentifier(Ident, IdentLoc); 13352 D.takeAttributes(Attrs); 13353 13354 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13355 IdentLoc); 13356 Decl *Var = ActOnDeclarator(S, D); 13357 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13358 FinalizeDeclaration(Var); 13359 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13360 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 13361 : IdentLoc); 13362 } 13363 13364 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13365 if (var->isInvalidDecl()) return; 13366 13367 MaybeAddCUDAConstantAttr(var); 13368 13369 if (getLangOpts().OpenCL) { 13370 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13371 // initialiser 13372 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13373 !var->hasInit()) { 13374 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13375 << 1 /*Init*/; 13376 var->setInvalidDecl(); 13377 return; 13378 } 13379 } 13380 13381 // In Objective-C, don't allow jumps past the implicit initialization of a 13382 // local retaining variable. 13383 if (getLangOpts().ObjC && 13384 var->hasLocalStorage()) { 13385 switch (var->getType().getObjCLifetime()) { 13386 case Qualifiers::OCL_None: 13387 case Qualifiers::OCL_ExplicitNone: 13388 case Qualifiers::OCL_Autoreleasing: 13389 break; 13390 13391 case Qualifiers::OCL_Weak: 13392 case Qualifiers::OCL_Strong: 13393 setFunctionHasBranchProtectedScope(); 13394 break; 13395 } 13396 } 13397 13398 if (var->hasLocalStorage() && 13399 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13400 setFunctionHasBranchProtectedScope(); 13401 13402 // Warn about externally-visible variables being defined without a 13403 // prior declaration. We only want to do this for global 13404 // declarations, but we also specifically need to avoid doing it for 13405 // class members because the linkage of an anonymous class can 13406 // change if it's later given a typedef name. 13407 if (var->isThisDeclarationADefinition() && 13408 var->getDeclContext()->getRedeclContext()->isFileContext() && 13409 var->isExternallyVisible() && var->hasLinkage() && 13410 !var->isInline() && !var->getDescribedVarTemplate() && 13411 !isa<VarTemplatePartialSpecializationDecl>(var) && 13412 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13413 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13414 var->getLocation())) { 13415 // Find a previous declaration that's not a definition. 13416 VarDecl *prev = var->getPreviousDecl(); 13417 while (prev && prev->isThisDeclarationADefinition()) 13418 prev = prev->getPreviousDecl(); 13419 13420 if (!prev) { 13421 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13422 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13423 << /* variable */ 0; 13424 } 13425 } 13426 13427 // Cache the result of checking for constant initialization. 13428 Optional<bool> CacheHasConstInit; 13429 const Expr *CacheCulprit = nullptr; 13430 auto checkConstInit = [&]() mutable { 13431 if (!CacheHasConstInit) 13432 CacheHasConstInit = var->getInit()->isConstantInitializer( 13433 Context, var->getType()->isReferenceType(), &CacheCulprit); 13434 return *CacheHasConstInit; 13435 }; 13436 13437 if (var->getTLSKind() == VarDecl::TLS_Static) { 13438 if (var->getType().isDestructedType()) { 13439 // GNU C++98 edits for __thread, [basic.start.term]p3: 13440 // The type of an object with thread storage duration shall not 13441 // have a non-trivial destructor. 13442 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13443 if (getLangOpts().CPlusPlus11) 13444 Diag(var->getLocation(), diag::note_use_thread_local); 13445 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13446 if (!checkConstInit()) { 13447 // GNU C++98 edits for __thread, [basic.start.init]p4: 13448 // An object of thread storage duration shall not require dynamic 13449 // initialization. 13450 // FIXME: Need strict checking here. 13451 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13452 << CacheCulprit->getSourceRange(); 13453 if (getLangOpts().CPlusPlus11) 13454 Diag(var->getLocation(), diag::note_use_thread_local); 13455 } 13456 } 13457 } 13458 13459 13460 if (!var->getType()->isStructureType() && var->hasInit() && 13461 isa<InitListExpr>(var->getInit())) { 13462 const auto *ILE = cast<InitListExpr>(var->getInit()); 13463 unsigned NumInits = ILE->getNumInits(); 13464 if (NumInits > 2) 13465 for (unsigned I = 0; I < NumInits; ++I) { 13466 const auto *Init = ILE->getInit(I); 13467 if (!Init) 13468 break; 13469 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13470 if (!SL) 13471 break; 13472 13473 unsigned NumConcat = SL->getNumConcatenated(); 13474 // Diagnose missing comma in string array initialization. 13475 // Do not warn when all the elements in the initializer are concatenated 13476 // together. Do not warn for macros too. 13477 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13478 bool OnlyOneMissingComma = true; 13479 for (unsigned J = I + 1; J < NumInits; ++J) { 13480 const auto *Init = ILE->getInit(J); 13481 if (!Init) 13482 break; 13483 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13484 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13485 OnlyOneMissingComma = false; 13486 break; 13487 } 13488 } 13489 13490 if (OnlyOneMissingComma) { 13491 SmallVector<FixItHint, 1> Hints; 13492 for (unsigned i = 0; i < NumConcat - 1; ++i) 13493 Hints.push_back(FixItHint::CreateInsertion( 13494 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13495 13496 Diag(SL->getStrTokenLoc(1), 13497 diag::warn_concatenated_literal_array_init) 13498 << Hints; 13499 Diag(SL->getBeginLoc(), 13500 diag::note_concatenated_string_literal_silence); 13501 } 13502 // In any case, stop now. 13503 break; 13504 } 13505 } 13506 } 13507 13508 13509 QualType type = var->getType(); 13510 13511 if (var->hasAttr<BlocksAttr>()) 13512 getCurFunction()->addByrefBlockVar(var); 13513 13514 Expr *Init = var->getInit(); 13515 bool GlobalStorage = var->hasGlobalStorage(); 13516 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13517 QualType baseType = Context.getBaseElementType(type); 13518 bool HasConstInit = true; 13519 13520 // Check whether the initializer is sufficiently constant. 13521 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13522 !Init->isValueDependent() && 13523 (GlobalStorage || var->isConstexpr() || 13524 var->mightBeUsableInConstantExpressions(Context))) { 13525 // If this variable might have a constant initializer or might be usable in 13526 // constant expressions, check whether or not it actually is now. We can't 13527 // do this lazily, because the result might depend on things that change 13528 // later, such as which constexpr functions happen to be defined. 13529 SmallVector<PartialDiagnosticAt, 8> Notes; 13530 if (!getLangOpts().CPlusPlus11) { 13531 // Prior to C++11, in contexts where a constant initializer is required, 13532 // the set of valid constant initializers is described by syntactic rules 13533 // in [expr.const]p2-6. 13534 // FIXME: Stricter checking for these rules would be useful for constinit / 13535 // -Wglobal-constructors. 13536 HasConstInit = checkConstInit(); 13537 13538 // Compute and cache the constant value, and remember that we have a 13539 // constant initializer. 13540 if (HasConstInit) { 13541 (void)var->checkForConstantInitialization(Notes); 13542 Notes.clear(); 13543 } else if (CacheCulprit) { 13544 Notes.emplace_back(CacheCulprit->getExprLoc(), 13545 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13546 Notes.back().second << CacheCulprit->getSourceRange(); 13547 } 13548 } else { 13549 // Evaluate the initializer to see if it's a constant initializer. 13550 HasConstInit = var->checkForConstantInitialization(Notes); 13551 } 13552 13553 if (HasConstInit) { 13554 // FIXME: Consider replacing the initializer with a ConstantExpr. 13555 } else if (var->isConstexpr()) { 13556 SourceLocation DiagLoc = var->getLocation(); 13557 // If the note doesn't add any useful information other than a source 13558 // location, fold it into the primary diagnostic. 13559 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13560 diag::note_invalid_subexpr_in_const_expr) { 13561 DiagLoc = Notes[0].first; 13562 Notes.clear(); 13563 } 13564 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13565 << var << Init->getSourceRange(); 13566 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13567 Diag(Notes[I].first, Notes[I].second); 13568 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13569 auto *Attr = var->getAttr<ConstInitAttr>(); 13570 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13571 << Init->getSourceRange(); 13572 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13573 << Attr->getRange() << Attr->isConstinit(); 13574 for (auto &it : Notes) 13575 Diag(it.first, it.second); 13576 } else if (IsGlobal && 13577 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13578 var->getLocation())) { 13579 // Warn about globals which don't have a constant initializer. Don't 13580 // warn about globals with a non-trivial destructor because we already 13581 // warned about them. 13582 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13583 if (!(RD && !RD->hasTrivialDestructor())) { 13584 // checkConstInit() here permits trivial default initialization even in 13585 // C++11 onwards, where such an initializer is not a constant initializer 13586 // but nonetheless doesn't require a global constructor. 13587 if (!checkConstInit()) 13588 Diag(var->getLocation(), diag::warn_global_constructor) 13589 << Init->getSourceRange(); 13590 } 13591 } 13592 } 13593 13594 // Apply section attributes and pragmas to global variables. 13595 if (GlobalStorage && var->isThisDeclarationADefinition() && 13596 !inTemplateInstantiation()) { 13597 PragmaStack<StringLiteral *> *Stack = nullptr; 13598 int SectionFlags = ASTContext::PSF_Read; 13599 if (var->getType().isConstQualified()) { 13600 if (HasConstInit) 13601 Stack = &ConstSegStack; 13602 else { 13603 Stack = &BSSSegStack; 13604 SectionFlags |= ASTContext::PSF_Write; 13605 } 13606 } else if (var->hasInit() && HasConstInit) { 13607 Stack = &DataSegStack; 13608 SectionFlags |= ASTContext::PSF_Write; 13609 } else { 13610 Stack = &BSSSegStack; 13611 SectionFlags |= ASTContext::PSF_Write; 13612 } 13613 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13614 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13615 SectionFlags |= ASTContext::PSF_Implicit; 13616 UnifySection(SA->getName(), SectionFlags, var); 13617 } else if (Stack->CurrentValue) { 13618 SectionFlags |= ASTContext::PSF_Implicit; 13619 auto SectionName = Stack->CurrentValue->getString(); 13620 var->addAttr(SectionAttr::CreateImplicit( 13621 Context, SectionName, Stack->CurrentPragmaLocation, 13622 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13623 if (UnifySection(SectionName, SectionFlags, var)) 13624 var->dropAttr<SectionAttr>(); 13625 } 13626 13627 // Apply the init_seg attribute if this has an initializer. If the 13628 // initializer turns out to not be dynamic, we'll end up ignoring this 13629 // attribute. 13630 if (CurInitSeg && var->getInit()) 13631 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13632 CurInitSegLoc, 13633 AttributeCommonInfo::AS_Pragma)); 13634 } 13635 13636 // All the following checks are C++ only. 13637 if (!getLangOpts().CPlusPlus) { 13638 // If this variable must be emitted, add it as an initializer for the 13639 // current module. 13640 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13641 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13642 return; 13643 } 13644 13645 // Require the destructor. 13646 if (!type->isDependentType()) 13647 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13648 FinalizeVarWithDestructor(var, recordType); 13649 13650 // If this variable must be emitted, add it as an initializer for the current 13651 // module. 13652 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13653 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13654 13655 // Build the bindings if this is a structured binding declaration. 13656 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13657 CheckCompleteDecompositionDeclaration(DD); 13658 } 13659 13660 /// Check if VD needs to be dllexport/dllimport due to being in a 13661 /// dllexport/import function. 13662 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13663 assert(VD->isStaticLocal()); 13664 13665 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13666 13667 // Find outermost function when VD is in lambda function. 13668 while (FD && !getDLLAttr(FD) && 13669 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13670 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13671 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13672 } 13673 13674 if (!FD) 13675 return; 13676 13677 // Static locals inherit dll attributes from their function. 13678 if (Attr *A = getDLLAttr(FD)) { 13679 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13680 NewAttr->setInherited(true); 13681 VD->addAttr(NewAttr); 13682 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13683 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13684 NewAttr->setInherited(true); 13685 VD->addAttr(NewAttr); 13686 13687 // Export this function to enforce exporting this static variable even 13688 // if it is not used in this compilation unit. 13689 if (!FD->hasAttr<DLLExportAttr>()) 13690 FD->addAttr(NewAttr); 13691 13692 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13693 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13694 NewAttr->setInherited(true); 13695 VD->addAttr(NewAttr); 13696 } 13697 } 13698 13699 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13700 /// any semantic actions necessary after any initializer has been attached. 13701 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13702 // Note that we are no longer parsing the initializer for this declaration. 13703 ParsingInitForAutoVars.erase(ThisDecl); 13704 13705 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13706 if (!VD) 13707 return; 13708 13709 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13710 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13711 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13712 if (PragmaClangBSSSection.Valid) 13713 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13714 Context, PragmaClangBSSSection.SectionName, 13715 PragmaClangBSSSection.PragmaLocation, 13716 AttributeCommonInfo::AS_Pragma)); 13717 if (PragmaClangDataSection.Valid) 13718 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13719 Context, PragmaClangDataSection.SectionName, 13720 PragmaClangDataSection.PragmaLocation, 13721 AttributeCommonInfo::AS_Pragma)); 13722 if (PragmaClangRodataSection.Valid) 13723 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13724 Context, PragmaClangRodataSection.SectionName, 13725 PragmaClangRodataSection.PragmaLocation, 13726 AttributeCommonInfo::AS_Pragma)); 13727 if (PragmaClangRelroSection.Valid) 13728 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13729 Context, PragmaClangRelroSection.SectionName, 13730 PragmaClangRelroSection.PragmaLocation, 13731 AttributeCommonInfo::AS_Pragma)); 13732 } 13733 13734 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13735 for (auto *BD : DD->bindings()) { 13736 FinalizeDeclaration(BD); 13737 } 13738 } 13739 13740 checkAttributesAfterMerging(*this, *VD); 13741 13742 // Perform TLS alignment check here after attributes attached to the variable 13743 // which may affect the alignment have been processed. Only perform the check 13744 // if the target has a maximum TLS alignment (zero means no constraints). 13745 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13746 // Protect the check so that it's not performed on dependent types and 13747 // dependent alignments (we can't determine the alignment in that case). 13748 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13749 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13750 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13751 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13752 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13753 << (unsigned)MaxAlignChars.getQuantity(); 13754 } 13755 } 13756 } 13757 13758 if (VD->isStaticLocal()) 13759 CheckStaticLocalForDllExport(VD); 13760 13761 // Perform check for initializers of device-side global variables. 13762 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13763 // 7.5). We must also apply the same checks to all __shared__ 13764 // variables whether they are local or not. CUDA also allows 13765 // constant initializers for __constant__ and __device__ variables. 13766 if (getLangOpts().CUDA) 13767 checkAllowedCUDAInitializer(VD); 13768 13769 // Grab the dllimport or dllexport attribute off of the VarDecl. 13770 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13771 13772 // Imported static data members cannot be defined out-of-line. 13773 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13774 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13775 VD->isThisDeclarationADefinition()) { 13776 // We allow definitions of dllimport class template static data members 13777 // with a warning. 13778 CXXRecordDecl *Context = 13779 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13780 bool IsClassTemplateMember = 13781 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13782 Context->getDescribedClassTemplate(); 13783 13784 Diag(VD->getLocation(), 13785 IsClassTemplateMember 13786 ? diag::warn_attribute_dllimport_static_field_definition 13787 : diag::err_attribute_dllimport_static_field_definition); 13788 Diag(IA->getLocation(), diag::note_attribute); 13789 if (!IsClassTemplateMember) 13790 VD->setInvalidDecl(); 13791 } 13792 } 13793 13794 // dllimport/dllexport variables cannot be thread local, their TLS index 13795 // isn't exported with the variable. 13796 if (DLLAttr && VD->getTLSKind()) { 13797 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13798 if (F && getDLLAttr(F)) { 13799 assert(VD->isStaticLocal()); 13800 // But if this is a static local in a dlimport/dllexport function, the 13801 // function will never be inlined, which means the var would never be 13802 // imported, so having it marked import/export is safe. 13803 } else { 13804 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13805 << DLLAttr; 13806 VD->setInvalidDecl(); 13807 } 13808 } 13809 13810 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13811 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13812 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13813 << Attr; 13814 VD->dropAttr<UsedAttr>(); 13815 } 13816 } 13817 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13818 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13819 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13820 << Attr; 13821 VD->dropAttr<RetainAttr>(); 13822 } 13823 } 13824 13825 const DeclContext *DC = VD->getDeclContext(); 13826 // If there's a #pragma GCC visibility in scope, and this isn't a class 13827 // member, set the visibility of this variable. 13828 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13829 AddPushedVisibilityAttribute(VD); 13830 13831 // FIXME: Warn on unused var template partial specializations. 13832 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13833 MarkUnusedFileScopedDecl(VD); 13834 13835 // Now we have parsed the initializer and can update the table of magic 13836 // tag values. 13837 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13838 !VD->getType()->isIntegralOrEnumerationType()) 13839 return; 13840 13841 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13842 const Expr *MagicValueExpr = VD->getInit(); 13843 if (!MagicValueExpr) { 13844 continue; 13845 } 13846 Optional<llvm::APSInt> MagicValueInt; 13847 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13848 Diag(I->getRange().getBegin(), 13849 diag::err_type_tag_for_datatype_not_ice) 13850 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13851 continue; 13852 } 13853 if (MagicValueInt->getActiveBits() > 64) { 13854 Diag(I->getRange().getBegin(), 13855 diag::err_type_tag_for_datatype_too_large) 13856 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13857 continue; 13858 } 13859 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13860 RegisterTypeTagForDatatype(I->getArgumentKind(), 13861 MagicValue, 13862 I->getMatchingCType(), 13863 I->getLayoutCompatible(), 13864 I->getMustBeNull()); 13865 } 13866 } 13867 13868 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13869 auto *VD = dyn_cast<VarDecl>(DD); 13870 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13871 } 13872 13873 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13874 ArrayRef<Decl *> Group) { 13875 SmallVector<Decl*, 8> Decls; 13876 13877 if (DS.isTypeSpecOwned()) 13878 Decls.push_back(DS.getRepAsDecl()); 13879 13880 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13881 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13882 bool DiagnosedMultipleDecomps = false; 13883 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13884 bool DiagnosedNonDeducedAuto = false; 13885 13886 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13887 if (Decl *D = Group[i]) { 13888 // For declarators, there are some additional syntactic-ish checks we need 13889 // to perform. 13890 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13891 if (!FirstDeclaratorInGroup) 13892 FirstDeclaratorInGroup = DD; 13893 if (!FirstDecompDeclaratorInGroup) 13894 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13895 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13896 !hasDeducedAuto(DD)) 13897 FirstNonDeducedAutoInGroup = DD; 13898 13899 if (FirstDeclaratorInGroup != DD) { 13900 // A decomposition declaration cannot be combined with any other 13901 // declaration in the same group. 13902 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13903 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13904 diag::err_decomp_decl_not_alone) 13905 << FirstDeclaratorInGroup->getSourceRange() 13906 << DD->getSourceRange(); 13907 DiagnosedMultipleDecomps = true; 13908 } 13909 13910 // A declarator that uses 'auto' in any way other than to declare a 13911 // variable with a deduced type cannot be combined with any other 13912 // declarator in the same group. 13913 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13914 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13915 diag::err_auto_non_deduced_not_alone) 13916 << FirstNonDeducedAutoInGroup->getType() 13917 ->hasAutoForTrailingReturnType() 13918 << FirstDeclaratorInGroup->getSourceRange() 13919 << DD->getSourceRange(); 13920 DiagnosedNonDeducedAuto = true; 13921 } 13922 } 13923 } 13924 13925 Decls.push_back(D); 13926 } 13927 } 13928 13929 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13930 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13931 handleTagNumbering(Tag, S); 13932 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13933 getLangOpts().CPlusPlus) 13934 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13935 } 13936 } 13937 13938 return BuildDeclaratorGroup(Decls); 13939 } 13940 13941 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13942 /// group, performing any necessary semantic checking. 13943 Sema::DeclGroupPtrTy 13944 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13945 // C++14 [dcl.spec.auto]p7: (DR1347) 13946 // If the type that replaces the placeholder type is not the same in each 13947 // deduction, the program is ill-formed. 13948 if (Group.size() > 1) { 13949 QualType Deduced; 13950 VarDecl *DeducedDecl = nullptr; 13951 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13952 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13953 if (!D || D->isInvalidDecl()) 13954 break; 13955 DeducedType *DT = D->getType()->getContainedDeducedType(); 13956 if (!DT || DT->getDeducedType().isNull()) 13957 continue; 13958 if (Deduced.isNull()) { 13959 Deduced = DT->getDeducedType(); 13960 DeducedDecl = D; 13961 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13962 auto *AT = dyn_cast<AutoType>(DT); 13963 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13964 diag::err_auto_different_deductions) 13965 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13966 << DeducedDecl->getDeclName() << DT->getDeducedType() 13967 << D->getDeclName(); 13968 if (DeducedDecl->hasInit()) 13969 Dia << DeducedDecl->getInit()->getSourceRange(); 13970 if (D->getInit()) 13971 Dia << D->getInit()->getSourceRange(); 13972 D->setInvalidDecl(); 13973 break; 13974 } 13975 } 13976 } 13977 13978 ActOnDocumentableDecls(Group); 13979 13980 return DeclGroupPtrTy::make( 13981 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13982 } 13983 13984 void Sema::ActOnDocumentableDecl(Decl *D) { 13985 ActOnDocumentableDecls(D); 13986 } 13987 13988 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13989 // Don't parse the comment if Doxygen diagnostics are ignored. 13990 if (Group.empty() || !Group[0]) 13991 return; 13992 13993 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13994 Group[0]->getLocation()) && 13995 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13996 Group[0]->getLocation())) 13997 return; 13998 13999 if (Group.size() >= 2) { 14000 // This is a decl group. Normally it will contain only declarations 14001 // produced from declarator list. But in case we have any definitions or 14002 // additional declaration references: 14003 // 'typedef struct S {} S;' 14004 // 'typedef struct S *S;' 14005 // 'struct S *pS;' 14006 // FinalizeDeclaratorGroup adds these as separate declarations. 14007 Decl *MaybeTagDecl = Group[0]; 14008 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 14009 Group = Group.slice(1); 14010 } 14011 } 14012 14013 // FIMXE: We assume every Decl in the group is in the same file. 14014 // This is false when preprocessor constructs the group from decls in 14015 // different files (e. g. macros or #include). 14016 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 14017 } 14018 14019 /// Common checks for a parameter-declaration that should apply to both function 14020 /// parameters and non-type template parameters. 14021 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 14022 // Check that there are no default arguments inside the type of this 14023 // parameter. 14024 if (getLangOpts().CPlusPlus) 14025 CheckExtraCXXDefaultArguments(D); 14026 14027 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 14028 if (D.getCXXScopeSpec().isSet()) { 14029 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 14030 << D.getCXXScopeSpec().getRange(); 14031 } 14032 14033 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 14034 // simple identifier except [...irrelevant cases...]. 14035 switch (D.getName().getKind()) { 14036 case UnqualifiedIdKind::IK_Identifier: 14037 break; 14038 14039 case UnqualifiedIdKind::IK_OperatorFunctionId: 14040 case UnqualifiedIdKind::IK_ConversionFunctionId: 14041 case UnqualifiedIdKind::IK_LiteralOperatorId: 14042 case UnqualifiedIdKind::IK_ConstructorName: 14043 case UnqualifiedIdKind::IK_DestructorName: 14044 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14045 case UnqualifiedIdKind::IK_DeductionGuideName: 14046 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 14047 << GetNameForDeclarator(D).getName(); 14048 break; 14049 14050 case UnqualifiedIdKind::IK_TemplateId: 14051 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14052 // GetNameForDeclarator would not produce a useful name in this case. 14053 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 14054 break; 14055 } 14056 } 14057 14058 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 14059 /// to introduce parameters into function prototype scope. 14060 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 14061 const DeclSpec &DS = D.getDeclSpec(); 14062 14063 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 14064 14065 // C++03 [dcl.stc]p2 also permits 'auto'. 14066 StorageClass SC = SC_None; 14067 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 14068 SC = SC_Register; 14069 // In C++11, the 'register' storage class specifier is deprecated. 14070 // In C++17, it is not allowed, but we tolerate it as an extension. 14071 if (getLangOpts().CPlusPlus11) { 14072 Diag(DS.getStorageClassSpecLoc(), 14073 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 14074 : diag::warn_deprecated_register) 14075 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 14076 } 14077 } else if (getLangOpts().CPlusPlus && 14078 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 14079 SC = SC_Auto; 14080 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 14081 Diag(DS.getStorageClassSpecLoc(), 14082 diag::err_invalid_storage_class_in_func_decl); 14083 D.getMutableDeclSpec().ClearStorageClassSpecs(); 14084 } 14085 14086 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 14087 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 14088 << DeclSpec::getSpecifierName(TSCS); 14089 if (DS.isInlineSpecified()) 14090 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 14091 << getLangOpts().CPlusPlus17; 14092 if (DS.hasConstexprSpecifier()) 14093 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 14094 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 14095 14096 DiagnoseFunctionSpecifiers(DS); 14097 14098 CheckFunctionOrTemplateParamDeclarator(S, D); 14099 14100 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14101 QualType parmDeclType = TInfo->getType(); 14102 14103 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 14104 IdentifierInfo *II = D.getIdentifier(); 14105 if (II) { 14106 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 14107 ForVisibleRedeclaration); 14108 LookupName(R, S); 14109 if (R.isSingleResult()) { 14110 NamedDecl *PrevDecl = R.getFoundDecl(); 14111 if (PrevDecl->isTemplateParameter()) { 14112 // Maybe we will complain about the shadowed template parameter. 14113 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14114 // Just pretend that we didn't see the previous declaration. 14115 PrevDecl = nullptr; 14116 } else if (S->isDeclScope(PrevDecl)) { 14117 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 14118 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14119 14120 // Recover by removing the name 14121 II = nullptr; 14122 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 14123 D.setInvalidType(true); 14124 } 14125 } 14126 } 14127 14128 // Temporarily put parameter variables in the translation unit, not 14129 // the enclosing context. This prevents them from accidentally 14130 // looking like class members in C++. 14131 ParmVarDecl *New = 14132 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 14133 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 14134 14135 if (D.isInvalidType()) 14136 New->setInvalidDecl(); 14137 14138 assert(S->isFunctionPrototypeScope()); 14139 assert(S->getFunctionPrototypeDepth() >= 1); 14140 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 14141 S->getNextFunctionPrototypeIndex()); 14142 14143 // Add the parameter declaration into this scope. 14144 S->AddDecl(New); 14145 if (II) 14146 IdResolver.AddDecl(New); 14147 14148 ProcessDeclAttributes(S, New, D); 14149 14150 if (D.getDeclSpec().isModulePrivateSpecified()) 14151 Diag(New->getLocation(), diag::err_module_private_local) 14152 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14153 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14154 14155 if (New->hasAttr<BlocksAttr>()) { 14156 Diag(New->getLocation(), diag::err_block_on_nonlocal); 14157 } 14158 14159 if (getLangOpts().OpenCL) 14160 deduceOpenCLAddressSpace(New); 14161 14162 return New; 14163 } 14164 14165 /// Synthesizes a variable for a parameter arising from a 14166 /// typedef. 14167 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 14168 SourceLocation Loc, 14169 QualType T) { 14170 /* FIXME: setting StartLoc == Loc. 14171 Would it be worth to modify callers so as to provide proper source 14172 location for the unnamed parameters, embedding the parameter's type? */ 14173 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 14174 T, Context.getTrivialTypeSourceInfo(T, Loc), 14175 SC_None, nullptr); 14176 Param->setImplicit(); 14177 return Param; 14178 } 14179 14180 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 14181 // Don't diagnose unused-parameter errors in template instantiations; we 14182 // will already have done so in the template itself. 14183 if (inTemplateInstantiation()) 14184 return; 14185 14186 for (const ParmVarDecl *Parameter : Parameters) { 14187 if (!Parameter->isReferenced() && Parameter->getDeclName() && 14188 !Parameter->hasAttr<UnusedAttr>()) { 14189 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 14190 << Parameter->getDeclName(); 14191 } 14192 } 14193 } 14194 14195 void Sema::DiagnoseSizeOfParametersAndReturnValue( 14196 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 14197 if (LangOpts.NumLargeByValueCopy == 0) // No check. 14198 return; 14199 14200 // Warn if the return value is pass-by-value and larger than the specified 14201 // threshold. 14202 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 14203 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 14204 if (Size > LangOpts.NumLargeByValueCopy) 14205 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 14206 } 14207 14208 // Warn if any parameter is pass-by-value and larger than the specified 14209 // threshold. 14210 for (const ParmVarDecl *Parameter : Parameters) { 14211 QualType T = Parameter->getType(); 14212 if (T->isDependentType() || !T.isPODType(Context)) 14213 continue; 14214 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 14215 if (Size > LangOpts.NumLargeByValueCopy) 14216 Diag(Parameter->getLocation(), diag::warn_parameter_size) 14217 << Parameter << Size; 14218 } 14219 } 14220 14221 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 14222 SourceLocation NameLoc, IdentifierInfo *Name, 14223 QualType T, TypeSourceInfo *TSInfo, 14224 StorageClass SC) { 14225 // In ARC, infer a lifetime qualifier for appropriate parameter types. 14226 if (getLangOpts().ObjCAutoRefCount && 14227 T.getObjCLifetime() == Qualifiers::OCL_None && 14228 T->isObjCLifetimeType()) { 14229 14230 Qualifiers::ObjCLifetime lifetime; 14231 14232 // Special cases for arrays: 14233 // - if it's const, use __unsafe_unretained 14234 // - otherwise, it's an error 14235 if (T->isArrayType()) { 14236 if (!T.isConstQualified()) { 14237 if (DelayedDiagnostics.shouldDelayDiagnostics()) 14238 DelayedDiagnostics.add( 14239 sema::DelayedDiagnostic::makeForbiddenType( 14240 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 14241 else 14242 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 14243 << TSInfo->getTypeLoc().getSourceRange(); 14244 } 14245 lifetime = Qualifiers::OCL_ExplicitNone; 14246 } else { 14247 lifetime = T->getObjCARCImplicitLifetime(); 14248 } 14249 T = Context.getLifetimeQualifiedType(T, lifetime); 14250 } 14251 14252 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 14253 Context.getAdjustedParameterType(T), 14254 TSInfo, SC, nullptr); 14255 14256 // Make a note if we created a new pack in the scope of a lambda, so that 14257 // we know that references to that pack must also be expanded within the 14258 // lambda scope. 14259 if (New->isParameterPack()) 14260 if (auto *LSI = getEnclosingLambda()) 14261 LSI->LocalPacks.push_back(New); 14262 14263 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 14264 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14265 checkNonTrivialCUnion(New->getType(), New->getLocation(), 14266 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 14267 14268 // Parameters can not be abstract class types. 14269 // For record types, this is done by the AbstractClassUsageDiagnoser once 14270 // the class has been completely parsed. 14271 if (!CurContext->isRecord() && 14272 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 14273 AbstractParamType)) 14274 New->setInvalidDecl(); 14275 14276 // Parameter declarators cannot be interface types. All ObjC objects are 14277 // passed by reference. 14278 if (T->isObjCObjectType()) { 14279 SourceLocation TypeEndLoc = 14280 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 14281 Diag(NameLoc, 14282 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 14283 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 14284 T = Context.getObjCObjectPointerType(T); 14285 New->setType(T); 14286 } 14287 14288 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 14289 // duration shall not be qualified by an address-space qualifier." 14290 // Since all parameters have automatic store duration, they can not have 14291 // an address space. 14292 if (T.getAddressSpace() != LangAS::Default && 14293 // OpenCL allows function arguments declared to be an array of a type 14294 // to be qualified with an address space. 14295 !(getLangOpts().OpenCL && 14296 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 14297 Diag(NameLoc, diag::err_arg_with_address_space); 14298 New->setInvalidDecl(); 14299 } 14300 14301 // PPC MMA non-pointer types are not allowed as function argument types. 14302 if (Context.getTargetInfo().getTriple().isPPC64() && 14303 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 14304 New->setInvalidDecl(); 14305 } 14306 14307 return New; 14308 } 14309 14310 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 14311 SourceLocation LocAfterDecls) { 14312 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 14313 14314 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 14315 // for a K&R function. 14316 if (!FTI.hasPrototype) { 14317 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 14318 --i; 14319 if (FTI.Params[i].Param == nullptr) { 14320 SmallString<256> Code; 14321 llvm::raw_svector_ostream(Code) 14322 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 14323 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 14324 << FTI.Params[i].Ident 14325 << FixItHint::CreateInsertion(LocAfterDecls, Code); 14326 14327 // Implicitly declare the argument as type 'int' for lack of a better 14328 // type. 14329 AttributeFactory attrs; 14330 DeclSpec DS(attrs); 14331 const char* PrevSpec; // unused 14332 unsigned DiagID; // unused 14333 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14334 DiagID, Context.getPrintingPolicy()); 14335 // Use the identifier location for the type source range. 14336 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14337 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14338 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14339 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14340 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14341 } 14342 } 14343 } 14344 } 14345 14346 Decl * 14347 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14348 MultiTemplateParamsArg TemplateParameterLists, 14349 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { 14350 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14351 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14352 Scope *ParentScope = FnBodyScope->getParent(); 14353 14354 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14355 // we define a non-templated function definition, we will create a declaration 14356 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14357 // The base function declaration will have the equivalent of an `omp declare 14358 // variant` annotation which specifies the mangled definition as a 14359 // specialization function under the OpenMP context defined as part of the 14360 // `omp begin declare variant`. 14361 SmallVector<FunctionDecl *, 4> Bases; 14362 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14363 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14364 ParentScope, D, TemplateParameterLists, Bases); 14365 14366 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14367 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14368 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind); 14369 14370 if (!Bases.empty()) 14371 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14372 14373 return Dcl; 14374 } 14375 14376 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14377 Consumer.HandleInlineFunctionDefinition(D); 14378 } 14379 14380 static bool 14381 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14382 const FunctionDecl *&PossiblePrototype) { 14383 // Don't warn about invalid declarations. 14384 if (FD->isInvalidDecl()) 14385 return false; 14386 14387 // Or declarations that aren't global. 14388 if (!FD->isGlobal()) 14389 return false; 14390 14391 // Don't warn about C++ member functions. 14392 if (isa<CXXMethodDecl>(FD)) 14393 return false; 14394 14395 // Don't warn about 'main'. 14396 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14397 if (IdentifierInfo *II = FD->getIdentifier()) 14398 if (II->isStr("main") || II->isStr("efi_main")) 14399 return false; 14400 14401 // Don't warn about inline functions. 14402 if (FD->isInlined()) 14403 return false; 14404 14405 // Don't warn about function templates. 14406 if (FD->getDescribedFunctionTemplate()) 14407 return false; 14408 14409 // Don't warn about function template specializations. 14410 if (FD->isFunctionTemplateSpecialization()) 14411 return false; 14412 14413 // Don't warn for OpenCL kernels. 14414 if (FD->hasAttr<OpenCLKernelAttr>()) 14415 return false; 14416 14417 // Don't warn on explicitly deleted functions. 14418 if (FD->isDeleted()) 14419 return false; 14420 14421 // Don't warn on implicitly local functions (such as having local-typed 14422 // parameters). 14423 if (!FD->isExternallyVisible()) 14424 return false; 14425 14426 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14427 Prev; Prev = Prev->getPreviousDecl()) { 14428 // Ignore any declarations that occur in function or method 14429 // scope, because they aren't visible from the header. 14430 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14431 continue; 14432 14433 PossiblePrototype = Prev; 14434 return Prev->getType()->isFunctionNoProtoType(); 14435 } 14436 14437 return true; 14438 } 14439 14440 void 14441 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14442 const FunctionDecl *EffectiveDefinition, 14443 SkipBodyInfo *SkipBody) { 14444 const FunctionDecl *Definition = EffectiveDefinition; 14445 if (!Definition && 14446 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14447 return; 14448 14449 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14450 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14451 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14452 // A merged copy of the same function, instantiated as a member of 14453 // the same class, is OK. 14454 if (declaresSameEntity(OrigFD, OrigDef) && 14455 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14456 cast<Decl>(FD->getLexicalDeclContext()))) 14457 return; 14458 } 14459 } 14460 } 14461 14462 if (canRedefineFunction(Definition, getLangOpts())) 14463 return; 14464 14465 // Don't emit an error when this is redefinition of a typo-corrected 14466 // definition. 14467 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14468 return; 14469 14470 // If we don't have a visible definition of the function, and it's inline or 14471 // a template, skip the new definition. 14472 if (SkipBody && !hasVisibleDefinition(Definition) && 14473 (Definition->getFormalLinkage() == InternalLinkage || 14474 Definition->isInlined() || 14475 Definition->getDescribedFunctionTemplate() || 14476 Definition->getNumTemplateParameterLists())) { 14477 SkipBody->ShouldSkip = true; 14478 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14479 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14480 makeMergedDefinitionVisible(TD); 14481 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14482 return; 14483 } 14484 14485 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14486 Definition->getStorageClass() == SC_Extern) 14487 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14488 << FD << getLangOpts().CPlusPlus; 14489 else 14490 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14491 14492 Diag(Definition->getLocation(), diag::note_previous_definition); 14493 FD->setInvalidDecl(); 14494 } 14495 14496 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14497 Sema &S) { 14498 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14499 14500 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14501 LSI->CallOperator = CallOperator; 14502 LSI->Lambda = LambdaClass; 14503 LSI->ReturnType = CallOperator->getReturnType(); 14504 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14505 14506 if (LCD == LCD_None) 14507 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14508 else if (LCD == LCD_ByCopy) 14509 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14510 else if (LCD == LCD_ByRef) 14511 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14512 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14513 14514 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14515 LSI->Mutable = !CallOperator->isConst(); 14516 14517 // Add the captures to the LSI so they can be noted as already 14518 // captured within tryCaptureVar. 14519 auto I = LambdaClass->field_begin(); 14520 for (const auto &C : LambdaClass->captures()) { 14521 if (C.capturesVariable()) { 14522 VarDecl *VD = C.getCapturedVar(); 14523 if (VD->isInitCapture()) 14524 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14525 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14526 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14527 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14528 /*EllipsisLoc*/C.isPackExpansion() 14529 ? C.getEllipsisLoc() : SourceLocation(), 14530 I->getType(), /*Invalid*/false); 14531 14532 } else if (C.capturesThis()) { 14533 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14534 C.getCaptureKind() == LCK_StarThis); 14535 } else { 14536 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14537 I->getType()); 14538 } 14539 ++I; 14540 } 14541 } 14542 14543 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14544 SkipBodyInfo *SkipBody, 14545 FnBodyKind BodyKind) { 14546 if (!D) { 14547 // Parsing the function declaration failed in some way. Push on a fake scope 14548 // anyway so we can try to parse the function body. 14549 PushFunctionScope(); 14550 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14551 return D; 14552 } 14553 14554 FunctionDecl *FD = nullptr; 14555 14556 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14557 FD = FunTmpl->getTemplatedDecl(); 14558 else 14559 FD = cast<FunctionDecl>(D); 14560 14561 // Do not push if it is a lambda because one is already pushed when building 14562 // the lambda in ActOnStartOfLambdaDefinition(). 14563 if (!isLambdaCallOperator(FD)) 14564 PushExpressionEvaluationContext( 14565 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14566 : ExprEvalContexts.back().Context); 14567 14568 // Check for defining attributes before the check for redefinition. 14569 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14570 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14571 FD->dropAttr<AliasAttr>(); 14572 FD->setInvalidDecl(); 14573 } 14574 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14575 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14576 FD->dropAttr<IFuncAttr>(); 14577 FD->setInvalidDecl(); 14578 } 14579 14580 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14581 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14582 Ctor->isDefaultConstructor() && 14583 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14584 // If this is an MS ABI dllexport default constructor, instantiate any 14585 // default arguments. 14586 InstantiateDefaultCtorDefaultArgs(Ctor); 14587 } 14588 } 14589 14590 // See if this is a redefinition. If 'will have body' (or similar) is already 14591 // set, then these checks were already performed when it was set. 14592 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14593 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14594 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14595 14596 // If we're skipping the body, we're done. Don't enter the scope. 14597 if (SkipBody && SkipBody->ShouldSkip) 14598 return D; 14599 } 14600 14601 // Mark this function as "will have a body eventually". This lets users to 14602 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14603 // this function. 14604 FD->setWillHaveBody(); 14605 14606 // If we are instantiating a generic lambda call operator, push 14607 // a LambdaScopeInfo onto the function stack. But use the information 14608 // that's already been calculated (ActOnLambdaExpr) to prime the current 14609 // LambdaScopeInfo. 14610 // When the template operator is being specialized, the LambdaScopeInfo, 14611 // has to be properly restored so that tryCaptureVariable doesn't try 14612 // and capture any new variables. In addition when calculating potential 14613 // captures during transformation of nested lambdas, it is necessary to 14614 // have the LSI properly restored. 14615 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14616 assert(inTemplateInstantiation() && 14617 "There should be an active template instantiation on the stack " 14618 "when instantiating a generic lambda!"); 14619 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14620 } else { 14621 // Enter a new function scope 14622 PushFunctionScope(); 14623 } 14624 14625 // Builtin functions cannot be defined. 14626 if (unsigned BuiltinID = FD->getBuiltinID()) { 14627 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14628 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14629 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14630 FD->setInvalidDecl(); 14631 } 14632 } 14633 14634 // The return type of a function definition must be complete (C99 6.9.1p3), 14635 // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2) 14636 QualType ResultType = FD->getReturnType(); 14637 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14638 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && 14639 RequireCompleteType(FD->getLocation(), ResultType, 14640 diag::err_func_def_incomplete_result)) 14641 FD->setInvalidDecl(); 14642 14643 if (FnBodyScope) 14644 PushDeclContext(FnBodyScope, FD); 14645 14646 // Check the validity of our function parameters 14647 if (BodyKind != FnBodyKind::Delete) 14648 CheckParmsForFunctionDef(FD->parameters(), 14649 /*CheckParameterNames=*/true); 14650 14651 // Add non-parameter declarations already in the function to the current 14652 // scope. 14653 if (FnBodyScope) { 14654 for (Decl *NPD : FD->decls()) { 14655 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14656 if (!NonParmDecl) 14657 continue; 14658 assert(!isa<ParmVarDecl>(NonParmDecl) && 14659 "parameters should not be in newly created FD yet"); 14660 14661 // If the decl has a name, make it accessible in the current scope. 14662 if (NonParmDecl->getDeclName()) 14663 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14664 14665 // Similarly, dive into enums and fish their constants out, making them 14666 // accessible in this scope. 14667 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14668 for (auto *EI : ED->enumerators()) 14669 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14670 } 14671 } 14672 } 14673 14674 // Introduce our parameters into the function scope 14675 for (auto Param : FD->parameters()) { 14676 Param->setOwningFunction(FD); 14677 14678 // If this has an identifier, add it to the scope stack. 14679 if (Param->getIdentifier() && FnBodyScope) { 14680 CheckShadow(FnBodyScope, Param); 14681 14682 PushOnScopeChains(Param, FnBodyScope); 14683 } 14684 } 14685 14686 // Ensure that the function's exception specification is instantiated. 14687 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14688 ResolveExceptionSpec(D->getLocation(), FPT); 14689 14690 // dllimport cannot be applied to non-inline function definitions. 14691 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14692 !FD->isTemplateInstantiation()) { 14693 assert(!FD->hasAttr<DLLExportAttr>()); 14694 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14695 FD->setInvalidDecl(); 14696 return D; 14697 } 14698 // We want to attach documentation to original Decl (which might be 14699 // a function template). 14700 ActOnDocumentableDecl(D); 14701 if (getCurLexicalContext()->isObjCContainer() && 14702 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14703 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14704 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14705 14706 return D; 14707 } 14708 14709 /// Given the set of return statements within a function body, 14710 /// compute the variables that are subject to the named return value 14711 /// optimization. 14712 /// 14713 /// Each of the variables that is subject to the named return value 14714 /// optimization will be marked as NRVO variables in the AST, and any 14715 /// return statement that has a marked NRVO variable as its NRVO candidate can 14716 /// use the named return value optimization. 14717 /// 14718 /// This function applies a very simplistic algorithm for NRVO: if every return 14719 /// statement in the scope of a variable has the same NRVO candidate, that 14720 /// candidate is an NRVO variable. 14721 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14722 ReturnStmt **Returns = Scope->Returns.data(); 14723 14724 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14725 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14726 if (!NRVOCandidate->isNRVOVariable()) 14727 Returns[I]->setNRVOCandidate(nullptr); 14728 } 14729 } 14730 } 14731 14732 bool Sema::canDelayFunctionBody(const Declarator &D) { 14733 // We can't delay parsing the body of a constexpr function template (yet). 14734 if (D.getDeclSpec().hasConstexprSpecifier()) 14735 return false; 14736 14737 // We can't delay parsing the body of a function template with a deduced 14738 // return type (yet). 14739 if (D.getDeclSpec().hasAutoTypeSpec()) { 14740 // If the placeholder introduces a non-deduced trailing return type, 14741 // we can still delay parsing it. 14742 if (D.getNumTypeObjects()) { 14743 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14744 if (Outer.Kind == DeclaratorChunk::Function && 14745 Outer.Fun.hasTrailingReturnType()) { 14746 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14747 return Ty.isNull() || !Ty->isUndeducedType(); 14748 } 14749 } 14750 return false; 14751 } 14752 14753 return true; 14754 } 14755 14756 bool Sema::canSkipFunctionBody(Decl *D) { 14757 // We cannot skip the body of a function (or function template) which is 14758 // constexpr, since we may need to evaluate its body in order to parse the 14759 // rest of the file. 14760 // We cannot skip the body of a function with an undeduced return type, 14761 // because any callers of that function need to know the type. 14762 if (const FunctionDecl *FD = D->getAsFunction()) { 14763 if (FD->isConstexpr()) 14764 return false; 14765 // We can't simply call Type::isUndeducedType here, because inside template 14766 // auto can be deduced to a dependent type, which is not considered 14767 // "undeduced". 14768 if (FD->getReturnType()->getContainedDeducedType()) 14769 return false; 14770 } 14771 return Consumer.shouldSkipFunctionBody(D); 14772 } 14773 14774 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14775 if (!Decl) 14776 return nullptr; 14777 if (FunctionDecl *FD = Decl->getAsFunction()) 14778 FD->setHasSkippedBody(); 14779 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14780 MD->setHasSkippedBody(); 14781 return Decl; 14782 } 14783 14784 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14785 return ActOnFinishFunctionBody(D, BodyArg, false); 14786 } 14787 14788 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14789 /// body. 14790 class ExitFunctionBodyRAII { 14791 public: 14792 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14793 ~ExitFunctionBodyRAII() { 14794 if (!IsLambda) 14795 S.PopExpressionEvaluationContext(); 14796 } 14797 14798 private: 14799 Sema &S; 14800 bool IsLambda = false; 14801 }; 14802 14803 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14804 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14805 14806 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14807 if (EscapeInfo.count(BD)) 14808 return EscapeInfo[BD]; 14809 14810 bool R = false; 14811 const BlockDecl *CurBD = BD; 14812 14813 do { 14814 R = !CurBD->doesNotEscape(); 14815 if (R) 14816 break; 14817 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14818 } while (CurBD); 14819 14820 return EscapeInfo[BD] = R; 14821 }; 14822 14823 // If the location where 'self' is implicitly retained is inside a escaping 14824 // block, emit a diagnostic. 14825 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14826 S.ImplicitlyRetainedSelfLocs) 14827 if (IsOrNestedInEscapingBlock(P.second)) 14828 S.Diag(P.first, diag::warn_implicitly_retains_self) 14829 << FixItHint::CreateInsertion(P.first, "self->"); 14830 } 14831 14832 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14833 bool IsInstantiation) { 14834 FunctionScopeInfo *FSI = getCurFunction(); 14835 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14836 14837 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14838 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14839 14840 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14841 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14842 14843 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14844 CheckCompletedCoroutineBody(FD, Body); 14845 14846 { 14847 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14848 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14849 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14850 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14851 14852 if (FD) { 14853 FD->setBody(Body); 14854 FD->setWillHaveBody(false); 14855 14856 if (getLangOpts().CPlusPlus14) { 14857 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14858 FD->getReturnType()->isUndeducedType()) { 14859 // For a function with a deduced result type to return void, 14860 // the result type as written must be 'auto' or 'decltype(auto)', 14861 // possibly cv-qualified or constrained, but not ref-qualified. 14862 if (!FD->getReturnType()->getAs<AutoType>()) { 14863 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14864 << FD->getReturnType(); 14865 FD->setInvalidDecl(); 14866 } else { 14867 // Falling off the end of the function is the same as 'return;'. 14868 Expr *Dummy = nullptr; 14869 if (DeduceFunctionTypeFromReturnExpr( 14870 FD, dcl->getLocation(), Dummy, 14871 FD->getReturnType()->getAs<AutoType>())) 14872 FD->setInvalidDecl(); 14873 } 14874 } 14875 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14876 // In C++11, we don't use 'auto' deduction rules for lambda call 14877 // operators because we don't support return type deduction. 14878 auto *LSI = getCurLambda(); 14879 if (LSI->HasImplicitReturnType) { 14880 deduceClosureReturnType(*LSI); 14881 14882 // C++11 [expr.prim.lambda]p4: 14883 // [...] if there are no return statements in the compound-statement 14884 // [the deduced type is] the type void 14885 QualType RetType = 14886 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14887 14888 // Update the return type to the deduced type. 14889 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14890 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14891 Proto->getExtProtoInfo())); 14892 } 14893 } 14894 14895 // If the function implicitly returns zero (like 'main') or is naked, 14896 // don't complain about missing return statements. 14897 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14898 WP.disableCheckFallThrough(); 14899 14900 // MSVC permits the use of pure specifier (=0) on function definition, 14901 // defined at class scope, warn about this non-standard construct. 14902 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14903 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14904 14905 if (!FD->isInvalidDecl()) { 14906 // Don't diagnose unused parameters of defaulted, deleted or naked 14907 // functions. 14908 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 14909 !FD->hasAttr<NakedAttr>()) 14910 DiagnoseUnusedParameters(FD->parameters()); 14911 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14912 FD->getReturnType(), FD); 14913 14914 // If this is a structor, we need a vtable. 14915 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14916 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14917 else if (CXXDestructorDecl *Destructor = 14918 dyn_cast<CXXDestructorDecl>(FD)) 14919 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14920 14921 // Try to apply the named return value optimization. We have to check 14922 // if we can do this here because lambdas keep return statements around 14923 // to deduce an implicit return type. 14924 if (FD->getReturnType()->isRecordType() && 14925 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14926 computeNRVO(Body, FSI); 14927 } 14928 14929 // GNU warning -Wmissing-prototypes: 14930 // Warn if a global function is defined without a previous 14931 // prototype declaration. This warning is issued even if the 14932 // definition itself provides a prototype. The aim is to detect 14933 // global functions that fail to be declared in header files. 14934 const FunctionDecl *PossiblePrototype = nullptr; 14935 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14936 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14937 14938 if (PossiblePrototype) { 14939 // We found a declaration that is not a prototype, 14940 // but that could be a zero-parameter prototype 14941 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14942 TypeLoc TL = TI->getTypeLoc(); 14943 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14944 Diag(PossiblePrototype->getLocation(), 14945 diag::note_declaration_not_a_prototype) 14946 << (FD->getNumParams() != 0) 14947 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 14948 FTL.getRParenLoc(), "void") 14949 : FixItHint{}); 14950 } 14951 } else { 14952 // Returns true if the token beginning at this Loc is `const`. 14953 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14954 const LangOptions &LangOpts) { 14955 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14956 if (LocInfo.first.isInvalid()) 14957 return false; 14958 14959 bool Invalid = false; 14960 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14961 if (Invalid) 14962 return false; 14963 14964 if (LocInfo.second > Buffer.size()) 14965 return false; 14966 14967 const char *LexStart = Buffer.data() + LocInfo.second; 14968 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14969 14970 return StartTok.consume_front("const") && 14971 (StartTok.empty() || isWhitespace(StartTok[0]) || 14972 StartTok.startswith("/*") || StartTok.startswith("//")); 14973 }; 14974 14975 auto findBeginLoc = [&]() { 14976 // If the return type has `const` qualifier, we want to insert 14977 // `static` before `const` (and not before the typename). 14978 if ((FD->getReturnType()->isAnyPointerType() && 14979 FD->getReturnType()->getPointeeType().isConstQualified()) || 14980 FD->getReturnType().isConstQualified()) { 14981 // But only do this if we can determine where the `const` is. 14982 14983 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14984 getLangOpts())) 14985 14986 return FD->getBeginLoc(); 14987 } 14988 return FD->getTypeSpecStartLoc(); 14989 }; 14990 Diag(FD->getTypeSpecStartLoc(), 14991 diag::note_static_for_internal_linkage) 14992 << /* function */ 1 14993 << (FD->getStorageClass() == SC_None 14994 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14995 : FixItHint{}); 14996 } 14997 } 14998 14999 // If the function being defined does not have a prototype, then we may 15000 // need to diagnose it as changing behavior in C2x because we now know 15001 // whether the function accepts arguments or not. This only handles the 15002 // case where the definition has no prototype but does have parameters 15003 // and either there is no previous potential prototype, or the previous 15004 // potential prototype also has no actual prototype. This handles cases 15005 // like: 15006 // void f(); void f(a) int a; {} 15007 // void g(a) int a; {} 15008 // See MergeFunctionDecl() for other cases of the behavior change 15009 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 15010 // type without a prototype. 15011 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && 15012 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && 15013 !PossiblePrototype->isImplicit()))) { 15014 // The function definition has parameters, so this will change behavior 15015 // in C2x. If there is a possible prototype, it comes before the 15016 // function definition. 15017 // FIXME: The declaration may have already been diagnosed as being 15018 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but 15019 // there's no way to test for the "changes behavior" condition in 15020 // SemaType.cpp when forming the declaration's function type. So, we do 15021 // this awkward dance instead. 15022 // 15023 // If we have a possible prototype and it declares a function with a 15024 // prototype, we don't want to diagnose it; if we have a possible 15025 // prototype and it has no prototype, it may have already been 15026 // diagnosed in SemaType.cpp as deprecated depending on whether 15027 // -Wstrict-prototypes is enabled. If we already warned about it being 15028 // deprecated, add a note that it also changes behavior. If we didn't 15029 // warn about it being deprecated (because the diagnostic is not 15030 // enabled), warn now that it is deprecated and changes behavior. 15031 bool AddNote = false; 15032 if (PossiblePrototype) { 15033 if (Diags.isIgnored(diag::warn_strict_prototypes, 15034 PossiblePrototype->getLocation())) { 15035 15036 PartialDiagnostic PD = 15037 PDiag(diag::warn_non_prototype_changes_behavior); 15038 if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) { 15039 if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>()) 15040 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 15041 } 15042 Diag(PossiblePrototype->getLocation(), PD); 15043 } else { 15044 AddNote = true; 15045 } 15046 } 15047 15048 // Because this function definition has no prototype and it has 15049 // parameters, it will definitely change behavior in C2x. 15050 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior); 15051 if (AddNote) 15052 Diag(PossiblePrototype->getLocation(), 15053 diag::note_func_decl_changes_behavior); 15054 } 15055 15056 // Warn on CPUDispatch with an actual body. 15057 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 15058 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 15059 if (!CmpndBody->body_empty()) 15060 Diag(CmpndBody->body_front()->getBeginLoc(), 15061 diag::warn_dispatch_body_ignored); 15062 15063 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 15064 const CXXMethodDecl *KeyFunction; 15065 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 15066 MD->isVirtual() && 15067 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 15068 MD == KeyFunction->getCanonicalDecl()) { 15069 // Update the key-function state if necessary for this ABI. 15070 if (FD->isInlined() && 15071 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 15072 Context.setNonKeyFunction(MD); 15073 15074 // If the newly-chosen key function is already defined, then we 15075 // need to mark the vtable as used retroactively. 15076 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 15077 const FunctionDecl *Definition; 15078 if (KeyFunction && KeyFunction->isDefined(Definition)) 15079 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 15080 } else { 15081 // We just defined they key function; mark the vtable as used. 15082 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 15083 } 15084 } 15085 } 15086 15087 assert( 15088 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 15089 "Function parsing confused"); 15090 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 15091 assert(MD == getCurMethodDecl() && "Method parsing confused"); 15092 MD->setBody(Body); 15093 if (!MD->isInvalidDecl()) { 15094 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 15095 MD->getReturnType(), MD); 15096 15097 if (Body) 15098 computeNRVO(Body, FSI); 15099 } 15100 if (FSI->ObjCShouldCallSuper) { 15101 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 15102 << MD->getSelector().getAsString(); 15103 FSI->ObjCShouldCallSuper = false; 15104 } 15105 if (FSI->ObjCWarnForNoDesignatedInitChain) { 15106 const ObjCMethodDecl *InitMethod = nullptr; 15107 bool isDesignated = 15108 MD->isDesignatedInitializerForTheInterface(&InitMethod); 15109 assert(isDesignated && InitMethod); 15110 (void)isDesignated; 15111 15112 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 15113 auto IFace = MD->getClassInterface(); 15114 if (!IFace) 15115 return false; 15116 auto SuperD = IFace->getSuperClass(); 15117 if (!SuperD) 15118 return false; 15119 return SuperD->getIdentifier() == 15120 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 15121 }; 15122 // Don't issue this warning for unavailable inits or direct subclasses 15123 // of NSObject. 15124 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 15125 Diag(MD->getLocation(), 15126 diag::warn_objc_designated_init_missing_super_call); 15127 Diag(InitMethod->getLocation(), 15128 diag::note_objc_designated_init_marked_here); 15129 } 15130 FSI->ObjCWarnForNoDesignatedInitChain = false; 15131 } 15132 if (FSI->ObjCWarnForNoInitDelegation) { 15133 // Don't issue this warning for unavaialable inits. 15134 if (!MD->isUnavailable()) 15135 Diag(MD->getLocation(), 15136 diag::warn_objc_secondary_init_missing_init_call); 15137 FSI->ObjCWarnForNoInitDelegation = false; 15138 } 15139 15140 diagnoseImplicitlyRetainedSelf(*this); 15141 } else { 15142 // Parsing the function declaration failed in some way. Pop the fake scope 15143 // we pushed on. 15144 PopFunctionScopeInfo(ActivePolicy, dcl); 15145 return nullptr; 15146 } 15147 15148 if (Body && FSI->HasPotentialAvailabilityViolations) 15149 DiagnoseUnguardedAvailabilityViolations(dcl); 15150 15151 assert(!FSI->ObjCShouldCallSuper && 15152 "This should only be set for ObjC methods, which should have been " 15153 "handled in the block above."); 15154 15155 // Verify and clean out per-function state. 15156 if (Body && (!FD || !FD->isDefaulted())) { 15157 // C++ constructors that have function-try-blocks can't have return 15158 // statements in the handlers of that block. (C++ [except.handle]p14) 15159 // Verify this. 15160 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 15161 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 15162 15163 // Verify that gotos and switch cases don't jump into scopes illegally. 15164 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 15165 DiagnoseInvalidJumps(Body); 15166 15167 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 15168 if (!Destructor->getParent()->isDependentType()) 15169 CheckDestructor(Destructor); 15170 15171 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 15172 Destructor->getParent()); 15173 } 15174 15175 // If any errors have occurred, clear out any temporaries that may have 15176 // been leftover. This ensures that these temporaries won't be picked up 15177 // for deletion in some later function. 15178 if (hasUncompilableErrorOccurred() || 15179 getDiagnostics().getSuppressAllDiagnostics()) { 15180 DiscardCleanupsInEvaluationContext(); 15181 } 15182 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 15183 // Since the body is valid, issue any analysis-based warnings that are 15184 // enabled. 15185 ActivePolicy = &WP; 15186 } 15187 15188 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 15189 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 15190 FD->setInvalidDecl(); 15191 15192 if (FD && FD->hasAttr<NakedAttr>()) { 15193 for (const Stmt *S : Body->children()) { 15194 // Allow local register variables without initializer as they don't 15195 // require prologue. 15196 bool RegisterVariables = false; 15197 if (auto *DS = dyn_cast<DeclStmt>(S)) { 15198 for (const auto *Decl : DS->decls()) { 15199 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 15200 RegisterVariables = 15201 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 15202 if (!RegisterVariables) 15203 break; 15204 } 15205 } 15206 } 15207 if (RegisterVariables) 15208 continue; 15209 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 15210 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 15211 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 15212 FD->setInvalidDecl(); 15213 break; 15214 } 15215 } 15216 } 15217 15218 assert(ExprCleanupObjects.size() == 15219 ExprEvalContexts.back().NumCleanupObjects && 15220 "Leftover temporaries in function"); 15221 assert(!Cleanup.exprNeedsCleanups() && 15222 "Unaccounted cleanups in function"); 15223 assert(MaybeODRUseExprs.empty() && 15224 "Leftover expressions for odr-use checking"); 15225 } 15226 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 15227 // the declaration context below. Otherwise, we're unable to transform 15228 // 'this' expressions when transforming immediate context functions. 15229 15230 if (!IsInstantiation) 15231 PopDeclContext(); 15232 15233 PopFunctionScopeInfo(ActivePolicy, dcl); 15234 // If any errors have occurred, clear out any temporaries that may have 15235 // been leftover. This ensures that these temporaries won't be picked up for 15236 // deletion in some later function. 15237 if (hasUncompilableErrorOccurred()) { 15238 DiscardCleanupsInEvaluationContext(); 15239 } 15240 15241 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 15242 !LangOpts.OMPTargetTriples.empty())) || 15243 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 15244 auto ES = getEmissionStatus(FD); 15245 if (ES == Sema::FunctionEmissionStatus::Emitted || 15246 ES == Sema::FunctionEmissionStatus::Unknown) 15247 DeclsToCheckForDeferredDiags.insert(FD); 15248 } 15249 15250 if (FD && !FD->isDeleted()) 15251 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 15252 15253 return dcl; 15254 } 15255 15256 /// When we finish delayed parsing of an attribute, we must attach it to the 15257 /// relevant Decl. 15258 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 15259 ParsedAttributes &Attrs) { 15260 // Always attach attributes to the underlying decl. 15261 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 15262 D = TD->getTemplatedDecl(); 15263 ProcessDeclAttributeList(S, D, Attrs); 15264 15265 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 15266 if (Method->isStatic()) 15267 checkThisInStaticMemberFunctionAttributes(Method); 15268 } 15269 15270 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 15271 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 15272 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 15273 IdentifierInfo &II, Scope *S) { 15274 // It is not valid to implicitly define a function in C2x. 15275 assert(!LangOpts.C2x && "Cannot implicitly define a function in C2x"); 15276 15277 // Find the scope in which the identifier is injected and the corresponding 15278 // DeclContext. 15279 // FIXME: C89 does not say what happens if there is no enclosing block scope. 15280 // In that case, we inject the declaration into the translation unit scope 15281 // instead. 15282 Scope *BlockScope = S; 15283 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 15284 BlockScope = BlockScope->getParent(); 15285 15286 Scope *ContextScope = BlockScope; 15287 while (!ContextScope->getEntity()) 15288 ContextScope = ContextScope->getParent(); 15289 ContextRAII SavedContext(*this, ContextScope->getEntity()); 15290 15291 // Before we produce a declaration for an implicitly defined 15292 // function, see whether there was a locally-scoped declaration of 15293 // this name as a function or variable. If so, use that 15294 // (non-visible) declaration, and complain about it. 15295 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 15296 if (ExternCPrev) { 15297 // We still need to inject the function into the enclosing block scope so 15298 // that later (non-call) uses can see it. 15299 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 15300 15301 // C89 footnote 38: 15302 // If in fact it is not defined as having type "function returning int", 15303 // the behavior is undefined. 15304 if (!isa<FunctionDecl>(ExternCPrev) || 15305 !Context.typesAreCompatible( 15306 cast<FunctionDecl>(ExternCPrev)->getType(), 15307 Context.getFunctionNoProtoType(Context.IntTy))) { 15308 Diag(Loc, diag::ext_use_out_of_scope_declaration) 15309 << ExternCPrev << !getLangOpts().C99; 15310 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 15311 return ExternCPrev; 15312 } 15313 } 15314 15315 // Extension in C99 (defaults to error). Legal in C89, but warn about it. 15316 unsigned diag_id; 15317 if (II.getName().startswith("__builtin_")) 15318 diag_id = diag::warn_builtin_unknown; 15319 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 15320 else if (getLangOpts().OpenCL) 15321 diag_id = diag::err_opencl_implicit_function_decl; 15322 else if (getLangOpts().C99) 15323 diag_id = diag::ext_implicit_function_decl_c99; 15324 else 15325 diag_id = diag::warn_implicit_function_decl; 15326 15327 TypoCorrection Corrected; 15328 // Because typo correction is expensive, only do it if the implicit 15329 // function declaration is going to be treated as an error. 15330 // 15331 // Perform the corection before issuing the main diagnostic, as some consumers 15332 // use typo-correction callbacks to enhance the main diagnostic. 15333 if (S && !ExternCPrev && 15334 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 15335 DeclFilterCCC<FunctionDecl> CCC{}; 15336 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 15337 S, nullptr, CCC, CTK_NonError); 15338 } 15339 15340 Diag(Loc, diag_id) << &II; 15341 if (Corrected) { 15342 // If the correction is going to suggest an implicitly defined function, 15343 // skip the correction as not being a particularly good idea. 15344 bool Diagnose = true; 15345 if (const auto *D = Corrected.getCorrectionDecl()) 15346 Diagnose = !D->isImplicit(); 15347 if (Diagnose) 15348 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 15349 /*ErrorRecovery*/ false); 15350 } 15351 15352 // If we found a prior declaration of this function, don't bother building 15353 // another one. We've already pushed that one into scope, so there's nothing 15354 // more to do. 15355 if (ExternCPrev) 15356 return ExternCPrev; 15357 15358 // Set a Declarator for the implicit definition: int foo(); 15359 const char *Dummy; 15360 AttributeFactory attrFactory; 15361 DeclSpec DS(attrFactory); 15362 unsigned DiagID; 15363 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 15364 Context.getPrintingPolicy()); 15365 (void)Error; // Silence warning. 15366 assert(!Error && "Error setting up implicit decl!"); 15367 SourceLocation NoLoc; 15368 Declarator D(DS, DeclaratorContext::Block); 15369 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 15370 /*IsAmbiguous=*/false, 15371 /*LParenLoc=*/NoLoc, 15372 /*Params=*/nullptr, 15373 /*NumParams=*/0, 15374 /*EllipsisLoc=*/NoLoc, 15375 /*RParenLoc=*/NoLoc, 15376 /*RefQualifierIsLvalueRef=*/true, 15377 /*RefQualifierLoc=*/NoLoc, 15378 /*MutableLoc=*/NoLoc, EST_None, 15379 /*ESpecRange=*/SourceRange(), 15380 /*Exceptions=*/nullptr, 15381 /*ExceptionRanges=*/nullptr, 15382 /*NumExceptions=*/0, 15383 /*NoexceptExpr=*/nullptr, 15384 /*ExceptionSpecTokens=*/nullptr, 15385 /*DeclsInPrototype=*/None, Loc, 15386 Loc, D), 15387 std::move(DS.getAttributes()), SourceLocation()); 15388 D.SetIdentifier(&II, Loc); 15389 15390 // Insert this function into the enclosing block scope. 15391 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 15392 FD->setImplicit(); 15393 15394 AddKnownFunctionAttributes(FD); 15395 15396 return FD; 15397 } 15398 15399 /// If this function is a C++ replaceable global allocation function 15400 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15401 /// adds any function attributes that we know a priori based on the standard. 15402 /// 15403 /// We need to check for duplicate attributes both here and where user-written 15404 /// attributes are applied to declarations. 15405 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15406 FunctionDecl *FD) { 15407 if (FD->isInvalidDecl()) 15408 return; 15409 15410 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15411 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15412 return; 15413 15414 Optional<unsigned> AlignmentParam; 15415 bool IsNothrow = false; 15416 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15417 return; 15418 15419 // C++2a [basic.stc.dynamic.allocation]p4: 15420 // An allocation function that has a non-throwing exception specification 15421 // indicates failure by returning a null pointer value. Any other allocation 15422 // function never returns a null pointer value and indicates failure only by 15423 // throwing an exception [...] 15424 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15425 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15426 15427 // C++2a [basic.stc.dynamic.allocation]p2: 15428 // An allocation function attempts to allocate the requested amount of 15429 // storage. [...] If the request succeeds, the value returned by a 15430 // replaceable allocation function is a [...] pointer value p0 different 15431 // from any previously returned value p1 [...] 15432 // 15433 // However, this particular information is being added in codegen, 15434 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15435 15436 // C++2a [basic.stc.dynamic.allocation]p2: 15437 // An allocation function attempts to allocate the requested amount of 15438 // storage. If it is successful, it returns the address of the start of a 15439 // block of storage whose length in bytes is at least as large as the 15440 // requested size. 15441 if (!FD->hasAttr<AllocSizeAttr>()) { 15442 FD->addAttr(AllocSizeAttr::CreateImplicit( 15443 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15444 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15445 } 15446 15447 // C++2a [basic.stc.dynamic.allocation]p3: 15448 // For an allocation function [...], the pointer returned on a successful 15449 // call shall represent the address of storage that is aligned as follows: 15450 // (3.1) If the allocation function takes an argument of type 15451 // std::align_val_t, the storage will have the alignment 15452 // specified by the value of this argument. 15453 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15454 FD->addAttr(AllocAlignAttr::CreateImplicit( 15455 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15456 } 15457 15458 // FIXME: 15459 // C++2a [basic.stc.dynamic.allocation]p3: 15460 // For an allocation function [...], the pointer returned on a successful 15461 // call shall represent the address of storage that is aligned as follows: 15462 // (3.2) Otherwise, if the allocation function is named operator new[], 15463 // the storage is aligned for any object that does not have 15464 // new-extended alignment ([basic.align]) and is no larger than the 15465 // requested size. 15466 // (3.3) Otherwise, the storage is aligned for any object that does not 15467 // have new-extended alignment and is of the requested size. 15468 } 15469 15470 /// Adds any function attributes that we know a priori based on 15471 /// the declaration of this function. 15472 /// 15473 /// These attributes can apply both to implicitly-declared builtins 15474 /// (like __builtin___printf_chk) or to library-declared functions 15475 /// like NSLog or printf. 15476 /// 15477 /// We need to check for duplicate attributes both here and where user-written 15478 /// attributes are applied to declarations. 15479 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15480 if (FD->isInvalidDecl()) 15481 return; 15482 15483 // If this is a built-in function, map its builtin attributes to 15484 // actual attributes. 15485 if (unsigned BuiltinID = FD->getBuiltinID()) { 15486 // Handle printf-formatting attributes. 15487 unsigned FormatIdx; 15488 bool HasVAListArg; 15489 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15490 if (!FD->hasAttr<FormatAttr>()) { 15491 const char *fmt = "printf"; 15492 unsigned int NumParams = FD->getNumParams(); 15493 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15494 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15495 fmt = "NSString"; 15496 FD->addAttr(FormatAttr::CreateImplicit(Context, 15497 &Context.Idents.get(fmt), 15498 FormatIdx+1, 15499 HasVAListArg ? 0 : FormatIdx+2, 15500 FD->getLocation())); 15501 } 15502 } 15503 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15504 HasVAListArg)) { 15505 if (!FD->hasAttr<FormatAttr>()) 15506 FD->addAttr(FormatAttr::CreateImplicit(Context, 15507 &Context.Idents.get("scanf"), 15508 FormatIdx+1, 15509 HasVAListArg ? 0 : FormatIdx+2, 15510 FD->getLocation())); 15511 } 15512 15513 // Handle automatically recognized callbacks. 15514 SmallVector<int, 4> Encoding; 15515 if (!FD->hasAttr<CallbackAttr>() && 15516 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15517 FD->addAttr(CallbackAttr::CreateImplicit( 15518 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15519 15520 // Mark const if we don't care about errno and that is the only thing 15521 // preventing the function from being const. This allows IRgen to use LLVM 15522 // intrinsics for such functions. 15523 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15524 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15525 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15526 15527 // We make "fma" on GNU or Windows const because we know it does not set 15528 // errno in those environments even though it could set errno based on the 15529 // C standard. 15530 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15531 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 15532 !FD->hasAttr<ConstAttr>()) { 15533 switch (BuiltinID) { 15534 case Builtin::BI__builtin_fma: 15535 case Builtin::BI__builtin_fmaf: 15536 case Builtin::BI__builtin_fmal: 15537 case Builtin::BIfma: 15538 case Builtin::BIfmaf: 15539 case Builtin::BIfmal: 15540 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15541 break; 15542 default: 15543 break; 15544 } 15545 } 15546 15547 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15548 !FD->hasAttr<ReturnsTwiceAttr>()) 15549 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15550 FD->getLocation())); 15551 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15552 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15553 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15554 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15555 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15556 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15557 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15558 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15559 // Add the appropriate attribute, depending on the CUDA compilation mode 15560 // and which target the builtin belongs to. For example, during host 15561 // compilation, aux builtins are __device__, while the rest are __host__. 15562 if (getLangOpts().CUDAIsDevice != 15563 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15564 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15565 else 15566 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15567 } 15568 15569 // Add known guaranteed alignment for allocation functions. 15570 switch (BuiltinID) { 15571 case Builtin::BImemalign: 15572 case Builtin::BIaligned_alloc: 15573 if (!FD->hasAttr<AllocAlignAttr>()) 15574 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15575 FD->getLocation())); 15576 break; 15577 default: 15578 break; 15579 } 15580 15581 // Add allocsize attribute for allocation functions. 15582 switch (BuiltinID) { 15583 case Builtin::BIcalloc: 15584 FD->addAttr(AllocSizeAttr::CreateImplicit( 15585 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 15586 break; 15587 case Builtin::BImemalign: 15588 case Builtin::BIaligned_alloc: 15589 case Builtin::BIrealloc: 15590 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 15591 ParamIdx(), FD->getLocation())); 15592 break; 15593 case Builtin::BImalloc: 15594 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 15595 ParamIdx(), FD->getLocation())); 15596 break; 15597 default: 15598 break; 15599 } 15600 } 15601 15602 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15603 15604 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15605 // throw, add an implicit nothrow attribute to any extern "C" function we come 15606 // across. 15607 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15608 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15609 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15610 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15611 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15612 } 15613 15614 IdentifierInfo *Name = FD->getIdentifier(); 15615 if (!Name) 15616 return; 15617 if ((!getLangOpts().CPlusPlus && 15618 FD->getDeclContext()->isTranslationUnit()) || 15619 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15620 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15621 LinkageSpecDecl::lang_c)) { 15622 // Okay: this could be a libc/libm/Objective-C function we know 15623 // about. 15624 } else 15625 return; 15626 15627 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15628 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15629 // target-specific builtins, perhaps? 15630 if (!FD->hasAttr<FormatAttr>()) 15631 FD->addAttr(FormatAttr::CreateImplicit(Context, 15632 &Context.Idents.get("printf"), 2, 15633 Name->isStr("vasprintf") ? 0 : 3, 15634 FD->getLocation())); 15635 } 15636 15637 if (Name->isStr("__CFStringMakeConstantString")) { 15638 // We already have a __builtin___CFStringMakeConstantString, 15639 // but builds that use -fno-constant-cfstrings don't go through that. 15640 if (!FD->hasAttr<FormatArgAttr>()) 15641 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15642 FD->getLocation())); 15643 } 15644 } 15645 15646 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15647 TypeSourceInfo *TInfo) { 15648 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15649 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15650 15651 if (!TInfo) { 15652 assert(D.isInvalidType() && "no declarator info for valid type"); 15653 TInfo = Context.getTrivialTypeSourceInfo(T); 15654 } 15655 15656 // Scope manipulation handled by caller. 15657 TypedefDecl *NewTD = 15658 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15659 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15660 15661 // Bail out immediately if we have an invalid declaration. 15662 if (D.isInvalidType()) { 15663 NewTD->setInvalidDecl(); 15664 return NewTD; 15665 } 15666 15667 if (D.getDeclSpec().isModulePrivateSpecified()) { 15668 if (CurContext->isFunctionOrMethod()) 15669 Diag(NewTD->getLocation(), diag::err_module_private_local) 15670 << 2 << NewTD 15671 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15672 << FixItHint::CreateRemoval( 15673 D.getDeclSpec().getModulePrivateSpecLoc()); 15674 else 15675 NewTD->setModulePrivate(); 15676 } 15677 15678 // C++ [dcl.typedef]p8: 15679 // If the typedef declaration defines an unnamed class (or 15680 // enum), the first typedef-name declared by the declaration 15681 // to be that class type (or enum type) is used to denote the 15682 // class type (or enum type) for linkage purposes only. 15683 // We need to check whether the type was declared in the declaration. 15684 switch (D.getDeclSpec().getTypeSpecType()) { 15685 case TST_enum: 15686 case TST_struct: 15687 case TST_interface: 15688 case TST_union: 15689 case TST_class: { 15690 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15691 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15692 break; 15693 } 15694 15695 default: 15696 break; 15697 } 15698 15699 return NewTD; 15700 } 15701 15702 /// Check that this is a valid underlying type for an enum declaration. 15703 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15704 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15705 QualType T = TI->getType(); 15706 15707 if (T->isDependentType()) 15708 return false; 15709 15710 // This doesn't use 'isIntegralType' despite the error message mentioning 15711 // integral type because isIntegralType would also allow enum types in C. 15712 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15713 if (BT->isInteger()) 15714 return false; 15715 15716 if (T->isBitIntType()) 15717 return false; 15718 15719 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15720 } 15721 15722 /// Check whether this is a valid redeclaration of a previous enumeration. 15723 /// \return true if the redeclaration was invalid. 15724 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15725 QualType EnumUnderlyingTy, bool IsFixed, 15726 const EnumDecl *Prev) { 15727 if (IsScoped != Prev->isScoped()) { 15728 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15729 << Prev->isScoped(); 15730 Diag(Prev->getLocation(), diag::note_previous_declaration); 15731 return true; 15732 } 15733 15734 if (IsFixed && Prev->isFixed()) { 15735 if (!EnumUnderlyingTy->isDependentType() && 15736 !Prev->getIntegerType()->isDependentType() && 15737 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15738 Prev->getIntegerType())) { 15739 // TODO: Highlight the underlying type of the redeclaration. 15740 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15741 << EnumUnderlyingTy << Prev->getIntegerType(); 15742 Diag(Prev->getLocation(), diag::note_previous_declaration) 15743 << Prev->getIntegerTypeRange(); 15744 return true; 15745 } 15746 } else if (IsFixed != Prev->isFixed()) { 15747 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15748 << Prev->isFixed(); 15749 Diag(Prev->getLocation(), diag::note_previous_declaration); 15750 return true; 15751 } 15752 15753 return false; 15754 } 15755 15756 /// Get diagnostic %select index for tag kind for 15757 /// redeclaration diagnostic message. 15758 /// WARNING: Indexes apply to particular diagnostics only! 15759 /// 15760 /// \returns diagnostic %select index. 15761 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15762 switch (Tag) { 15763 case TTK_Struct: return 0; 15764 case TTK_Interface: return 1; 15765 case TTK_Class: return 2; 15766 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15767 } 15768 } 15769 15770 /// Determine if tag kind is a class-key compatible with 15771 /// class for redeclaration (class, struct, or __interface). 15772 /// 15773 /// \returns true iff the tag kind is compatible. 15774 static bool isClassCompatTagKind(TagTypeKind Tag) 15775 { 15776 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15777 } 15778 15779 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15780 TagTypeKind TTK) { 15781 if (isa<TypedefDecl>(PrevDecl)) 15782 return NTK_Typedef; 15783 else if (isa<TypeAliasDecl>(PrevDecl)) 15784 return NTK_TypeAlias; 15785 else if (isa<ClassTemplateDecl>(PrevDecl)) 15786 return NTK_Template; 15787 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15788 return NTK_TypeAliasTemplate; 15789 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15790 return NTK_TemplateTemplateArgument; 15791 switch (TTK) { 15792 case TTK_Struct: 15793 case TTK_Interface: 15794 case TTK_Class: 15795 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15796 case TTK_Union: 15797 return NTK_NonUnion; 15798 case TTK_Enum: 15799 return NTK_NonEnum; 15800 } 15801 llvm_unreachable("invalid TTK"); 15802 } 15803 15804 /// Determine whether a tag with a given kind is acceptable 15805 /// as a redeclaration of the given tag declaration. 15806 /// 15807 /// \returns true if the new tag kind is acceptable, false otherwise. 15808 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15809 TagTypeKind NewTag, bool isDefinition, 15810 SourceLocation NewTagLoc, 15811 const IdentifierInfo *Name) { 15812 // C++ [dcl.type.elab]p3: 15813 // The class-key or enum keyword present in the 15814 // elaborated-type-specifier shall agree in kind with the 15815 // declaration to which the name in the elaborated-type-specifier 15816 // refers. This rule also applies to the form of 15817 // elaborated-type-specifier that declares a class-name or 15818 // friend class since it can be construed as referring to the 15819 // definition of the class. Thus, in any 15820 // elaborated-type-specifier, the enum keyword shall be used to 15821 // refer to an enumeration (7.2), the union class-key shall be 15822 // used to refer to a union (clause 9), and either the class or 15823 // struct class-key shall be used to refer to a class (clause 9) 15824 // declared using the class or struct class-key. 15825 TagTypeKind OldTag = Previous->getTagKind(); 15826 if (OldTag != NewTag && 15827 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15828 return false; 15829 15830 // Tags are compatible, but we might still want to warn on mismatched tags. 15831 // Non-class tags can't be mismatched at this point. 15832 if (!isClassCompatTagKind(NewTag)) 15833 return true; 15834 15835 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15836 // by our warning analysis. We don't want to warn about mismatches with (eg) 15837 // declarations in system headers that are designed to be specialized, but if 15838 // a user asks us to warn, we should warn if their code contains mismatched 15839 // declarations. 15840 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15841 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15842 Loc); 15843 }; 15844 if (IsIgnoredLoc(NewTagLoc)) 15845 return true; 15846 15847 auto IsIgnored = [&](const TagDecl *Tag) { 15848 return IsIgnoredLoc(Tag->getLocation()); 15849 }; 15850 while (IsIgnored(Previous)) { 15851 Previous = Previous->getPreviousDecl(); 15852 if (!Previous) 15853 return true; 15854 OldTag = Previous->getTagKind(); 15855 } 15856 15857 bool isTemplate = false; 15858 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15859 isTemplate = Record->getDescribedClassTemplate(); 15860 15861 if (inTemplateInstantiation()) { 15862 if (OldTag != NewTag) { 15863 // In a template instantiation, do not offer fix-its for tag mismatches 15864 // since they usually mess up the template instead of fixing the problem. 15865 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15866 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15867 << getRedeclDiagFromTagKind(OldTag); 15868 // FIXME: Note previous location? 15869 } 15870 return true; 15871 } 15872 15873 if (isDefinition) { 15874 // On definitions, check all previous tags and issue a fix-it for each 15875 // one that doesn't match the current tag. 15876 if (Previous->getDefinition()) { 15877 // Don't suggest fix-its for redefinitions. 15878 return true; 15879 } 15880 15881 bool previousMismatch = false; 15882 for (const TagDecl *I : Previous->redecls()) { 15883 if (I->getTagKind() != NewTag) { 15884 // Ignore previous declarations for which the warning was disabled. 15885 if (IsIgnored(I)) 15886 continue; 15887 15888 if (!previousMismatch) { 15889 previousMismatch = true; 15890 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15891 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15892 << getRedeclDiagFromTagKind(I->getTagKind()); 15893 } 15894 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15895 << getRedeclDiagFromTagKind(NewTag) 15896 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15897 TypeWithKeyword::getTagTypeKindName(NewTag)); 15898 } 15899 } 15900 return true; 15901 } 15902 15903 // Identify the prevailing tag kind: this is the kind of the definition (if 15904 // there is a non-ignored definition), or otherwise the kind of the prior 15905 // (non-ignored) declaration. 15906 const TagDecl *PrevDef = Previous->getDefinition(); 15907 if (PrevDef && IsIgnored(PrevDef)) 15908 PrevDef = nullptr; 15909 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15910 if (Redecl->getTagKind() != NewTag) { 15911 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15912 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15913 << getRedeclDiagFromTagKind(OldTag); 15914 Diag(Redecl->getLocation(), diag::note_previous_use); 15915 15916 // If there is a previous definition, suggest a fix-it. 15917 if (PrevDef) { 15918 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15919 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15920 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15921 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15922 } 15923 } 15924 15925 return true; 15926 } 15927 15928 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15929 /// from an outer enclosing namespace or file scope inside a friend declaration. 15930 /// This should provide the commented out code in the following snippet: 15931 /// namespace N { 15932 /// struct X; 15933 /// namespace M { 15934 /// struct Y { friend struct /*N::*/ X; }; 15935 /// } 15936 /// } 15937 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15938 SourceLocation NameLoc) { 15939 // While the decl is in a namespace, do repeated lookup of that name and see 15940 // if we get the same namespace back. If we do not, continue until 15941 // translation unit scope, at which point we have a fully qualified NNS. 15942 SmallVector<IdentifierInfo *, 4> Namespaces; 15943 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15944 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15945 // This tag should be declared in a namespace, which can only be enclosed by 15946 // other namespaces. Bail if there's an anonymous namespace in the chain. 15947 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15948 if (!Namespace || Namespace->isAnonymousNamespace()) 15949 return FixItHint(); 15950 IdentifierInfo *II = Namespace->getIdentifier(); 15951 Namespaces.push_back(II); 15952 NamedDecl *Lookup = SemaRef.LookupSingleName( 15953 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15954 if (Lookup == Namespace) 15955 break; 15956 } 15957 15958 // Once we have all the namespaces, reverse them to go outermost first, and 15959 // build an NNS. 15960 SmallString<64> Insertion; 15961 llvm::raw_svector_ostream OS(Insertion); 15962 if (DC->isTranslationUnit()) 15963 OS << "::"; 15964 std::reverse(Namespaces.begin(), Namespaces.end()); 15965 for (auto *II : Namespaces) 15966 OS << II->getName() << "::"; 15967 return FixItHint::CreateInsertion(NameLoc, Insertion); 15968 } 15969 15970 /// Determine whether a tag originally declared in context \p OldDC can 15971 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15972 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15973 /// using-declaration). 15974 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15975 DeclContext *NewDC) { 15976 OldDC = OldDC->getRedeclContext(); 15977 NewDC = NewDC->getRedeclContext(); 15978 15979 if (OldDC->Equals(NewDC)) 15980 return true; 15981 15982 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15983 // encloses the other). 15984 if (S.getLangOpts().MSVCCompat && 15985 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15986 return true; 15987 15988 return false; 15989 } 15990 15991 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15992 /// former case, Name will be non-null. In the later case, Name will be null. 15993 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15994 /// reference/declaration/definition of a tag. 15995 /// 15996 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15997 /// trailing-type-specifier) other than one in an alias-declaration. 15998 /// 15999 /// \param SkipBody If non-null, will be set to indicate if the caller should 16000 /// skip the definition of this tag and treat it as if it were a declaration. 16001 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 16002 SourceLocation KWLoc, CXXScopeSpec &SS, 16003 IdentifierInfo *Name, SourceLocation NameLoc, 16004 const ParsedAttributesView &Attrs, AccessSpecifier AS, 16005 SourceLocation ModulePrivateLoc, 16006 MultiTemplateParamsArg TemplateParameterLists, 16007 bool &OwnedDecl, bool &IsDependent, 16008 SourceLocation ScopedEnumKWLoc, 16009 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 16010 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 16011 SkipBodyInfo *SkipBody) { 16012 // If this is not a definition, it must have a name. 16013 IdentifierInfo *OrigName = Name; 16014 assert((Name != nullptr || TUK == TUK_Definition) && 16015 "Nameless record must be a definition!"); 16016 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 16017 16018 OwnedDecl = false; 16019 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16020 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 16021 16022 // FIXME: Check member specializations more carefully. 16023 bool isMemberSpecialization = false; 16024 bool Invalid = false; 16025 16026 // We only need to do this matching if we have template parameters 16027 // or a scope specifier, which also conveniently avoids this work 16028 // for non-C++ cases. 16029 if (TemplateParameterLists.size() > 0 || 16030 (SS.isNotEmpty() && TUK != TUK_Reference)) { 16031 if (TemplateParameterList *TemplateParams = 16032 MatchTemplateParametersToScopeSpecifier( 16033 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 16034 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 16035 if (Kind == TTK_Enum) { 16036 Diag(KWLoc, diag::err_enum_template); 16037 return nullptr; 16038 } 16039 16040 if (TemplateParams->size() > 0) { 16041 // This is a declaration or definition of a class template (which may 16042 // be a member of another template). 16043 16044 if (Invalid) 16045 return nullptr; 16046 16047 OwnedDecl = false; 16048 DeclResult Result = CheckClassTemplate( 16049 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 16050 AS, ModulePrivateLoc, 16051 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 16052 TemplateParameterLists.data(), SkipBody); 16053 return Result.get(); 16054 } else { 16055 // The "template<>" header is extraneous. 16056 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16057 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16058 isMemberSpecialization = true; 16059 } 16060 } 16061 16062 if (!TemplateParameterLists.empty() && isMemberSpecialization && 16063 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 16064 return nullptr; 16065 } 16066 16067 // Figure out the underlying type if this a enum declaration. We need to do 16068 // this early, because it's needed to detect if this is an incompatible 16069 // redeclaration. 16070 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 16071 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 16072 16073 if (Kind == TTK_Enum) { 16074 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 16075 // No underlying type explicitly specified, or we failed to parse the 16076 // type, default to int. 16077 EnumUnderlying = Context.IntTy.getTypePtr(); 16078 } else if (UnderlyingType.get()) { 16079 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 16080 // integral type; any cv-qualification is ignored. 16081 TypeSourceInfo *TI = nullptr; 16082 GetTypeFromParser(UnderlyingType.get(), &TI); 16083 EnumUnderlying = TI; 16084 16085 if (CheckEnumUnderlyingType(TI)) 16086 // Recover by falling back to int. 16087 EnumUnderlying = Context.IntTy.getTypePtr(); 16088 16089 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 16090 UPPC_FixedUnderlyingType)) 16091 EnumUnderlying = Context.IntTy.getTypePtr(); 16092 16093 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 16094 // For MSVC ABI compatibility, unfixed enums must use an underlying type 16095 // of 'int'. However, if this is an unfixed forward declaration, don't set 16096 // the underlying type unless the user enables -fms-compatibility. This 16097 // makes unfixed forward declared enums incomplete and is more conforming. 16098 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 16099 EnumUnderlying = Context.IntTy.getTypePtr(); 16100 } 16101 } 16102 16103 DeclContext *SearchDC = CurContext; 16104 DeclContext *DC = CurContext; 16105 bool isStdBadAlloc = false; 16106 bool isStdAlignValT = false; 16107 16108 RedeclarationKind Redecl = forRedeclarationInCurContext(); 16109 if (TUK == TUK_Friend || TUK == TUK_Reference) 16110 Redecl = NotForRedeclaration; 16111 16112 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 16113 /// implemented asks for structural equivalence checking, the returned decl 16114 /// here is passed back to the parser, allowing the tag body to be parsed. 16115 auto createTagFromNewDecl = [&]() -> TagDecl * { 16116 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 16117 // If there is an identifier, use the location of the identifier as the 16118 // location of the decl, otherwise use the location of the struct/union 16119 // keyword. 16120 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16121 TagDecl *New = nullptr; 16122 16123 if (Kind == TTK_Enum) { 16124 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 16125 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 16126 // If this is an undefined enum, bail. 16127 if (TUK != TUK_Definition && !Invalid) 16128 return nullptr; 16129 if (EnumUnderlying) { 16130 EnumDecl *ED = cast<EnumDecl>(New); 16131 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 16132 ED->setIntegerTypeSourceInfo(TI); 16133 else 16134 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 16135 ED->setPromotionType(ED->getIntegerType()); 16136 } 16137 } else { // struct/union 16138 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16139 nullptr); 16140 } 16141 16142 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16143 // Add alignment attributes if necessary; these attributes are checked 16144 // when the ASTContext lays out the structure. 16145 // 16146 // It is important for implementing the correct semantics that this 16147 // happen here (in ActOnTag). The #pragma pack stack is 16148 // maintained as a result of parser callbacks which can occur at 16149 // many points during the parsing of a struct declaration (because 16150 // the #pragma tokens are effectively skipped over during the 16151 // parsing of the struct). 16152 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16153 AddAlignmentAttributesForRecord(RD); 16154 AddMsStructLayoutForRecord(RD); 16155 } 16156 } 16157 New->setLexicalDeclContext(CurContext); 16158 return New; 16159 }; 16160 16161 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 16162 if (Name && SS.isNotEmpty()) { 16163 // We have a nested-name tag ('struct foo::bar'). 16164 16165 // Check for invalid 'foo::'. 16166 if (SS.isInvalid()) { 16167 Name = nullptr; 16168 goto CreateNewDecl; 16169 } 16170 16171 // If this is a friend or a reference to a class in a dependent 16172 // context, don't try to make a decl for it. 16173 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16174 DC = computeDeclContext(SS, false); 16175 if (!DC) { 16176 IsDependent = true; 16177 return nullptr; 16178 } 16179 } else { 16180 DC = computeDeclContext(SS, true); 16181 if (!DC) { 16182 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 16183 << SS.getRange(); 16184 return nullptr; 16185 } 16186 } 16187 16188 if (RequireCompleteDeclContext(SS, DC)) 16189 return nullptr; 16190 16191 SearchDC = DC; 16192 // Look-up name inside 'foo::'. 16193 LookupQualifiedName(Previous, DC); 16194 16195 if (Previous.isAmbiguous()) 16196 return nullptr; 16197 16198 if (Previous.empty()) { 16199 // Name lookup did not find anything. However, if the 16200 // nested-name-specifier refers to the current instantiation, 16201 // and that current instantiation has any dependent base 16202 // classes, we might find something at instantiation time: treat 16203 // this as a dependent elaborated-type-specifier. 16204 // But this only makes any sense for reference-like lookups. 16205 if (Previous.wasNotFoundInCurrentInstantiation() && 16206 (TUK == TUK_Reference || TUK == TUK_Friend)) { 16207 IsDependent = true; 16208 return nullptr; 16209 } 16210 16211 // A tag 'foo::bar' must already exist. 16212 Diag(NameLoc, diag::err_not_tag_in_scope) 16213 << Kind << Name << DC << SS.getRange(); 16214 Name = nullptr; 16215 Invalid = true; 16216 goto CreateNewDecl; 16217 } 16218 } else if (Name) { 16219 // C++14 [class.mem]p14: 16220 // If T is the name of a class, then each of the following shall have a 16221 // name different from T: 16222 // -- every member of class T that is itself a type 16223 if (TUK != TUK_Reference && TUK != TUK_Friend && 16224 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 16225 return nullptr; 16226 16227 // If this is a named struct, check to see if there was a previous forward 16228 // declaration or definition. 16229 // FIXME: We're looking into outer scopes here, even when we 16230 // shouldn't be. Doing so can result in ambiguities that we 16231 // shouldn't be diagnosing. 16232 LookupName(Previous, S); 16233 16234 // When declaring or defining a tag, ignore ambiguities introduced 16235 // by types using'ed into this scope. 16236 if (Previous.isAmbiguous() && 16237 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 16238 LookupResult::Filter F = Previous.makeFilter(); 16239 while (F.hasNext()) { 16240 NamedDecl *ND = F.next(); 16241 if (!ND->getDeclContext()->getRedeclContext()->Equals( 16242 SearchDC->getRedeclContext())) 16243 F.erase(); 16244 } 16245 F.done(); 16246 } 16247 16248 // C++11 [namespace.memdef]p3: 16249 // If the name in a friend declaration is neither qualified nor 16250 // a template-id and the declaration is a function or an 16251 // elaborated-type-specifier, the lookup to determine whether 16252 // the entity has been previously declared shall not consider 16253 // any scopes outside the innermost enclosing namespace. 16254 // 16255 // MSVC doesn't implement the above rule for types, so a friend tag 16256 // declaration may be a redeclaration of a type declared in an enclosing 16257 // scope. They do implement this rule for friend functions. 16258 // 16259 // Does it matter that this should be by scope instead of by 16260 // semantic context? 16261 if (!Previous.empty() && TUK == TUK_Friend) { 16262 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 16263 LookupResult::Filter F = Previous.makeFilter(); 16264 bool FriendSawTagOutsideEnclosingNamespace = false; 16265 while (F.hasNext()) { 16266 NamedDecl *ND = F.next(); 16267 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 16268 if (DC->isFileContext() && 16269 !EnclosingNS->Encloses(ND->getDeclContext())) { 16270 if (getLangOpts().MSVCCompat) 16271 FriendSawTagOutsideEnclosingNamespace = true; 16272 else 16273 F.erase(); 16274 } 16275 } 16276 F.done(); 16277 16278 // Diagnose this MSVC extension in the easy case where lookup would have 16279 // unambiguously found something outside the enclosing namespace. 16280 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 16281 NamedDecl *ND = Previous.getFoundDecl(); 16282 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 16283 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 16284 } 16285 } 16286 16287 // Note: there used to be some attempt at recovery here. 16288 if (Previous.isAmbiguous()) 16289 return nullptr; 16290 16291 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 16292 // FIXME: This makes sure that we ignore the contexts associated 16293 // with C structs, unions, and enums when looking for a matching 16294 // tag declaration or definition. See the similar lookup tweak 16295 // in Sema::LookupName; is there a better way to deal with this? 16296 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) 16297 SearchDC = SearchDC->getParent(); 16298 } else if (getLangOpts().CPlusPlus) { 16299 // Inside ObjCContainer want to keep it as a lexical decl context but go 16300 // past it (most often to TranslationUnit) to find the semantic decl 16301 // context. 16302 while (isa<ObjCContainerDecl>(SearchDC)) 16303 SearchDC = SearchDC->getParent(); 16304 } 16305 } else if (getLangOpts().CPlusPlus) { 16306 // Don't use ObjCContainerDecl as the semantic decl context for anonymous 16307 // TagDecl the same way as we skip it for named TagDecl. 16308 while (isa<ObjCContainerDecl>(SearchDC)) 16309 SearchDC = SearchDC->getParent(); 16310 } 16311 16312 if (Previous.isSingleResult() && 16313 Previous.getFoundDecl()->isTemplateParameter()) { 16314 // Maybe we will complain about the shadowed template parameter. 16315 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 16316 // Just pretend that we didn't see the previous declaration. 16317 Previous.clear(); 16318 } 16319 16320 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 16321 DC->Equals(getStdNamespace())) { 16322 if (Name->isStr("bad_alloc")) { 16323 // This is a declaration of or a reference to "std::bad_alloc". 16324 isStdBadAlloc = true; 16325 16326 // If std::bad_alloc has been implicitly declared (but made invisible to 16327 // name lookup), fill in this implicit declaration as the previous 16328 // declaration, so that the declarations get chained appropriately. 16329 if (Previous.empty() && StdBadAlloc) 16330 Previous.addDecl(getStdBadAlloc()); 16331 } else if (Name->isStr("align_val_t")) { 16332 isStdAlignValT = true; 16333 if (Previous.empty() && StdAlignValT) 16334 Previous.addDecl(getStdAlignValT()); 16335 } 16336 } 16337 16338 // If we didn't find a previous declaration, and this is a reference 16339 // (or friend reference), move to the correct scope. In C++, we 16340 // also need to do a redeclaration lookup there, just in case 16341 // there's a shadow friend decl. 16342 if (Name && Previous.empty() && 16343 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 16344 if (Invalid) goto CreateNewDecl; 16345 assert(SS.isEmpty()); 16346 16347 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 16348 // C++ [basic.scope.pdecl]p5: 16349 // -- for an elaborated-type-specifier of the form 16350 // 16351 // class-key identifier 16352 // 16353 // if the elaborated-type-specifier is used in the 16354 // decl-specifier-seq or parameter-declaration-clause of a 16355 // function defined in namespace scope, the identifier is 16356 // declared as a class-name in the namespace that contains 16357 // the declaration; otherwise, except as a friend 16358 // declaration, the identifier is declared in the smallest 16359 // non-class, non-function-prototype scope that contains the 16360 // declaration. 16361 // 16362 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 16363 // C structs and unions. 16364 // 16365 // It is an error in C++ to declare (rather than define) an enum 16366 // type, including via an elaborated type specifier. We'll 16367 // diagnose that later; for now, declare the enum in the same 16368 // scope as we would have picked for any other tag type. 16369 // 16370 // GNU C also supports this behavior as part of its incomplete 16371 // enum types extension, while GNU C++ does not. 16372 // 16373 // Find the context where we'll be declaring the tag. 16374 // FIXME: We would like to maintain the current DeclContext as the 16375 // lexical context, 16376 SearchDC = getTagInjectionContext(SearchDC); 16377 16378 // Find the scope where we'll be declaring the tag. 16379 S = getTagInjectionScope(S, getLangOpts()); 16380 } else { 16381 assert(TUK == TUK_Friend); 16382 // C++ [namespace.memdef]p3: 16383 // If a friend declaration in a non-local class first declares a 16384 // class or function, the friend class or function is a member of 16385 // the innermost enclosing namespace. 16386 SearchDC = SearchDC->getEnclosingNamespaceContext(); 16387 } 16388 16389 // In C++, we need to do a redeclaration lookup to properly 16390 // diagnose some problems. 16391 // FIXME: redeclaration lookup is also used (with and without C++) to find a 16392 // hidden declaration so that we don't get ambiguity errors when using a 16393 // type declared by an elaborated-type-specifier. In C that is not correct 16394 // and we should instead merge compatible types found by lookup. 16395 if (getLangOpts().CPlusPlus) { 16396 // FIXME: This can perform qualified lookups into function contexts, 16397 // which are meaningless. 16398 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16399 LookupQualifiedName(Previous, SearchDC); 16400 } else { 16401 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16402 LookupName(Previous, S); 16403 } 16404 } 16405 16406 // If we have a known previous declaration to use, then use it. 16407 if (Previous.empty() && SkipBody && SkipBody->Previous) 16408 Previous.addDecl(SkipBody->Previous); 16409 16410 if (!Previous.empty()) { 16411 NamedDecl *PrevDecl = Previous.getFoundDecl(); 16412 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 16413 16414 // It's okay to have a tag decl in the same scope as a typedef 16415 // which hides a tag decl in the same scope. Finding this 16416 // with a redeclaration lookup can only actually happen in C++. 16417 // 16418 // This is also okay for elaborated-type-specifiers, which is 16419 // technically forbidden by the current standard but which is 16420 // okay according to the likely resolution of an open issue; 16421 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16422 if (getLangOpts().CPlusPlus) { 16423 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16424 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16425 TagDecl *Tag = TT->getDecl(); 16426 if (Tag->getDeclName() == Name && 16427 Tag->getDeclContext()->getRedeclContext() 16428 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16429 PrevDecl = Tag; 16430 Previous.clear(); 16431 Previous.addDecl(Tag); 16432 Previous.resolveKind(); 16433 } 16434 } 16435 } 16436 } 16437 16438 // If this is a redeclaration of a using shadow declaration, it must 16439 // declare a tag in the same context. In MSVC mode, we allow a 16440 // redefinition if either context is within the other. 16441 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16442 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16443 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16444 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16445 !(OldTag && isAcceptableTagRedeclContext( 16446 *this, OldTag->getDeclContext(), SearchDC))) { 16447 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16448 Diag(Shadow->getTargetDecl()->getLocation(), 16449 diag::note_using_decl_target); 16450 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16451 << 0; 16452 // Recover by ignoring the old declaration. 16453 Previous.clear(); 16454 goto CreateNewDecl; 16455 } 16456 } 16457 16458 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16459 // If this is a use of a previous tag, or if the tag is already declared 16460 // in the same scope (so that the definition/declaration completes or 16461 // rementions the tag), reuse the decl. 16462 if (TUK == TUK_Reference || TUK == TUK_Friend || 16463 isDeclInScope(DirectPrevDecl, SearchDC, S, 16464 SS.isNotEmpty() || isMemberSpecialization)) { 16465 // Make sure that this wasn't declared as an enum and now used as a 16466 // struct or something similar. 16467 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16468 TUK == TUK_Definition, KWLoc, 16469 Name)) { 16470 bool SafeToContinue 16471 = (PrevTagDecl->getTagKind() != TTK_Enum && 16472 Kind != TTK_Enum); 16473 if (SafeToContinue) 16474 Diag(KWLoc, diag::err_use_with_wrong_tag) 16475 << Name 16476 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16477 PrevTagDecl->getKindName()); 16478 else 16479 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16480 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16481 16482 if (SafeToContinue) 16483 Kind = PrevTagDecl->getTagKind(); 16484 else { 16485 // Recover by making this an anonymous redefinition. 16486 Name = nullptr; 16487 Previous.clear(); 16488 Invalid = true; 16489 } 16490 } 16491 16492 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16493 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16494 if (TUK == TUK_Reference || TUK == TUK_Friend) 16495 return PrevTagDecl; 16496 16497 QualType EnumUnderlyingTy; 16498 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16499 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16500 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16501 EnumUnderlyingTy = QualType(T, 0); 16502 16503 // All conflicts with previous declarations are recovered by 16504 // returning the previous declaration, unless this is a definition, 16505 // in which case we want the caller to bail out. 16506 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16507 ScopedEnum, EnumUnderlyingTy, 16508 IsFixed, PrevEnum)) 16509 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16510 } 16511 16512 // C++11 [class.mem]p1: 16513 // A member shall not be declared twice in the member-specification, 16514 // except that a nested class or member class template can be declared 16515 // and then later defined. 16516 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16517 S->isDeclScope(PrevDecl)) { 16518 Diag(NameLoc, diag::ext_member_redeclared); 16519 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16520 } 16521 16522 if (!Invalid) { 16523 // If this is a use, just return the declaration we found, unless 16524 // we have attributes. 16525 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16526 if (!Attrs.empty()) { 16527 // FIXME: Diagnose these attributes. For now, we create a new 16528 // declaration to hold them. 16529 } else if (TUK == TUK_Reference && 16530 (PrevTagDecl->getFriendObjectKind() == 16531 Decl::FOK_Undeclared || 16532 PrevDecl->getOwningModule() != getCurrentModule()) && 16533 SS.isEmpty()) { 16534 // This declaration is a reference to an existing entity, but 16535 // has different visibility from that entity: it either makes 16536 // a friend visible or it makes a type visible in a new module. 16537 // In either case, create a new declaration. We only do this if 16538 // the declaration would have meant the same thing if no prior 16539 // declaration were found, that is, if it was found in the same 16540 // scope where we would have injected a declaration. 16541 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16542 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16543 return PrevTagDecl; 16544 // This is in the injected scope, create a new declaration in 16545 // that scope. 16546 S = getTagInjectionScope(S, getLangOpts()); 16547 } else { 16548 return PrevTagDecl; 16549 } 16550 } 16551 16552 // Diagnose attempts to redefine a tag. 16553 if (TUK == TUK_Definition) { 16554 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16555 // If we're defining a specialization and the previous definition 16556 // is from an implicit instantiation, don't emit an error 16557 // here; we'll catch this in the general case below. 16558 bool IsExplicitSpecializationAfterInstantiation = false; 16559 if (isMemberSpecialization) { 16560 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16561 IsExplicitSpecializationAfterInstantiation = 16562 RD->getTemplateSpecializationKind() != 16563 TSK_ExplicitSpecialization; 16564 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16565 IsExplicitSpecializationAfterInstantiation = 16566 ED->getTemplateSpecializationKind() != 16567 TSK_ExplicitSpecialization; 16568 } 16569 16570 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16571 // not keep more that one definition around (merge them). However, 16572 // ensure the decl passes the structural compatibility check in 16573 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16574 NamedDecl *Hidden = nullptr; 16575 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16576 // There is a definition of this tag, but it is not visible. We 16577 // explicitly make use of C++'s one definition rule here, and 16578 // assume that this definition is identical to the hidden one 16579 // we already have. Make the existing definition visible and 16580 // use it in place of this one. 16581 if (!getLangOpts().CPlusPlus) { 16582 // Postpone making the old definition visible until after we 16583 // complete parsing the new one and do the structural 16584 // comparison. 16585 SkipBody->CheckSameAsPrevious = true; 16586 SkipBody->New = createTagFromNewDecl(); 16587 SkipBody->Previous = Def; 16588 return Def; 16589 } else { 16590 SkipBody->ShouldSkip = true; 16591 SkipBody->Previous = Def; 16592 makeMergedDefinitionVisible(Hidden); 16593 // Carry on and handle it like a normal definition. We'll 16594 // skip starting the definitiion later. 16595 } 16596 } else if (!IsExplicitSpecializationAfterInstantiation) { 16597 // A redeclaration in function prototype scope in C isn't 16598 // visible elsewhere, so merely issue a warning. 16599 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16600 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16601 else 16602 Diag(NameLoc, diag::err_redefinition) << Name; 16603 notePreviousDefinition(Def, 16604 NameLoc.isValid() ? NameLoc : KWLoc); 16605 // If this is a redefinition, recover by making this 16606 // struct be anonymous, which will make any later 16607 // references get the previous definition. 16608 Name = nullptr; 16609 Previous.clear(); 16610 Invalid = true; 16611 } 16612 } else { 16613 // If the type is currently being defined, complain 16614 // about a nested redefinition. 16615 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16616 if (TD->isBeingDefined()) { 16617 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16618 Diag(PrevTagDecl->getLocation(), 16619 diag::note_previous_definition); 16620 Name = nullptr; 16621 Previous.clear(); 16622 Invalid = true; 16623 } 16624 } 16625 16626 // Okay, this is definition of a previously declared or referenced 16627 // tag. We're going to create a new Decl for it. 16628 } 16629 16630 // Okay, we're going to make a redeclaration. If this is some kind 16631 // of reference, make sure we build the redeclaration in the same DC 16632 // as the original, and ignore the current access specifier. 16633 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16634 SearchDC = PrevTagDecl->getDeclContext(); 16635 AS = AS_none; 16636 } 16637 } 16638 // If we get here we have (another) forward declaration or we 16639 // have a definition. Just create a new decl. 16640 16641 } else { 16642 // If we get here, this is a definition of a new tag type in a nested 16643 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16644 // new decl/type. We set PrevDecl to NULL so that the entities 16645 // have distinct types. 16646 Previous.clear(); 16647 } 16648 // If we get here, we're going to create a new Decl. If PrevDecl 16649 // is non-NULL, it's a definition of the tag declared by 16650 // PrevDecl. If it's NULL, we have a new definition. 16651 16652 // Otherwise, PrevDecl is not a tag, but was found with tag 16653 // lookup. This is only actually possible in C++, where a few 16654 // things like templates still live in the tag namespace. 16655 } else { 16656 // Use a better diagnostic if an elaborated-type-specifier 16657 // found the wrong kind of type on the first 16658 // (non-redeclaration) lookup. 16659 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16660 !Previous.isForRedeclaration()) { 16661 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16662 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16663 << Kind; 16664 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16665 Invalid = true; 16666 16667 // Otherwise, only diagnose if the declaration is in scope. 16668 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16669 SS.isNotEmpty() || isMemberSpecialization)) { 16670 // do nothing 16671 16672 // Diagnose implicit declarations introduced by elaborated types. 16673 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16674 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16675 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16676 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16677 Invalid = true; 16678 16679 // Otherwise it's a declaration. Call out a particularly common 16680 // case here. 16681 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16682 unsigned Kind = 0; 16683 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16684 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16685 << Name << Kind << TND->getUnderlyingType(); 16686 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16687 Invalid = true; 16688 16689 // Otherwise, diagnose. 16690 } else { 16691 // The tag name clashes with something else in the target scope, 16692 // issue an error and recover by making this tag be anonymous. 16693 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16694 notePreviousDefinition(PrevDecl, NameLoc); 16695 Name = nullptr; 16696 Invalid = true; 16697 } 16698 16699 // The existing declaration isn't relevant to us; we're in a 16700 // new scope, so clear out the previous declaration. 16701 Previous.clear(); 16702 } 16703 } 16704 16705 CreateNewDecl: 16706 16707 TagDecl *PrevDecl = nullptr; 16708 if (Previous.isSingleResult()) 16709 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16710 16711 // If there is an identifier, use the location of the identifier as the 16712 // location of the decl, otherwise use the location of the struct/union 16713 // keyword. 16714 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16715 16716 // Otherwise, create a new declaration. If there is a previous 16717 // declaration of the same entity, the two will be linked via 16718 // PrevDecl. 16719 TagDecl *New; 16720 16721 if (Kind == TTK_Enum) { 16722 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16723 // enum X { A, B, C } D; D should chain to X. 16724 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16725 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16726 ScopedEnumUsesClassTag, IsFixed); 16727 16728 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16729 StdAlignValT = cast<EnumDecl>(New); 16730 16731 // If this is an undefined enum, warn. 16732 if (TUK != TUK_Definition && !Invalid) { 16733 TagDecl *Def; 16734 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16735 // C++0x: 7.2p2: opaque-enum-declaration. 16736 // Conflicts are diagnosed above. Do nothing. 16737 } 16738 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16739 Diag(Loc, diag::ext_forward_ref_enum_def) 16740 << New; 16741 Diag(Def->getLocation(), diag::note_previous_definition); 16742 } else { 16743 unsigned DiagID = diag::ext_forward_ref_enum; 16744 if (getLangOpts().MSVCCompat) 16745 DiagID = diag::ext_ms_forward_ref_enum; 16746 else if (getLangOpts().CPlusPlus) 16747 DiagID = diag::err_forward_ref_enum; 16748 Diag(Loc, DiagID); 16749 } 16750 } 16751 16752 if (EnumUnderlying) { 16753 EnumDecl *ED = cast<EnumDecl>(New); 16754 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16755 ED->setIntegerTypeSourceInfo(TI); 16756 else 16757 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16758 ED->setPromotionType(ED->getIntegerType()); 16759 assert(ED->isComplete() && "enum with type should be complete"); 16760 } 16761 } else { 16762 // struct/union/class 16763 16764 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16765 // struct X { int A; } D; D should chain to X. 16766 if (getLangOpts().CPlusPlus) { 16767 // FIXME: Look for a way to use RecordDecl for simple structs. 16768 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16769 cast_or_null<CXXRecordDecl>(PrevDecl)); 16770 16771 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16772 StdBadAlloc = cast<CXXRecordDecl>(New); 16773 } else 16774 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16775 cast_or_null<RecordDecl>(PrevDecl)); 16776 } 16777 16778 // C++11 [dcl.type]p3: 16779 // A type-specifier-seq shall not define a class or enumeration [...]. 16780 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16781 TUK == TUK_Definition) { 16782 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16783 << Context.getTagDeclType(New); 16784 Invalid = true; 16785 } 16786 16787 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16788 DC->getDeclKind() == Decl::Enum) { 16789 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16790 << Context.getTagDeclType(New); 16791 Invalid = true; 16792 } 16793 16794 // Maybe add qualifier info. 16795 if (SS.isNotEmpty()) { 16796 if (SS.isSet()) { 16797 // If this is either a declaration or a definition, check the 16798 // nested-name-specifier against the current context. 16799 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16800 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16801 isMemberSpecialization)) 16802 Invalid = true; 16803 16804 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16805 if (TemplateParameterLists.size() > 0) { 16806 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16807 } 16808 } 16809 else 16810 Invalid = true; 16811 } 16812 16813 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16814 // Add alignment attributes if necessary; these attributes are checked when 16815 // the ASTContext lays out the structure. 16816 // 16817 // It is important for implementing the correct semantics that this 16818 // happen here (in ActOnTag). The #pragma pack stack is 16819 // maintained as a result of parser callbacks which can occur at 16820 // many points during the parsing of a struct declaration (because 16821 // the #pragma tokens are effectively skipped over during the 16822 // parsing of the struct). 16823 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16824 AddAlignmentAttributesForRecord(RD); 16825 AddMsStructLayoutForRecord(RD); 16826 } 16827 } 16828 16829 if (ModulePrivateLoc.isValid()) { 16830 if (isMemberSpecialization) 16831 Diag(New->getLocation(), diag::err_module_private_specialization) 16832 << 2 16833 << FixItHint::CreateRemoval(ModulePrivateLoc); 16834 // __module_private__ does not apply to local classes. However, we only 16835 // diagnose this as an error when the declaration specifiers are 16836 // freestanding. Here, we just ignore the __module_private__. 16837 else if (!SearchDC->isFunctionOrMethod()) 16838 New->setModulePrivate(); 16839 } 16840 16841 // If this is a specialization of a member class (of a class template), 16842 // check the specialization. 16843 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16844 Invalid = true; 16845 16846 // If we're declaring or defining a tag in function prototype scope in C, 16847 // note that this type can only be used within the function and add it to 16848 // the list of decls to inject into the function definition scope. 16849 if ((Name || Kind == TTK_Enum) && 16850 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16851 if (getLangOpts().CPlusPlus) { 16852 // C++ [dcl.fct]p6: 16853 // Types shall not be defined in return or parameter types. 16854 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16855 Diag(Loc, diag::err_type_defined_in_param_type) 16856 << Name; 16857 Invalid = true; 16858 } 16859 } else if (!PrevDecl) { 16860 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16861 } 16862 } 16863 16864 if (Invalid) 16865 New->setInvalidDecl(); 16866 16867 // Set the lexical context. If the tag has a C++ scope specifier, the 16868 // lexical context will be different from the semantic context. 16869 New->setLexicalDeclContext(CurContext); 16870 16871 // Mark this as a friend decl if applicable. 16872 // In Microsoft mode, a friend declaration also acts as a forward 16873 // declaration so we always pass true to setObjectOfFriendDecl to make 16874 // the tag name visible. 16875 if (TUK == TUK_Friend) 16876 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16877 16878 // Set the access specifier. 16879 if (!Invalid && SearchDC->isRecord()) 16880 SetMemberAccessSpecifier(New, PrevDecl, AS); 16881 16882 if (PrevDecl) 16883 CheckRedeclarationInModule(New, PrevDecl); 16884 16885 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16886 New->startDefinition(); 16887 16888 ProcessDeclAttributeList(S, New, Attrs); 16889 AddPragmaAttributes(S, New); 16890 16891 // If this has an identifier, add it to the scope stack. 16892 if (TUK == TUK_Friend) { 16893 // We might be replacing an existing declaration in the lookup tables; 16894 // if so, borrow its access specifier. 16895 if (PrevDecl) 16896 New->setAccess(PrevDecl->getAccess()); 16897 16898 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16899 DC->makeDeclVisibleInContext(New); 16900 if (Name) // can be null along some error paths 16901 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16902 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16903 } else if (Name) { 16904 S = getNonFieldDeclScope(S); 16905 PushOnScopeChains(New, S, true); 16906 } else { 16907 CurContext->addDecl(New); 16908 } 16909 16910 // If this is the C FILE type, notify the AST context. 16911 if (IdentifierInfo *II = New->getIdentifier()) 16912 if (!New->isInvalidDecl() && 16913 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16914 II->isStr("FILE")) 16915 Context.setFILEDecl(New); 16916 16917 if (PrevDecl) 16918 mergeDeclAttributes(New, PrevDecl); 16919 16920 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16921 inferGslOwnerPointerAttribute(CXXRD); 16922 16923 // If there's a #pragma GCC visibility in scope, set the visibility of this 16924 // record. 16925 AddPushedVisibilityAttribute(New); 16926 16927 if (isMemberSpecialization && !New->isInvalidDecl()) 16928 CompleteMemberSpecialization(New, Previous); 16929 16930 OwnedDecl = true; 16931 // In C++, don't return an invalid declaration. We can't recover well from 16932 // the cases where we make the type anonymous. 16933 if (Invalid && getLangOpts().CPlusPlus) { 16934 if (New->isBeingDefined()) 16935 if (auto RD = dyn_cast<RecordDecl>(New)) 16936 RD->completeDefinition(); 16937 return nullptr; 16938 } else if (SkipBody && SkipBody->ShouldSkip) { 16939 return SkipBody->Previous; 16940 } else { 16941 return New; 16942 } 16943 } 16944 16945 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16946 AdjustDeclIfTemplate(TagD); 16947 TagDecl *Tag = cast<TagDecl>(TagD); 16948 16949 // Enter the tag context. 16950 PushDeclContext(S, Tag); 16951 16952 ActOnDocumentableDecl(TagD); 16953 16954 // If there's a #pragma GCC visibility in scope, set the visibility of this 16955 // record. 16956 AddPushedVisibilityAttribute(Tag); 16957 } 16958 16959 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { 16960 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16961 return false; 16962 16963 // Make the previous decl visible. 16964 makeMergedDefinitionVisible(SkipBody.Previous); 16965 return true; 16966 } 16967 16968 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16969 assert(isa<ObjCContainerDecl>(IDecl) && 16970 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16971 DeclContext *OCD = cast<DeclContext>(IDecl); 16972 assert(OCD->getLexicalParent() == CurContext && 16973 "The next DeclContext should be lexically contained in the current one."); 16974 CurContext = OCD; 16975 return IDecl; 16976 } 16977 16978 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16979 SourceLocation FinalLoc, 16980 bool IsFinalSpelledSealed, 16981 bool IsAbstract, 16982 SourceLocation LBraceLoc) { 16983 AdjustDeclIfTemplate(TagD); 16984 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16985 16986 FieldCollector->StartClass(); 16987 16988 if (!Record->getIdentifier()) 16989 return; 16990 16991 if (IsAbstract) 16992 Record->markAbstract(); 16993 16994 if (FinalLoc.isValid()) { 16995 Record->addAttr(FinalAttr::Create( 16996 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16997 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16998 } 16999 // C++ [class]p2: 17000 // [...] The class-name is also inserted into the scope of the 17001 // class itself; this is known as the injected-class-name. For 17002 // purposes of access checking, the injected-class-name is treated 17003 // as if it were a public member name. 17004 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 17005 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 17006 Record->getLocation(), Record->getIdentifier(), 17007 /*PrevDecl=*/nullptr, 17008 /*DelayTypeCreation=*/true); 17009 Context.getTypeDeclType(InjectedClassName, Record); 17010 InjectedClassName->setImplicit(); 17011 InjectedClassName->setAccess(AS_public); 17012 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 17013 InjectedClassName->setDescribedClassTemplate(Template); 17014 PushOnScopeChains(InjectedClassName, S); 17015 assert(InjectedClassName->isInjectedClassName() && 17016 "Broken injected-class-name"); 17017 } 17018 17019 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 17020 SourceRange BraceRange) { 17021 AdjustDeclIfTemplate(TagD); 17022 TagDecl *Tag = cast<TagDecl>(TagD); 17023 Tag->setBraceRange(BraceRange); 17024 17025 // Make sure we "complete" the definition even it is invalid. 17026 if (Tag->isBeingDefined()) { 17027 assert(Tag->isInvalidDecl() && "We should already have completed it"); 17028 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 17029 RD->completeDefinition(); 17030 } 17031 17032 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 17033 FieldCollector->FinishClass(); 17034 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 17035 auto *Def = RD->getDefinition(); 17036 assert(Def && "The record is expected to have a completed definition"); 17037 unsigned NumInitMethods = 0; 17038 for (auto *Method : Def->methods()) { 17039 if (!Method->getIdentifier()) 17040 continue; 17041 if (Method->getName() == "__init") 17042 NumInitMethods++; 17043 } 17044 if (NumInitMethods > 1 || !Def->hasInitMethod()) 17045 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 17046 } 17047 } 17048 17049 // Exit this scope of this tag's definition. 17050 PopDeclContext(); 17051 17052 if (getCurLexicalContext()->isObjCContainer() && 17053 Tag->getDeclContext()->isFileContext()) 17054 Tag->setTopLevelDeclInObjCContainer(); 17055 17056 // Notify the consumer that we've defined a tag. 17057 if (!Tag->isInvalidDecl()) 17058 Consumer.HandleTagDeclDefinition(Tag); 17059 17060 // Clangs implementation of #pragma align(packed) differs in bitfield layout 17061 // from XLs and instead matches the XL #pragma pack(1) behavior. 17062 if (Context.getTargetInfo().getTriple().isOSAIX() && 17063 AlignPackStack.hasValue()) { 17064 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 17065 // Only diagnose #pragma align(packed). 17066 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 17067 return; 17068 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 17069 if (!RD) 17070 return; 17071 // Only warn if there is at least 1 bitfield member. 17072 if (llvm::any_of(RD->fields(), 17073 [](const FieldDecl *FD) { return FD->isBitField(); })) 17074 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 17075 } 17076 } 17077 17078 void Sema::ActOnObjCContainerFinishDefinition() { 17079 // Exit this scope of this interface definition. 17080 PopDeclContext(); 17081 } 17082 17083 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 17084 assert(DC == CurContext && "Mismatch of container contexts"); 17085 OriginalLexicalContext = DC; 17086 ActOnObjCContainerFinishDefinition(); 17087 } 17088 17089 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 17090 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 17091 OriginalLexicalContext = nullptr; 17092 } 17093 17094 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 17095 AdjustDeclIfTemplate(TagD); 17096 TagDecl *Tag = cast<TagDecl>(TagD); 17097 Tag->setInvalidDecl(); 17098 17099 // Make sure we "complete" the definition even it is invalid. 17100 if (Tag->isBeingDefined()) { 17101 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 17102 RD->completeDefinition(); 17103 } 17104 17105 // We're undoing ActOnTagStartDefinition here, not 17106 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 17107 // the FieldCollector. 17108 17109 PopDeclContext(); 17110 } 17111 17112 // Note that FieldName may be null for anonymous bitfields. 17113 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 17114 IdentifierInfo *FieldName, 17115 QualType FieldTy, bool IsMsStruct, 17116 Expr *BitWidth, bool *ZeroWidth) { 17117 assert(BitWidth); 17118 if (BitWidth->containsErrors()) 17119 return ExprError(); 17120 17121 // Default to true; that shouldn't confuse checks for emptiness 17122 if (ZeroWidth) 17123 *ZeroWidth = true; 17124 17125 // C99 6.7.2.1p4 - verify the field type. 17126 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 17127 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 17128 // Handle incomplete and sizeless types with a specific error. 17129 if (RequireCompleteSizedType(FieldLoc, FieldTy, 17130 diag::err_field_incomplete_or_sizeless)) 17131 return ExprError(); 17132 if (FieldName) 17133 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 17134 << FieldName << FieldTy << BitWidth->getSourceRange(); 17135 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 17136 << FieldTy << BitWidth->getSourceRange(); 17137 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 17138 UPPC_BitFieldWidth)) 17139 return ExprError(); 17140 17141 // If the bit-width is type- or value-dependent, don't try to check 17142 // it now. 17143 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 17144 return BitWidth; 17145 17146 llvm::APSInt Value; 17147 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 17148 if (ICE.isInvalid()) 17149 return ICE; 17150 BitWidth = ICE.get(); 17151 17152 if (Value != 0 && ZeroWidth) 17153 *ZeroWidth = false; 17154 17155 // Zero-width bitfield is ok for anonymous field. 17156 if (Value == 0 && FieldName) 17157 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 17158 17159 if (Value.isSigned() && Value.isNegative()) { 17160 if (FieldName) 17161 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 17162 << FieldName << toString(Value, 10); 17163 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 17164 << toString(Value, 10); 17165 } 17166 17167 // The size of the bit-field must not exceed our maximum permitted object 17168 // size. 17169 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 17170 return Diag(FieldLoc, diag::err_bitfield_too_wide) 17171 << !FieldName << FieldName << toString(Value, 10); 17172 } 17173 17174 if (!FieldTy->isDependentType()) { 17175 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 17176 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 17177 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 17178 17179 // Over-wide bitfields are an error in C or when using the MSVC bitfield 17180 // ABI. 17181 bool CStdConstraintViolation = 17182 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 17183 bool MSBitfieldViolation = 17184 Value.ugt(TypeStorageSize) && 17185 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 17186 if (CStdConstraintViolation || MSBitfieldViolation) { 17187 unsigned DiagWidth = 17188 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 17189 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 17190 << (bool)FieldName << FieldName << toString(Value, 10) 17191 << !CStdConstraintViolation << DiagWidth; 17192 } 17193 17194 // Warn on types where the user might conceivably expect to get all 17195 // specified bits as value bits: that's all integral types other than 17196 // 'bool'. 17197 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 17198 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 17199 << FieldName << toString(Value, 10) 17200 << (unsigned)TypeWidth; 17201 } 17202 } 17203 17204 return BitWidth; 17205 } 17206 17207 /// ActOnField - Each field of a C struct/union is passed into this in order 17208 /// to create a FieldDecl object for it. 17209 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 17210 Declarator &D, Expr *BitfieldWidth) { 17211 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 17212 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 17213 /*InitStyle=*/ICIS_NoInit, AS_public); 17214 return Res; 17215 } 17216 17217 /// HandleField - Analyze a field of a C struct or a C++ data member. 17218 /// 17219 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 17220 SourceLocation DeclStart, 17221 Declarator &D, Expr *BitWidth, 17222 InClassInitStyle InitStyle, 17223 AccessSpecifier AS) { 17224 if (D.isDecompositionDeclarator()) { 17225 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 17226 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 17227 << Decomp.getSourceRange(); 17228 return nullptr; 17229 } 17230 17231 IdentifierInfo *II = D.getIdentifier(); 17232 SourceLocation Loc = DeclStart; 17233 if (II) Loc = D.getIdentifierLoc(); 17234 17235 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17236 QualType T = TInfo->getType(); 17237 if (getLangOpts().CPlusPlus) { 17238 CheckExtraCXXDefaultArguments(D); 17239 17240 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17241 UPPC_DataMemberType)) { 17242 D.setInvalidType(); 17243 T = Context.IntTy; 17244 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17245 } 17246 } 17247 17248 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17249 17250 if (D.getDeclSpec().isInlineSpecified()) 17251 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17252 << getLangOpts().CPlusPlus17; 17253 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17254 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17255 diag::err_invalid_thread) 17256 << DeclSpec::getSpecifierName(TSCS); 17257 17258 // Check to see if this name was declared as a member previously 17259 NamedDecl *PrevDecl = nullptr; 17260 LookupResult Previous(*this, II, Loc, LookupMemberName, 17261 ForVisibleRedeclaration); 17262 LookupName(Previous, S); 17263 switch (Previous.getResultKind()) { 17264 case LookupResult::Found: 17265 case LookupResult::FoundUnresolvedValue: 17266 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17267 break; 17268 17269 case LookupResult::FoundOverloaded: 17270 PrevDecl = Previous.getRepresentativeDecl(); 17271 break; 17272 17273 case LookupResult::NotFound: 17274 case LookupResult::NotFoundInCurrentInstantiation: 17275 case LookupResult::Ambiguous: 17276 break; 17277 } 17278 Previous.suppressDiagnostics(); 17279 17280 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17281 // Maybe we will complain about the shadowed template parameter. 17282 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17283 // Just pretend that we didn't see the previous declaration. 17284 PrevDecl = nullptr; 17285 } 17286 17287 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17288 PrevDecl = nullptr; 17289 17290 bool Mutable 17291 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 17292 SourceLocation TSSL = D.getBeginLoc(); 17293 FieldDecl *NewFD 17294 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 17295 TSSL, AS, PrevDecl, &D); 17296 17297 if (NewFD->isInvalidDecl()) 17298 Record->setInvalidDecl(); 17299 17300 if (D.getDeclSpec().isModulePrivateSpecified()) 17301 NewFD->setModulePrivate(); 17302 17303 if (NewFD->isInvalidDecl() && PrevDecl) { 17304 // Don't introduce NewFD into scope; there's already something 17305 // with the same name in the same scope. 17306 } else if (II) { 17307 PushOnScopeChains(NewFD, S); 17308 } else 17309 Record->addDecl(NewFD); 17310 17311 return NewFD; 17312 } 17313 17314 /// Build a new FieldDecl and check its well-formedness. 17315 /// 17316 /// This routine builds a new FieldDecl given the fields name, type, 17317 /// record, etc. \p PrevDecl should refer to any previous declaration 17318 /// with the same name and in the same scope as the field to be 17319 /// created. 17320 /// 17321 /// \returns a new FieldDecl. 17322 /// 17323 /// \todo The Declarator argument is a hack. It will be removed once 17324 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 17325 TypeSourceInfo *TInfo, 17326 RecordDecl *Record, SourceLocation Loc, 17327 bool Mutable, Expr *BitWidth, 17328 InClassInitStyle InitStyle, 17329 SourceLocation TSSL, 17330 AccessSpecifier AS, NamedDecl *PrevDecl, 17331 Declarator *D) { 17332 IdentifierInfo *II = Name.getAsIdentifierInfo(); 17333 bool InvalidDecl = false; 17334 if (D) InvalidDecl = D->isInvalidType(); 17335 17336 // If we receive a broken type, recover by assuming 'int' and 17337 // marking this declaration as invalid. 17338 if (T.isNull() || T->containsErrors()) { 17339 InvalidDecl = true; 17340 T = Context.IntTy; 17341 } 17342 17343 QualType EltTy = Context.getBaseElementType(T); 17344 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 17345 if (RequireCompleteSizedType(Loc, EltTy, 17346 diag::err_field_incomplete_or_sizeless)) { 17347 // Fields of incomplete type force their record to be invalid. 17348 Record->setInvalidDecl(); 17349 InvalidDecl = true; 17350 } else { 17351 NamedDecl *Def; 17352 EltTy->isIncompleteType(&Def); 17353 if (Def && Def->isInvalidDecl()) { 17354 Record->setInvalidDecl(); 17355 InvalidDecl = true; 17356 } 17357 } 17358 } 17359 17360 // TR 18037 does not allow fields to be declared with address space 17361 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 17362 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 17363 Diag(Loc, diag::err_field_with_address_space); 17364 Record->setInvalidDecl(); 17365 InvalidDecl = true; 17366 } 17367 17368 if (LangOpts.OpenCL) { 17369 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 17370 // used as structure or union field: image, sampler, event or block types. 17371 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 17372 T->isBlockPointerType()) { 17373 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 17374 Record->setInvalidDecl(); 17375 InvalidDecl = true; 17376 } 17377 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 17378 // is enabled. 17379 if (BitWidth && !getOpenCLOptions().isAvailableOption( 17380 "__cl_clang_bitfields", LangOpts)) { 17381 Diag(Loc, diag::err_opencl_bitfields); 17382 InvalidDecl = true; 17383 } 17384 } 17385 17386 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 17387 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 17388 T.hasQualifiers()) { 17389 InvalidDecl = true; 17390 Diag(Loc, diag::err_anon_bitfield_qualifiers); 17391 } 17392 17393 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17394 // than a variably modified type. 17395 if (!InvalidDecl && T->isVariablyModifiedType()) { 17396 if (!tryToFixVariablyModifiedVarType( 17397 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 17398 InvalidDecl = true; 17399 } 17400 17401 // Fields can not have abstract class types 17402 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 17403 diag::err_abstract_type_in_decl, 17404 AbstractFieldType)) 17405 InvalidDecl = true; 17406 17407 bool ZeroWidth = false; 17408 if (InvalidDecl) 17409 BitWidth = nullptr; 17410 // If this is declared as a bit-field, check the bit-field. 17411 if (BitWidth) { 17412 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 17413 &ZeroWidth).get(); 17414 if (!BitWidth) { 17415 InvalidDecl = true; 17416 BitWidth = nullptr; 17417 ZeroWidth = false; 17418 } 17419 } 17420 17421 // Check that 'mutable' is consistent with the type of the declaration. 17422 if (!InvalidDecl && Mutable) { 17423 unsigned DiagID = 0; 17424 if (T->isReferenceType()) 17425 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 17426 : diag::err_mutable_reference; 17427 else if (T.isConstQualified()) 17428 DiagID = diag::err_mutable_const; 17429 17430 if (DiagID) { 17431 SourceLocation ErrLoc = Loc; 17432 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17433 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17434 Diag(ErrLoc, DiagID); 17435 if (DiagID != diag::ext_mutable_reference) { 17436 Mutable = false; 17437 InvalidDecl = true; 17438 } 17439 } 17440 } 17441 17442 // C++11 [class.union]p8 (DR1460): 17443 // At most one variant member of a union may have a 17444 // brace-or-equal-initializer. 17445 if (InitStyle != ICIS_NoInit) 17446 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17447 17448 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17449 BitWidth, Mutable, InitStyle); 17450 if (InvalidDecl) 17451 NewFD->setInvalidDecl(); 17452 17453 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17454 Diag(Loc, diag::err_duplicate_member) << II; 17455 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17456 NewFD->setInvalidDecl(); 17457 } 17458 17459 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17460 if (Record->isUnion()) { 17461 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17462 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17463 if (RDecl->getDefinition()) { 17464 // C++ [class.union]p1: An object of a class with a non-trivial 17465 // constructor, a non-trivial copy constructor, a non-trivial 17466 // destructor, or a non-trivial copy assignment operator 17467 // cannot be a member of a union, nor can an array of such 17468 // objects. 17469 if (CheckNontrivialField(NewFD)) 17470 NewFD->setInvalidDecl(); 17471 } 17472 } 17473 17474 // C++ [class.union]p1: If a union contains a member of reference type, 17475 // the program is ill-formed, except when compiling with MSVC extensions 17476 // enabled. 17477 if (EltTy->isReferenceType()) { 17478 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17479 diag::ext_union_member_of_reference_type : 17480 diag::err_union_member_of_reference_type) 17481 << NewFD->getDeclName() << EltTy; 17482 if (!getLangOpts().MicrosoftExt) 17483 NewFD->setInvalidDecl(); 17484 } 17485 } 17486 } 17487 17488 // FIXME: We need to pass in the attributes given an AST 17489 // representation, not a parser representation. 17490 if (D) { 17491 // FIXME: The current scope is almost... but not entirely... correct here. 17492 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17493 17494 if (NewFD->hasAttrs()) 17495 CheckAlignasUnderalignment(NewFD); 17496 } 17497 17498 // In auto-retain/release, infer strong retension for fields of 17499 // retainable type. 17500 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17501 NewFD->setInvalidDecl(); 17502 17503 if (T.isObjCGCWeak()) 17504 Diag(Loc, diag::warn_attribute_weak_on_field); 17505 17506 // PPC MMA non-pointer types are not allowed as field types. 17507 if (Context.getTargetInfo().getTriple().isPPC64() && 17508 CheckPPCMMAType(T, NewFD->getLocation())) 17509 NewFD->setInvalidDecl(); 17510 17511 NewFD->setAccess(AS); 17512 return NewFD; 17513 } 17514 17515 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17516 assert(FD); 17517 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17518 17519 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17520 return false; 17521 17522 QualType EltTy = Context.getBaseElementType(FD->getType()); 17523 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17524 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17525 if (RDecl->getDefinition()) { 17526 // We check for copy constructors before constructors 17527 // because otherwise we'll never get complaints about 17528 // copy constructors. 17529 17530 CXXSpecialMember member = CXXInvalid; 17531 // We're required to check for any non-trivial constructors. Since the 17532 // implicit default constructor is suppressed if there are any 17533 // user-declared constructors, we just need to check that there is a 17534 // trivial default constructor and a trivial copy constructor. (We don't 17535 // worry about move constructors here, since this is a C++98 check.) 17536 if (RDecl->hasNonTrivialCopyConstructor()) 17537 member = CXXCopyConstructor; 17538 else if (!RDecl->hasTrivialDefaultConstructor()) 17539 member = CXXDefaultConstructor; 17540 else if (RDecl->hasNonTrivialCopyAssignment()) 17541 member = CXXCopyAssignment; 17542 else if (RDecl->hasNonTrivialDestructor()) 17543 member = CXXDestructor; 17544 17545 if (member != CXXInvalid) { 17546 if (!getLangOpts().CPlusPlus11 && 17547 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17548 // Objective-C++ ARC: it is an error to have a non-trivial field of 17549 // a union. However, system headers in Objective-C programs 17550 // occasionally have Objective-C lifetime objects within unions, 17551 // and rather than cause the program to fail, we make those 17552 // members unavailable. 17553 SourceLocation Loc = FD->getLocation(); 17554 if (getSourceManager().isInSystemHeader(Loc)) { 17555 if (!FD->hasAttr<UnavailableAttr>()) 17556 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17557 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17558 return false; 17559 } 17560 } 17561 17562 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17563 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17564 diag::err_illegal_union_or_anon_struct_member) 17565 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17566 DiagnoseNontrivial(RDecl, member); 17567 return !getLangOpts().CPlusPlus11; 17568 } 17569 } 17570 } 17571 17572 return false; 17573 } 17574 17575 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17576 /// AST enum value. 17577 static ObjCIvarDecl::AccessControl 17578 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17579 switch (ivarVisibility) { 17580 default: llvm_unreachable("Unknown visitibility kind"); 17581 case tok::objc_private: return ObjCIvarDecl::Private; 17582 case tok::objc_public: return ObjCIvarDecl::Public; 17583 case tok::objc_protected: return ObjCIvarDecl::Protected; 17584 case tok::objc_package: return ObjCIvarDecl::Package; 17585 } 17586 } 17587 17588 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17589 /// in order to create an IvarDecl object for it. 17590 Decl *Sema::ActOnIvar(Scope *S, 17591 SourceLocation DeclStart, 17592 Declarator &D, Expr *BitfieldWidth, 17593 tok::ObjCKeywordKind Visibility) { 17594 17595 IdentifierInfo *II = D.getIdentifier(); 17596 Expr *BitWidth = (Expr*)BitfieldWidth; 17597 SourceLocation Loc = DeclStart; 17598 if (II) Loc = D.getIdentifierLoc(); 17599 17600 // FIXME: Unnamed fields can be handled in various different ways, for 17601 // example, unnamed unions inject all members into the struct namespace! 17602 17603 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17604 QualType T = TInfo->getType(); 17605 17606 if (BitWidth) { 17607 // 6.7.2.1p3, 6.7.2.1p4 17608 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17609 if (!BitWidth) 17610 D.setInvalidType(); 17611 } else { 17612 // Not a bitfield. 17613 17614 // validate II. 17615 17616 } 17617 if (T->isReferenceType()) { 17618 Diag(Loc, diag::err_ivar_reference_type); 17619 D.setInvalidType(); 17620 } 17621 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17622 // than a variably modified type. 17623 else if (T->isVariablyModifiedType()) { 17624 if (!tryToFixVariablyModifiedVarType( 17625 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17626 D.setInvalidType(); 17627 } 17628 17629 // Get the visibility (access control) for this ivar. 17630 ObjCIvarDecl::AccessControl ac = 17631 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17632 : ObjCIvarDecl::None; 17633 // Must set ivar's DeclContext to its enclosing interface. 17634 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17635 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17636 return nullptr; 17637 ObjCContainerDecl *EnclosingContext; 17638 if (ObjCImplementationDecl *IMPDecl = 17639 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17640 if (LangOpts.ObjCRuntime.isFragile()) { 17641 // Case of ivar declared in an implementation. Context is that of its class. 17642 EnclosingContext = IMPDecl->getClassInterface(); 17643 assert(EnclosingContext && "Implementation has no class interface!"); 17644 } 17645 else 17646 EnclosingContext = EnclosingDecl; 17647 } else { 17648 if (ObjCCategoryDecl *CDecl = 17649 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17650 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17651 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17652 return nullptr; 17653 } 17654 } 17655 EnclosingContext = EnclosingDecl; 17656 } 17657 17658 // Construct the decl. 17659 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17660 DeclStart, Loc, II, T, 17661 TInfo, ac, (Expr *)BitfieldWidth); 17662 17663 if (II) { 17664 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17665 ForVisibleRedeclaration); 17666 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17667 && !isa<TagDecl>(PrevDecl)) { 17668 Diag(Loc, diag::err_duplicate_member) << II; 17669 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17670 NewID->setInvalidDecl(); 17671 } 17672 } 17673 17674 // Process attributes attached to the ivar. 17675 ProcessDeclAttributes(S, NewID, D); 17676 17677 if (D.isInvalidType()) 17678 NewID->setInvalidDecl(); 17679 17680 // In ARC, infer 'retaining' for ivars of retainable type. 17681 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17682 NewID->setInvalidDecl(); 17683 17684 if (D.getDeclSpec().isModulePrivateSpecified()) 17685 NewID->setModulePrivate(); 17686 17687 if (II) { 17688 // FIXME: When interfaces are DeclContexts, we'll need to add 17689 // these to the interface. 17690 S->AddDecl(NewID); 17691 IdResolver.AddDecl(NewID); 17692 } 17693 17694 if (LangOpts.ObjCRuntime.isNonFragile() && 17695 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17696 Diag(Loc, diag::warn_ivars_in_interface); 17697 17698 return NewID; 17699 } 17700 17701 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17702 /// class and class extensions. For every class \@interface and class 17703 /// extension \@interface, if the last ivar is a bitfield of any type, 17704 /// then add an implicit `char :0` ivar to the end of that interface. 17705 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17706 SmallVectorImpl<Decl *> &AllIvarDecls) { 17707 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17708 return; 17709 17710 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17711 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17712 17713 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17714 return; 17715 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17716 if (!ID) { 17717 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17718 if (!CD->IsClassExtension()) 17719 return; 17720 } 17721 // No need to add this to end of @implementation. 17722 else 17723 return; 17724 } 17725 // All conditions are met. Add a new bitfield to the tail end of ivars. 17726 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17727 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17728 17729 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17730 DeclLoc, DeclLoc, nullptr, 17731 Context.CharTy, 17732 Context.getTrivialTypeSourceInfo(Context.CharTy, 17733 DeclLoc), 17734 ObjCIvarDecl::Private, BW, 17735 true); 17736 AllIvarDecls.push_back(Ivar); 17737 } 17738 17739 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17740 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17741 SourceLocation RBrac, 17742 const ParsedAttributesView &Attrs) { 17743 assert(EnclosingDecl && "missing record or interface decl"); 17744 17745 // If this is an Objective-C @implementation or category and we have 17746 // new fields here we should reset the layout of the interface since 17747 // it will now change. 17748 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17749 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17750 switch (DC->getKind()) { 17751 default: break; 17752 case Decl::ObjCCategory: 17753 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17754 break; 17755 case Decl::ObjCImplementation: 17756 Context. 17757 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17758 break; 17759 } 17760 } 17761 17762 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17763 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17764 17765 // Start counting up the number of named members; make sure to include 17766 // members of anonymous structs and unions in the total. 17767 unsigned NumNamedMembers = 0; 17768 if (Record) { 17769 for (const auto *I : Record->decls()) { 17770 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17771 if (IFD->getDeclName()) 17772 ++NumNamedMembers; 17773 } 17774 } 17775 17776 // Verify that all the fields are okay. 17777 SmallVector<FieldDecl*, 32> RecFields; 17778 17779 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17780 i != end; ++i) { 17781 FieldDecl *FD = cast<FieldDecl>(*i); 17782 17783 // Get the type for the field. 17784 const Type *FDTy = FD->getType().getTypePtr(); 17785 17786 if (!FD->isAnonymousStructOrUnion()) { 17787 // Remember all fields written by the user. 17788 RecFields.push_back(FD); 17789 } 17790 17791 // If the field is already invalid for some reason, don't emit more 17792 // diagnostics about it. 17793 if (FD->isInvalidDecl()) { 17794 EnclosingDecl->setInvalidDecl(); 17795 continue; 17796 } 17797 17798 // C99 6.7.2.1p2: 17799 // A structure or union shall not contain a member with 17800 // incomplete or function type (hence, a structure shall not 17801 // contain an instance of itself, but may contain a pointer to 17802 // an instance of itself), except that the last member of a 17803 // structure with more than one named member may have incomplete 17804 // array type; such a structure (and any union containing, 17805 // possibly recursively, a member that is such a structure) 17806 // shall not be a member of a structure or an element of an 17807 // array. 17808 bool IsLastField = (i + 1 == Fields.end()); 17809 if (FDTy->isFunctionType()) { 17810 // Field declared as a function. 17811 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17812 << FD->getDeclName(); 17813 FD->setInvalidDecl(); 17814 EnclosingDecl->setInvalidDecl(); 17815 continue; 17816 } else if (FDTy->isIncompleteArrayType() && 17817 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17818 if (Record) { 17819 // Flexible array member. 17820 // Microsoft and g++ is more permissive regarding flexible array. 17821 // It will accept flexible array in union and also 17822 // as the sole element of a struct/class. 17823 unsigned DiagID = 0; 17824 if (!Record->isUnion() && !IsLastField) { 17825 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17826 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17827 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17828 FD->setInvalidDecl(); 17829 EnclosingDecl->setInvalidDecl(); 17830 continue; 17831 } else if (Record->isUnion()) 17832 DiagID = getLangOpts().MicrosoftExt 17833 ? diag::ext_flexible_array_union_ms 17834 : getLangOpts().CPlusPlus 17835 ? diag::ext_flexible_array_union_gnu 17836 : diag::err_flexible_array_union; 17837 else if (NumNamedMembers < 1) 17838 DiagID = getLangOpts().MicrosoftExt 17839 ? diag::ext_flexible_array_empty_aggregate_ms 17840 : getLangOpts().CPlusPlus 17841 ? diag::ext_flexible_array_empty_aggregate_gnu 17842 : diag::err_flexible_array_empty_aggregate; 17843 17844 if (DiagID) 17845 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17846 << Record->getTagKind(); 17847 // While the layout of types that contain virtual bases is not specified 17848 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17849 // virtual bases after the derived members. This would make a flexible 17850 // array member declared at the end of an object not adjacent to the end 17851 // of the type. 17852 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17853 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17854 << FD->getDeclName() << Record->getTagKind(); 17855 if (!getLangOpts().C99) 17856 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17857 << FD->getDeclName() << Record->getTagKind(); 17858 17859 // If the element type has a non-trivial destructor, we would not 17860 // implicitly destroy the elements, so disallow it for now. 17861 // 17862 // FIXME: GCC allows this. We should probably either implicitly delete 17863 // the destructor of the containing class, or just allow this. 17864 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17865 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17866 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17867 << FD->getDeclName() << FD->getType(); 17868 FD->setInvalidDecl(); 17869 EnclosingDecl->setInvalidDecl(); 17870 continue; 17871 } 17872 // Okay, we have a legal flexible array member at the end of the struct. 17873 Record->setHasFlexibleArrayMember(true); 17874 } else { 17875 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17876 // unless they are followed by another ivar. That check is done 17877 // elsewhere, after synthesized ivars are known. 17878 } 17879 } else if (!FDTy->isDependentType() && 17880 RequireCompleteSizedType( 17881 FD->getLocation(), FD->getType(), 17882 diag::err_field_incomplete_or_sizeless)) { 17883 // Incomplete type 17884 FD->setInvalidDecl(); 17885 EnclosingDecl->setInvalidDecl(); 17886 continue; 17887 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17888 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17889 // A type which contains a flexible array member is considered to be a 17890 // flexible array member. 17891 Record->setHasFlexibleArrayMember(true); 17892 if (!Record->isUnion()) { 17893 // If this is a struct/class and this is not the last element, reject 17894 // it. Note that GCC supports variable sized arrays in the middle of 17895 // structures. 17896 if (!IsLastField) 17897 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17898 << FD->getDeclName() << FD->getType(); 17899 else { 17900 // We support flexible arrays at the end of structs in 17901 // other structs as an extension. 17902 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17903 << FD->getDeclName(); 17904 } 17905 } 17906 } 17907 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17908 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17909 diag::err_abstract_type_in_decl, 17910 AbstractIvarType)) { 17911 // Ivars can not have abstract class types 17912 FD->setInvalidDecl(); 17913 } 17914 if (Record && FDTTy->getDecl()->hasObjectMember()) 17915 Record->setHasObjectMember(true); 17916 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17917 Record->setHasVolatileMember(true); 17918 } else if (FDTy->isObjCObjectType()) { 17919 /// A field cannot be an Objective-c object 17920 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17921 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17922 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17923 FD->setType(T); 17924 } else if (Record && Record->isUnion() && 17925 FD->getType().hasNonTrivialObjCLifetime() && 17926 getSourceManager().isInSystemHeader(FD->getLocation()) && 17927 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17928 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17929 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17930 // For backward compatibility, fields of C unions declared in system 17931 // headers that have non-trivial ObjC ownership qualifications are marked 17932 // as unavailable unless the qualifier is explicit and __strong. This can 17933 // break ABI compatibility between programs compiled with ARC and MRR, but 17934 // is a better option than rejecting programs using those unions under 17935 // ARC. 17936 FD->addAttr(UnavailableAttr::CreateImplicit( 17937 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17938 FD->getLocation())); 17939 } else if (getLangOpts().ObjC && 17940 getLangOpts().getGC() != LangOptions::NonGC && Record && 17941 !Record->hasObjectMember()) { 17942 if (FD->getType()->isObjCObjectPointerType() || 17943 FD->getType().isObjCGCStrong()) 17944 Record->setHasObjectMember(true); 17945 else if (Context.getAsArrayType(FD->getType())) { 17946 QualType BaseType = Context.getBaseElementType(FD->getType()); 17947 if (BaseType->isRecordType() && 17948 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17949 Record->setHasObjectMember(true); 17950 else if (BaseType->isObjCObjectPointerType() || 17951 BaseType.isObjCGCStrong()) 17952 Record->setHasObjectMember(true); 17953 } 17954 } 17955 17956 if (Record && !getLangOpts().CPlusPlus && 17957 !shouldIgnoreForRecordTriviality(FD)) { 17958 QualType FT = FD->getType(); 17959 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17960 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17961 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17962 Record->isUnion()) 17963 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17964 } 17965 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17966 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17967 Record->setNonTrivialToPrimitiveCopy(true); 17968 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17969 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17970 } 17971 if (FT.isDestructedType()) { 17972 Record->setNonTrivialToPrimitiveDestroy(true); 17973 Record->setParamDestroyedInCallee(true); 17974 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17975 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17976 } 17977 17978 if (const auto *RT = FT->getAs<RecordType>()) { 17979 if (RT->getDecl()->getArgPassingRestrictions() == 17980 RecordDecl::APK_CanNeverPassInRegs) 17981 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17982 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17983 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17984 } 17985 17986 if (Record && FD->getType().isVolatileQualified()) 17987 Record->setHasVolatileMember(true); 17988 // Keep track of the number of named members. 17989 if (FD->getIdentifier()) 17990 ++NumNamedMembers; 17991 } 17992 17993 // Okay, we successfully defined 'Record'. 17994 if (Record) { 17995 bool Completed = false; 17996 if (CXXRecord) { 17997 if (!CXXRecord->isInvalidDecl()) { 17998 // Set access bits correctly on the directly-declared conversions. 17999 for (CXXRecordDecl::conversion_iterator 18000 I = CXXRecord->conversion_begin(), 18001 E = CXXRecord->conversion_end(); I != E; ++I) 18002 I.setAccess((*I)->getAccess()); 18003 } 18004 18005 // Add any implicitly-declared members to this class. 18006 AddImplicitlyDeclaredMembersToClass(CXXRecord); 18007 18008 if (!CXXRecord->isDependentType()) { 18009 if (!CXXRecord->isInvalidDecl()) { 18010 // If we have virtual base classes, we may end up finding multiple 18011 // final overriders for a given virtual function. Check for this 18012 // problem now. 18013 if (CXXRecord->getNumVBases()) { 18014 CXXFinalOverriderMap FinalOverriders; 18015 CXXRecord->getFinalOverriders(FinalOverriders); 18016 18017 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 18018 MEnd = FinalOverriders.end(); 18019 M != MEnd; ++M) { 18020 for (OverridingMethods::iterator SO = M->second.begin(), 18021 SOEnd = M->second.end(); 18022 SO != SOEnd; ++SO) { 18023 assert(SO->second.size() > 0 && 18024 "Virtual function without overriding functions?"); 18025 if (SO->second.size() == 1) 18026 continue; 18027 18028 // C++ [class.virtual]p2: 18029 // In a derived class, if a virtual member function of a base 18030 // class subobject has more than one final overrider the 18031 // program is ill-formed. 18032 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 18033 << (const NamedDecl *)M->first << Record; 18034 Diag(M->first->getLocation(), 18035 diag::note_overridden_virtual_function); 18036 for (OverridingMethods::overriding_iterator 18037 OM = SO->second.begin(), 18038 OMEnd = SO->second.end(); 18039 OM != OMEnd; ++OM) 18040 Diag(OM->Method->getLocation(), diag::note_final_overrider) 18041 << (const NamedDecl *)M->first << OM->Method->getParent(); 18042 18043 Record->setInvalidDecl(); 18044 } 18045 } 18046 CXXRecord->completeDefinition(&FinalOverriders); 18047 Completed = true; 18048 } 18049 } 18050 } 18051 } 18052 18053 if (!Completed) 18054 Record->completeDefinition(); 18055 18056 // Handle attributes before checking the layout. 18057 ProcessDeclAttributeList(S, Record, Attrs); 18058 18059 // Maybe randomize the field order. 18060 if (!getLangOpts().CPlusPlus && Record->hasAttr<RandomizeLayoutAttr>() && 18061 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && 18062 !Record->isRandomized()) { 18063 SmallVector<Decl *, 32> OrigFieldOrdering(Record->fields()); 18064 SmallVector<Decl *, 32> NewFieldOrdering; 18065 if (randstruct::randomizeStructureLayout( 18066 Context, Record->getNameAsString(), OrigFieldOrdering, 18067 NewFieldOrdering)) 18068 Record->reorderFields(NewFieldOrdering); 18069 } 18070 18071 // We may have deferred checking for a deleted destructor. Check now. 18072 if (CXXRecord) { 18073 auto *Dtor = CXXRecord->getDestructor(); 18074 if (Dtor && Dtor->isImplicit() && 18075 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 18076 CXXRecord->setImplicitDestructorIsDeleted(); 18077 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 18078 } 18079 } 18080 18081 if (Record->hasAttrs()) { 18082 CheckAlignasUnderalignment(Record); 18083 18084 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 18085 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 18086 IA->getRange(), IA->getBestCase(), 18087 IA->getInheritanceModel()); 18088 } 18089 18090 // Check if the structure/union declaration is a type that can have zero 18091 // size in C. For C this is a language extension, for C++ it may cause 18092 // compatibility problems. 18093 bool CheckForZeroSize; 18094 if (!getLangOpts().CPlusPlus) { 18095 CheckForZeroSize = true; 18096 } else { 18097 // For C++ filter out types that cannot be referenced in C code. 18098 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 18099 CheckForZeroSize = 18100 CXXRecord->getLexicalDeclContext()->isExternCContext() && 18101 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 18102 CXXRecord->isCLike(); 18103 } 18104 if (CheckForZeroSize) { 18105 bool ZeroSize = true; 18106 bool IsEmpty = true; 18107 unsigned NonBitFields = 0; 18108 for (RecordDecl::field_iterator I = Record->field_begin(), 18109 E = Record->field_end(); 18110 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 18111 IsEmpty = false; 18112 if (I->isUnnamedBitfield()) { 18113 if (!I->isZeroLengthBitField(Context)) 18114 ZeroSize = false; 18115 } else { 18116 ++NonBitFields; 18117 QualType FieldType = I->getType(); 18118 if (FieldType->isIncompleteType() || 18119 !Context.getTypeSizeInChars(FieldType).isZero()) 18120 ZeroSize = false; 18121 } 18122 } 18123 18124 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 18125 // allowed in C++, but warn if its declaration is inside 18126 // extern "C" block. 18127 if (ZeroSize) { 18128 Diag(RecLoc, getLangOpts().CPlusPlus ? 18129 diag::warn_zero_size_struct_union_in_extern_c : 18130 diag::warn_zero_size_struct_union_compat) 18131 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 18132 } 18133 18134 // Structs without named members are extension in C (C99 6.7.2.1p7), 18135 // but are accepted by GCC. 18136 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 18137 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 18138 diag::ext_no_named_members_in_struct_union) 18139 << Record->isUnion(); 18140 } 18141 } 18142 } else { 18143 ObjCIvarDecl **ClsFields = 18144 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 18145 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 18146 ID->setEndOfDefinitionLoc(RBrac); 18147 // Add ivar's to class's DeclContext. 18148 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18149 ClsFields[i]->setLexicalDeclContext(ID); 18150 ID->addDecl(ClsFields[i]); 18151 } 18152 // Must enforce the rule that ivars in the base classes may not be 18153 // duplicates. 18154 if (ID->getSuperClass()) 18155 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 18156 } else if (ObjCImplementationDecl *IMPDecl = 18157 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 18158 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 18159 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 18160 // Ivar declared in @implementation never belongs to the implementation. 18161 // Only it is in implementation's lexical context. 18162 ClsFields[I]->setLexicalDeclContext(IMPDecl); 18163 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 18164 IMPDecl->setIvarLBraceLoc(LBrac); 18165 IMPDecl->setIvarRBraceLoc(RBrac); 18166 } else if (ObjCCategoryDecl *CDecl = 18167 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 18168 // case of ivars in class extension; all other cases have been 18169 // reported as errors elsewhere. 18170 // FIXME. Class extension does not have a LocEnd field. 18171 // CDecl->setLocEnd(RBrac); 18172 // Add ivar's to class extension's DeclContext. 18173 // Diagnose redeclaration of private ivars. 18174 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 18175 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18176 if (IDecl) { 18177 if (const ObjCIvarDecl *ClsIvar = 18178 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 18179 Diag(ClsFields[i]->getLocation(), 18180 diag::err_duplicate_ivar_declaration); 18181 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 18182 continue; 18183 } 18184 for (const auto *Ext : IDecl->known_extensions()) { 18185 if (const ObjCIvarDecl *ClsExtIvar 18186 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 18187 Diag(ClsFields[i]->getLocation(), 18188 diag::err_duplicate_ivar_declaration); 18189 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 18190 continue; 18191 } 18192 } 18193 } 18194 ClsFields[i]->setLexicalDeclContext(CDecl); 18195 CDecl->addDecl(ClsFields[i]); 18196 } 18197 CDecl->setIvarLBraceLoc(LBrac); 18198 CDecl->setIvarRBraceLoc(RBrac); 18199 } 18200 } 18201 } 18202 18203 /// Determine whether the given integral value is representable within 18204 /// the given type T. 18205 static bool isRepresentableIntegerValue(ASTContext &Context, 18206 llvm::APSInt &Value, 18207 QualType T) { 18208 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 18209 "Integral type required!"); 18210 unsigned BitWidth = Context.getIntWidth(T); 18211 18212 if (Value.isUnsigned() || Value.isNonNegative()) { 18213 if (T->isSignedIntegerOrEnumerationType()) 18214 --BitWidth; 18215 return Value.getActiveBits() <= BitWidth; 18216 } 18217 return Value.getMinSignedBits() <= BitWidth; 18218 } 18219 18220 // Given an integral type, return the next larger integral type 18221 // (or a NULL type of no such type exists). 18222 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 18223 // FIXME: Int128/UInt128 support, which also needs to be introduced into 18224 // enum checking below. 18225 assert((T->isIntegralType(Context) || 18226 T->isEnumeralType()) && "Integral type required!"); 18227 const unsigned NumTypes = 4; 18228 QualType SignedIntegralTypes[NumTypes] = { 18229 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 18230 }; 18231 QualType UnsignedIntegralTypes[NumTypes] = { 18232 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 18233 Context.UnsignedLongLongTy 18234 }; 18235 18236 unsigned BitWidth = Context.getTypeSize(T); 18237 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 18238 : UnsignedIntegralTypes; 18239 for (unsigned I = 0; I != NumTypes; ++I) 18240 if (Context.getTypeSize(Types[I]) > BitWidth) 18241 return Types[I]; 18242 18243 return QualType(); 18244 } 18245 18246 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 18247 EnumConstantDecl *LastEnumConst, 18248 SourceLocation IdLoc, 18249 IdentifierInfo *Id, 18250 Expr *Val) { 18251 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18252 llvm::APSInt EnumVal(IntWidth); 18253 QualType EltTy; 18254 18255 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 18256 Val = nullptr; 18257 18258 if (Val) 18259 Val = DefaultLvalueConversion(Val).get(); 18260 18261 if (Val) { 18262 if (Enum->isDependentType() || Val->isTypeDependent() || 18263 Val->containsErrors()) 18264 EltTy = Context.DependentTy; 18265 else { 18266 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 18267 // underlying type, but do allow it in all other contexts. 18268 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 18269 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 18270 // constant-expression in the enumerator-definition shall be a converted 18271 // constant expression of the underlying type. 18272 EltTy = Enum->getIntegerType(); 18273 ExprResult Converted = 18274 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 18275 CCEK_Enumerator); 18276 if (Converted.isInvalid()) 18277 Val = nullptr; 18278 else 18279 Val = Converted.get(); 18280 } else if (!Val->isValueDependent() && 18281 !(Val = 18282 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 18283 .get())) { 18284 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 18285 } else { 18286 if (Enum->isComplete()) { 18287 EltTy = Enum->getIntegerType(); 18288 18289 // In Obj-C and Microsoft mode, require the enumeration value to be 18290 // representable in the underlying type of the enumeration. In C++11, 18291 // we perform a non-narrowing conversion as part of converted constant 18292 // expression checking. 18293 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18294 if (Context.getTargetInfo() 18295 .getTriple() 18296 .isWindowsMSVCEnvironment()) { 18297 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 18298 } else { 18299 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 18300 } 18301 } 18302 18303 // Cast to the underlying type. 18304 Val = ImpCastExprToType(Val, EltTy, 18305 EltTy->isBooleanType() ? CK_IntegralToBoolean 18306 : CK_IntegralCast) 18307 .get(); 18308 } else if (getLangOpts().CPlusPlus) { 18309 // C++11 [dcl.enum]p5: 18310 // If the underlying type is not fixed, the type of each enumerator 18311 // is the type of its initializing value: 18312 // - If an initializer is specified for an enumerator, the 18313 // initializing value has the same type as the expression. 18314 EltTy = Val->getType(); 18315 } else { 18316 // C99 6.7.2.2p2: 18317 // The expression that defines the value of an enumeration constant 18318 // shall be an integer constant expression that has a value 18319 // representable as an int. 18320 18321 // Complain if the value is not representable in an int. 18322 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 18323 Diag(IdLoc, diag::ext_enum_value_not_int) 18324 << toString(EnumVal, 10) << Val->getSourceRange() 18325 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 18326 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 18327 // Force the type of the expression to 'int'. 18328 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 18329 } 18330 EltTy = Val->getType(); 18331 } 18332 } 18333 } 18334 } 18335 18336 if (!Val) { 18337 if (Enum->isDependentType()) 18338 EltTy = Context.DependentTy; 18339 else if (!LastEnumConst) { 18340 // C++0x [dcl.enum]p5: 18341 // If the underlying type is not fixed, the type of each enumerator 18342 // is the type of its initializing value: 18343 // - If no initializer is specified for the first enumerator, the 18344 // initializing value has an unspecified integral type. 18345 // 18346 // GCC uses 'int' for its unspecified integral type, as does 18347 // C99 6.7.2.2p3. 18348 if (Enum->isFixed()) { 18349 EltTy = Enum->getIntegerType(); 18350 } 18351 else { 18352 EltTy = Context.IntTy; 18353 } 18354 } else { 18355 // Assign the last value + 1. 18356 EnumVal = LastEnumConst->getInitVal(); 18357 ++EnumVal; 18358 EltTy = LastEnumConst->getType(); 18359 18360 // Check for overflow on increment. 18361 if (EnumVal < LastEnumConst->getInitVal()) { 18362 // C++0x [dcl.enum]p5: 18363 // If the underlying type is not fixed, the type of each enumerator 18364 // is the type of its initializing value: 18365 // 18366 // - Otherwise the type of the initializing value is the same as 18367 // the type of the initializing value of the preceding enumerator 18368 // unless the incremented value is not representable in that type, 18369 // in which case the type is an unspecified integral type 18370 // sufficient to contain the incremented value. If no such type 18371 // exists, the program is ill-formed. 18372 QualType T = getNextLargerIntegralType(Context, EltTy); 18373 if (T.isNull() || Enum->isFixed()) { 18374 // There is no integral type larger enough to represent this 18375 // value. Complain, then allow the value to wrap around. 18376 EnumVal = LastEnumConst->getInitVal(); 18377 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 18378 ++EnumVal; 18379 if (Enum->isFixed()) 18380 // When the underlying type is fixed, this is ill-formed. 18381 Diag(IdLoc, diag::err_enumerator_wrapped) 18382 << toString(EnumVal, 10) 18383 << EltTy; 18384 else 18385 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 18386 << toString(EnumVal, 10); 18387 } else { 18388 EltTy = T; 18389 } 18390 18391 // Retrieve the last enumerator's value, extent that type to the 18392 // type that is supposed to be large enough to represent the incremented 18393 // value, then increment. 18394 EnumVal = LastEnumConst->getInitVal(); 18395 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18396 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 18397 ++EnumVal; 18398 18399 // If we're not in C++, diagnose the overflow of enumerator values, 18400 // which in C99 means that the enumerator value is not representable in 18401 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 18402 // permits enumerator values that are representable in some larger 18403 // integral type. 18404 if (!getLangOpts().CPlusPlus && !T.isNull()) 18405 Diag(IdLoc, diag::warn_enum_value_overflow); 18406 } else if (!getLangOpts().CPlusPlus && 18407 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18408 // Enforce C99 6.7.2.2p2 even when we compute the next value. 18409 Diag(IdLoc, diag::ext_enum_value_not_int) 18410 << toString(EnumVal, 10) << 1; 18411 } 18412 } 18413 } 18414 18415 if (!EltTy->isDependentType()) { 18416 // Make the enumerator value match the signedness and size of the 18417 // enumerator's type. 18418 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 18419 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18420 } 18421 18422 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 18423 Val, EnumVal); 18424 } 18425 18426 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 18427 SourceLocation IILoc) { 18428 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 18429 !getLangOpts().CPlusPlus) 18430 return SkipBodyInfo(); 18431 18432 // We have an anonymous enum definition. Look up the first enumerator to 18433 // determine if we should merge the definition with an existing one and 18434 // skip the body. 18435 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 18436 forRedeclarationInCurContext()); 18437 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 18438 if (!PrevECD) 18439 return SkipBodyInfo(); 18440 18441 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18442 NamedDecl *Hidden; 18443 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18444 SkipBodyInfo Skip; 18445 Skip.Previous = Hidden; 18446 return Skip; 18447 } 18448 18449 return SkipBodyInfo(); 18450 } 18451 18452 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18453 SourceLocation IdLoc, IdentifierInfo *Id, 18454 const ParsedAttributesView &Attrs, 18455 SourceLocation EqualLoc, Expr *Val) { 18456 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18457 EnumConstantDecl *LastEnumConst = 18458 cast_or_null<EnumConstantDecl>(lastEnumConst); 18459 18460 // The scope passed in may not be a decl scope. Zip up the scope tree until 18461 // we find one that is. 18462 S = getNonFieldDeclScope(S); 18463 18464 // Verify that there isn't already something declared with this name in this 18465 // scope. 18466 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18467 LookupName(R, S); 18468 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18469 18470 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18471 // Maybe we will complain about the shadowed template parameter. 18472 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18473 // Just pretend that we didn't see the previous declaration. 18474 PrevDecl = nullptr; 18475 } 18476 18477 // C++ [class.mem]p15: 18478 // If T is the name of a class, then each of the following shall have a name 18479 // different from T: 18480 // - every enumerator of every member of class T that is an unscoped 18481 // enumerated type 18482 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18483 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18484 DeclarationNameInfo(Id, IdLoc)); 18485 18486 EnumConstantDecl *New = 18487 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18488 if (!New) 18489 return nullptr; 18490 18491 if (PrevDecl) { 18492 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18493 // Check for other kinds of shadowing not already handled. 18494 CheckShadow(New, PrevDecl, R); 18495 } 18496 18497 // When in C++, we may get a TagDecl with the same name; in this case the 18498 // enum constant will 'hide' the tag. 18499 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18500 "Received TagDecl when not in C++!"); 18501 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18502 if (isa<EnumConstantDecl>(PrevDecl)) 18503 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18504 else 18505 Diag(IdLoc, diag::err_redefinition) << Id; 18506 notePreviousDefinition(PrevDecl, IdLoc); 18507 return nullptr; 18508 } 18509 } 18510 18511 // Process attributes. 18512 ProcessDeclAttributeList(S, New, Attrs); 18513 AddPragmaAttributes(S, New); 18514 18515 // Register this decl in the current scope stack. 18516 New->setAccess(TheEnumDecl->getAccess()); 18517 PushOnScopeChains(New, S); 18518 18519 ActOnDocumentableDecl(New); 18520 18521 return New; 18522 } 18523 18524 // Returns true when the enum initial expression does not trigger the 18525 // duplicate enum warning. A few common cases are exempted as follows: 18526 // Element2 = Element1 18527 // Element2 = Element1 + 1 18528 // Element2 = Element1 - 1 18529 // Where Element2 and Element1 are from the same enum. 18530 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18531 Expr *InitExpr = ECD->getInitExpr(); 18532 if (!InitExpr) 18533 return true; 18534 InitExpr = InitExpr->IgnoreImpCasts(); 18535 18536 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18537 if (!BO->isAdditiveOp()) 18538 return true; 18539 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18540 if (!IL) 18541 return true; 18542 if (IL->getValue() != 1) 18543 return true; 18544 18545 InitExpr = BO->getLHS(); 18546 } 18547 18548 // This checks if the elements are from the same enum. 18549 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18550 if (!DRE) 18551 return true; 18552 18553 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18554 if (!EnumConstant) 18555 return true; 18556 18557 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18558 Enum) 18559 return true; 18560 18561 return false; 18562 } 18563 18564 // Emits a warning when an element is implicitly set a value that 18565 // a previous element has already been set to. 18566 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18567 EnumDecl *Enum, QualType EnumType) { 18568 // Avoid anonymous enums 18569 if (!Enum->getIdentifier()) 18570 return; 18571 18572 // Only check for small enums. 18573 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18574 return; 18575 18576 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18577 return; 18578 18579 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18580 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18581 18582 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18583 18584 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18585 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18586 18587 // Use int64_t as a key to avoid needing special handling for map keys. 18588 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18589 llvm::APSInt Val = D->getInitVal(); 18590 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18591 }; 18592 18593 DuplicatesVector DupVector; 18594 ValueToVectorMap EnumMap; 18595 18596 // Populate the EnumMap with all values represented by enum constants without 18597 // an initializer. 18598 for (auto *Element : Elements) { 18599 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18600 18601 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18602 // this constant. Skip this enum since it may be ill-formed. 18603 if (!ECD) { 18604 return; 18605 } 18606 18607 // Constants with initalizers are handled in the next loop. 18608 if (ECD->getInitExpr()) 18609 continue; 18610 18611 // Duplicate values are handled in the next loop. 18612 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18613 } 18614 18615 if (EnumMap.size() == 0) 18616 return; 18617 18618 // Create vectors for any values that has duplicates. 18619 for (auto *Element : Elements) { 18620 // The last loop returned if any constant was null. 18621 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18622 if (!ValidDuplicateEnum(ECD, Enum)) 18623 continue; 18624 18625 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18626 if (Iter == EnumMap.end()) 18627 continue; 18628 18629 DeclOrVector& Entry = Iter->second; 18630 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18631 // Ensure constants are different. 18632 if (D == ECD) 18633 continue; 18634 18635 // Create new vector and push values onto it. 18636 auto Vec = std::make_unique<ECDVector>(); 18637 Vec->push_back(D); 18638 Vec->push_back(ECD); 18639 18640 // Update entry to point to the duplicates vector. 18641 Entry = Vec.get(); 18642 18643 // Store the vector somewhere we can consult later for quick emission of 18644 // diagnostics. 18645 DupVector.emplace_back(std::move(Vec)); 18646 continue; 18647 } 18648 18649 ECDVector *Vec = Entry.get<ECDVector*>(); 18650 // Make sure constants are not added more than once. 18651 if (*Vec->begin() == ECD) 18652 continue; 18653 18654 Vec->push_back(ECD); 18655 } 18656 18657 // Emit diagnostics. 18658 for (const auto &Vec : DupVector) { 18659 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18660 18661 // Emit warning for one enum constant. 18662 auto *FirstECD = Vec->front(); 18663 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18664 << FirstECD << toString(FirstECD->getInitVal(), 10) 18665 << FirstECD->getSourceRange(); 18666 18667 // Emit one note for each of the remaining enum constants with 18668 // the same value. 18669 for (auto *ECD : llvm::drop_begin(*Vec)) 18670 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18671 << ECD << toString(ECD->getInitVal(), 10) 18672 << ECD->getSourceRange(); 18673 } 18674 } 18675 18676 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18677 bool AllowMask) const { 18678 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18679 assert(ED->isCompleteDefinition() && "expected enum definition"); 18680 18681 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18682 llvm::APInt &FlagBits = R.first->second; 18683 18684 if (R.second) { 18685 for (auto *E : ED->enumerators()) { 18686 const auto &EVal = E->getInitVal(); 18687 // Only single-bit enumerators introduce new flag values. 18688 if (EVal.isPowerOf2()) 18689 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18690 } 18691 } 18692 18693 // A value is in a flag enum if either its bits are a subset of the enum's 18694 // flag bits (the first condition) or we are allowing masks and the same is 18695 // true of its complement (the second condition). When masks are allowed, we 18696 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18697 // 18698 // While it's true that any value could be used as a mask, the assumption is 18699 // that a mask will have all of the insignificant bits set. Anything else is 18700 // likely a logic error. 18701 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18702 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18703 } 18704 18705 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18706 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18707 const ParsedAttributesView &Attrs) { 18708 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18709 QualType EnumType = Context.getTypeDeclType(Enum); 18710 18711 ProcessDeclAttributeList(S, Enum, Attrs); 18712 18713 if (Enum->isDependentType()) { 18714 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18715 EnumConstantDecl *ECD = 18716 cast_or_null<EnumConstantDecl>(Elements[i]); 18717 if (!ECD) continue; 18718 18719 ECD->setType(EnumType); 18720 } 18721 18722 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18723 return; 18724 } 18725 18726 // TODO: If the result value doesn't fit in an int, it must be a long or long 18727 // long value. ISO C does not support this, but GCC does as an extension, 18728 // emit a warning. 18729 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18730 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18731 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18732 18733 // Verify that all the values are okay, compute the size of the values, and 18734 // reverse the list. 18735 unsigned NumNegativeBits = 0; 18736 unsigned NumPositiveBits = 0; 18737 18738 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18739 EnumConstantDecl *ECD = 18740 cast_or_null<EnumConstantDecl>(Elements[i]); 18741 if (!ECD) continue; // Already issued a diagnostic. 18742 18743 const llvm::APSInt &InitVal = ECD->getInitVal(); 18744 18745 // Keep track of the size of positive and negative values. 18746 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18747 NumPositiveBits = std::max(NumPositiveBits, 18748 (unsigned)InitVal.getActiveBits()); 18749 else 18750 NumNegativeBits = std::max(NumNegativeBits, 18751 (unsigned)InitVal.getMinSignedBits()); 18752 } 18753 18754 // Figure out the type that should be used for this enum. 18755 QualType BestType; 18756 unsigned BestWidth; 18757 18758 // C++0x N3000 [conv.prom]p3: 18759 // An rvalue of an unscoped enumeration type whose underlying 18760 // type is not fixed can be converted to an rvalue of the first 18761 // of the following types that can represent all the values of 18762 // the enumeration: int, unsigned int, long int, unsigned long 18763 // int, long long int, or unsigned long long int. 18764 // C99 6.4.4.3p2: 18765 // An identifier declared as an enumeration constant has type int. 18766 // The C99 rule is modified by a gcc extension 18767 QualType BestPromotionType; 18768 18769 bool Packed = Enum->hasAttr<PackedAttr>(); 18770 // -fshort-enums is the equivalent to specifying the packed attribute on all 18771 // enum definitions. 18772 if (LangOpts.ShortEnums) 18773 Packed = true; 18774 18775 // If the enum already has a type because it is fixed or dictated by the 18776 // target, promote that type instead of analyzing the enumerators. 18777 if (Enum->isComplete()) { 18778 BestType = Enum->getIntegerType(); 18779 if (BestType->isPromotableIntegerType()) 18780 BestPromotionType = Context.getPromotedIntegerType(BestType); 18781 else 18782 BestPromotionType = BestType; 18783 18784 BestWidth = Context.getIntWidth(BestType); 18785 } 18786 else if (NumNegativeBits) { 18787 // If there is a negative value, figure out the smallest integer type (of 18788 // int/long/longlong) that fits. 18789 // If it's packed, check also if it fits a char or a short. 18790 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18791 BestType = Context.SignedCharTy; 18792 BestWidth = CharWidth; 18793 } else if (Packed && NumNegativeBits <= ShortWidth && 18794 NumPositiveBits < ShortWidth) { 18795 BestType = Context.ShortTy; 18796 BestWidth = ShortWidth; 18797 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18798 BestType = Context.IntTy; 18799 BestWidth = IntWidth; 18800 } else { 18801 BestWidth = Context.getTargetInfo().getLongWidth(); 18802 18803 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18804 BestType = Context.LongTy; 18805 } else { 18806 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18807 18808 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18809 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18810 BestType = Context.LongLongTy; 18811 } 18812 } 18813 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18814 } else { 18815 // If there is no negative value, figure out the smallest type that fits 18816 // all of the enumerator values. 18817 // If it's packed, check also if it fits a char or a short. 18818 if (Packed && NumPositiveBits <= CharWidth) { 18819 BestType = Context.UnsignedCharTy; 18820 BestPromotionType = Context.IntTy; 18821 BestWidth = CharWidth; 18822 } else if (Packed && NumPositiveBits <= ShortWidth) { 18823 BestType = Context.UnsignedShortTy; 18824 BestPromotionType = Context.IntTy; 18825 BestWidth = ShortWidth; 18826 } else if (NumPositiveBits <= IntWidth) { 18827 BestType = Context.UnsignedIntTy; 18828 BestWidth = IntWidth; 18829 BestPromotionType 18830 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18831 ? Context.UnsignedIntTy : Context.IntTy; 18832 } else if (NumPositiveBits <= 18833 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18834 BestType = Context.UnsignedLongTy; 18835 BestPromotionType 18836 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18837 ? Context.UnsignedLongTy : Context.LongTy; 18838 } else { 18839 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18840 assert(NumPositiveBits <= BestWidth && 18841 "How could an initializer get larger than ULL?"); 18842 BestType = Context.UnsignedLongLongTy; 18843 BestPromotionType 18844 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18845 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18846 } 18847 } 18848 18849 // Loop over all of the enumerator constants, changing their types to match 18850 // the type of the enum if needed. 18851 for (auto *D : Elements) { 18852 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18853 if (!ECD) continue; // Already issued a diagnostic. 18854 18855 // Standard C says the enumerators have int type, but we allow, as an 18856 // extension, the enumerators to be larger than int size. If each 18857 // enumerator value fits in an int, type it as an int, otherwise type it the 18858 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18859 // that X has type 'int', not 'unsigned'. 18860 18861 // Determine whether the value fits into an int. 18862 llvm::APSInt InitVal = ECD->getInitVal(); 18863 18864 // If it fits into an integer type, force it. Otherwise force it to match 18865 // the enum decl type. 18866 QualType NewTy; 18867 unsigned NewWidth; 18868 bool NewSign; 18869 if (!getLangOpts().CPlusPlus && 18870 !Enum->isFixed() && 18871 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18872 NewTy = Context.IntTy; 18873 NewWidth = IntWidth; 18874 NewSign = true; 18875 } else if (ECD->getType() == BestType) { 18876 // Already the right type! 18877 if (getLangOpts().CPlusPlus) 18878 // C++ [dcl.enum]p4: Following the closing brace of an 18879 // enum-specifier, each enumerator has the type of its 18880 // enumeration. 18881 ECD->setType(EnumType); 18882 continue; 18883 } else { 18884 NewTy = BestType; 18885 NewWidth = BestWidth; 18886 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18887 } 18888 18889 // Adjust the APSInt value. 18890 InitVal = InitVal.extOrTrunc(NewWidth); 18891 InitVal.setIsSigned(NewSign); 18892 ECD->setInitVal(InitVal); 18893 18894 // Adjust the Expr initializer and type. 18895 if (ECD->getInitExpr() && 18896 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18897 ECD->setInitExpr(ImplicitCastExpr::Create( 18898 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18899 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18900 if (getLangOpts().CPlusPlus) 18901 // C++ [dcl.enum]p4: Following the closing brace of an 18902 // enum-specifier, each enumerator has the type of its 18903 // enumeration. 18904 ECD->setType(EnumType); 18905 else 18906 ECD->setType(NewTy); 18907 } 18908 18909 Enum->completeDefinition(BestType, BestPromotionType, 18910 NumPositiveBits, NumNegativeBits); 18911 18912 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18913 18914 if (Enum->isClosedFlag()) { 18915 for (Decl *D : Elements) { 18916 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18917 if (!ECD) continue; // Already issued a diagnostic. 18918 18919 llvm::APSInt InitVal = ECD->getInitVal(); 18920 if (InitVal != 0 && !InitVal.isPowerOf2() && 18921 !IsValueInFlagEnum(Enum, InitVal, true)) 18922 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18923 << ECD << Enum; 18924 } 18925 } 18926 18927 // Now that the enum type is defined, ensure it's not been underaligned. 18928 if (Enum->hasAttrs()) 18929 CheckAlignasUnderalignment(Enum); 18930 } 18931 18932 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18933 SourceLocation StartLoc, 18934 SourceLocation EndLoc) { 18935 StringLiteral *AsmString = cast<StringLiteral>(expr); 18936 18937 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18938 AsmString, StartLoc, 18939 EndLoc); 18940 CurContext->addDecl(New); 18941 return New; 18942 } 18943 18944 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18945 IdentifierInfo* AliasName, 18946 SourceLocation PragmaLoc, 18947 SourceLocation NameLoc, 18948 SourceLocation AliasNameLoc) { 18949 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18950 LookupOrdinaryName); 18951 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18952 AttributeCommonInfo::AS_Pragma); 18953 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18954 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 18955 18956 // If a declaration that: 18957 // 1) declares a function or a variable 18958 // 2) has external linkage 18959 // already exists, add a label attribute to it. 18960 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18961 if (isDeclExternC(PrevDecl)) 18962 PrevDecl->addAttr(Attr); 18963 else 18964 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18965 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18966 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18967 } else 18968 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18969 } 18970 18971 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18972 SourceLocation PragmaLoc, 18973 SourceLocation NameLoc) { 18974 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18975 18976 if (PrevDecl) { 18977 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18978 } else { 18979 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 18980 } 18981 } 18982 18983 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18984 IdentifierInfo* AliasName, 18985 SourceLocation PragmaLoc, 18986 SourceLocation NameLoc, 18987 SourceLocation AliasNameLoc) { 18988 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18989 LookupOrdinaryName); 18990 WeakInfo W = WeakInfo(Name, NameLoc); 18991 18992 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18993 if (!PrevDecl->hasAttr<AliasAttr>()) 18994 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18995 DeclApplyPragmaWeak(TUScope, ND, W); 18996 } else { 18997 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 18998 } 18999 } 19000 19001 Decl *Sema::getObjCDeclContext() const { 19002 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 19003 } 19004 19005 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 19006 bool Final) { 19007 assert(FD && "Expected non-null FunctionDecl"); 19008 19009 // SYCL functions can be template, so we check if they have appropriate 19010 // attribute prior to checking if it is a template. 19011 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 19012 return FunctionEmissionStatus::Emitted; 19013 19014 // Templates are emitted when they're instantiated. 19015 if (FD->isDependentContext()) 19016 return FunctionEmissionStatus::TemplateDiscarded; 19017 19018 // Check whether this function is an externally visible definition. 19019 auto IsEmittedForExternalSymbol = [this, FD]() { 19020 // We have to check the GVA linkage of the function's *definition* -- if we 19021 // only have a declaration, we don't know whether or not the function will 19022 // be emitted, because (say) the definition could include "inline". 19023 FunctionDecl *Def = FD->getDefinition(); 19024 19025 return Def && !isDiscardableGVALinkage( 19026 getASTContext().GetGVALinkageForFunction(Def)); 19027 }; 19028 19029 if (LangOpts.OpenMPIsDevice) { 19030 // In OpenMP device mode we will not emit host only functions, or functions 19031 // we don't need due to their linkage. 19032 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 19033 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 19034 // DevTy may be changed later by 19035 // #pragma omp declare target to(*) device_type(*). 19036 // Therefore DevTy having no value does not imply host. The emission status 19037 // will be checked again at the end of compilation unit with Final = true. 19038 if (DevTy.hasValue()) 19039 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 19040 return FunctionEmissionStatus::OMPDiscarded; 19041 // If we have an explicit value for the device type, or we are in a target 19042 // declare context, we need to emit all extern and used symbols. 19043 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 19044 if (IsEmittedForExternalSymbol()) 19045 return FunctionEmissionStatus::Emitted; 19046 // Device mode only emits what it must, if it wasn't tagged yet and needed, 19047 // we'll omit it. 19048 if (Final) 19049 return FunctionEmissionStatus::OMPDiscarded; 19050 } else if (LangOpts.OpenMP > 45) { 19051 // In OpenMP host compilation prior to 5.0 everything was an emitted host 19052 // function. In 5.0, no_host was introduced which might cause a function to 19053 // be ommitted. 19054 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 19055 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 19056 if (DevTy.hasValue()) 19057 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 19058 return FunctionEmissionStatus::OMPDiscarded; 19059 } 19060 19061 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 19062 return FunctionEmissionStatus::Emitted; 19063 19064 if (LangOpts.CUDA) { 19065 // When compiling for device, host functions are never emitted. Similarly, 19066 // when compiling for host, device and global functions are never emitted. 19067 // (Technically, we do emit a host-side stub for global functions, but this 19068 // doesn't count for our purposes here.) 19069 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 19070 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 19071 return FunctionEmissionStatus::CUDADiscarded; 19072 if (!LangOpts.CUDAIsDevice && 19073 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 19074 return FunctionEmissionStatus::CUDADiscarded; 19075 19076 if (IsEmittedForExternalSymbol()) 19077 return FunctionEmissionStatus::Emitted; 19078 } 19079 19080 // Otherwise, the function is known-emitted if it's in our set of 19081 // known-emitted functions. 19082 return FunctionEmissionStatus::Unknown; 19083 } 19084 19085 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 19086 // Host-side references to a __global__ function refer to the stub, so the 19087 // function itself is never emitted and therefore should not be marked. 19088 // If we have host fn calls kernel fn calls host+device, the HD function 19089 // does not get instantiated on the host. We model this by omitting at the 19090 // call to the kernel from the callgraph. This ensures that, when compiling 19091 // for host, only HD functions actually called from the host get marked as 19092 // known-emitted. 19093 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 19094 IdentifyCUDATarget(Callee) == CFT_Global; 19095 } 19096